content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _resize_row(array, new_len):
"""Alter the size of a list to match a specified length
If the list is too long, trim it. If it is too short, pad it with Nones
Args:
array (list): The data set to pad or trim
new_len int): The desired length for the data set
Returns:
list: A c... | 810be7f94234e428135598dc32eca99dd0d3fcca | 48,738 |
def pdact(a: float) -> float:
"""Partial derivative of activation function."""
return a * (1 - a) | 98007d118b050911a16776cf604fcbbe9898bc15 | 48,740 |
def deep_encode(e, encoding='ascii'):
"""
Encodes all strings using encoding, default ascii.
"""
if isinstance(e, dict):
return dict((i, deep_encode(j, encoding)) for (i, j) in e.items())
elif isinstance(e, list):
return [deep_encode(i, encoding) for i in e]
elif isinstance(e, str):
e = e.encode... | 6541695e741cb2f47d7d2fe87a45f1d8d8ca67fe | 48,742 |
def simplify_arg_role_name(role_name: str):
"""Converts the name of the argument role to the simple form (e.g. "Time-Within" to "Time").
"""
cols = role_name.split("-")
if len(cols) > 1 and cols[0] != "Time":
print(cols)
return cols[0] | b9cba2234da2656055945da7c39896b1d4d29416 | 48,749 |
def find_nth_loc(string=None, search_query=None, n=0):
"""
Searches the string via the search_query and
returns the nth index in which the query occurs.
If there are less than 'n' the last loc is returned
:param string: Input string, to be searched
:type string: str
:param search_query:... | 1293bda0ee8a681e8b8647e10fcbadda2a788df5 | 48,755 |
from typing import Sequence
def count_number_of_depth_increases(depths: Sequence[int], window_size: int = 1) -> int:
"""Counts the number of times depth increases in a sequence of sonar measurements."""
depth_changes = (
sum(depths[i : i + window_size]) - sum(depths[i - 1 : i - 1 + window_size])
... | 8435c3ea61c204ee3db9565f929e0b510420e127 | 48,756 |
def validate_tag(tag):
""" Chceks if tag is valid. Tag should not be empty and should start with '#' character """
tag = tag.strip().lower()
return len(tag) > 1 and tag.startswith("#") | 16e112376368567dee7d03faed8f37f14931328b | 48,760 |
def expose_header(header, response):
"""
Add a header name to Access-Control-Expose-Headers to allow client code to access that header's value
"""
exposedHeaders = response.get('Access-Control-Expose-Headers', '')
exposedHeaders += f', {header}' if exposedHeaders else header
response['Access-Con... | 049383730da4fbc5a6286ed072655c28ea647c1e | 48,768 |
def unique(lst):
"""
Returns a copy of 'lst' with only unique entries.
The list is stable (the first occurance is kept).
"""
found = set()
lst2 = []
for i in lst:
if i not in found:
lst2.append(i)
found.add(i)
return lst2 | 6e50803439b65a3fa71814956e947103ca2b634d | 48,769 |
import math
def pickLabelFormat(increment):
"""Pick an appropriate label format for the given increment.
Examples:
>>> print pickLabelFormat(1)
%.0f
>>> print pickLabelFormat(20)
%.0f
>>> print pickLabelFormat(.2)
%.1f
>>> print pickLabelFormat(.01)
%.2f
"""
i_log... | a91372f7b1b770531b23147a6704a20bf8a5e689 | 48,770 |
def ensure_valid_model_type(specified_type, model_type_list):
"""
Checks to make sure that `specified_type` is in `model_type_list` and
raises a helpful error if this is not the case.
Parameters
----------
specified_type : str.
Denotes the user-specified model type that is to be checked... | 6708e44d7ea381c89ea31343cb8f435f40fc279f | 48,772 |
import heapq
def top10(m):
"""Return the top 10 keys from a dict ordered by their values."""
return heapq.nlargest(10, m.keys(), key=m.get) | 3e5e5eddf6c11a4a46fcb0e3e9bc342cfa219826 | 48,773 |
from typing import Union
def find_error_character(chunk: str) -> Union[str, None]:
"""Find the first illegal character for a given chunk."""
stack = []
bracket_mapping = {")": "(", "]": "[", "}": "{", ">": "<"}
open_brackets = ["(", "[", "{", "<"]
for char in chunk:
if char in open_br... | fd5aa5360f68b2e61f7d658caedbf1ec67b9de99 | 48,774 |
import platform
def generate_user_agent(package_name: str, package_version: str) -> str:
"""Generate a user-agent string in the form <package info> <python info> <os info>.
Parameters
----------
package_name : str
Name of the package to include in the user-agent string.
package_version : ... | adb7d164de435c606a01abc35c963b0f8d5505e8 | 48,776 |
def summary(txt):
"""
Returns the first line of a string.
"""
lines = txt.split('\n')
return lines[0] | eb86e9a5225f2b99b500b79927ef3af1ccc7fabb | 48,778 |
def dict_no_none(*args, **kwargs) -> dict:
"""
Helper to build a dict containing given key-value pairs where the value is not None.
"""
return {
k: v
for k, v in dict(*args, **kwargs).items()
if v is not None
} | de0dbf04f0cea588f190f9ae52cf2696e0c5c6ea | 48,779 |
from typing import Any
def shortname(obj: Any) -> str:
"""Get object name (non-qualified)."""
if not hasattr(obj, '__name__') and hasattr(obj, '__class__'):
obj = obj.__class__
return '.'.join((obj.__module__, obj.__name__)) | 78a3d85ad11e8262d515fb2bead6c9d9fdbf085b | 48,780 |
def unique(sequence):
"""
Returns a unique list preserve the order of original list
"""
seen = set()
return [x for x in sequence if not (x in seen or seen.add(x))] | 433bc766e21f1e0a6e983383054f51ba84cd5636 | 48,783 |
def flatten(items):
"""Removes one level of nesting from items
Parameters
----------
items : iterable
list of items to flatten one level
Returns
-------
flattened_items : list
list of flattened items, items can be any sequence, but flatten always
returns a list.
... | 5c280d08911e4fdbd32de3e20e75410e871b1d57 | 48,784 |
def get_help_text(instance, field_name):
"""
Returns help_text for a field.
inspired by https://stackoverflow.com/questions/14496978/fields-verbose-name-in-templates
call in template like e.g. get_help_text <classname> "<fieldname>"
"""
try:
label = instance._meta.get_field(field_name).... | b2432ee430744c28630efe27489c68607ca0a495 | 48,785 |
def _format_collider_string(colliders):
""" Write the string for the bath gas collider and their efficiencies
for the Lindemann and Troe functional expressions:
:param colliders: the {collider: efficiency} dct
:type colliders: dct {str: float}
:return: collider_str: Chemkin string w... | 4e4aa8ae46dfcf05f00222b4cf5c95384977d651 | 48,788 |
def is_users_personal_account(context, account):
"""
Return `true` if the current path is for the user's personal account.
Used to determine which items to show in the settings submenu.
"""
request = context["request"]
return account.is_personal and (
request.path.startswith("/me/")
... | 9a5938761fb3a8c5876152bb326f008b8e607f95 | 48,793 |
def layer_size(X, Y):
"""
Get number of input and output size, and set hidden layer size
:param X: input dataset's shape(m, 784)
:param Y: input labels's shape(m,1)
:return:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size of the output layer
"""... | 81add6bf528cfe872e62f622161bb25fb7dcb1d3 | 48,800 |
from typing import Set
def done(job: str, completed: Set[str]) -> str:
"""Convert set membership into `Yes` for `No`.
:param job: The job to check if it was acted on
:param completed: The jobs acted on,
:returns: Yes or No
"""
return 'Yes' if job in completed else 'No' | 6d056f2471dafb3cab274ffb916e073c2fb62cf6 | 48,801 |
from typing import get_origin
from typing import get_args
def has_origin(typ, origin, num_args=None):
"""
Determines if a concrete class (a generic class with arguments) matches an origin
and has a specified number of arguments.
This does a direct match rather than a subclass check.
The typing c... | 9ba281ac18f1e152d9456103a61070e8e6c70e09 | 48,804 |
def extend(cls, static=False):
"""Extends the cls class.
Parameters
----------
cls : class
Class to extend.
static : boolean, default = False
Wheter extend as a static method.
Returns
-------
decorator
Decorator for extending classes.
"""
if static:
... | ab3456d11b2ce7edde1a468e743fc77bcc1e3f58 | 48,807 |
def create_collector(collector_class, result_dir, test_name):
"""Return a new Collector of the given class
:param collector_class: The collector class to be used.
:param result_dir: Directory with test results
:param test_name: Test to be run
:return: A new CollectorController.
"""
return c... | 5780297706e8ee00b3e7cc7cfd5da7997fd5dd66 | 48,808 |
from typing import Dict
def multimodel_num_layers() -> Dict[str, int]:
"""Number of layers in each of sub-models in `multimodel` fixture."""
return {
'encoder': 2,
'forecaster': 6,
'combined': 10,
} | 115e274decf2e18f5fae31d07fca46183853f513 | 48,810 |
def sublist(list1: list, list2: list) -> bool:
"""
Check if all the element of list1 are inside list2, preserving
the order and subsequence of the elements
:param list1: list1 of element to find
:param list2: list2 target list
:return: a boolean which represent True if the statement is
respe... | 6981a35efe0bb18b9d2ca2593a9f38ea049acb28 | 48,811 |
from typing import Dict
from typing import List
def get_available_languages(localisation: Dict) -> List[str]:
"""Get list of languages that are available for outputting human readable
procedure descriptions.
Args:
Dict: Localisation collection, e.g. ``PlatformClass().localisation``
Returns:
... | 25506eb7a7819f89b54df05e67e65c44f58285bb | 48,815 |
def sql_number_list(target):
"""
Returns a list of numbers suitable for placement after the SQL IN operator in
a query statement, as in "(1, 2, 3)".
"""
if not target:
raise ValueError
elif not isinstance(target, list):
target = [target]
return "(%s)" % (", ".join(["%d" % (i... | 386a8d10ed9fb7f625080eb3636f9d3909cacc6a | 48,816 |
import torch
def fold(input: torch.Tensor,
window_size: int,
height: int,
width: int) -> torch.Tensor:
"""
Fold a tensor of windows again to a 4D feature map
:param input: (torch.Tensor) Input tensor of windows [batch size * windows, channels, window size, window size]
:para... | 92a68279b357f8b977d4b144fd249540de833fb5 | 48,817 |
from typing import Optional
from pathlib import Path
def to_uri(
path: str, local_basedir: Optional[Path] = None, relative_prefix: str = ""
) -> str:
"""
Given a path or URI, normalize it to an absolute path.
If the path is relative and without protocol, it is prefixed with `relative_prefix`
befo... | 6ebe76a1574fe844d808ac4889afe163d9d3131a | 48,818 |
import torch
import math
def sym_diag(mat):
"""Diagonal of a symmetric matrix
Parameters
----------
mat : (..., M * (M+1) // 2) tensor
A symmetric matrix that is stored in a sparse way.
Its elements along the last (flat) dimension are the
diagonal elements followed by the flat... | 23c29d1c6429089e88720e9ba7d3d6f8968f9ca0 | 48,831 |
def intersect(seq1, seq2):
"""Returns a list of elements in both seq1 and seq2."""
ret = []
for elem in seq1:
if elem in seq2:
ret.append(elem)
return ret | b7cb43616e8000427005c350b2b07a59768f2995 | 48,833 |
def code(value: int) -> str:
"""Constructs an ANSI code with the provided `value`."""
return f'\033[{value}m' | 48b499b5055d616bc7f51043e96429be123b5dd2 | 48,834 |
def unwrap_filter(response, category):
"""
Strips one layer of aggregations (named by <category>) from
a ElasticSearch query response, leaving it still in proper ES
response format.
:param response: An Elasticsearch aggregation response dictionary.
:param category: Name of the topmost aggregati... | 82d6533edf8091e5a6b353f903f652bcb700dcde | 48,836 |
def get_longest_consecutive_chars(string):
"""
Given a string, return the longest consecutive character sequence.
"""
longest_consecutive_chars = ''
current_consecutive_chars = ''
for char in string:
if char not in current_consecutive_chars:
current_consecutive_chars += char... | 4607a1adada254c36e46a28c036cb852992544a5 | 48,837 |
import math
def root_mean_squared_error(LeadDay,df,model,observed):
"""
Args:
LeadDay: specifically applies to forecast models with lead times
if no lead day is available input None
LeadDay is desired Lead day (int)
df: data frame where Observed and Model data is found
... | 0bd5b5627fa2dda1ef444bd12c69f670daa18e44 | 48,838 |
def module_file(module):
"""Return the correct original file name of a module."""
name = module.__file__
return name[:-1] if name.endswith('.pyc') else name | 4fbda2b1c839690f880a6f6c1bcba2ca4168a701 | 48,857 |
def clamp(value, smallest, largest):
"""Return `value` if in bounds else returns the exceeded bound"""
return max(smallest, min(value, largest)) | 8ce129fd2bccacf7b45d9b4924f69a54bbb15e3b | 48,859 |
def oid_outside_tree(oid1, oid2):
"""
Return True if oid2 outside of oid1 tree
Used by SNMPSession.walk
"""
try:
if oid2.startswith(oid1):
return False
return True
except:
return True | a1957c9d6b04dcd97db321f8d8779c349d14e265 | 48,867 |
def calculate_iou(bb1, bb2):
"""
Calculates the Intersection Over Union (IOU) score of the two bounding-boxes
(the overlap between two bounding boxes).
each bounding-box coordinates are in the form of: (x_min, y_min, x_max, y_max).
"""
bb1_x_min, bb1_y_min, bb1_x_max, bb1_y_max = bb1
bb2_x_m... | 5a0379085bbe428e812b2b0a39b39046cc0adefc | 48,868 |
def string_to_seq(seq_str):
"""Return a codepoint sequence (tuple) given its string representation."""
return tuple([int(s, 16) for s in seq_str.split("_")]) | 1021578ecb694ec9fc974f0b590ef0fc7c71f20a | 48,872 |
import torch
def create_pytorch_model(
number_of_features, number_of_categories_by_label, label_to_test, **kwargs
):
"""
Create a toy PyTorch model that has the right shape for inputs and outputs
"""
class TorchToy(torch.nn.modules.module.Module):
def __init__(self, number_of_features, nu... | d27a82bd581accb4fccba3c09f88f26b00127eab | 48,873 |
from typing import Counter
import collections
def numericalize_tok(tokens, max_vocab=50000, min_freq=0, unk_tok="_unk_", pad_tok="_pad_", bos_tok="_bos_", eos_tok="_eos_"):
"""Takes in text tokens and returns int2tok and tok2int converters
Arguments:
tokens(list): List of tokens. Can be a list of... | 48fafe61938203bde66edcab90ded616ed23aa82 | 48,874 |
import multiprocessing
def get_n_jobs(n_jobs):
"""get_n_jobs.
Determine the number of jobs which are going to run in parallel.
This is the same function used by joblib in the PoolManager backend.
"""
if n_jobs == 0:
raise ValueError('n_jobs == 0 in Parallel has no meaning')
elif n_job... | 53fe32e94c771095bdab2601abba1761548f2d4c | 48,875 |
def extract_position_relations(qdmr_step):
"""Extract a relation regarding entity positions
in a QDMR step. Relevant for VQA data
Parameters
----------
qdmr_step : str
string of the QDMR step containg relative position knowledge.
Either a FILTER of BOOLEAN step.
Returns
-------
str
strin... | ca3ca61ac66419c0fb48ad784a6397a67ba3d653 | 48,881 |
def get_module_properties(properties):
"""
Get dict of properties for output module.
Args:
properties (list): list of properties
Returns:
(dict): dict with prop, der and contrib
"""
module_props = dict(property=None, derivative=None, contributions=None)
for prop in propert... | 8f69335538b738a4a6523e6919b8e5080ab045af | 48,885 |
def to_int_float_or_string(s):
""" Convert string to int or float if possible
If s is an integer, return int(s)
>>> to_int_float_or_string("3")
3
>>> to_int_float_or_string("-7")
-7
If s is a float, return float(2)
>>> to_int_float_or_string("3.52")
3.52
>>> to_int_float_or_str... | 18fbc417edb85219f3fbd2ae8e5eb8aa4df61d87 | 48,889 |
def get_urs_pass_user(netrc_file):
"""
retrieve the urs password and username from a .netrc file
:param netrc_file: this is a path to a file that contains the urs username
and password in the .netrc format
:return: [tuple] (user_name, password)
"""
with open(netrc_file, 'r') as f:
te... | a72938a04c5d0b50608446d87bbbd819cd9c9607 | 48,890 |
def merge_left(b):
"""
Merge the board left
Args: b (list) two dimensional board to merge
Returns: list
"""
def merge(row, acc):
"""
Recursive helper for merge_left. If we're finished with the list,
nothing to do; return the accumulator. Otherwise, if we have
mor... | 96af9931dffee9193c565efbe89b463e93921151 | 48,892 |
import typing
def filesDiffer(a:typing.List[str], b:typing.List[str]) -> bool:
"""
Compares two files for meaningingful differences. Traffic Ops Headers are
stripped out of the file contents before comparison. Trailing whitespace
is ignored
:param a: The contents of the first file, as a list of its lines
:para... | 41f01627e0b51841a116f65c1cc3fc2fed14e91d | 48,895 |
def multiply_1(factor: int):
"""
Example where input argument has specified variable annotation.
This example is showing how to cast variable. And assert in order to check for any error at the early stage.
:param factor:
:return: results: int
"""
# This will print a data type of this variabl... | 5bbd5ec6c7636775855a9e3c63a1ee30d6eabb95 | 48,896 |
def get_util_shape(row):
"""Get utility term shape based on ROI.
Parameters
----------
row : pandas.core.series.Series
Row of func_df DataFrame.
Returns
-------
str
If 'chest' or 'rib in row['Roi'], then return 'linear'.
Otherwise, return 'linear_quadratic'.
""... | 4ebb50dd0991f3edda7f33ad17fb3a3dfaf39de3 | 48,897 |
from typing import Optional
from typing import Match
import re
def _replace_html_saving_export_path_by_doc_path(code: str) -> str:
"""
Replace html saving interace's export path argument value
in the code by document path.
Parameters
----------
code : str
Target Python code.
Retu... | 0bfcfdd234ae72c70feafb1efd9799387b75c8f1 | 48,900 |
from typing import List
def body_25_to_coco_18(keypoints: List[float]) -> List[float]:
"""
noqa
BODY_25 to COCO_18 key mapping based on the following:
https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/doc/output.md
The only difference is that COCO_18 doesn't have the MidHip (#... | 6945a1057e94fbe306810e6b1aa3f7a5dd1ad6df | 48,901 |
def factory_register(SuperClass, ClassName):
"""Register an concrete class to a factory Class."""
def decorator(Class):
# return Class
if not hasattr(SuperClass, "_factory"):
setattr(SuperClass, "_factory", {})
SuperClass._factory[ClassName] = Class
setattr(Class, "_f... | 891fd2419fbb545507f3fe79ad1ad27e28cdf2d0 | 48,903 |
def _type_error(actual, expected):
"""Returns a ValueError that the actual type is not the expected type."""
msg = 'invalid type: %s is not in %s' % (actual.__name__,
[t.__name__ for t in expected])
return ValueError(msg) | fc9b09c6bd684a1132ca7c0a792aca9da37be2e9 | 48,906 |
def extract_callback_args(args, kwargs, name, type_):
"""Extract arguments for callback from a name and type"""
parameters = kwargs.get(name, [])
if parameters:
if not isinstance(parameters, (list, tuple)):
# accept a single item, not wrapped in a list, for any of the
# categ... | 9ed14a40dee7799d49f0001818c20e9e2935c69b | 48,908 |
def truncate_line(line: str, length: int = 80) -> str:
"""Truncates a line to a given length, replacing the remainder with ..."""
return (line if len(line) <= length else line[: length - 3] + "...").replace("\n", "") | 1bc7e34b85afc59ff5afcfa9a57b575aa3d032fe | 48,909 |
def track_point(start, direction, z):
"""
This function returns the segment coordinates for a point along the `z` coordinate
Args:
start (tuple): start coordinates
direction (tuple): direction coordinates
z (float): `z` coordinate corresponding to the `x`, `y` coordinates
Retur... | 72313aa592d8014641d8533acbe40661142df1c0 | 48,912 |
def mod(n, size):
"""Returns the position of a cell based on modulo arithmetic"""
size -= 1
if n < 0:
return size
elif n > size:
return 0
return n | d035bb05f5553671ac35abfcfdc1d9914482721d | 48,913 |
import json
def _load_query(query_file: str) -> str:
"""
Load the advanced query from a json file.
:param query_file: path to the json file.
:return: advanced query in json string format (single line).
"""
with open(query_file, 'r', encoding='utf-8') as file_pointer:
query = json.load... | eebc23785499010b780c1a671ef12fad12fe3c37 | 48,918 |
def create_scatter_legend(axi, color_labels, class_names, show=False,
**kwargs):
"""Generate a legend for a scatter plot with class labels.
Parameters
----------
axi : object like :class:`matplotlib.axes.Axes`
The axes we will add the legend for.
color_labels : dic... | 3e7551f5b9f3b7f74181aa75adfe092d5389ddbb | 48,919 |
def is_float(potential_float: str) -> bool:
"""
Check if potential_float is a valid float.
Returns
-------
is_float : bool
Examples
--------
>>> is_float('123')
True
>>> is_float('1234567890123456789')
True
>>> is_float('0')
True
>>> is_float('-123')
True
... | 19d907f3cba743f3b6a9867c7c29ad505f6a26e4 | 48,923 |
def styblinski_tang(ind):
"""Styblinski-Tang function defined as:
$$ f(x) = 1/2 \sum_{i=1}^{n} x_i^4 - 16 x_i^2 + 5 x_i $$
with a search domain of $-5 < x_i < 5, 1 \leq i \leq n$.
"""
return sum(((x ** 4.) - 16. * (x ** 2.) + 5. * x for x in ind)) / 2., | 9e060448b02558e33e7b6b2aa74ce1a2806f3c0b | 48,925 |
def clean_path(path):
""" remove index.html from end of a path, add / if not at beginning """
path = path.split("index.html")[0]
if not path.startswith("/"): path = "/" + path
if not path.endswith("/"): path += "/"
return path | 55360f0e0729b9cb0510308f5e5be32a404f1e70 | 48,930 |
import re
def _extract_subcats(pattern, categs):
"""Extract the category names matching `pattern`."""
return {cat for cat in categs if re.match(pattern, cat)} | 1092e247b2fdd3290759ceedb309691ef640058b | 48,934 |
def my_key(t):
""" Customize your sorting logic using this function. The parameter to
this function is a tuple. Comment/uncomment the return statements to test
different logics.
"""
# return t[1] # sort by artist names of the songs
return t[1], t[0] # sort by artist names, t... | ae416506de1820290d97d558ff899ba930d68705 | 48,937 |
def parse_query(query_to_parse):
"""
Converts a comma or space-separated string of query terms into a list to use
as filters. The use of positional arguments on the CLI provides lists (which
we join and resplit to avoid any formatting issues), while strings passed
from pssh.py just get split since ... | edd1cb6b42cd895a2eeb5f4f024dc1f2c92743af | 48,941 |
def str_has_one_word(search_str):
"""
Test if string which has a substring in quotes, that has wildcards.
>>> str_has_one_word(r"test* 12?")
False
>>> str_has_one_word(r"test**")
True
"""
if len(search_str.split()) == 1: # has more than 1 word
return True
else:
... | 203d6468d01b17216ffdc89dcf6e40d44b8a3b77 | 48,942 |
from typing import Union
def tab(text:Union[list, str], pad=" ") -> Union[list, str]:
"""Adds a tab before each line. str in, str out. List in, list out"""
if isinstance(text, str):
return "\n".join([pad + line for line in text.split("\n")])
else: return [pad + line for line in text] | bc6e20dfa9ed51b0e8058020feafe92cd1bdcbe8 | 48,946 |
def is_final_id(id_path, pda, acceptance):
"""Helper for final_id
---
If the id of id_path meets the acceptance criterion
that is passed in, then it is "final"; else not.
"""
(id, path) = id_path
(q, inp_str, stk_str) = id
if (acceptance == "ACCEPT_F"):
return (inp_str... | 8b93568a61f0470813a237f6cde17ff15f701f9d | 48,948 |
import re
def find_text(text):
"""
Find string inside double quotes
"""
matches = re.findall(r'\"(.+?)\"', text)
return matches[0] | 55238d27db4c3a8b682e4616b253d63db1af38fd | 48,949 |
def user_exist(username):
"""
判断用户是否存在
:param username: 用户名
:return: True or False 用户是否存在
"""
with open("db", "r", encoding="utf-8") as f:
for line in f:
result = line.strip().split("@")
# 判断是否是存在该用户
if username == result[0]:
return T... | 0040f75562103397f7d5ad9e0e4d3ba3e2d7b11b | 48,957 |
def iou(box1, box2):
""" Calculate intersection over union between two boxes
"""
x_min_1, y_min_1, width_1, height_1 = box1
x_min_2, y_min_2, width_2, height_2 = box2
assert width_1 * height_1 > 0
assert width_2 * height_2 > 0
x_max_1, y_max_1 = x_min_1 + width_1, y_min_1 + height_1
x_m... | 4de8ce8314c1833d56fcd81a254f65d2d8a02df9 | 48,959 |
import torch
def extract_tensors(from_this):
"""
Given a dict from_this, returns two dicts, one containing all of the key/value pairs corresponding to tensors in from_this, and the other
containing the remaining pairs.
"""
tensor_dict = {k:v for k, v in from_this.items() if type(v) is torch.Tensor... | d557ab786e6af935a1b6f093d2257e32dae2357c | 48,960 |
from datetime import datetime
def Date(year, month, day):
"""Construct an object holding a date value."""
return datetime(year, month, day) | 1994d9f8720bf19c9b7493ec2164bc9e74d1a72a | 48,961 |
import six
import re
def isidentifier(s):
"""
Check whether the given string can be used as a Python identifier.
"""
if six.PY2:
return re.match("[_A-Za-z][_a-zA-Z0-9]*$", s)
return s.isidentifier() | 7769d6b93cd2a49bbd104558c354c60d8d27530d | 48,962 |
def L_shaped_context(image, y, x):
"""This grabs the L-shaped context around a given pixel.
Out-of-bounds values are set to 0xFFFFFFFF."""
context = [0xFFFFFFFF] * 4
if x > 0:
context[3] = image[y][x - 1]
if y > 0:
context[2] = image[y - 1][x]
context[1] = image[y - 1][x - ... | 84a7a298b43ffddf697986f2f9af6402990b832c | 48,963 |
def wrap_fn(newname: str, doc: str):
"""
Decorator which renames a function.
Parameters
----------
newname: str
Name of the new function.
doc: str
Docstring of the new function.
"""
def decorator(f):
f.__name__ = newname
f.__doc__ = doc
return... | 248999597b06665d52246656cb8ee8f3322b4338 | 48,967 |
def hsl_to_hsv(h :float, s :float, l :float) -> tuple:
"""
HSL to HSV color conversion.
https://en.wikipedia.org/wiki/HSL_and_HSV#Interconversion
Args:
h: `float` in [0.0, 1.0] corresponding to hue.
s: `float` in [0.0, 1.0] corresponding to saturation.
l: `float` in [0.0, 1.0] co... | 77b7613f276cac51bf5f851e175fa42790084036 | 48,968 |
def rescale(value, in_min, in_max, out_min, out_max):
"""
Maps an input value in a given range (in_min, in_max)
to an output range (out_min, out_max) and returns it as float.
usage:
>>> rescale(20, 10, 30, 0, 100)
<<< 50.0
"""
in_range = in_max - in_min
out_range = out_max -... | 69444386da45b2747cea3b304bba0f2fcc4a8978 | 48,969 |
def get_bbox_from_gt(gt):
"""
Get bounding box from ground truth image
"""
return gt.convert('RGB').getbbox() | d7b7bcf9c5963393c04ae6f355981fdecae72088 | 48,973 |
def titlecase_keys(d):
"""
Takes a dict with keys of type str and returns a new dict with all keys titlecased.
"""
return {k.title(): v for k, v in d.items()} | 8c5d2cbdc8bc28e384798c3e5b0f096068926945 | 48,979 |
def printable_device(device):
"""Returns a printable form of a device record."""
if device is None:
return "<device NULL>"
output_list = []
assert device.StartSize + len(device.DeltaValue) - 1 == device.EndSize
for index in range(len(device.DeltaValue)):
output_list.append(
... | 2b3bdea992402188687e7270fca47bf612d76e13 | 48,983 |
def parse_date(date):
"""Parse date int string into to date int (no-op)."""
if date is None:
return 0
return int(date) | 46cba9bcc9a0ba90028579994df4e92b9165a1b8 | 48,984 |
import math
def giantstep_babyStep(m, c, n, phi, group) :
"""
With c = m^e % n
given m, c, n, 𝜙(𝑛), and the target group
This function will find out e % group in time O(√N).
Give :
@m : plaintxt data
@c : cipher data
@n : module
@phi : 𝜙(𝑛)
@grou... | 9afaeef7ad647d8c1cd3bfeac01711642282f7f7 | 48,985 |
async def root():
"""
Simple welcome message for GETs to the root, directing to the documentation.
"""
return {"message": "Welcome! Check out the interactive documentation at /docs"} | 08482501d5a5a45bdcf53b52be1929d431f9c9c7 | 48,989 |
def isRetrovirus(lineage):
"""
Determine whether a lineage corresponds to a retrovirus.
@param lineage: An iterable of C{LineageElement} instances.
@return: C{True} if the lineage corresponds to a retrovirus, C{False}
otherwise.
"""
for element in lineage:
if element.rank == 'fa... | e4f0aa37a673e9640ca6c6ed0c76d993d6eefb82 | 48,990 |
def compute_transitions(bands,in_list,fin_list):
"""
Compute the (positive) transition energies for the bands (on a single kpoint).
The `fast` index is associated to the bands in the fin_list list.
Args:
bands (list) : list with the energies
in_list (list) : indexes of the bands used as... | 09bc38199f7f36aa80cc7834e13f3e5f55546099 | 48,997 |
def contains(first, second):
"""Returns True if any item in `first` matches an item in `second`."""
return any(i in first for i in second) | 0157fd1c9ad3e48f9a6e9aef39e58240dbcb64e8 | 48,998 |
def _uprank(a):
"""Get `a` as a rank-two tensor, correctly handling the case where `a` is
rank one.
Args:
a (tensor): Tensor to get as a rank-two tensor.
Returns:
tensor: `a` as a rank-two vector.
"""
if a.ndim == 1:
return a[:, None]
else:
return a | f2aa483234d4dbe98989984eb28b3011ad7a4194 | 49,002 |
def unflat_len(obj):
"""Return number of non-list/tuple elements in obj."""
if not isinstance(obj, (list, tuple)):
return 1
else:
return sum([unflat_len(x) for x in obj]) | d11c1c05b3f80f166781006ad573176dbf4752db | 49,003 |
def _scale(dimen: str, scale: float = 1) -> int | str:
"""Get a scaled dimen.
Args:
dimen (str): dimension in px
scale (float): scale
Returns:
Optional[int, str]: scaled dimen (min=1)
"""
if scale == 1:
return dimen
return max(int(int(dimen) * scale), 1) | 450a969f658f5768b1e3988859c4f20ff6b2dfd3 | 49,005 |
from typing import List
def scale_prev(prev_vals: List[float], fraction: float) -> float:
"""
Apply a multiplier to the previous value.
"""
return prev_vals[-1] * fraction | 9685214aaece3a6935886cbf91472e877f7e3619 | 49,008 |
def convert (hour):
"""
converts Hours in to seconds (hours * 3600)
Args: hours(int)
return: (int value) number of seconds in hours
"""
seconds = 3600
result = hour * seconds
return result | 1c7d06da2582c0c580ed48ddc18f142727001fa8 | 49,011 |
def _r_count_num_m(n, factors_d, i):
"""Count of numbers coprime to d less than end; sum( gcd(m, d) == 1 for m in range(n, n+i) )
Uses inclusion exclusion on prime factorization of d
"""
if n == 0:
return 0
if i < 0:
return n
return _r_count_num_m(n, factors_d, i-1) - _r_coun... | 2d5eacf6d1df2d4277bd9abd760bc132a09452d8 | 49,013 |
def NormalizeLineEndings(s):
"""Convert string containing various line endings like \n, \r or \r\n,
to uniform \n."""
return '\n'.join(s.splitlines()) | 8dc5c3cf579427fe402ee84cc15b73ccc2bbe88d | 49,014 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.