content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def display_width(str):
"""Return the required over-/underline length for str."""
try:
# Respect &ambiwidth and &tabstop, but old vim may not support this
return vim.strdisplaywidth(str)
except AttributeError:
# Fallback
from unicodedata import east_asian_width
result... | 47,200 |
def read_str_4_by_4():
"""
>>> n = 44100 * 2 * 2
>>> stream = BitStream(n * "A")
>>> for i in range(n / 4):
... stream.read(str, 4)
""" | 47,201 |
def get_short_int(filename, ptr):
"""Jump to position 'ptr' in file and read a 16-bit integer."""
val = get_val(filename, ptr, np.int16)
return int( val ) | 47,202 |
def u32_from_dto(dto: U32DTOType) -> int:
"""Convert DTO to 32-bit int."""
check_overflow(0 <= dto <= U32_MAX)
return dto | 47,203 |
def diagonal_basis_commutes(pauli_a, pauli_b):
"""
Test if `pauli_a` and `pauli_b` share a diagonal basis
Example:
Check if [A, B] with the constraint that A & B must share a one-qubit
diagonalizing basis. If the inputs were [sZ(0), sZ(0) * sZ(1)] then this
function would return Tr... | 47,204 |
def cost_using_SigmoidCrossEntropyWithLogits(logits, labels):
"""
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've bee... | 47,205 |
def clone_to_df(clone):
"""Convert a clone to a pandas.DataFrame."""
number_of_mutations = clone.deltas.shape[0]
clone_stats = pd.DataFrame(
np.stack([clone.frequencies for _ in range(number_of_mutations)]),
columns=clone.frequencies.index,
index=clone.deltas.index
)
clone_st... | 47,206 |
def get_points_on_rim(mesh_dir, scale=1.2, obj_name='cup'):
"""This will return me points which lie on the rim of the cup or bowl
"""
assert os.path.exists(mesh_dir)
meshes = [osp.join(mesh_dir, m) for m in os.listdir(mesh_dir) if "visual" not in m]
meshes = [m for m in meshes if "convex" in m]
... | 47,207 |
def reorder_kernel_weight(torch_weight):
""" Reorder a torch kernel weight into a tf format """
len_shape = len(torch_weight.shape)
transpose_target = list(range(len_shape))
transpose_target = transpose_target[2:] + transpose_target[:2][::-1]
return torch_weight.transpose(transpose_target) | 47,208 |
def print(*value, sep: str = ' ', end: str = '\n', file=sys.stdout, flush: bool = False):
"""
Print values on the terminal or a stream
----------
value - Things to print (see Python print() docs).
sep : str - The string that separates the arguments in value (Default: space).
end : str - The s... | 47,209 |
def make_windows(x, window_size, horizon):
"""
Creates a window out of
"""
# Create a window of specific window size
window_step = np.expand_dims(np.arange(window_size+horizon), axis=0)
# Create a 2D array of multiple window steps
window_indices = window_step + np.expand_dims(np.arang... | 47,210 |
def interpolate(arr_old, arr_new, I_old, J_old):
# deprecated 2013-08-26
"""
input: array, i, j
output: value
(int(x),
int(y)+1)
+ + (int(x)+1, int(y)+1)
(x,y)
+ + (int(x)+1, int(y))
(int(x),
int(y))
be careful - floor(x)=ceil... | 47,211 |
def create_tif_file(left: float, bottom: float, right: float, top: float, to_file: Optional[str] = None,
cache_dir: str = CACHE_DIR, nodata: int = 0) -> Union[str, MemoryFile]:
"""Create a TIF file using SRTM data for the box defined by left,
bottom, right, top. If to_file is provided, sa... | 47,212 |
def point_seg_sep(ar, br1, br2):
"""Return the minimum separation vector between a point and a line segment,
in 3 dimensions.
Parameters
----------
ar: array-like, shape (3,)
Coordinates of a point.
br1, br2: array-like, shape (3,)
Coordinates for the points of a line segment
... | 47,213 |
def get_bucket(args: argparse.Namespace):
"""
Print bucket of SSDS deployment
"""
ssds = Staging[args.deployment].ssds
print(f"{ssds.blobstore.schema}{ssds.bucket}") | 47,214 |
def get_creds():
"""
Function which will take no arguments, but look for API credentials which are stored on the internet.
Unfortunately, this is the most recognizable and weakest part of the code, since it fetches the creds
from the same places over and over again.
TODO: Rework this so we're not ha... | 47,215 |
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up climate controls for TOLO Sauna."""
coordinator = hass.data[DOMAIN][entry.entry_id]
async_add_entities([SaunaClimate(coordinator, entry)]) | 47,216 |
def shd(node_1: BinaryTreeNode,
node_2: BinaryTreeNode,
hd: Callable[[BinaryTreeNode, BinaryTreeNode], float]) -> float:
"""Structural Hamming distance (SHD)
:param node_1:
:param node_2:
:param hd:
:return:
"""
if node_1 is None or node_2 is None:
return 1
# fir... | 47,217 |
def movmeanstd(ts, m=0):
"""
Calculate the mean and standard deviation within a moving window passing across a time series.
Parameters
----------
ts: Time series to evaluate.
m: Width of the moving window.
"""
if m <= 1:
raise ValueError("Query length must be longer th... | 47,218 |
def importing_regiondata():
"""
Loads the regiondata
Should convert the year column to proper year
Should immediately create geopandas dataframe
Returns: a dataframe
"""
regiondata = pd.read_stata("data/regiondata.dta")
return regiondata | 47,219 |
def load_docked_ligands(
pdbqt_output: str) -> Tuple[List[RDKitMol], List[float]]:
"""This function loads ligands docked by autodock vina.
Autodock vina writes outputs to disk in a PDBQT file format. This
PDBQT file can contain multiple docked "poses". Recall that a pose
is an energetically favorable 3D co... | 47,220 |
def rotationFromQuaternion(*args):
"""rotationFromQuaternion(float pA, float pB, float pC, float pD) -> Rotation"""
return _almath.rotationFromQuaternion(*args) | 47,221 |
def generate_chat_messages(in_dir, out_dir):
"""Generate chatting messages from the screenshots in in_dir to out_dir.
"""
files = sorted(common.get_image_paths(in_dir, "bmp"))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
mk_bytes = Image.open("resources/chat_imgs/marketkeeper.png")... | 47,222 |
def get_username(identifier):
"""Checks if a string is a email adress or not."""
pattern = re.compile('.+@\w+\..+')
if pattern.match(identifier):
try:
user = User.objects.get(email=identifier)
except:
raise Http404
else:
return user.username
el... | 47,223 |
def halo_particles(mock_dm_halo):
"""Spherical mock halo."""
def make(N_part=100, seed=None):
random = np.random.RandomState(seed=seed)
mass_dm, pos_dm = mock_dm_halo(N_part=N_part)
vel_dm = random.random_sample(size=(N_part, 3))
return mass_dm, pos_dm, vel_dm
return make | 47,224 |
def TensorRTCompileSpec(compile_spec: Dict[str, Any]) -> torch.classes.tensorrt.CompileSpec:
"""
Utility to create a formated spec dictionary for using the PyTorch TensorRT backend
Args:
compile_spec (dict): Compilation settings including operating precision, target device, etc.
One key... | 47,225 |
def get_sec (hdr,key='BIASSEC') :
"""
Returns the numpy range for a FITS section based on a FITS header entry using the standard format
{key} = '[{col1}:{col2},{row1}:row2}]'
where 1 <= col <= NAXIS1, 1 <= row <= NAXIS2.
"""
if key in hdr :
s = hdr.get(key) # WITHOUT CARD COMMENT
ny = hdr['NAXIS2']
sx = ... | 47,226 |
def _fetch_object_array(cursor, type_tree=None):
"""
_fetch_object_array() fetches arrays with a basetype that is not considered
scalar.
"""
arrayShape = cursor_get_array_dim(cursor)
# handle a rank-0 array by converting it to
# a 1-dimensional array of size 1.
if len(arrayShape) == 0:... | 47,227 |
def load_training_batch(batch_id, batch_size):
"""Load the Preprocessed Training data and return them in batches of <batch_size> or less"""
filename = 'data/cifar_pickle/' + 'batch_' + str(batch_id) + '.pkl'
features, labels = pickle.load(open(filename, mode='rb'))
return batch_features_labels(features,... | 47,228 |
def check_gzip(f):
"""Checks if a local gzipped file is ok
Runs gunzip -t on the file using subprocess. Returns True on returncode 0.
"""
status = subprocess.run(["gzip", "-t", f], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if status.returncode == 0:
return True
return False | 47,229 |
def reason_key_for_alert(alert):
"""Computes the reason key for an alert.
The reason key for an alert is used to group related alerts together. Alerts
for the same step name and reason are grouped together, and alerts for the
same step name and builder are grouped together.
"""
# FIXME: May need something ... | 47,230 |
def get_record(params,record_uid):
"""Return the referenced record cache"""
record_uid = record_uid.strip()
if not record_uid:
logging.warning('No record UID provided')
return
if not params.record_cache:
logging.warning('No record cache. Sync down first.')
return
... | 47,231 |
def test_bootcamp_run_serializer_with_page():
"""BootcampRunSerializer should serialize the bootcamp run with CMS page data if requested in the context"""
run = BootcampRunFactory.create()
serialized = BootcampRunSerializer(run, context={"include_page": True}).data
assert "page" in serialized
assert... | 47,232 |
def get_probabilities(path, seq_len, model, outfile, mode):
"""
Get network-assigned probabilities
Parameters:
filename (str): Input file to be loaded
seq_len (int): Length of input DNA sequence
Returns:
probas (ndarray): An array of probabilities for the test set
true ... | 47,233 |
def install_dependencies(python) -> str:
"""
Copy aiohttp and virtualenv install locations (and their transitive
dependencies in new virtualenv so that the update server can install
without access to full system site-packages or connection to the internet.
Full access to system site-packages causes ... | 47,234 |
def get_sql_management_client(_):
"""
Gets the SQL management client
"""
from azure.mgmt.sql import SqlManagementClient
from azure.cli.core.commands.client_factory import get_mgmt_service_client
return get_mgmt_service_client(SqlManagementClient) | 47,235 |
def string_to_gast(node):
"""
handles primitive string base case
example: "hello"
exampleIn: Str(s='hello')
exampleOut: {'type': 'str', 'value': 'hello'}
"""
return {"type": "str", "value": node.s} | 47,236 |
def ed25519_generate_key_pair_from_secret(secret):
"""
Generate a new key pair.
Args:
secret (:class:`string`): A secret that serves as a seed
Returns:
A tuple of (private_key, public_key) encoded in base58.
"""
# if you want to do this correctly, use a key derivation function... | 47,237 |
def align_tiles_naive(request: AlignNaiveRequest,
tiles: List[TileModelDB]) -> List[AlignedTiledModel]:
"""
performs a naive aligning of the tiles simply based on the given rows and method.
does not perform any advanced stitching or pixel checking.
Does not use the row ... | 47,238 |
def estimate_operating_empty_mass(mtom, fuse_length, fuse_width, wing_area,
wing_span, TURBOPROP):
""" The function estimates the operating empty mass (OEM)
Source: Raymer, D.P. "Aircraft design: a conceptual approach"
AIAA educational Series, Fourth edition (2006)... | 47,239 |
def var_gaussian(r, level=5, modified=False):
"""
Returns the Parametric Gaussian VaR of a Series or DataFrame
"""
# compute the Z score assuming it was Gaussian
z = norm.ppf(level/100)
if modified:
# modify the Z score based on observed skewness and kurtosis
s = skewness(r)
... | 47,240 |
def grid_search_serial(data, greens, misfit, grid):
"""
Grid search over moment tensors. For each moment tensor in grid, generates
synthetics and evaluates data misfit
"""
results = np.zeros(grid.size)
count = 0
for mt in grid:
print grid.index
for key in data:
... | 47,241 |
def getSqTransMoment(system):
"""//Input SYSTEM is a string with both the molecular species AND the band "system"
// Electronic transition moment, Re, needed for "Line strength", S = |R_e|^2*q_v'v" or just |R_e|^2
// //Allen's Astrophysical quantities, 4.12.2 - 4.13.1
// // ROtational & vibrational constant... | 47,242 |
def volumes(assets,
start,
end,
frequency='daily',
symbol_reference_date=None,
start_offset=0,
use_amount=False):
"""
获取资产期间成交量(或成交额)
Parameters
----------
assets (int/str/Asset or iterable of same)
Identifiers ... | 47,243 |
def test_force_srs():
"""Test the force_srs() function"""
rdnew = osr.SpatialReference()
rdnew.SetFromUserInput( "EPSG:28992" )
latlon = osr.SpatialReference()
latlon.SetFromUserInput( "EPSG:4326" )
# using offset and srs (text)
pcA = pcl.PointCloud( [[1,2,3]] )
force_srs( pcA, offse... | 47,244 |
def fetch(path, url=None):
"""Fetches a file from either url or accession id in filename,
updates file if local version is older.
Checks a given path for file and downloads if a url is given or
file name is an accession id. Also downloads the file if the remote
location has a more recent version. C... | 47,245 |
def qipy_action(cd_to_tmpdir):
""" QiPy Action """
return QiPyAction() | 47,246 |
def recordProxyAccessInfo(directory, record):
"""
Group membership info for a record.
"""
# FIXME: This proxy finding logic should be in DirectoryRecord.
def meAndMyGroups(record=record, groups=set((record,))):
for group in record.groups():
groups.add(group)
meAndMyG... | 47,247 |
def vectorized_range(start, end):
""" Return an array of NxD, iterating from the start to the end"""
N = int(np.max(end - start)) + 1
idxes = np.floor(np.arange(N) * (end - start)[:, None] / N + start[:, None]).astype('int')
return idxes | 47,248 |
def stratified(W, M):
"""Stratified resampling.
"""
su = (random.rand(M) + np.arange(M)) / M
return inverse_cdf(su, W) | 47,249 |
def is_configured():
"""Return if Azure account is configured."""
return False | 47,250 |
def box_strings(*strings: str, width: int = 80) -> str:
"""Centre-align and visually box some strings.
Args:
*strings (str): Strings to box. Each string will be printed on its own
line. You need to ensure the strings are short enough to fit in the
box (width-6) or the results wi... | 47,251 |
def handle_gist_info(gapi, args, *vargs):
"""Handle 'gist info' command
Arguments:
gapi: a GistAPI object
args: parsed command line arguments
"""
logger.debug(u"action: info")
logger.debug(u"action: - {}".format(args.id))
info = gapi.info(args.id)
print(json.dumps(info, ind... | 47,252 |
def exceptions(e):
"""This exceptions handler manages Flask/Werkzeug exceptions.
For Renku exception handlers check ``service/decorators.py``
"""
# NOTE: Capture werkzeug exceptions and propagate them to sentry.
capture_exception(e)
# NOTE: Capture traceback for dumping it to the log.
tb ... | 47,253 |
def top_k_top_p_filtering(logits, top_k, top_p, filter_value=-float("Inf")):
"""
top_k或top_p解码策略,仅保留top_k个或累积概率到达top_p的标记,其他标记设为filter_value,后续在选取标记的过程中会取不到值设为无穷小。
Args:
logits: 预测结果,即预测成为词典中每个词的分数
top_k: 只保留概率最高的top_k个标记
top_p: 只保留概率累积达到top_p的标记
filter_value: 过滤标记值
Retu... | 47,254 |
def install_rules(client: PolicyDBStub, args):
"""
Installs the specified static rules for the session.
Also associates the static rules to the subscriber.
"""
message = EnableStaticRuleRequest(
imsi=args.imsi,
rule_ids=args.rules,
base_names=args.basenames,
)
try:
... | 47,255 |
def get_alb(alb_name, aws_auth_cred):
"""
Find and return loadbalancers of mentioned name
Args:
alb_name (str): Load balancer name
aws_auth (dict): Dict containing AWS credentials
Returns:
alb (dict): Loadbalancer details
"""
client = get_elbv2_client(aws_auth_cred)
... | 47,256 |
def align_left_position(anchor, size, alignment, margin):
"""Find the position of a rectangle to the left of a given anchor.
:param anchor: A :py:class:`~skald.geometry.Rectangle` to anchor the
rectangle to.
:param size: The :py:class:`~skald.geometry.Size` of the rectangle.
:param alignment: T... | 47,257 |
def test_ping_slack():
"""test_ping_slack"""
actual = subprocess.run(
["cicada", "ping_slack"], check=False, stderr=subprocess.PIPE
).stderr.decode("utf-8")
expected = """usage: ping_slack [-h] --text TEXT
ping_slack: error: the following arguments are required: --text
"""
assert actual == ... | 47,258 |
def quickdraw_to_linestring(qd_image):
"""Returns a Shapely MultiLineString for the provided quickdraw image.
This MultiLineString can be passed to vsketch
"""
linestrings = []
for i in range(0, len(qd_image["image"])):
line = zip(qd_image["image"][i][0], qd_image["image"][i][1])
lin... | 47,259 |
def visualize_tile_labels_with_datastore(app_config: str, datastore_id: str, method_data: dict):
"""Visualize tile scores from inference.
Args:
app_config (string): path to application configuration file.
datastore_id (string): datastore name. usually a slide id.
method_data (dict): met... | 47,260 |
def get_device_details():
"""TODO(jordanhuus): add description
"""
ptpTransport = PtpUsbTransport(
PtpUsbTransport.findptps(PtpUsbTransport.USB_CLASS_PTP))
bulk_in, bulk_out, interrupt_in = \
PtpUsbTransport.retrieve_device_endpoints(
PtpUsbTransport.findptps(PtpUsbTransport.... | 47,261 |
def remove_color(colors, name):
"""
Remove color of the disconnected user
"""
del colors[name] | 47,262 |
def build(image_resizer_config):
"""Builds callable for image resizing operations.
Args:
image_resizer_config: image_resizer.proto object containing parameters for
an image resizing operation.
Returns:
image_resizer_fn: Callable for image resizing. This callable always takes
a rank-3 image ... | 47,263 |
def plotly_protein_structure_graph(
G: nx.Graph,
plot_title: Optional[str] = None,
figsize: Tuple[int, int] = (620, 650),
node_alpha: float = 0.7,
node_size_min: float = 20.0,
node_size_multiplier: float = 20.0,
label_node_ids: bool = True,
node_colour_map=plt.cm.plasma,
edge_color_m... | 47,264 |
def get_configuration_route(model_name: str) -> str:
"""Gets the prediction configuration file of a model.
Args:
model_name (str): Name of the model
Raises:
ModelToLoadNotFoundError: The model to load could not be found or
opened.
Returns:
str: Evaluation file
... | 47,265 |
def execute_bash(command):
"""Executes bash command, prints output and throws an exception on failure."""
#print(subprocess.check_output(command.split(' '), shell=True))
process = subprocess.Popen(command,
shell=True,
stdout=subprocess.PIPE,
... | 47,266 |
def create_folder(path, *folders):
""" Creates folder in given path
"""
newpath = path + ''.join(map(str, [r'\\' + f for f in folders]))
if not os.path.exists(newpath):
os.makedirs(newpath) | 47,267 |
def mag_scale_rel_to_hazardlib(mag_scale_rel, use_default=False):
"""
Returns the magnitude scaling relation in a format readable by
openquake.hazardlib
"""
if isinstance(mag_scale_rel, BaseMSR):
return mag_scale_rel
elif isinstance(mag_scale_rel, str):
if not mag_scale_rel in SC... | 47,268 |
def write_config(conf):
"""
write_config(conf) function dumps app configuration to TOML file $NOTESDIR/config
:param conf: Dictionary containing configuration
(see_default_config as a sample structure)
:return bool: returns True on successful write of configfile
... | 47,269 |
def __get_words(text, by_spaces):
"""
Helper function which splits the given text string into words. If by_spaces is false, then text like
'01-02-2014' will be split into 3 separate words. For backwards compatibility, this is the default for all
expression functions.
:param text: the text to split
... | 47,270 |
def gera_paragrafo(data: pd.DataFrame) -> pd.DataFrame:
"""docstring for gera_paragrafo"""
data[["div_sup", "par"]] = data.location.str.split(".", n=1, expand=True)
data.dropna(inplace=True)
j: Any = data.groupby(["author", "text", "file", "div_sup", "par", "genero"]).agg(
{"lemma": lambda x:... | 47,271 |
def set_creds_data(credentials):
"""Set credentials, either as a dictionary or a JSON-encoded string.
"""
global _credentials_file, _credentials_data
_credentials_data = credentials
if _credentials_data:
_credentials_file = None
if isinstance(_credentials_data, str):
_cre... | 47,272 |
def _parse_boolean(xml_boolean):
"""Converts strings "true" and "false" from XML files to Python bool"""
if xml_boolean is not None:
assert xml_boolean in ["true", "false"], \
"The boolean string must be \"true\" or \"false\""
return {"true": True, "false": False}[xml_boolean] | 47,273 |
def to_heterogeneous(G, ntypes, etypes, ntype_field=NTYPE,
etype_field=ETYPE, metagraph=None):
"""Convert a homogeneous graph to a heterogeneous graph and return.
The input graph should have only one type of nodes and edges. Each node and edge
stores an integer feature as its type ID
... | 47,274 |
def delete_archived_data(schema_name, provider_type, provider_uuid):
"""
Delete archived data from our S3 bucket for a given provider.
This function chiefly follows the deletion of a provider.
This task is defined to attempt up to 10 retries using exponential backoff
starting with a 10-second dela... | 47,275 |
def start():
"""Start a development server."""
run(f"{docker_exe()} compose up") | 47,276 |
def Solution(image):
"""
input: same size (256*256) rgb image
output: the label of the image
"l" -> left
"m" -> middle
"r" -> right
"o" -> other(NO target)
if no target detected, return "o", which is the initial value
"""
#initial two point for locatate the ... | 47,277 |
def index_to_tag(v, index_tag):
"""
:param v: vector
:param index_tag:
:return:
"""
idx = np.nonzero(v)
tags = [index_tag[i] for i in idx[0]]
return ' '.join(tags) | 47,278 |
def train(train_loader, model, criterion, optimizer, epoch, opt):
"""one epoch training"""
model.train()
losses = AverageMeter()
end = time.time()
for idx, (train_x, labels) in enumerate(train_loader):
train_x = train_x.cuda()
labels = labels.cuda()
bsz = labels.sha... | 47,279 |
def first_phrase_span(utterance, phrases):
"""Returns the span (start, end+1) of the first phrase from the given list
that is found in the utterance. Returns (-1, -1) if no phrase is found.
:param utterance: The utterance to search in
:param phrases: a list of phrases to be tried (in the given order)
... | 47,280 |
def parse_date(value):
"""Parse a string and return a datetime.date.
Raise ValueError if the input is well formatted but not a valid date.
Return None if the input isn't well formatted.
"""
match = date_re.match(value)
if match:
kw = {k: int(v) for k, v in list(match.groupdict().items()... | 47,281 |
def construct_Dfunc(delays, plot=False):
"""Return interpolation functions fD(t) and fdD(t).
fD(t) is the delay between infection and reporting at reporting time t.
fdD(t) is its derivative.
Parameter:
- delays: tuples (time_report, delay_days)
- plot: whether to generate a plot.
Return:... | 47,282 |
def deimmunization_rate_80():
"""
Real Name: b'deimmunization rate 80'
Original Eqn: b'Recovered 80/immunity time 80'
Units: b'person/Day'
Limits: (None, None)
Type: component
b''
"""
return recovered_80() / immunity_time_80() | 47,283 |
def decrypt_fileobj(key, in_fileobj, out_fileobj, chunksize):
""" Decrypts a file object using AES (CBC mode) with the given key, and writes
the contents to the given output file object.
:param key: The encryption key - a string that must be
either 16, 24 or 32 bytes long. Longer keys
are m... | 47,284 |
def connect_to_lightsail():
"""
Uses Paramiko to create a connection to Brendan's instance. Relies on authetication information from a JSON file.
:return SFTP_Client:
"""
return open_sftp_from_json(JSON_PRIVATE_DIR / 'lightsail_server_info.json') | 47,285 |
def coleman_operator(c, cp):
"""
The approximate Coleman operator.
Iteration with this operator corresponds to time iteration on the Euler
equation. Computes and returns the updated consumption policy
c. The array c is replaced with a function cf that implements
univariate linear interpolatio... | 47,286 |
def generate_scanset_metadata( image_set_dictionary, html_base_path, session_id ):
"""This is passed a set of NII images, their PNG equilvalents, and an html base path, and then it generates the metadata needed """
cur_subj_info = {}
"""need to think through the data structure a bit more.... but can always adju... | 47,287 |
def read_error_codes(src_root='src/mongo'):
"""Define callback, call parse_source_files() with callback, save matches to global codes list."""
seen = {}
errors = []
dups = defaultdict(list)
skips = []
malformed = [] # type: ignore
# define validation callbacks
def check_dups(assert_loc... | 47,288 |
def filter_check_vlan_number(value):
"""
Function to check for a good VLAN number in a template
:param value:
:return:
"""
error = f'{value} !!!! possible error the VLAN# should be between 1 and 4096!!!!'
if not value: # pylint: disable=no-else-return
J2_FILTER_LOGGER.info('filter_c... | 47,289 |
def _sanitize(element) -> Gst.Element:
"""
Passthrough function which sure element is not `None`
Returns `Gst.Element` or raises Error
"""
if element is None:
raise Exception("Element is none!")
else:
return element | 47,290 |
def test_tables_extension_201():
"""
Test case 201: (part 1) The table is broken at the first empty line, or beginning of another block-level structure:
"""
# Arrange
source_markdown = """| abc | def |
| --- | --- |
| bar | baz |
> bar"""
expected_tokens = [
"[para(1,1):\n\n]",
... | 47,291 |
def run():
"""
Execution pipeline for each mode
"""
classifier = args.classifier
#used for training the model on train and dev, executes only once, simpliest version
if args.mode =='train_test':
init_data(dev = False)
model = create_model(dev = False, preload = False)
tr... | 47,292 |
def clean(session):
"""Remove all .venv's, build files and caches in the directory."""
rmtree("build", ignore_errors=True)
rmtree("dist", ignore_errors=True)
rmtree("node_modules", ignore_errors=True)
rmtree("pip-wheel-metadata", ignore_errors=True)
rmtree("src/" + PROJECT_NAME + ".egg-info", ig... | 47,293 |
def mean(dt_list):
"""
.. py:function:: mean(dt_list)
Returns the mean datetime from an Iterable collection of datetime objects.
Collection can be all naive datetime objects or all datatime objects with tz
(if non-naive datetimes are provided, result will be cast to UTC).
However, collection ca... | 47,294 |
def test_set_agencies_mixed():
""" Test that we can properly derive agency info from the metadata and add
it to the XML if we have a parent-child relationship and an unrelated
agency. """
agencies_info = [
{
'name': 'Treasury Department',
'parent_id': None,
'... | 47,295 |
def comment_after_flag_callback(signal, **kwargs):
"""
Method receives signal after a flag has been posted.
This method has to be loaded before hand for not missing any signals.
So, its imported into __init__
Description:
Email all 'CommentModerators' group after a user flagged comment
... | 47,296 |
def win_get_nonblocking(name: str, src_weights: Optional[Dict[int, float]] = None,
require_mutex: bool = False) -> int:
""" Passively get the tensor(s) from neighbors' shared window memory into
local shared memory, which cannot be accessed in python directly.
The win_update function ... | 47,297 |
def parse(file, beautifulsoup=None, makeelement=None, **bsargs):
"""Parse a file into an ElemenTree using the BeautifulSoup parser.
You can pass a different BeautifulSoup parser through the
`beautifulsoup` keyword, and a diffent Element factory function
through the `makeelement` keyword. By default, t... | 47,298 |
def get_L_dashdash_b1_d(L_dashdash_b1_d_t):
"""
Args:
L_dashdash_b1_d_t: 1時間当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/h)
Returns:
1日当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/d)
"""
return np.sum(L_dashdash_b1_d_t.reshape((365, 24)), axis=1) | 47,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.