content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def local_maximum_touching_neighbor_count_map(input : Image, destination : Image = None) -> Image:
"""Takes a label map, determines which labels touch and replaces every
label with the number of touching neighboring labels.
Parameters
----------
input : Image
destination : Image
Retur... | 5,301,400 |
def split_to_discretized_mix_logistic_params(inputs):
"""Splits input tensor into parameters of discretized mixture logistic.
Args:
inputs: A [batch, height, width, num_mixtures*10] tensor of floats
comprising one unconstrained mixture probability, three means
(one per channel), three standard devi... | 5,301,401 |
def get_clean_urls(raw_urls):
"""
Known problems so far:
https vs http
https://www.test.de vs https://test.de
https://www.test.de/something vs https://www.test.de/something#something
https://www.test.de/something.html vs https://www.test.de/something.html?something
"""
cleaned_urls = []
... | 5,301,402 |
def _pytest_has_xdist() -> bool:
"""
Check if the pytest-xdist plugin is installed, providing parallel tests
"""
# Check xdist exists without importing, otherwise pytests emits warnings
from importlib.util import find_spec
return find_spec("xdist") is not None | 5,301,403 |
def collaborative_baseline(data_train, testData, corrMatrix, K):
"""
Baseline method is used to compute the reconstructed matrix
Parameters
----------
data_train :
data present in train.csv file
testData :
data in test.csv file
corrMatrix :
... | 5,301,404 |
def unpack_contours(df_filename: str, threshold: float = 0.6) -> gpd.GeoDataFrame:
""" Convert multipolygon contour row above given threshold into multiple Polygon rows. """
df = gpd.read_file(df_filename)
if len(df) <= 2:
if len(df[df.amax > threshold]):
return gpd.GeoDataFrame(geometry... | 5,301,405 |
def makedist(dist_type, *pars, **kwards):
"""
Creates a distribution class from scipy continuous distributions
See https://docs.scipy.org/doc/scipy/reference/stats.html.
Parameters
----------
dist_type: String -> Type of the distribution (see the scipy documentation)
*pars and **kwards... | 5,301,406 |
def is_list_of_matching_dicts(list_of_dicts, expected_keys=None):
"""Comprueba que una lista esté compuesta únicamente por diccionarios,
que comparten exactamente las mismas claves.
Args:
list_of_dicts (list): Lista de diccionarios a comparar.
expected_keys (set): Conjunto de las claves que... | 5,301,407 |
def sort(left_lane_sa,right_lane_sa):
""" Sorts lane values for left and right lanes
@left_lane_sa: Left Lane values after split and Append method
@right_lane_sa: Right Lane values after split and Append method
"""
#print(len(right_lane_sa));
if (len(left_lane_sa) != 0):
left_lane_sa =... | 5,301,408 |
def normalize_km(KM, method='cosine'):
"""
Normalize a kernel matrix to have unit diagonal.
Cosine normalization normalizes the kernel matrix to have unit diagonal.
Implements definition according to Section 5.1 in book (Page 113)
Shawe-Taylor and Cristianini, "Kernels Methods for Pattern Analysis"... | 5,301,409 |
def colored(s, c):
""" Takes in string s and outputs it with color """
if sys.stdout.isatty():
return '{}{}{}'.format(c, s, color.reset)
return s | 5,301,410 |
def init_tags(meta_tables, diffs):
"""
Initialize executable tags.
:param list[MetaTable] meta_tables: All related meta-tables.
:param list[bool] diffs: Whether to generate diff tags.
:rtype: list, dict
"""
tags = list()
meta_info = {
'cont': list(),
'disc': list(),
... | 5,301,411 |
def test_urls_exist():
"""
Test that urls that may be cached still exist on the server
"""
urls = [
"http://cs231n.stanford.edu/tiny-imagenet-200.zip",
"https://github.com/onnx/models/raw/main/vision/style_transfer/fast_neural_style/model/pointilism-9.onnx",
"https://storage.open... | 5,301,412 |
def createDataset(config, generate_additional=0, checkpt_path=None, char_map=None):
"""
Create LMDB dataset for training and evaluation.
ARGS:
config : config file
generate_additional : number of additional images to be generated
checkpt_path : Path of the model checkpoint file ... | 5,301,413 |
def get_bprop_concat(self):
"""Generate bprop for Concat"""
axis = self.axis
def bprop(x, out, dout):
dx = ()
out_offset = G.ConcatOffset(F.tuple_len(x), axis)(x)
for i in range(F.tuple_len(x)):
slice_out = P.Slice()(dout, out_offset[i], shape_op(x[i]))
dx = ... | 5,301,414 |
def test_ok_names(schema: Type[BaseModel], data: Dict[str, Any]):
"""
Test that a name with everything between 1 and 255 characters is valid
"""
schema(name="a", **data)
schema(name="a" * 255, **data) | 5,301,415 |
def network_allocation_update(context, id, values):
"""Update a network allocation DB record."""
return IMPL.network_allocation_update(context, id, values) | 5,301,416 |
def build_model(model_name, weights_file=None, **kwargs):
"""Build the desired model."""
mod = importlib.import_module("."+model_name, __name__)
model = mod.build_model(**kwargs)
if weights_file:
try:
model.load_weights(weights_file, by_name=True)
print("Loaded existing model:", weights_file)
... | 5,301,417 |
def getExistingLineStringInBounds(*args, **kwargs):
"""Return the geom of the first Path whose geom is in bounds"""
bbox = kwargs.pop('bbox', settings.SPATIAL_EXTENT)
p = Polygon.from_bbox(bbox)
return models.Path.objects.filter(geom__contained=p)[0].geom | 5,301,418 |
def test_write_read_multiplePyfarObjects(
filter,
filterFIR,
filterIIR,
filterSOS,
coordinates,
orientations,
sphericalvoronoi,
time_data,
frequency_data,
sine,
tmpdir):
""" Check if multiple different PyFar-objects can be writt... | 5,301,419 |
def solve(_n, tree):
"""
Given a list of list of tokens:
. (empty), or # (tree), compute the
number of trees one would encounter
if one traverses the 2D grid along
a slope of (3, 1).
:param _n: The number of rows in the
2D grid.
:param tree: The 2D grid as a list of list.
... | 5,301,420 |
def reencode_video(dict_, path_folder_encoded):
"""reencode videos
Args:
dict_ (dataframe): columns: [video_resolution_to_change,
file_path_folder_origin,
file_name_origin]
path_folder_encoded (str): path_folder destinati... | 5,301,421 |
def create_argument_parser() -> argparse.ArgumentParser:
"""
Create argument parser with subparsers for commands.
:return: argument parser.
"""
# Create main parser
parser = MyArgumentParser(
prog='contradictory-my-dear-watson',
description='Program to solve the Contradictory, M... | 5,301,422 |
def _getNodeType(node): # {{{
""" return NodeType as String """
if node.nodeType == node.ELEMENT_NODE : return "ELEMENT_NODE"
elif node.nodeType == node.ATTRIBUTE_NODE : return "ATTRIBUTE_NODE"
elif node.nodeType == node.TEXT_NODE : re... | 5,301,423 |
def rotate_map(hmap, rot_theta, rot_phi):
"""
Take hmap (a healpix map array) and return another healpix map array
which is ordered such that it has been rotated in (theta, phi) by the
amounts given.
"""
nside = hp.npix2nside(len(hmap))
# Get theta, phi for non-rotated map
t,... | 5,301,424 |
def get_request(profile, resource):
"""Do a GET request to Github's API.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
r... | 5,301,425 |
def author_case_query(qn, author):
"""
Given a query number and an author, return a query for finding author
in VIVO
"""
if qn == 1:
query = """
SELECT ?uri
WHERE {
?uri foaf:lastName "{{ln}}" .
?uri a ufVivo:UFCurrentEntity .
?uri foaf:fir... | 5,301,426 |
def snake() -> dict:
""" 4x2 Sanake """
temp = {
0 : {
0 : Conway(Position(0,0),True),
1 : Conway(Position(0,1),True),
2 : Conway(Position(0,2),False),
3 : Conway(Position(0,3),True)
},
1 : {
0 : Con... | 5,301,427 |
def parse_from_any(*classes):
"""Decorator for parsing a variably-typed class instance.
Attempt to parse the input as each of the provided classes, passing
the first successfully parsed class instance to the constructor of
this class. This operation is short-circuiting. Raise ParseError if
none of ... | 5,301,428 |
def github_markdown_toc_go_repositories():
"""Declares the Golang repository dependencies for github-markdown-toc-go."""
go_repository(
name = "com_github_alecthomas_assert",
importpath = "github.com/alecthomas/assert",
sum = "h1:smF2tmSOzy2Mm+0dGI2AIUHY+w0BUc+4tn40djz7+6U=",
ver... | 5,301,429 |
def get_obs_dict(sys,
qp: brax.QP,
info: brax.Info,
observer: str = None,
component: Dict[str, Any] = None):
"""Observe."""
obs_dict = collections.OrderedDict()
if observer == 'qp':
# get all positions/orientations/velocities/ang velocities o... | 5,301,430 |
def init_weights_slimmable(m):
"""Slimmable network style initialization."""
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
if m.affine:
if isinst... | 5,301,431 |
def part_two(data):
"""Part two"""
particles = []
i = 0
for line in data.splitlines():
split = line.split('>, ')
p, v, a = read(split[0]), read(split[1]), read(split[2])
particles.append([p, v, a, i])
i += 1
for _ in range(1000):
for particle in particles:
... | 5,301,432 |
def _raw_clean_data(survey):
"""Remaps values and cleans the data for saving"""
# Remap values for vote choice 2016 and 2020
remp_2020 = {
'I am not sure/don\'t know': 'No Vote',
'I will not vote, but am eligible': 'No Vote',
'I would not vote': 'No Vote',
'I am not eligible... | 5,301,433 |
def HT_TRENDMODE(data: xr.DataArray) -> xr.DataArray:
"""
Hilbert Transform - Trend vs Cycle Mode (Cycle Indicators)
Input:
data: time series
Output:
time series (values are 0 or 1)
"""
return single_series_call(talib.HT_TRENDMODE, data, ds.TIME) | 5,301,434 |
def get_with_text(key, path):
"""Get links for generated images."""
template = app.template_service.find(key)
if template.key != key:
return redirect(route('.get', key=template.key, path=path))
text = Text(path)
if text.path != path:
return redirect(route('.get', key=key, path=text.... | 5,301,435 |
def buildTimelineStats(category, route, probes, txnSubCollection): # pylint: disable=too-many-locals
"""
Builds timeline statistics from a subcollection of transactions
:param probes: List of probes enabled for a profiling session
:param txnSubCollection: A subcollection of transactions
"""
from xpedite.t... | 5,301,436 |
def get_margin(home_team, away_team, home_team_score, away_team_score):
"""
Get the multiplier for the margin of victory
"""
goal_differential = home_team_score - away_team_score
return max(1, math.log(
abs(goal_differential - .85 * ((home_team.elo - away_team.elo)/100)) + math.e - 1)
) | 5,301,437 |
def _merge_a_into_b(a, b, stack=None):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
"""
assert isinstance(a, AttrDict), \
'`a` (cur type {}) must be an instance of {}'.format(type(a), AttrDict)
assert isinstance(b, ... | 5,301,438 |
def chunks(l, n):
"""
Yield successive n-sized chunks from l.
"""
for i in range(0, len(l), n):
yield l[i:i + n] | 5,301,439 |
def profile_cucim(input_file: Path,
output_file: Path) -> None:
"""
Load an input_file with cuCIM, print out basic properties, and save as output_file.
:param input_file: Input file path.
:param output_file: Output file path.
:return: None
"""
img = cucim.CuImage(str(input... | 5,301,440 |
async def async_get_actions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device actions for Humidifier devices."""
registry = await entity_registry.async_get_registry(hass)
actions = await toggle_entity.async_get_actions(hass, device_id, DOMAIN)
# Get all the integrations... | 5,301,441 |
def json_to_file(data_dict, file_name):
"""
Dump python dictionary to json file
:param data_dict: python dictionary to be dumped
:type data_dict: dict
:param file_name: filepath to dump data to
:type file_name: str
"""
with open(file_name, "w", encoding="utf-8") as f:
json.dump(d... | 5,301,442 |
def map_all(process):
"""
"""
process_params1 = set_extra_values(process['arguments'])
process_params2 = get_process_params(process['arguments'], {'ignore_nodata': 'bool'})
return map_default(process, 'all_', 'reduce', {**process_params1, **process_params2}) | 5,301,443 |
def create_scales(options):
"""
Creates the scales for imfil.m. Nothing much here right now, but
custom scales ... are in the near future.
dscal = create_scales(options)
C. T. Kelley, September 15, 2008
This code comes with no guarantee or warranty of any kind."""
custom_scales = options.custom_sca... | 5,301,444 |
def make_schema_test_class(test_file, test_args, test_num, schema_class, check_with_lxml):
"""
Creates a schema test class.
:param test_file: the schema test file path.
:param test_args: line arguments for test case.
:param test_num: a positive integer number associated with the test case.
:par... | 5,301,445 |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Demo climate devices."""
name = config.get(CONF_NAME)
topic = config.get(CONF_TOPIC)
min_temp = config.get(CONF_MIN_TEMP)
max_temp = config.get(CONF_MAX_TEMP)
add_devices([
ILPClimate(hass, name, min_temp, m... | 5,301,446 |
def load_data_into_grakn(session,input_df):
"""
Loading the data form the DataFrame to the graph in parts
"""
print("Inserting characters...")
# using progress_apply instead of apply so we have a progress bar form tqdm
input_df.progress_apply(insert_one_character, axis=1, session=session)
... | 5,301,447 |
def trim_sdf_file():
"""Remove the superfluous leading lines inchi-1 wrote in the .sdf."""
register = []
with open("output.sdf", mode="r") as newfile:
register = newfile.readlines()
register = register[1:]
with open("output.sdf", mode="w") as newfile:
for line in register:
... | 5,301,448 |
def translate_promela_to_slugsin(code):
"""Return SlugsIn code from Promela `code`."""
t0 = time.time()
spec = logic.compile_spec(code)
aut = slugs._symbolic._bitblast(spec)
s = slugs._to_slugs(aut)
t1 = time.time()
dt = datetime.timedelta(seconds=t1 - t0)
logger.info('translated Promela... | 5,301,449 |
def validate(val_dataloader, model, criterion, config, save_dir=None):
"""Run validation.
Args:
val_dataloader (batchgenerators.dataloading.MultiThreadedAugmenter): val data iterator.
model (torch.nn.Module): model to train.
criterion (torch.nn.Module): loss module.
config (YACS... | 5,301,450 |
def load_recommendations(recommendations_file):
"""
Load ratings from file.
Parameters
----------
scores_file : str
The file that contains the rating info
Returns
-------
recs : dict
A recommendations dictionary in which userID is the key.
"""
if not isfile(reco... | 5,301,451 |
def cosponsored_from_offset(member_id, offset, *, verbose=False):
""" Fetches the list of bill_id cosponsored by member """
ans = _get(common.URL_COSPONS(member_id, offset), verbose=verbose)
if ans:
bills = ans["bills"]
return [bill["bill_id"] for bill in bills]
else:
return [] | 5,301,452 |
async def get_all_units():
"""
Get a list of all known unit symbols.
"""
return sorted(getAllUnitSymbols()) | 5,301,453 |
def get_out_off_date_packages() -> frozenset:
"""
Gets all the packages which connected to pip and out off date.
:side-effect: prints
:rtype: frozenset
"""
updater_logger.info("Getting packages")
pip_output_lines = subprocess.check_output(['pip', 'list', '-o']).decode().splitlines()
pa... | 5,301,454 |
def create_initial_servers_and_domains():
"""Use the singleton from the DesignateCharm to run create inital servers
and domains in designate
@returns: None
"""
DesignateCharm.singleton.create_initial_servers_and_domains() | 5,301,455 |
def hmrc_storage(s3):
"""Patch HMRCStorage with moto so that nothing is really uploaded to s3."""
from exporter.storages import HMRCStorage
return make_storage_mock(
s3,
HMRCStorage,
bucket_name=settings.HMRC_STORAGE_BUCKET_NAME,
) | 5,301,456 |
def _chunks(lst: List[T], chunk_size: int) -> Generator[List[T], None, None]:
"""return chunks of chunk_size for list lst
>>> list(chunks([0, 1, 2, 3, 4], 2))
[[0, 1], [2, 3], [4]]
"""
return (lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)) | 5,301,457 |
def cooccurrence_distance(X, discount=False):
"""
Parameters
----------
X : np.ndarray of shape (n_sample, n_features)
discount : bool, default=False
If True, then increase the co-occurrence distance
between sample A and B proportional to the number
of samples both A and B i... | 5,301,458 |
def argerror(urls, listfile):
"""
This function will get all the files path (including filename) recursively, given root folder.
Parameters
----------
urls : str
URL to scan for information.
listfile: str
Path of file which contains urls seperated by newline.
"""
if (ur... | 5,301,459 |
def load_data():
""" Load the csv data """
data = pd.read_csv(DATA_URL)
data['tweet_created'] = pd.to_datetime(data['tweet_created'])
return data | 5,301,460 |
def run_command(cmd):
"""
Runs a command on the command line. Similar to
treadmill.easy.run_command,
but this method has not restrictions on what can be execute. Use
with caution!
:param cmd: command to run as an ordered list
:return: list of output lines
"""
logger.debug("Running... | 5,301,461 |
def main():
"""Main function of the app"""
args = analyse_args()
video_capture = cv2.VideoCapture(0)
lower_color = np.array([0, 50, 120], dtype=np.uint8)
upper_color = np.array([180, 150, 250], dtype=np.uint8)
while True:
_, frame = video_capture.read()
frame = cv2.flip(frame, 1... | 5,301,462 |
def _sbtype_has_field(sbtype, field_name):
"""Recursive helper to have has_field search up the inheritance hierarchy."""
for f in sbtype.fields:
if f.name == field_name:
return True
for b in sbtype.bases:
if _sbtype_has_field(b.type, field_name):
return True
for b in sbtype.vbases:
if ... | 5,301,463 |
def t_s(n, costheta):
"""Fresneltransmittance for two interfaces.
**Arguments:**
- **n**: iterable with two entries for (n_0, n_1)
- **theta:** iterable with two entries for (theta_0, theta_1)
"""
i, j = 0, 1
a = 2 * n[i] * costheta[i]
b = n[i] * costheta[i] + n[j] * costheta[j]
... | 5,301,464 |
def calc_linhas_largura(dict_circ_desc, ponto):
"""criar linhas de largura"""
if dict_circ_desc["tipo_circulo"] == "meio":
linha_nao_intersecta_ponto = None
point_circ = Point()
point_circ.X = dict_circ_desc["pt_medios_circ"]["x_ptm"]
point_circ.Y = dict_circ_desc["pt_medios_circ... | 5,301,465 |
def _GenVersion(output):
"""Writes the version.h file to the given file object."""
version = GetVersionStr()
major, minor, revision, tag = ParseVersion(version)
assert major >= 0 and major <= _MAX_VERSION
assert minor >= 0 and minor <= _MAX_VERSION
assert revision >= 0 and revision <= _MAX_VERSION
assert... | 5,301,466 |
def rfc_1123_date() -> str:
"""
Return the date formatted as per RFC 2616, section 3.3.1, rfc1123-date, as
described in
https://library.vuforia.com/articles/Training/Using-the-VWS-API.
"""
return email.utils.formatdate(None, localtime=False, usegmt=True) | 5,301,467 |
async def secure_mont(a, b, r, n, n_prime):
"""Montgomery multiplication.
See mont() docstring for details.
"""
assert type(a).bit_length >= 3 * (r.bit_length()) # Ensure a*b*n_prime fits
t = a * b
t_np_mod_r = t*n_prime % r
u = (t + t_np_mod_r * n) / r
return mpc.if_else(u >=... | 5,301,468 |
def test_unparse():
"""Test that unparsing produces valid grammars"""
parser = peg.parse
for i in range(3):
prev_gram = peg.unparse(parser)
parser = create_parser(prev_gram, parser, {**actions, "unescape": peg.unescape})
# grammar is not optimal for peg when coming from bpeg
... | 5,301,469 |
def slice_out_int_literals(tensor, args):
"""
Allow passing int literals to factors in place of marginal distributions.
For those args which are int, specialise the tensor to handle these integer
values & eliminate these args from the arg list.
"""
n_args = len(args)
tensor, output_size, er... | 5,301,470 |
def make_color_checker_image_with_system_gamma(
width=1920, height=1080, luminance=100, system_gamma=1.0):
"""
Make a ColorChecker image with system-gamma applied.
"""
color_checker_width = int(width * 0.4)
font_st_pos = np.uint16(np.array([width, width]) * 0.03)
font_size = int(width * ... | 5,301,471 |
def calculate_normalization_info(paths_to_data_information=None, plot_histograms=True, user_correction=True, path_to_norm_info=None):
"""
This function creates csv file with information about dataset statistics which may be used for normalization.
The statistics are calculated from provided datafiles
BU... | 5,301,472 |
async def printStatus():
"""Print the status of the bot every 10 minutes."""
global preventPrematureUpdates
await client.wait_until_ready()
while not client.is_closed:
if preventPrematureUpdates is True:
print('{0} still running || {1}'.format(client.user.name,
getT... | 5,301,473 |
def get_tf_config():
"""Get configuration from TF_CONFIG environment variable.
"""
tf_config = json.loads(os.getenv('TF_CONFIG', '{}'))
if not tf_config:
return None
task = tf_config['task']
cluster = tf_config['cluster']
task_type = task['type']
task_id = int(task['index'])
tf_config_type = colle... | 5,301,474 |
def bin_bucket_sort(arr):
"""
Binary bucket sort / 2-Radix sort
Time: O(NLog2N)
Space: O(N)
input: 1D-list array
output: 1D-list sorted array
"""
bucket = [[], []]
aux = list(arr)
flgkey = 1
while True:
for ele in aux:
bucket[int(b... | 5,301,475 |
def get_pythainlp_data_path():
"""
Return full path where PyThaiNLP keeps its (downloaded) data
"""
path = os.path.join(os.path.expanduser("~"), PYTHAINLP_DATA_DIR)
if not os.path.exists(path):
os.makedirs(path)
return path | 5,301,476 |
def _identity(store: KeyValueStore) -> KeyValueStore:
"""
Helper function for `lazy_store`.
"""
return store | 5,301,477 |
def spawn(*popenargs, **kwargs):
"""Helper function around the Popen constructor
that puts the created process into a registry
"""
proc = subprocess.Popen(*popenargs, **kwargs)
CURRENT_SUBPROCS.append(proc)
return proc | 5,301,478 |
def generate_settlement_lut(country):
"""
Generate a lookup table of all settlements over the defined
settlement thresholds for the country being modeled.
Parameters
----------
country : dict
Contains all country-specific information for modeling.
"""
iso3 = country['iso3']
... | 5,301,479 |
def log2(x):
"""
Compute the logarithm base 2 of `x`.
Return the "principal value" (for a description of this, see
`numpy.log2`) of :math:`log_2(x)`. For real `x > 0`, this is
a real number (``log2(0)`` returns ``-inf`` and ``log2(np.inf)`` returns
``inf``). Otherwise, the complex principle val... | 5,301,480 |
def test_fields_available():
"""
Test that the metaclass does it's thing
"""
# The test record
record = TestRecord()
# Filter out private attributes
flds = {
key: val for (key, val) in six.iteritems(record.__class__.__dict__)
if not key.startswith('_')
}
# Test that... | 5,301,481 |
def test_update_cells(klass, mocker):
"""Ensure the cells are updated properly."""
report = mocker.Mock()
report.table = [
['Ionic', 'Doric', 'Corinthian'],
['how to get the weeaboo to stop using the holodeck', 'malarkey', ''],
['does universal translator work on the weeaboo', ],
... | 5,301,482 |
def get_url(query_str: str, base_url: str, page: int = 1) -> str:
"""Create query URL for Google CSE API search.
Args:
query_str: Search term to use.
base_url: Site URL.
page: Result page to start at.
Returns:
Completed URL.
"""
return (
_API_URL
+ "... | 5,301,483 |
def reset_translations(lang):
"""
Empty django's internal translations dictionary when a message translation
changes or the translations list is regenerated.
"""
from django.utils import translation
from django.utils.translation import trans_real
import gettext
if lang in trans_real._tr... | 5,301,484 |
def build_full_traversal():
"""
Builds a traversal spec that will recurse through all objects .. or at
least I think it does. additions welcome.
See com.vmware.apputils.vim25.ServiceUtil.buildFullTraversal in the java
API. Extended by Sebastian Tello's examples from pysphere to reach networks
a... | 5,301,485 |
def tonum(s):
"""Converts a string representation of a decimal, hexadecimal, or binary number to a number value or None."""
if type(s) in (int, float):
return s
if s is None:
return 0
base = 10
if isinstance(s, str):
if "x" in s:
base = 16
elif "b" in s:... | 5,301,486 |
def resolve_weak_types(storage):
"""
Resolve weak type rules W1 - W3.
See: http://unicode.org/reports/tr9/#Resolving_Weak_Types
"""
for run in storage["runs"]:
prev_strong = prev_type = run["sor"]
start, length = run["start"], run["length"]
chars = storage["chars"][start ... | 5,301,487 |
def mock_derived_metadata_derivation(
path: Path, parameters: any_pb2.Any) -> symfs_pb2.Metadata:
"""Mock custom derived metadata function.
The metadata this function generates will be simply a copy of the parameters,
which is assumed to be everchanging.symfs.ext.TestMessage, with TestMessage.s
replaced wi... | 5,301,488 |
def test_error_checking():
"""Test that exceptions are raised."""
with pytest.raises(ValueError):
direction("North")
with pytest.raises(ValueError):
direction(-10)
with pytest.raises(ValueError):
direction("361") | 5,301,489 |
def has_permissions(*permissions: typing.Tuple[str]):
"""
Checks if the user has the permissions.
"""
def decorator(func: typing.Awaitable):
func.has_permissions = permissions
return func
return decorator | 5,301,490 |
def fromtree(
tree: etree.Element,
use_builtin_types: Optional[bool] = None,
dict_type: Type[MutableMapping[str, Any]] = dict,
) -> Any:
"""Convert an XML tree to a plist structure.
Args:
tree: An ``etree`` ``Element``.
use_builtin_types: If True, binary data is deserialized to
... | 5,301,491 |
def patch_with_user_globals(data, skip_noexist=True):
"""
Patch the paths.json data structure with the user's globals in place.
:param data: the paths.json data structure
:param skip_noexist: skip applying global data if it doesn't exist
otherwise raise an error for a non-existant file
:ret... | 5,301,492 |
def crop_frames(args, data):
""" Indexing is done this way
##################
# 1 # 2 # 3 #
# 4 # 5 # 6 #
#################
"""
if args.num_features % (args.v_crop_scale * args.h_crop_scale) != 0:
print("Incorrect Crop Scaling selected. Please ensure original dimension is d... | 5,301,493 |
def test_genLabels():
"""Test the generation of atomic labels for visualization program"""
# Test that lists expand from emperical key
full = np.zeros((432, 432))
empirical = {'H': 1, 'C': 2, 'N': 3, 'O': 4}
t = Visualizer(full, empirical)
t._genLabels()
assert len(t.labels) == 10, "Atomic ... | 5,301,494 |
def getdeleted(ref):
"""
Return the deleted positions (p=0 or p=1) from a report file.
"""
return [int(i) for i in fopen(ref+'.rep')[7]] | 5,301,495 |
def recursive_glob(rootdir=".", suffix=""):
"""Performs recursive glob with given suffix and rootdir
:param rootdir is the root directory
:param suffix is the suffix to be searched
"""
return [
os.path.join(looproot, filename)
for looproot, _, filenames in os.walk(root... | 5,301,496 |
def generate_permutations(ls):
"""
Question 16.3: Generate all permutations of a list
"""
if len(ls) <= 1:
return [ls]
result = []
for perm in generate_permutations(ls[1:]):
for idx in xrange(len(ls)):
result.append(perm[:idx] + ls[0:1] + perm[idx:])
return resu... | 5,301,497 |
def get_filename(work_dir, product_id):
"""Retrieve the Landsat metadata filename to use
The file may have issues, so call the fix function to remove those issues.
"""
try:
parser = lambda x: 'old' not in x and not x.startswith('lnd')
filename = filter(parser, glob.glob('{0}_MTL.*'.form... | 5,301,498 |
async def async_setup_platform(
hass: HomeAssistantType,
config: ConfigType,
async_add_entities: Callable[[Iterable[Entity]], Any],
discovery_info=None,
):
"""Set up the sensor platform"""
return False | 5,301,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.