Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
LutBuilder._pattern_permute | (self, basic_pattern, options, basic_result) | pattern_permute takes a basic pattern and its result and clones
the pattern according to the modifications described in the $options
parameter. It returns a list of all cloned patterns. | pattern_permute takes a basic pattern and its result and clones
the pattern according to the modifications described in the $options
parameter. It returns a list of all cloned patterns. | def _pattern_permute(self, basic_pattern, options, basic_result):
"""pattern_permute takes a basic pattern and its result and clones
the pattern according to the modifications described in the $options
parameter. It returns a list of all cloned patterns."""
patterns = [(basic_pattern, ba... | [
"def",
"_pattern_permute",
"(",
"self",
",",
"basic_pattern",
",",
"options",
",",
"basic_result",
")",
":",
"patterns",
"=",
"[",
"(",
"basic_pattern",
",",
"basic_result",
")",
"]",
"# rotations",
"if",
"\"4\"",
"in",
"options",
":",
"res",
"=",
"patterns"... | [
105,
4
] | [
133,
23
] | python | en | ['en', 'en', 'en'] | True |
LutBuilder.build_lut | (self) | Compile all patterns into a morphology lut.
TBD :Build based on (file) morphlut:modify_lut
| Compile all patterns into a morphology lut. | def build_lut(self):
"""Compile all patterns into a morphology lut.
TBD :Build based on (file) morphlut:modify_lut
"""
self.build_default_lut()
patterns = []
# Parse and create symmetries of the patterns strings
for p in self.patterns:
m = re.search(... | [
"def",
"build_lut",
"(",
"self",
")",
":",
"self",
".",
"build_default_lut",
"(",
")",
"patterns",
"=",
"[",
"]",
"# Parse and create symmetries of the patterns strings",
"for",
"p",
"in",
"self",
".",
"patterns",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r\... | [
135,
4
] | [
175,
23
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.__init__ | (self, lut=None, op_name=None, patterns=None) | Create a binary morphological operator | Create a binary morphological operator | def __init__(self, lut=None, op_name=None, patterns=None):
"""Create a binary morphological operator"""
self.lut = lut
if op_name is not None:
self.lut = LutBuilder(op_name=op_name).build_lut()
elif patterns is not None:
self.lut = LutBuilder(patterns=patterns).bu... | [
"def",
"__init__",
"(",
"self",
",",
"lut",
"=",
"None",
",",
"op_name",
"=",
"None",
",",
"patterns",
"=",
"None",
")",
":",
"self",
".",
"lut",
"=",
"lut",
"if",
"op_name",
"is",
"not",
"None",
":",
"self",
".",
"lut",
"=",
"LutBuilder",
"(",
"... | [
181,
4
] | [
187,
64
] | python | en | ['en', 'ig', 'en'] | True |
MorphOp.apply | (self, image) | Run a single morphological operation on an image
Returns a tuple of the number of changed pixels and the
morphed image | Run a single morphological operation on an image | def apply(self, image):
"""Run a single morphological operation on an image
Returns a tuple of the number of changed pixels and the
morphed image"""
if self.lut is None:
raise Exception("No operator loaded")
if image.mode != "L":
raise Exception("Image m... | [
"def",
"apply",
"(",
"self",
",",
"image",
")",
":",
"if",
"self",
".",
"lut",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"No operator loaded\"",
")",
"if",
"image",
".",
"mode",
"!=",
"\"L\"",
":",
"raise",
"Exception",
"(",
"\"Image must be binary, ... | [
189,
4
] | [
201,
30
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.match | (self, image) | Get a list of coordinates matching the morphological operation on
an image.
Returns a list of tuples of (x,y) coordinates
of all matching pixels. See :ref:`coordinate-system`. | Get a list of coordinates matching the morphological operation on
an image. | def match(self, image):
"""Get a list of coordinates matching the morphological operation on
an image.
Returns a list of tuples of (x,y) coordinates
of all matching pixels. See :ref:`coordinate-system`."""
if self.lut is None:
raise Exception("No operator loaded")
... | [
"def",
"match",
"(",
"self",
",",
"image",
")",
":",
"if",
"self",
".",
"lut",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"No operator loaded\"",
")",
"if",
"image",
".",
"mode",
"!=",
"\"L\"",
":",
"raise",
"Exception",
"(",
"\"Image must be binary, ... | [
203,
4
] | [
214,
64
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.get_on_pixels | (self, image) | Get a list of all turned on pixels in a binary image
Returns a list of tuples of (x,y) coordinates
of all matching pixels. See :ref:`coordinate-system`. | Get a list of all turned on pixels in a binary image | def get_on_pixels(self, image):
"""Get a list of all turned on pixels in a binary image
Returns a list of tuples of (x,y) coordinates
of all matching pixels. See :ref:`coordinate-system`."""
if image.mode != "L":
raise Exception("Image must be binary, meaning it must use mo... | [
"def",
"get_on_pixels",
"(",
"self",
",",
"image",
")",
":",
"if",
"image",
".",
"mode",
"!=",
"\"L\"",
":",
"raise",
"Exception",
"(",
"\"Image must be binary, meaning it must use mode L\"",
")",
"return",
"_imagingmorph",
".",
"get_on_pixels",
"(",
"image",
".",... | [
216,
4
] | [
224,
55
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.load_lut | (self, filename) | Load an operator from an mrl file | Load an operator from an mrl file | def load_lut(self, filename):
"""Load an operator from an mrl file"""
with open(filename, "rb") as f:
self.lut = bytearray(f.read())
if len(self.lut) != LUT_SIZE:
self.lut = None
raise Exception("Wrong size operator file!") | [
"def",
"load_lut",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"self",
".",
"lut",
"=",
"bytearray",
"(",
"f",
".",
"read",
"(",
")",
")",
"if",
"len",
"(",
"self",
".",
"lut",
")... | [
226,
4
] | [
233,
56
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.save_lut | (self, filename) | Save an operator to an mrl file | Save an operator to an mrl file | def save_lut(self, filename):
"""Save an operator to an mrl file"""
if self.lut is None:
raise Exception("No operator loaded")
with open(filename, "wb") as f:
f.write(self.lut) | [
"def",
"save_lut",
"(",
"self",
",",
"filename",
")",
":",
"if",
"self",
".",
"lut",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"No operator loaded\"",
")",
"with",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
... | [
235,
4
] | [
240,
29
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.set_lut | (self, lut) | Set the lut from an external source | Set the lut from an external source | def set_lut(self, lut):
"""Set the lut from an external source"""
self.lut = lut | [
"def",
"set_lut",
"(",
"self",
",",
"lut",
")",
":",
"self",
".",
"lut",
"=",
"lut"
] | [
242,
4
] | [
244,
22
] | python | en | ['en', 'lb', 'en'] | True |
build_suffix_tree | (text) |
Build a suffix tree of the string text and return a list
with all of the labels of its edges (the corresponding
substrings of the text) in any order.
|
Build a suffix tree of the string text and return a list
with all of the labels of its edges (the corresponding
substrings of the text) in any order.
| def build_suffix_tree(text):
"""
Build a suffix tree of the string text and return a list
with all of the labels of its edges (the corresponding
substrings of the text) in any order.
"""
result = []
# Implement this function yourself
return result | [
"def",
"build_suffix_tree",
"(",
"text",
")",
":",
"result",
"=",
"[",
"]",
"# Implement this function yourself",
"return",
"result"
] | [
4,
0
] | [
12,
15
] | python | en | ['en', 'error', 'th'] | False |
ImagenetModel.fit_normal | (self) |
TODO: Write Comment
|
TODO: Write Comment
| def fit_normal(self):
"""
TODO: Write Comment
"""
history = self._model.fit(
self.processed_train_dataset, steps_per_epoch=self.iterations_train,
epochs=self.epochs, callbacks=self.cbks, verbose=1,
# workers=12, use_multiprocessing=True, ... | [
"def",
"fit_normal",
"(",
"self",
")",
":",
"history",
"=",
"self",
".",
"_model",
".",
"fit",
"(",
"self",
".",
"processed_train_dataset",
",",
"steps_per_epoch",
"=",
"self",
".",
"iterations_train",
",",
"epochs",
"=",
"self",
".",
"epochs",
",",
"callb... | [
176,
4
] | [
188,
30
] | python | en | ['en', 'error', 'th'] | False |
ImagenetModel.get | (self, samples) |
TODO: Write Comment
|
TODO: Write Comment
| def get(self, samples):
"""
TODO: Write Comment
"""
indices, xs, ys = [], [], []
count = 0
for index, x, y in self.raw_test_dataset.take(self.num_images['test']):
index = index.numpy()
x = x.numpy()
y = y.numpy()
# if ... | [
"def",
"get",
"(",
"self",
",",
"samples",
")",
":",
"indices",
",",
"xs",
",",
"ys",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"count",
"=",
"0",
"for",
"index",
",",
"x",
",",
"y",
"in",
"self",
".",
"raw_test_dataset",
".",
"take",
"(",... | [
190,
4
] | [
210,
30
] | python | en | ['en', 'error', 'th'] | False |
ImagenetModel.scheduler | (self, epoch) |
TODO: Write Comment
|
TODO: Write Comment
| def scheduler(self, epoch):
"""
TODO: Write Comment
"""
if epoch < 30: return 0.1
if epoch < 60: return 0.01
if epoch < 80: return 0.001
return 0.0001 | [
"def",
"scheduler",
"(",
"self",
",",
"epoch",
")",
":",
"if",
"epoch",
"<",
"30",
":",
"return",
"0.1",
"if",
"epoch",
"<",
"60",
":",
"return",
"0.01",
"if",
"epoch",
"<",
"80",
":",
"return",
"0.001",
"return",
"0.0001"
] | [
212,
4
] | [
220,
21
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.search_path | (self) |
Search first the vendor package then as a natural package.
|
Search first the vendor package then as a natural package.
| def search_path(self):
"""
Search first the vendor package then as a natural package.
"""
yield self.vendor_pkg + '.'
yield '' | [
"def",
"search_path",
"(",
"self",
")",
":",
"yield",
"self",
".",
"vendor_pkg",
"+",
"'.'",
"yield",
"''"
] | [
15,
4
] | [
20,
16
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.find_module | (self, fullname, path=None) |
Return self when fullname starts with root_name and the
target module is one vendored through this importer.
|
Return self when fullname starts with root_name and the
target module is one vendored through this importer.
| def find_module(self, fullname, path=None):
"""
Return self when fullname starts with root_name and the
target module is one vendored through this importer.
"""
root, base, target = fullname.partition(self.root_name + '.')
if root:
return
if not any(ma... | [
"def",
"find_module",
"(",
"self",
",",
"fullname",
",",
"path",
"=",
"None",
")",
":",
"root",
",",
"base",
",",
"target",
"=",
"fullname",
".",
"partition",
"(",
"self",
".",
"root_name",
"+",
"'.'",
")",
"if",
"root",
":",
"return",
"if",
"not",
... | [
22,
4
] | [
32,
19
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.load_module | (self, fullname) |
Iterate over the search path to locate and load fullname.
|
Iterate over the search path to locate and load fullname.
| def load_module(self, fullname):
"""
Iterate over the search path to locate and load fullname.
"""
root, base, target = fullname.partition(self.root_name + '.')
for prefix in self.search_path:
try:
extant = prefix + target
__import__(ex... | [
"def",
"load_module",
"(",
"self",
",",
"fullname",
")",
":",
"root",
",",
"base",
",",
"target",
"=",
"fullname",
".",
"partition",
"(",
"self",
".",
"root_name",
"+",
"'.'",
")",
"for",
"prefix",
"in",
"self",
".",
"search_path",
":",
"try",
":",
"... | [
34,
4
] | [
54,
13
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.install | (self) |
Install this importer into sys.meta_path if not already present.
|
Install this importer into sys.meta_path if not already present.
| def install(self):
"""
Install this importer into sys.meta_path if not already present.
"""
if self not in sys.meta_path:
sys.meta_path.append(self) | [
"def",
"install",
"(",
"self",
")",
":",
"if",
"self",
"not",
"in",
"sys",
".",
"meta_path",
":",
"sys",
".",
"meta_path",
".",
"append",
"(",
"self",
")"
] | [
56,
4
] | [
61,
38
] | python | en | ['en', 'error', 'th'] | False |
_last_assoc_timestamps | (session, dataset) |
Get the timestamps of the latest assocxtrc per runningcatalog and band.
We can't get the assoc ID's directly, because they are unique and can't
by put in the group by. You can get the eventual assoc ID's by joining
this query again with the assoc table (see last_assoc_per_band func)
args:
... |
Get the timestamps of the latest assocxtrc per runningcatalog and band. | def _last_assoc_timestamps(session, dataset):
"""
Get the timestamps of the latest assocxtrc per runningcatalog and band.
We can't get the assoc ID's directly, because they are unique and can't
by put in the group by. You can get the eventual assoc ID's by joining
this query again with the assoc ta... | [
"def",
"_last_assoc_timestamps",
"(",
"session",
",",
"dataset",
")",
":",
"a",
"=",
"aliased",
"(",
"Assocxtrsource",
",",
"name",
"=",
"'a_timestamps'",
")",
"e",
"=",
"aliased",
"(",
"Extractedsource",
",",
"name",
"=",
"'e_timestamps'",
")",
"r",
"=",
... | [
11,
0
] | [
39,
46
] | python | en | ['en', 'error', 'th'] | False |
_last_assoc_per_band | (session, dataset) |
Get the ID's of the latest assocxtrc per runningcatalog and band.
Very similar to last_assoc_timestamps, but returns the ID's
args:
session: SQLalchemy session objects
dataset: tkp.db.model.dataset object
returns: SQLAlchemy subquery
|
Get the ID's of the latest assocxtrc per runningcatalog and band. | def _last_assoc_per_band(session, dataset):
"""
Get the ID's of the latest assocxtrc per runningcatalog and band.
Very similar to last_assoc_timestamps, but returns the ID's
args:
session: SQLalchemy session objects
dataset: tkp.db.model.dataset object
returns: SQLAlchemy subquery... | [
"def",
"_last_assoc_per_band",
"(",
"session",
",",
"dataset",
")",
":",
"l",
"=",
"_last_assoc_timestamps",
"(",
"session",
",",
"dataset",
")",
"a",
"=",
"aliased",
"(",
"Assocxtrsource",
",",
"name",
"=",
"'a_laids'",
")",
"e",
"=",
"aliased",
"(",
"Ext... | [
42,
0
] | [
65,
44
] | python | en | ['en', 'error', 'th'] | False |
_last_ts_fmax | (session, dataset) |
Select peak flux per runcat at last timestep (over all bands)
args:
session: SQLalchemy session objects
dataset: tkp.db.model.dataset object
returns: SQLAlchemy subquery
|
Select peak flux per runcat at last timestep (over all bands) | def _last_ts_fmax(session, dataset):
"""
Select peak flux per runcat at last timestep (over all bands)
args:
session: SQLalchemy session objects
dataset: tkp.db.model.dataset object
returns: SQLAlchemy subquery
"""
a = aliased(Assocxtrsource, name='a_lt')
e = aliased(Extrac... | [
"def",
"_last_ts_fmax",
"(",
"session",
",",
"dataset",
")",
":",
"a",
"=",
"aliased",
"(",
"Assocxtrsource",
",",
"name",
"=",
"'a_lt'",
")",
"e",
"=",
"aliased",
"(",
"Extractedsource",
",",
"name",
"=",
"'e_lt'",
")",
"subquery",
"=",
"_last_assoc_per_b... | [
68,
0
] | [
89,
37
] | python | en | ['en', 'error', 'th'] | False |
_newsrc_trigger | (session, dataset) |
Grab newsource /trigger details where possible
args:
session: SQLalchemy session objects
returns: SQLAlchemy subquery
|
Grab newsource /trigger details where possible | def _newsrc_trigger(session, dataset):
"""
Grab newsource /trigger details where possible
args:
session: SQLalchemy session objects
returns: SQLAlchemy subquery
"""
newsource = aliased(Newsource, name='n_ntr')
e = aliased(Extractedsource, name='e_ntr')
i = aliased(Image, name='... | [
"def",
"_newsrc_trigger",
"(",
"session",
",",
"dataset",
")",
":",
"newsource",
"=",
"aliased",
"(",
"Newsource",
",",
"name",
"=",
"'n_ntr'",
")",
"e",
"=",
"aliased",
"(",
"Extractedsource",
",",
"name",
"=",
"'e_ntr'",
")",
"i",
"=",
"aliased",
"(",
... | [
92,
0
] | [
114,
39
] | python | en | ['en', 'error', 'th'] | False |
_combined | (session, dataset) |
args:
session (Session): SQLAlchemy session
runcat (Runningcatalog): Running catalog model object
dataset (Dataset): Dataset model object
return: a SQLALchemy subquery
| def _combined(session, dataset):
"""
args:
session (Session): SQLAlchemy session
runcat (Runningcatalog): Running catalog model object
dataset (Dataset): Dataset model object
return: a SQLALchemy subquery
"""
runcat = aliased(Runningcatalog, name='r')
match_assoc = ali... | [
"def",
"_combined",
"(",
"session",
",",
"dataset",
")",
":",
"runcat",
"=",
"aliased",
"(",
"Runningcatalog",
",",
"name",
"=",
"'r'",
")",
"match_assoc",
"=",
"aliased",
"(",
"Assocxtrsource",
",",
"name",
"=",
"'match_assoc'",
")",
"match_ex",
"=",
"ali... | [
117,
0
] | [
185,
18
] | python | en | ['en', 'error', 'th'] | False | |
del_duplicate_varmetric | (session, dataset) |
can't figure out how to update in a simple way, for now just delete
the updated rows. This code should be rewritten anyway when we make it
optional to specify a list of runcat entries to update
|
can't figure out how to update in a simple way, for now just delete
the updated rows. This code should be rewritten anyway when we make it
optional to specify a list of runcat entries to update
| def del_duplicate_varmetric(session, dataset):
"""
can't figure out how to update in a simple way, for now just delete
the updated rows. This code should be rewritten anyway when we make it
optional to specify a list of runcat entries to update
"""
del_varmetrics = session.query(Varmetric.id).\
... | [
"def",
"del_duplicate_varmetric",
"(",
"session",
",",
"dataset",
")",
":",
"del_varmetrics",
"=",
"session",
".",
"query",
"(",
"Varmetric",
".",
"id",
")",
".",
"filter",
"(",
"Varmetric",
".",
"runcat_id",
"==",
"Runningcatalog",
".",
"id",
",",
"Runningc... | [
188,
0
] | [
197,
68
] | python | en | ['en', 'error', 'th'] | False |
store_varmetric | (session, dataset) |
Stores the augmented runningcatalog values in the varmetric table.
args:
session: A SQLAlchemy session
dataset: a dataset model object
:return: a SQLAlchemy query
|
Stores the augmented runningcatalog values in the varmetric table.
args:
session: A SQLAlchemy session
dataset: a dataset model object | def store_varmetric(session, dataset):
"""
Stores the augmented runningcatalog values in the varmetric table.
args:
session: A SQLAlchemy session
dataset: a dataset model object
:return: a SQLAlchemy query
"""
fields = ['runcat', 'v_int', 'eta_int', 'band', 'newsource',
... | [
"def",
"store_varmetric",
"(",
"session",
",",
"dataset",
")",
":",
"fields",
"=",
"[",
"'runcat'",
",",
"'v_int'",
",",
"'eta_int'",
",",
"'band'",
",",
"'newsource'",
",",
"'sigma_rms_max'",
",",
"'sigma_rms_min'",
",",
"'lightcurve_max'",
",",
"'lightcurve_av... | [
200,
0
] | [
218,
71
] | python | en | ['en', 'error', 'th'] | False |
calculate_varmetric | (session, dataset, ra_range=None, decl_range=None,
v_int_min=None, eta_int_min=None, sigma_rms_min_range=None,
sigma_rms_max_range=None, new_src_only=False) |
Calculate sigma_min, sigma_max, v_int, eta_int and the max and avg
values for lightcurves, for all runningcatalogs
It starts by getting the extracted source from latest image for a runcat.
This is arbitrary, since you have multiple bands. We pick the band with the
max integrated flux. Now we have ... |
Calculate sigma_min, sigma_max, v_int, eta_int and the max and avg
values for lightcurves, for all runningcatalogs | def calculate_varmetric(session, dataset, ra_range=None, decl_range=None,
v_int_min=None, eta_int_min=None, sigma_rms_min_range=None,
sigma_rms_max_range=None, new_src_only=False):
"""
Calculate sigma_min, sigma_max, v_int, eta_int and the max and avg
values for lightcurves, fo... | [
"def",
"calculate_varmetric",
"(",
"session",
",",
"dataset",
",",
"ra_range",
"=",
"None",
",",
"decl_range",
"=",
"None",
",",
"v_int_min",
"=",
"None",
",",
"eta_int_min",
"=",
"None",
",",
"sigma_rms_min_range",
"=",
"None",
",",
"sigma_rms_max_range",
"="... | [
221,
0
] | [
270,
16
] | python | en | ['en', 'error', 'th'] | False |
Draw | (im, mode=None) |
A simple 2D drawing interface for PIL images.
:param im: The image to draw in.
:param mode: Optional mode to use for color values. For RGB
images, this argument can be RGB or RGBA (to blend the
drawing into the image). For all other modes, this argument
must be the same as the image... |
A simple 2D drawing interface for PIL images. | def Draw(im, mode=None):
"""
A simple 2D drawing interface for PIL images.
:param im: The image to draw in.
:param mode: Optional mode to use for color values. For RGB
images, this argument can be RGB or RGBA (to blend the
drawing into the image). For all other modes, this argument
... | [
"def",
"Draw",
"(",
"im",
",",
"mode",
"=",
"None",
")",
":",
"try",
":",
"return",
"im",
".",
"getdraw",
"(",
"mode",
")",
"except",
"AttributeError",
":",
"return",
"ImageDraw",
"(",
"im",
",",
"mode",
")"
] | [
669,
0
] | [
683,
34
] | python | en | ['en', 'error', 'th'] | False |
getdraw | (im=None, hints=None) |
(Experimental) A more advanced 2D drawing interface for PIL images,
based on the WCK interface.
:param im: The image to draw in.
:param hints: An optional list of hints.
:returns: A (drawing context, drawing resource factory) tuple.
|
(Experimental) A more advanced 2D drawing interface for PIL images,
based on the WCK interface. | def getdraw(im=None, hints=None):
"""
(Experimental) A more advanced 2D drawing interface for PIL images,
based on the WCK interface.
:param im: The image to draw in.
:param hints: An optional list of hints.
:returns: A (drawing context, drawing resource factory) tuple.
"""
# FIXME: thi... | [
"def",
"getdraw",
"(",
"im",
"=",
"None",
",",
"hints",
"=",
"None",
")",
":",
"# FIXME: this needs more work!",
"# FIXME: come up with a better 'hints' scheme.",
"handler",
"=",
"None",
"if",
"not",
"hints",
"or",
"\"nicest\"",
"in",
"hints",
":",
"try",
":",
"... | [
693,
0
] | [
714,
22
] | python | en | ['en', 'error', 'th'] | False |
floodfill | (image, xy, value, border=None, thresh=0) |
(experimental) Fills a bounded region with a given color.
:param image: Target image.
:param xy: Seed position (a 2-item coordinate tuple). See
:ref:`coordinate-system`.
:param value: Fill color.
:param border: Optional border value. If given, the region consists of
pixels with a ... |
(experimental) Fills a bounded region with a given color. | def floodfill(image, xy, value, border=None, thresh=0):
"""
(experimental) Fills a bounded region with a given color.
:param image: Target image.
:param xy: Seed position (a 2-item coordinate tuple). See
:ref:`coordinate-system`.
:param value: Fill color.
:param border: Optional border ... | [
"def",
"floodfill",
"(",
"image",
",",
"xy",
",",
"value",
",",
"border",
"=",
"None",
",",
"thresh",
"=",
"0",
")",
":",
"# based on an implementation by Eric S. Raymond",
"# amended by yo1995 @20180806",
"pixel",
"=",
"image",
".",
"load",
"(",
")",
"x",
","... | [
717,
0
] | [
770,
23
] | python | en | ['en', 'error', 'th'] | False |
_compute_regular_polygon_vertices | (bounding_circle, n_sides, rotation) |
Generate a list of vertices for a 2D regular polygon.
:param bounding_circle: The bounding circle is a tuple defined
by a point and radius. The polygon is inscribed in this circle.
(e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
:param n_sides: Number of sides
(e.g. ``n_sid... |
Generate a list of vertices for a 2D regular polygon. | def _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation):
"""
Generate a list of vertices for a 2D regular polygon.
:param bounding_circle: The bounding circle is a tuple defined
by a point and radius. The polygon is inscribed in this circle.
(e.g. ``bounding_circle=(x, y, ... | [
"def",
"_compute_regular_polygon_vertices",
"(",
"bounding_circle",
",",
"n_sides",
",",
"rotation",
")",
":",
"# 1. Error Handling",
"# 1.1 Check `n_sides` has an appropriate value",
"if",
"not",
"isinstance",
"(",
"n_sides",
",",
"int",
")",
":",
"raise",
"TypeError",
... | [
773,
0
] | [
887,
5
] | python | en | ['en', 'error', 'th'] | False |
_color_diff | (color1, color2) |
Uses 1-norm distance to calculate difference between two values.
|
Uses 1-norm distance to calculate difference between two values.
| def _color_diff(color1, color2):
"""
Uses 1-norm distance to calculate difference between two values.
"""
if isinstance(color2, tuple):
return sum([abs(color1[i] - color2[i]) for i in range(0, len(color2))])
else:
return abs(color1 - color2) | [
"def",
"_color_diff",
"(",
"color1",
",",
"color2",
")",
":",
"if",
"isinstance",
"(",
"color2",
",",
"tuple",
")",
":",
"return",
"sum",
"(",
"[",
"abs",
"(",
"color1",
"[",
"i",
"]",
"-",
"color2",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",... | [
890,
0
] | [
897,
35
] | python | en | ['en', 'error', 'th'] | False |
ImageDraw.__init__ | (self, im, mode=None) |
Create a drawing instance.
:param im: The image to draw in.
:param mode: Optional mode to use for color values. For RGB
images, this argument can be RGB or RGBA (to blend the
drawing into the image). For all other modes, this argument
must be the same as the ... |
Create a drawing instance. | def __init__(self, im, mode=None):
"""
Create a drawing instance.
:param im: The image to draw in.
:param mode: Optional mode to use for color values. For RGB
images, this argument can be RGB or RGBA (to blend the
drawing into the image). For all other modes, thi... | [
"def",
"__init__",
"(",
"self",
",",
"im",
",",
"mode",
"=",
"None",
")",
":",
"im",
".",
"load",
"(",
")",
"if",
"im",
".",
"readonly",
":",
"im",
".",
"_copy",
"(",
")",
"# make it writeable",
"blend",
"=",
"0",
"if",
"mode",
"is",
"None",
":",... | [
46,
4
] | [
85,
24
] | python | en | ['en', 'error', 'th'] | False |
ImageDraw.getfont | (self) |
Get the current default font.
:returns: An image font. |
Get the current default font. | def getfont(self):
"""
Get the current default font.
:returns: An image font."""
if not self.font:
# FIXME: should add a font repository
from . import ImageFont
self.font = ImageFont.load_default()
return self.font | [
"def",
"getfont",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"font",
":",
"# FIXME: should add a font repository",
"from",
".",
"import",
"ImageFont",
"self",
".",
"font",
"=",
"ImageFont",
".",
"load_default",
"(",
")",
"return",
"self",
".",
"font"
] | [
87,
4
] | [
97,
24
] | python | en | ['en', 'error', 'th'] | False |
ImageDraw.arc | (self, xy, start, end, fill=None, width=1) | Draw an arc. | Draw an arc. | def arc(self, xy, start, end, fill=None, width=1):
"""Draw an arc."""
ink, fill = self._getink(fill)
if ink is not None:
self.draw.draw_arc(xy, start, end, ink, width) | [
"def",
"arc",
"(",
"self",
",",
"xy",
",",
"start",
",",
"end",
",",
"fill",
"=",
"None",
",",
"width",
"=",
"1",
")",
":",
"ink",
",",
"fill",
"=",
"self",
".",
"_getink",
"(",
"fill",
")",
"if",
"ink",
"is",
"not",
"None",
":",
"self",
".",... | [
120,
4
] | [
124,
58
] | python | en | ['en', 'pl', 'en'] | True |
ImageDraw.bitmap | (self, xy, bitmap, fill=None) | Draw a bitmap. | Draw a bitmap. | def bitmap(self, xy, bitmap, fill=None):
"""Draw a bitmap."""
bitmap.load()
ink, fill = self._getink(fill)
if ink is None:
ink = fill
if ink is not None:
self.draw.draw_bitmap(xy, bitmap.im, ink) | [
"def",
"bitmap",
"(",
"self",
",",
"xy",
",",
"bitmap",
",",
"fill",
"=",
"None",
")",
":",
"bitmap",
".",
"load",
"(",
")",
"ink",
",",
"fill",
"=",
"self",
".",
"_getink",
"(",
"fill",
")",
"if",
"ink",
"is",
"None",
":",
"ink",
"=",
"fill",
... | [
126,
4
] | [
133,
53
] | python | en | ['en', 'mt', 'en'] | True |
ImageDraw.chord | (self, xy, start, end, fill=None, outline=None, width=1) | Draw a chord. | Draw a chord. | def chord(self, xy, start, end, fill=None, outline=None, width=1):
"""Draw a chord."""
ink, fill = self._getink(outline, fill)
if fill is not None:
self.draw.draw_chord(xy, start, end, fill, 1)
if ink is not None and ink != fill and width != 0:
self.draw.draw_chor... | [
"def",
"chord",
"(",
"self",
",",
"xy",
",",
"start",
",",
"end",
",",
"fill",
"=",
"None",
",",
"outline",
"=",
"None",
",",
"width",
"=",
"1",
")",
":",
"ink",
",",
"fill",
"=",
"self",
".",
"_getink",
"(",
"outline",
",",
"fill",
")",
"if",
... | [
135,
4
] | [
141,
63
] | python | cy | ['en', 'cy', 'hi'] | False |
ImageDraw.ellipse | (self, xy, fill=None, outline=None, width=1) | Draw an ellipse. | Draw an ellipse. | def ellipse(self, xy, fill=None, outline=None, width=1):
"""Draw an ellipse."""
ink, fill = self._getink(outline, fill)
if fill is not None:
self.draw.draw_ellipse(xy, fill, 1)
if ink is not None and ink != fill and width != 0:
self.draw.draw_ellipse(xy, ink, 0, w... | [
"def",
"ellipse",
"(",
"self",
",",
"xy",
",",
"fill",
"=",
"None",
",",
"outline",
"=",
"None",
",",
"width",
"=",
"1",
")",
":",
"ink",
",",
"fill",
"=",
"self",
".",
"_getink",
"(",
"outline",
",",
"fill",
")",
"if",
"fill",
"is",
"not",
"No... | [
143,
4
] | [
149,
53
] | python | en | ['en', 'fy', 'es'] | False |
ImageDraw.line | (self, xy, fill=None, width=0, joint=None) | Draw a line, or a connected sequence of line segments. | Draw a line, or a connected sequence of line segments. | def line(self, xy, fill=None, width=0, joint=None):
"""Draw a line, or a connected sequence of line segments."""
ink = self._getink(fill)[0]
if ink is not None:
self.draw.draw_lines(xy, ink, width)
if joint == "curve" and width > 4:
if not isinstance(xy[0]... | [
"def",
"line",
"(",
"self",
",",
"xy",
",",
"fill",
"=",
"None",
",",
"width",
"=",
"0",
",",
"joint",
"=",
"None",
")",
":",
"ink",
"=",
"self",
".",
"_getink",
"(",
"fill",
")",
"[",
"0",
"]",
"if",
"ink",
"is",
"not",
"None",
":",
"self",
... | [
151,
4
] | [
211,
59
] | python | en | ['en', 'en', 'en'] | True |
ImageDraw.shape | (self, shape, fill=None, outline=None) | (Experimental) Draw a shape. | (Experimental) Draw a shape. | def shape(self, shape, fill=None, outline=None):
"""(Experimental) Draw a shape."""
shape.close()
ink, fill = self._getink(outline, fill)
if fill is not None:
self.draw.draw_outline(shape, fill, 1)
if ink is not None and ink != fill:
self.draw.draw_outline... | [
"def",
"shape",
"(",
"self",
",",
"shape",
",",
"fill",
"=",
"None",
",",
"outline",
"=",
"None",
")",
":",
"shape",
".",
"close",
"(",
")",
"ink",
",",
"fill",
"=",
"self",
".",
"_getink",
"(",
"outline",
",",
"fill",
")",
"if",
"fill",
"is",
... | [
213,
4
] | [
220,
49
] | python | en | ['en', 'haw', 'en'] | True |
ImageDraw.pieslice | (self, xy, start, end, fill=None, outline=None, width=1) | Draw a pieslice. | Draw a pieslice. | def pieslice(self, xy, start, end, fill=None, outline=None, width=1):
"""Draw a pieslice."""
ink, fill = self._getink(outline, fill)
if fill is not None:
self.draw.draw_pieslice(xy, start, end, fill, 1)
if ink is not None and ink != fill and width != 0:
self.draw.... | [
"def",
"pieslice",
"(",
"self",
",",
"xy",
",",
"start",
",",
"end",
",",
"fill",
"=",
"None",
",",
"outline",
"=",
"None",
",",
"width",
"=",
"1",
")",
":",
"ink",
",",
"fill",
"=",
"self",
".",
"_getink",
"(",
"outline",
",",
"fill",
")",
"if... | [
222,
4
] | [
228,
66
] | python | pl | ['en', 'pl', 'pl'] | True |
ImageDraw.point | (self, xy, fill=None) | Draw one or more individual pixels. | Draw one or more individual pixels. | def point(self, xy, fill=None):
"""Draw one or more individual pixels."""
ink, fill = self._getink(fill)
if ink is not None:
self.draw.draw_points(xy, ink) | [
"def",
"point",
"(",
"self",
",",
"xy",
",",
"fill",
"=",
"None",
")",
":",
"ink",
",",
"fill",
"=",
"self",
".",
"_getink",
"(",
"fill",
")",
"if",
"ink",
"is",
"not",
"None",
":",
"self",
".",
"draw",
".",
"draw_points",
"(",
"xy",
",",
"ink"... | [
230,
4
] | [
234,
42
] | python | en | ['en', 'en', 'en'] | True |
ImageDraw.polygon | (self, xy, fill=None, outline=None) | Draw a polygon. | Draw a polygon. | def polygon(self, xy, fill=None, outline=None):
"""Draw a polygon."""
ink, fill = self._getink(outline, fill)
if fill is not None:
self.draw.draw_polygon(xy, fill, 1)
if ink is not None and ink != fill:
self.draw.draw_polygon(xy, ink, 0) | [
"def",
"polygon",
"(",
"self",
",",
"xy",
",",
"fill",
"=",
"None",
",",
"outline",
"=",
"None",
")",
":",
"ink",
",",
"fill",
"=",
"self",
".",
"_getink",
"(",
"outline",
",",
"fill",
")",
"if",
"fill",
"is",
"not",
"None",
":",
"self",
".",
"... | [
236,
4
] | [
242,
46
] | python | en | ['en', 'cy', 'en'] | True |
ImageDraw.regular_polygon | (
self, bounding_circle, n_sides, rotation=0, fill=None, outline=None
) | Draw a regular polygon. | Draw a regular polygon. | def regular_polygon(
self, bounding_circle, n_sides, rotation=0, fill=None, outline=None
):
"""Draw a regular polygon."""
xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
self.polygon(xy, fill, outline) | [
"def",
"regular_polygon",
"(",
"self",
",",
"bounding_circle",
",",
"n_sides",
",",
"rotation",
"=",
"0",
",",
"fill",
"=",
"None",
",",
"outline",
"=",
"None",
")",
":",
"xy",
"=",
"_compute_regular_polygon_vertices",
"(",
"bounding_circle",
",",
"n_sides",
... | [
244,
4
] | [
249,
39
] | python | en | ['en', 'cy', 'en'] | True |
ImageDraw.rectangle | (self, xy, fill=None, outline=None, width=1) | Draw a rectangle. | Draw a rectangle. | def rectangle(self, xy, fill=None, outline=None, width=1):
"""Draw a rectangle."""
ink, fill = self._getink(outline, fill)
if fill is not None:
self.draw.draw_rectangle(xy, fill, 1)
if ink is not None and ink != fill and width != 0:
self.draw.draw_rectangle(xy, in... | [
"def",
"rectangle",
"(",
"self",
",",
"xy",
",",
"fill",
"=",
"None",
",",
"outline",
"=",
"None",
",",
"width",
"=",
"1",
")",
":",
"ink",
",",
"fill",
"=",
"self",
".",
"_getink",
"(",
"outline",
",",
"fill",
")",
"if",
"fill",
"is",
"not",
"... | [
251,
4
] | [
257,
55
] | python | en | ['en', 'en', 'pt'] | True |
ImageDraw.textsize | (
self,
text,
font=None,
spacing=4,
direction=None,
features=None,
language=None,
stroke_width=0,
) | Get the size of a given string, in pixels. | Get the size of a given string, in pixels. | def textsize(
self,
text,
font=None,
spacing=4,
direction=None,
features=None,
language=None,
stroke_width=0,
):
"""Get the size of a given string, in pixels."""
if self._multiline_check(text):
return self.multiline_textsize... | [
"def",
"textsize",
"(",
"self",
",",
"text",
",",
"font",
"=",
"None",
",",
"spacing",
"=",
"4",
",",
"direction",
"=",
"None",
",",
"features",
"=",
"None",
",",
"language",
"=",
"None",
",",
"stroke_width",
"=",
"0",
",",
")",
":",
"if",
"self",
... | [
460,
4
] | [
478,
78
] | python | en | ['en', 'en', 'en'] | True |
ImageDraw.textlength | (
self,
text,
font=None,
direction=None,
features=None,
language=None,
embedded_color=False,
) | Get the length of a given string, in pixels with 1/64 precision. | Get the length of a given string, in pixels with 1/64 precision. | def textlength(
self,
text,
font=None,
direction=None,
features=None,
language=None,
embedded_color=False,
):
"""Get the length of a given string, in pixels with 1/64 precision."""
if self._multiline_check(text):
raise ValueError("c... | [
"def",
"textlength",
"(",
"self",
",",
"text",
",",
"font",
"=",
"None",
",",
"direction",
"=",
"None",
",",
"features",
"=",
"None",
",",
"language",
"=",
"None",
",",
"embedded_color",
"=",
"False",
",",
")",
":",
"if",
"self",
".",
"_multiline_check... | [
502,
4
] | [
528,
26
] | python | en | ['en', 'en', 'en'] | True |
ImageDraw.textbbox | (
self,
xy,
text,
font=None,
anchor=None,
spacing=4,
align="left",
direction=None,
features=None,
language=None,
stroke_width=0,
embedded_color=False,
) | Get the bounding box of a given string, in pixels. | Get the bounding box of a given string, in pixels. | def textbbox(
self,
xy,
text,
font=None,
anchor=None,
spacing=4,
align="left",
direction=None,
features=None,
language=None,
stroke_width=0,
embedded_color=False,
):
"""Get the bounding box of a given string, in ... | [
"def",
"textbbox",
"(",
"self",
",",
"xy",
",",
"text",
",",
"font",
"=",
"None",
",",
"anchor",
"=",
"None",
",",
"spacing",
"=",
"4",
",",
"align",
"=",
"\"left\"",
",",
"direction",
"=",
"None",
",",
"features",
"=",
"None",
",",
"language",
"="... | [
530,
4
] | [
569,
81
] | python | en | ['en', 'en', 'en'] | True |
source_profile_and_errors | (data, threshold, noise,
beam, fixed=None) | Return a number of measurable properties with errorbars
Given an island of pixels it will return a number of measurable
properties including errorbars. It will also compute residuals
from Gauss fitting and export these to a residual map.
In addition to handling the initial parameter estimation, and a... | Return a number of measurable properties with errorbars | def source_profile_and_errors(data, threshold, noise,
beam, fixed=None):
"""Return a number of measurable properties with errorbars
Given an island of pixels it will return a number of measurable
properties including errorbars. It will also compute residuals
from Gauss fi... | [
"def",
"source_profile_and_errors",
"(",
"data",
",",
"threshold",
",",
"noise",
",",
"beam",
",",
"fixed",
"=",
"None",
")",
":",
"if",
"fixed",
"is",
"None",
":",
"fixed",
"=",
"{",
"}",
"param",
"=",
"ParamSet",
"(",
")",
"if",
"threshold",
"is",
... | [
605,
0
] | [
717,
36
] | python | en | ['en', 'en', 'en'] | True |
Island.deblend | (self, niter=0) | Return a decomposed numpy array of all the subislands.
Iterate up through subthresholds, looking for our island
splitting into two. If it does, start again, with two or more
separate islands.
| Return a decomposed numpy array of all the subislands. | def deblend(self, niter=0):
"""Return a decomposed numpy array of all the subislands.
Iterate up through subthresholds, looking for our island
splitting into two. If it does, start again, with two or more
separate islands.
"""
logger.debug("Deblending source")
f... | [
"def",
"deblend",
"(",
"self",
",",
"niter",
"=",
"0",
")",
":",
"logger",
".",
"debug",
"(",
"\"Deblending source\"",
")",
"for",
"level",
"in",
"self",
".",
"subthrrange",
"[",
"niter",
":",
"]",
":",
"# The idea is to retain the parent island when no signific... | [
94,
4
] | [
196,
19
] | python | en | ['en', 'en', 'en'] | True |
Island.noise | (self) | Noise at maximum position | Noise at maximum position | def noise(self):
"""Noise at maximum position"""
return self.rms[self.max_pos] | [
"def",
"noise",
"(",
"self",
")",
":",
"return",
"self",
".",
"rms",
"[",
"self",
".",
"max_pos",
"]"
] | [
202,
4
] | [
204,
37
] | python | en | ['en', 'fr', 'en'] | True |
Island.fit | (self, fixed=None) | Fit the position | Fit the position | def fit(self, fixed=None):
"""Fit the position"""
try:
measurement, gauss_residual = source_profile_and_errors(
self.data, self.threshold(), self.noise(), self.beam, fixed=fixed
)
except ValueError:
# Fitting failed
logger.error("Mo... | [
"def",
"fit",
"(",
"self",
",",
"fixed",
"=",
"None",
")",
":",
"try",
":",
"measurement",
",",
"gauss_residual",
"=",
"source_profile_and_errors",
"(",
"self",
".",
"data",
",",
"self",
".",
"threshold",
"(",
")",
",",
"self",
".",
"noise",
"(",
")",
... | [
210,
4
] | [
223,
42
] | python | en | ['en', 'en', 'en'] | True |
ParamSet.calculate_errors | (self, noise, beam, threshold) | Calculate positional errors
Uses _condon_formulae() if this object is based on a Gaussian fit,
_error_bars_from_moments() if it's based on moments.
| Calculate positional errors | def calculate_errors(self, noise, beam, threshold):
"""Calculate positional errors
Uses _condon_formulae() if this object is based on a Gaussian fit,
_error_bars_from_moments() if it's based on moments.
"""
if self.gaussian:
return self._condon_formulae(noise, beam)... | [
"def",
"calculate_errors",
"(",
"self",
",",
"noise",
",",
"beam",
",",
"threshold",
")",
":",
"if",
"self",
".",
"gaussian",
":",
"return",
"self",
".",
"_condon_formulae",
"(",
"noise",
",",
"beam",
")",
"elif",
"self",
".",
"moments",
":",
"if",
"no... | [
290,
4
] | [
304,
24
] | python | en | ['en', 'en', 'en'] | True |
ParamSet._condon_formulae | (self, noise, beam) | Returns the errors on parameters from Gaussian fits according to
the Condon (PASP 109, 166 (1997)) formulae.
These formulae are not perfect, but we'll use them for the
time being. (See Refregier and Brown (astro-ph/9803279v1) for
a more rigorous approach.) It also returns the corrected... | Returns the errors on parameters from Gaussian fits according to
the Condon (PASP 109, 166 (1997)) formulae. | def _condon_formulae(self, noise, beam):
"""Returns the errors on parameters from Gaussian fits according to
the Condon (PASP 109, 166 (1997)) formulae.
These formulae are not perfect, but we'll use them for the
time being. (See Refregier and Brown (astro-ph/9803279v1) for
a mo... | [
"def",
"_condon_formulae",
"(",
"self",
",",
"noise",
",",
"beam",
")",
":",
"peak",
"=",
"self",
"[",
"'peak'",
"]",
".",
"value",
"flux",
"=",
"self",
"[",
"'flux'",
"]",
".",
"value",
"smaj",
"=",
"self",
"[",
"'semimajor'",
"]",
".",
"value",
"... | [
306,
4
] | [
395,
19
] | python | en | ['en', 'en', 'en'] | True |
ParamSet._error_bars_from_moments | (self, noise, beam, threshold) | Provide reasonable error estimates from the moments | Provide reasonable error estimates from the moments | def _error_bars_from_moments(self, noise, beam, threshold):
"""Provide reasonable error estimates from the moments"""
# The formulae below should give some reasonable estimate of the
# errors from moments, should always be higher than the errors from
# Gauss fitting.
peak = self... | [
"def",
"_error_bars_from_moments",
"(",
"self",
",",
"noise",
",",
"beam",
",",
"threshold",
")",
":",
"# The formulae below should give some reasonable estimate of the",
"# errors from moments, should always be higher than the errors from",
"# Gauss fitting.",
"peak",
"=",
"self",... | [
397,
4
] | [
490,
19
] | python | en | ['en', 'en', 'en'] | True |
ParamSet.deconvolve_from_clean_beam | (self, beam) | Deconvolve with the clean beam | Deconvolve with the clean beam | def deconvolve_from_clean_beam(self, beam):
"""Deconvolve with the clean beam"""
# If the fitted axes are smaller than the clean beam
# (=restoring beam) axes, the axes and position angle
# can be deconvolved from it.
fmaj = 2.*self['semimajor'].value
fmajerror = 2.*self... | [
"def",
"deconvolve_from_clean_beam",
"(",
"self",
",",
"beam",
")",
":",
"# If the fitted axes are smaller than the clean beam",
"# (=restoring beam) axes, the axes and position angle",
"# can be deconvolved from it.",
"fmaj",
"=",
"2.",
"*",
"self",
"[",
"'semimajor'",
"]",
".... | [
492,
4
] | [
602,
19
] | python | en | ['en', 'en', 'en'] | True |
Detection._physical_coordinates | (self) | Convert the pixel parameters for this object into something
physical. | Convert the pixel parameters for this object into something
physical. | def _physical_coordinates(self):
"""Convert the pixel parameters for this object into something
physical."""
# First, the RA & dec.
self.ra, self.dec = [Uncertain(x) for x in self.imagedata.wcs.p2s(
[self.x.value, self.y.value])]
if numpy.isnan(self.dec.value) or abs... | [
"def",
"_physical_coordinates",
"(",
"self",
")",
":",
"# First, the RA & dec.",
"self",
".",
"ra",
",",
"self",
".",
"dec",
"=",
"[",
"Uncertain",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"imagedata",
".",
"wcs",
".",
"p2s",
"(",
"[",
"self",
"... | [
813,
4
] | [
983,
59
] | python | en | ['en', 'en', 'en'] | True |
Detection.distance_from | (self, x, y) | Distance from center | Distance from center | def distance_from(self, x, y):
"""Distance from center"""
return ((self.x - x)**2 + (self.y - y)**2)**0.5 | [
"def",
"distance_from",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"(",
"(",
"self",
".",
"x",
"-",
"x",
")",
"**",
"2",
"+",
"(",
"self",
".",
"y",
"-",
"y",
")",
"**",
"2",
")",
"**",
"0.5"
] | [
985,
4
] | [
987,
55
] | python | en | ['en', 'en', 'en'] | True |
Detection.serialize | (self, ew_sys_err, ns_sys_err) |
Return source properties suitable for database storage.
We manually add ew_sys_err, ns_sys_err
returns: a list of tuples containing all relevant fields
|
Return source properties suitable for database storage. | def serialize(self, ew_sys_err, ns_sys_err):
"""
Return source properties suitable for database storage.
We manually add ew_sys_err, ns_sys_err
returns: a list of tuples containing all relevant fields
"""
return [
self.ra.value,
self.dec.value,
... | [
"def",
"serialize",
"(",
"self",
",",
"ew_sys_err",
",",
"ns_sys_err",
")",
":",
"return",
"[",
"self",
".",
"ra",
".",
"value",
",",
"self",
".",
"dec",
".",
"value",
",",
"self",
".",
"ra",
".",
"error",
",",
"self",
".",
"dec",
".",
"error",
"... | [
989,
4
] | [
1016,
9
] | python | en | ['en', 'error', 'th'] | False |
test_user_project_paged_list | (get, organization_factory) | Test project listing that spans multiple pages | Test project listing that spans multiple pages | def test_user_project_paged_list(get, organization_factory):
'Test project listing that spans multiple pages'
# 3 total projects, 1 per page, 3 pages
objects = organization_factory(
'org1',
projects=['project-%s' % i for i in range(3)],
users=['alice'],
roles=['project-%s.ad... | [
"def",
"test_user_project_paged_list",
"(",
"get",
",",
"organization_factory",
")",
":",
"# 3 total projects, 1 per page, 3 pages",
"objects",
"=",
"organization_factory",
"(",
"'org1'",
",",
"projects",
"=",
"[",
"'project-%s'",
"%",
"i",
"for",
"i",
"in",
"range",
... | [
40,
0
] | [
75,
34
] | python | en | ['en', 'en', 'en'] | True |
test_user_project_paged_list_with_unicode | (get, organization_factory) | Test project listing that contains unicode chars in the next/prev links | Test project listing that contains unicode chars in the next/prev links | def test_user_project_paged_list_with_unicode(get, organization_factory):
'Test project listing that contains unicode chars in the next/prev links'
# Create 2 projects that contain a "cloud" unicode character, make sure we
# can search it and properly generate next/previous page links
objects = organiz... | [
"def",
"test_user_project_paged_list_with_unicode",
"(",
"get",
",",
"organization_factory",
")",
":",
"# Create 2 projects that contain a \"cloud\" unicode character, make sure we",
"# can search it and properly generate next/previous page links",
"objects",
"=",
"organization_factory",
"... | [
79,
0
] | [
108,
108
] | python | en | ['en', 'en', 'en'] | True |
test_user_project_list | (get, organization_factory) | List of projects a user has access to, filtered by projects you can also see | List of projects a user has access to, filtered by projects you can also see | def test_user_project_list(get, organization_factory):
'List of projects a user has access to, filtered by projects you can also see'
objects = organization_factory(
'org1',
projects=['alice project', 'bob project', 'shared project'],
superusers=['admin'],
users=['alice', 'bob']... | [
"def",
"test_user_project_list",
"(",
"get",
",",
"organization_factory",
")",
":",
"objects",
"=",
"organization_factory",
"(",
"'org1'",
",",
"projects",
"=",
"[",
"'alice project'",
",",
"'bob project'",
",",
"'shared project'",
"]",
",",
"superusers",
"=",
"["... | [
112,
0
] | [
201,
5
] | python | en | ['en', 'en', 'en'] | True |
_match_vcs_scheme | (url) | Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match.
| Look for VCS schemes in the URL. | def _match_vcs_scheme(url):
# type: (str) -> Optional[str]
"""Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match.
"""
for scheme in vcs.schemes:
if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
return scheme
return Non... | [
"def",
"_match_vcs_scheme",
"(",
"url",
")",
":",
"# type: (str) -> Optional[str]",
"for",
"scheme",
"in",
"vcs",
".",
"schemes",
":",
"if",
"url",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"scheme",
")",
"and",
"url",
"[",
"len",
"(",
"scheme",
")... | [
55,
0
] | [
64,
15
] | python | en | ['en', 'en', 'en'] | True |
_ensure_html_header | (response) | Check the Content-Type header to ensure the response contains HTML.
Raises `_NotHTML` if the content type is not text/html.
| Check the Content-Type header to ensure the response contains HTML. | def _ensure_html_header(response):
# type: (Response) -> None
"""Check the Content-Type header to ensure the response contains HTML.
Raises `_NotHTML` if the content type is not text/html.
"""
content_type = response.headers.get("Content-Type", "")
if not content_type.lower().startswith("text/h... | [
"def",
"_ensure_html_header",
"(",
"response",
")",
":",
"# type: (Response) -> None",
"content_type",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"\"Content-Type\"",
",",
"\"\"",
")",
"if",
"not",
"content_type",
".",
"lower",
"(",
")",
".",
"startswith",... | [
75,
0
] | [
83,
61
] | python | en | ['en', 'en', 'en'] | True |
_ensure_html_response | (url, session) | Send a HEAD request to the URL, and ensure the response contains HTML.
Raises `_NotHTTP` if the URL is not available for a HEAD request, or
`_NotHTML` if the content type is not text/html.
| Send a HEAD request to the URL, and ensure the response contains HTML. | def _ensure_html_response(url, session):
# type: (str, PipSession) -> None
"""Send a HEAD request to the URL, and ensure the response contains HTML.
Raises `_NotHTTP` if the URL is not available for a HEAD request, or
`_NotHTML` if the content type is not text/html.
"""
scheme, netloc, path, qu... | [
"def",
"_ensure_html_response",
"(",
"url",
",",
"session",
")",
":",
"# type: (str, PipSession) -> None",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
"=",
"urllib_parse",
".",
"urlsplit",
"(",
"url",
")",
"if",
"scheme",
"not",
"in",
... | [
90,
0
] | [
104,
29
] | python | en | ['en', 'en', 'en'] | True |
_get_html_response | (url, session) | Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large file.
Raise `_NotHTTP` if the content type cannot be determined, or
`_No... | Access an HTML page with GET, and return the response. | def _get_html_response(url, session):
# type: (str, PipSession) -> Response
"""Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large... | [
"def",
"_get_html_response",
"(",
"url",
",",
"session",
")",
":",
"# type: (str, PipSession) -> Response",
"if",
"is_archive_file",
"(",
"Link",
"(",
"url",
")",
".",
"filename",
")",
":",
"_ensure_html_response",
"(",
"url",
",",
"session",
"=",
"session",
")"... | [
107,
0
] | [
155,
15
] | python | en | ['en', 'en', 'en'] | True |
_get_encoding_from_headers | (headers) | Determine if we have any encoding information in our headers.
| Determine if we have any encoding information in our headers.
| def _get_encoding_from_headers(headers):
# type: (ResponseHeaders) -> Optional[str]
"""Determine if we have any encoding information in our headers.
"""
if headers and "Content-Type" in headers:
content_type, params = cgi.parse_header(headers["Content-Type"])
if "charset" in params:
... | [
"def",
"_get_encoding_from_headers",
"(",
"headers",
")",
":",
"# type: (ResponseHeaders) -> Optional[str]",
"if",
"headers",
"and",
"\"Content-Type\"",
"in",
"headers",
":",
"content_type",
",",
"params",
"=",
"cgi",
".",
"parse_header",
"(",
"headers",
"[",
"\"Conte... | [
158,
0
] | [
166,
15
] | python | en | ['en', 'en', 'en'] | True |
_determine_base_url | (document, page_url) | Determine the HTML document's base URL.
This looks for a ``<base>`` tag in the HTML document. If present, its href
attribute denotes the base URL of anchor tags in the document. If there is
no such tag (or if it does not have a valid href attribute), the HTML
file's URL is used as the base URL.
:p... | Determine the HTML document's base URL. | def _determine_base_url(document, page_url):
# type: (HTMLElement, str) -> str
"""Determine the HTML document's base URL.
This looks for a ``<base>`` tag in the HTML document. If present, its href
attribute denotes the base URL of anchor tags in the document. If there is
no such tag (or if it does ... | [
"def",
"_determine_base_url",
"(",
"document",
",",
"page_url",
")",
":",
"# type: (HTMLElement, str) -> str",
"for",
"base",
"in",
"document",
".",
"findall",
"(",
"\".//base\"",
")",
":",
"href",
"=",
"base",
".",
"get",
"(",
"\"href\"",
")",
"if",
"href",
... | [
169,
0
] | [
186,
19
] | python | en | ['en', 'no', 'en'] | True |
_clean_url_path_part | (part) |
Clean a "part" of a URL path (i.e. after splitting on "@" characters).
|
Clean a "part" of a URL path (i.e. after splitting on " | def _clean_url_path_part(part):
# type: (str) -> str
"""
Clean a "part" of a URL path (i.e. after splitting on "@" characters).
"""
# We unquote prior to quoting to make sure nothing is double quoted.
return urllib_parse.quote(urllib_parse.unquote(part)) | [
"def",
"_clean_url_path_part",
"(",
"part",
")",
":",
"# type: (str) -> str",
"# We unquote prior to quoting to make sure nothing is double quoted.",
"return",
"urllib_parse",
".",
"quote",
"(",
"urllib_parse",
".",
"unquote",
"(",
"part",
")",
")"
] | [
189,
0
] | [
195,
57
] | python | en | ['en', 'error', 'th'] | False |
_clean_file_url_path | (part) |
Clean the first part of a URL path that corresponds to a local
filesystem path (i.e. the first part after splitting on "@" characters).
|
Clean the first part of a URL path that corresponds to a local
filesystem path (i.e. the first part after splitting on " | def _clean_file_url_path(part):
# type: (str) -> str
"""
Clean the first part of a URL path that corresponds to a local
filesystem path (i.e. the first part after splitting on "@" characters).
"""
# We unquote prior to quoting to make sure nothing is double quoted.
# Also, on Windows the pat... | [
"def",
"_clean_file_url_path",
"(",
"part",
")",
":",
"# type: (str) -> str",
"# We unquote prior to quoting to make sure nothing is double quoted.",
"# Also, on Windows the path part might contain a drive letter which",
"# should not be quoted. On Linux where drive letters do not",
"# exist, th... | [
198,
0
] | [
209,
73
] | python | en | ['en', 'error', 'th'] | False |
_clean_url_path | (path, is_local_path) |
Clean the path portion of a URL.
|
Clean the path portion of a URL.
| def _clean_url_path(path, is_local_path):
# type: (str, bool) -> str
"""
Clean the path portion of a URL.
"""
if is_local_path:
clean_func = _clean_file_url_path
else:
clean_func = _clean_url_path_part
# Split on the reserved characters prior to cleaning so that
# revisi... | [
"def",
"_clean_url_path",
"(",
"path",
",",
"is_local_path",
")",
":",
"# type: (str, bool) -> str",
"if",
"is_local_path",
":",
"clean_func",
"=",
"_clean_file_url_path",
"else",
":",
"clean_func",
"=",
"_clean_url_path_part",
"# Split on the reserved characters prior to cle... | [
216,
0
] | [
236,
33
] | python | en | ['en', 'error', 'th'] | False |
_clean_link | (url) |
Make sure a link is fully quoted.
For example, if ' ' occurs in the URL, it will be replaced with "%20",
and without double-quoting other characters.
|
Make sure a link is fully quoted.
For example, if ' ' occurs in the URL, it will be replaced with "%20",
and without double-quoting other characters.
| def _clean_link(url):
# type: (str) -> str
"""
Make sure a link is fully quoted.
For example, if ' ' occurs in the URL, it will be replaced with "%20",
and without double-quoting other characters.
"""
# Split the URL into parts according to the general structure
# `scheme://netloc/path;p... | [
"def",
"_clean_link",
"(",
"url",
")",
":",
"# type: (str) -> str",
"# Split the URL into parts according to the general structure",
"# `scheme://netloc/path;parameters?query#fragment`.",
"result",
"=",
"urllib_parse",
".",
"urlparse",
"(",
"url",
")",
"# If the netloc is empty, th... | [
239,
0
] | [
252,
62
] | python | en | ['en', 'error', 'th'] | False |
_create_link_from_element | (
anchor, # type: HTMLElement
page_url, # type: str
base_url, # type: str
) |
Convert an anchor element in a simple repository page to a Link.
|
Convert an anchor element in a simple repository page to a Link.
| def _create_link_from_element(
anchor, # type: HTMLElement
page_url, # type: str
base_url, # type: str
):
# type: (...) -> Optional[Link]
"""
Convert an anchor element in a simple repository page to a Link.
"""
href = anchor.get("href")
if not href:
return None
url ... | [
"def",
"_create_link_from_element",
"(",
"anchor",
",",
"# type: HTMLElement",
"page_url",
",",
"# type: str",
"base_url",
",",
"# type: str",
")",
":",
"# type: (...) -> Optional[Link]",
"href",
"=",
"anchor",
".",
"get",
"(",
"\"href\"",
")",
"if",
"not",
"href",
... | [
255,
0
] | [
284,
15
] | python | en | ['en', 'error', 'th'] | False |
with_cached_html_pages | (
fn, # type: Callable[[HTMLPage], Iterable[Link]]
) |
Given a function that parses an Iterable[Link] from an HTMLPage, cache the
function's result (keyed by CacheablePageContent), unless the HTMLPage
`page` has `page.cache_link_parsing == False`.
|
Given a function that parses an Iterable[Link] from an HTMLPage, cache the
function's result (keyed by CacheablePageContent), unless the HTMLPage
`page` has `page.cache_link_parsing == False`.
| def with_cached_html_pages(
fn, # type: Callable[[HTMLPage], Iterable[Link]]
):
# type: (...) -> Callable[[HTMLPage], List[Link]]
"""
Given a function that parses an Iterable[Link] from an HTMLPage, cache the
function's result (keyed by CacheablePageContent), unless the HTMLPage
`page` has `p... | [
"def",
"with_cached_html_pages",
"(",
"fn",
",",
"# type: Callable[[HTMLPage], Iterable[Link]]",
")",
":",
"# type: (...) -> Callable[[HTMLPage], List[Link]]",
"@",
"lru_cache",
"(",
"maxsize",
"=",
"None",
")",
"def",
"wrapper",
"(",
"cacheable_page",
")",
":",
"# type: ... | [
303,
0
] | [
325,
26
] | python | en | ['en', 'error', 'th'] | False |
parse_links | (page) |
Parse an HTML document, and yield its anchor elements as Link objects.
|
Parse an HTML document, and yield its anchor elements as Link objects.
| def parse_links(page):
# type: (HTMLPage) -> Iterable[Link]
"""
Parse an HTML document, and yield its anchor elements as Link objects.
"""
document = html5lib.parse(
page.content,
transport_encoding=page.encoding,
namespaceHTMLElements=False,
)
url = page.url
bas... | [
"def",
"parse_links",
"(",
"page",
")",
":",
"# type: (HTMLPage) -> Iterable[Link]",
"document",
"=",
"html5lib",
".",
"parse",
"(",
"page",
".",
"content",
",",
"transport_encoding",
"=",
"page",
".",
"encoding",
",",
"namespaceHTMLElements",
"=",
"False",
",",
... | [
329,
0
] | [
350,
18
] | python | en | ['en', 'error', 'th'] | False |
_remove_duplicate_links | (links) |
Return a list of links, with duplicates removed and ordering preserved.
|
Return a list of links, with duplicates removed and ordering preserved.
| def _remove_duplicate_links(links):
# type: (Iterable[Link]) -> List[Link]
"""
Return a list of links, with duplicates removed and ordering preserved.
"""
# We preserve the ordering when removing duplicates because we can.
return list(OrderedDict.fromkeys(links)) | [
"def",
"_remove_duplicate_links",
"(",
"links",
")",
":",
"# type: (Iterable[Link]) -> List[Link]",
"# We preserve the ordering when removing duplicates because we can.",
"return",
"list",
"(",
"OrderedDict",
".",
"fromkeys",
"(",
"links",
")",
")"
] | [
459,
0
] | [
465,
44
] | python | en | ['en', 'error', 'th'] | False |
group_locations | (locations, expand_dir=False) |
Divide a list of locations into two groups: "files" (archives) and "urls."
:return: A pair of lists (files, urls).
|
Divide a list of locations into two groups: "files" (archives) and "urls." | def group_locations(locations, expand_dir=False):
# type: (Sequence[str], bool) -> Tuple[List[str], List[str]]
"""
Divide a list of locations into two groups: "files" (archives) and "urls."
:return: A pair of lists (files, urls).
"""
files = []
urls = []
# puts the url for the given fi... | [
"def",
"group_locations",
"(",
"locations",
",",
"expand_dir",
"=",
"False",
")",
":",
"# type: (Sequence[str], bool) -> Tuple[List[str], List[str]]",
"files",
"=",
"[",
"]",
"urls",
"=",
"[",
"]",
"# puts the url for the given file path into the appropriate list",
"def",
"... | [
468,
0
] | [
524,
22
] | python | en | ['en', 'error', 'th'] | False |
HTMLPage.__init__ | (
self,
content, # type: bytes
encoding, # type: Optional[str]
url, # type: str
cache_link_parsing=True, # type: bool
) |
:param encoding: the encoding to decode the given content.
:param url: the URL from which the HTML was downloaded.
:param cache_link_parsing: whether links parsed from this page's url
should be cached. PyPI index urls should
... |
:param encoding: the encoding to decode the given content.
:param url: the URL from which the HTML was downloaded.
:param cache_link_parsing: whether links parsed from this page's url
should be cached. PyPI index urls should
... | def __init__(
self,
content, # type: bytes
encoding, # type: Optional[str]
url, # type: str
cache_link_parsing=True, # type: bool
):
# type: (...) -> None
"""
:param encoding: the encoding to decod... | [
"def",
"__init__",
"(",
"self",
",",
"content",
",",
"# type: bytes",
"encoding",
",",
"# type: Optional[str]",
"url",
",",
"# type: str",
"cache_link_parsing",
"=",
"True",
",",
"# type: bool",
")",
":",
"# type: (...) -> None",
"self",
".",
"content",
"=",
"cont... | [
356,
4
] | [
374,
52
] | python | en | ['en', 'error', 'th'] | False |
CollectedLinks.__init__ | (
self,
files, # type: List[Link]
find_links, # type: List[Link]
project_urls, # type: List[Link]
) |
:param files: Links from file locations.
:param find_links: Links from find_links.
:param project_urls: URLs to HTML project pages, as described by
the PEP 503 simple repository API.
|
:param files: Links from file locations.
:param find_links: Links from find_links.
:param project_urls: URLs to HTML project pages, as described by
the PEP 503 simple repository API.
| def __init__(
self,
files, # type: List[Link]
find_links, # type: List[Link]
project_urls, # type: List[Link]
):
# type: (...) -> None
"""
:param files: Links from file locations.
:param find_links: Links from find_links.
:param pro... | [
"def",
"__init__",
"(",
"self",
",",
"files",
",",
"# type: List[Link]",
"find_links",
",",
"# type: List[Link]",
"project_urls",
",",
"# type: List[Link]",
")",
":",
"# type: (...) -> None",
"self",
".",
"files",
"=",
"files",
"self",
".",
"find_links",
"=",
"fin... | [
544,
4
] | [
559,
40
] | python | en | ['en', 'error', 'th'] | False |
LinkCollector.create | (cls, session, options, suppress_no_index=False) |
:param session: The Session to use to make requests.
:param suppress_no_index: Whether to ignore the --no-index option
when constructing the SearchScope object.
|
:param session: The Session to use to make requests.
:param suppress_no_index: Whether to ignore the --no-index option
when constructing the SearchScope object.
| def create(cls, session, options, suppress_no_index=False):
# type: (PipSession, Values, bool) -> LinkCollector
"""
:param session: The Session to use to make requests.
:param suppress_no_index: Whether to ignore the --no-index option
when constructing the SearchScope object.... | [
"def",
"create",
"(",
"cls",
",",
"session",
",",
"options",
",",
"suppress_no_index",
"=",
"False",
")",
":",
"# type: (PipSession, Values, bool) -> LinkCollector",
"index_urls",
"=",
"[",
"options",
".",
"index_url",
"]",
"+",
"options",
".",
"extra_index_urls",
... | [
581,
4
] | [
605,
29
] | python | en | ['en', 'error', 'th'] | False |
LinkCollector.fetch_page | (self, location) |
Fetch an HTML page containing package links.
|
Fetch an HTML page containing package links.
| def fetch_page(self, location):
# type: (Link) -> Optional[HTMLPage]
"""
Fetch an HTML page containing package links.
"""
return _get_html_page(location, session=self.session) | [
"def",
"fetch_page",
"(",
"self",
",",
"location",
")",
":",
"# type: (Link) -> Optional[HTMLPage]",
"return",
"_get_html_page",
"(",
"location",
",",
"session",
"=",
"self",
".",
"session",
")"
] | [
612,
4
] | [
617,
61
] | python | en | ['en', 'error', 'th'] | False |
LinkCollector.collect_links | (self, project_name) | Find all available links for the given project name.
:return: All the Link objects (unfiltered), as a CollectedLinks object.
| Find all available links for the given project name. | def collect_links(self, project_name):
# type: (str) -> CollectedLinks
"""Find all available links for the given project name.
:return: All the Link objects (unfiltered), as a CollectedLinks object.
"""
search_scope = self.search_scope
index_locations = search_scope.get_... | [
"def",
"collect_links",
"(",
"self",
",",
"project_name",
")",
":",
"# type: (str) -> CollectedLinks",
"search_scope",
"=",
"self",
".",
"search_scope",
"index_locations",
"=",
"search_scope",
".",
"get_index_urls_locations",
"(",
"project_name",
")",
"index_file_loc",
... | [
619,
4
] | [
666,
9
] | python | en | ['en', 'en', 'en'] | True |
blankout | (src, char) |
Change every non-whitespace character to the given char.
Used in the templatize function.
|
Change every non-whitespace character to the given char.
Used in the templatize function.
| def blankout(src, char):
"""
Change every non-whitespace character to the given char.
Used in the templatize function.
"""
return dot_re.sub(char, src) | [
"def",
"blankout",
"(",
"src",
",",
"char",
")",
":",
"return",
"dot_re",
".",
"sub",
"(",
"char",
",",
"src",
")"
] | [
18,
0
] | [
23,
32
] | python | en | ['en', 'error', 'th'] | False |
templatize | (src, origin=None, charset='utf-8') |
Turn a Django template into something that is understood by xgettext. It
does so by translating the Django translation tags into standard gettext
function invocations.
|
Turn a Django template into something that is understood by xgettext. It
does so by translating the Django translation tags into standard gettext
function invocations.
| def templatize(src, origin=None, charset='utf-8'):
"""
Turn a Django template into something that is understood by xgettext. It
does so by translating the Django translation tags into standard gettext
function invocations.
"""
src = force_text(src, charset)
out = StringIO('')
message_con... | [
"def",
"templatize",
"(",
"src",
",",
"origin",
"=",
"None",
",",
"charset",
"=",
"'utf-8'",
")",
":",
"src",
"=",
"force_text",
"(",
"src",
",",
"charset",
")",
"out",
"=",
"StringIO",
"(",
"''",
")",
"message_context",
"=",
"None",
"intrans",
"=",
... | [
41,
0
] | [
235,
25
] | python | en | ['en', 'error', 'th'] | False |
lookup | (code, _cache={}) | Lookup an error code or class code and return its symbolic name.
Raise `KeyError` if the code is not found.
| Lookup an error code or class code and return its symbolic name. | def lookup(code, _cache={}):
"""Lookup an error code or class code and return its symbolic name.
Raise `KeyError` if the code is not found.
"""
if _cache:
return _cache[code]
# Generate the lookup map at first usage.
tmp = {}
for k, v in globals().items():
if isinstance(v, ... | [
"def",
"lookup",
"(",
"code",
",",
"_cache",
"=",
"{",
"}",
")",
":",
"if",
"_cache",
":",
"return",
"_cache",
"[",
"code",
"]",
"# Generate the lookup map at first usage.",
"tmp",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"globals",
"(",
")",
".",
... | [
32,
0
] | [
51,
23
] | python | en | ['en', 'en', 'en'] | True |
BaseAPIViewSet.find_object | (self, queryset, request) |
Override this to implement more find methods.
|
Override this to implement more find methods.
| def find_object(self, queryset, request):
"""
Override this to implement more find methods.
"""
if 'id' in request.GET:
return queryset.get(id=request.GET['id']) | [
"def",
"find_object",
"(",
"self",
",",
"queryset",
",",
"request",
")",
":",
"if",
"'id'",
"in",
"request",
".",
"GET",
":",
"return",
"queryset",
".",
"get",
"(",
"id",
"=",
"request",
".",
"GET",
"[",
"'id'",
"]",
")"
] | [
100,
4
] | [
105,
53
] | python | en | ['en', 'error', 'th'] | False |
BaseAPIViewSet.get_available_fields | (cls, model, db_fields_only=False) |
Returns a list of all the fields that can be used in the API for the
specified model class.
Setting db_fields_only to True will remove all fields that do not have
an underlying column in the database (eg, type/detail_url and any custom
fields that are callables)
|
Returns a list of all the fields that can be used in the API for the
specified model class. | def get_available_fields(cls, model, db_fields_only=False):
"""
Returns a list of all the fields that can be used in the API for the
specified model class.
Setting db_fields_only to True will remove all fields that do not have
an underlying column in the database (eg, type/detai... | [
"def",
"get_available_fields",
"(",
"cls",
",",
"model",
",",
"db_fields_only",
"=",
"False",
")",
":",
"fields",
"=",
"cls",
".",
"get_body_fields_names",
"(",
"model",
")",
"+",
"cls",
".",
"get_meta_fields_names",
"(",
"model",
")",
"if",
"db_fields_only",
... | [
144,
4
] | [
167,
21
] | python | en | ['en', 'error', 'th'] | False |
BaseAPIViewSet.check_query_parameters | (self, queryset) |
Ensure that only valid query parameters are included in the URL.
|
Ensure that only valid query parameters are included in the URL.
| def check_query_parameters(self, queryset):
"""
Ensure that only valid query parameters are included in the URL.
"""
query_parameters = set(self.request.GET.keys())
# All query parameters must be either a database field or an operation
allowed_query_parameters = set(self... | [
"def",
"check_query_parameters",
"(",
"self",
",",
"queryset",
")",
":",
"query_parameters",
"=",
"set",
"(",
"self",
".",
"request",
".",
"GET",
".",
"keys",
"(",
")",
")",
"# All query parameters must be either a database field or an operation",
"allowed_query_paramet... | [
181,
4
] | [
191,
138
] | python | en | ['en', 'error', 'th'] | False |
BaseAPIViewSet.get_serializer_context | (self) |
The serialization context differs between listing and detail views.
|
The serialization context differs between listing and detail views.
| def get_serializer_context(self):
"""
The serialization context differs between listing and detail views.
"""
return {
'request': self.request,
'view': self,
'router': self.request.wagtailapi_router
} | [
"def",
"get_serializer_context",
"(",
"self",
")",
":",
"return",
"{",
"'request'",
":",
"self",
".",
"request",
",",
"'view'",
":",
"self",
",",
"'router'",
":",
"self",
".",
"request",
".",
"wagtailapi_router",
"}"
] | [
318,
4
] | [
326,
9
] | python | en | ['en', 'error', 'th'] | False |
BaseAPIViewSet.get_urlpatterns | (cls) |
This returns a list of URL patterns for the endpoint
|
This returns a list of URL patterns for the endpoint
| def get_urlpatterns(cls):
"""
This returns a list of URL patterns for the endpoint
"""
return [
path('', cls.as_view({'get': 'listing_view'}), name='listing'),
path('<int:pk>/', cls.as_view({'get': 'detail_view'}), name='detail'),
path('find/', cls.as_... | [
"def",
"get_urlpatterns",
"(",
"cls",
")",
":",
"return",
"[",
"path",
"(",
"''",
",",
"cls",
".",
"as_view",
"(",
"{",
"'get'",
":",
"'listing_view'",
"}",
")",
",",
"name",
"=",
"'listing'",
")",
",",
"path",
"(",
"'<int:pk>/'",
",",
"cls",
".",
... | [
334,
4
] | [
342,
9
] | python | en | ['en', 'error', 'th'] | False |
PagesAPIViewSet.get_root_page | (self) |
Returns the page that is used when the `&child_of=root` filter is used.
|
Returns the page that is used when the `&child_of=root` filter is used.
| def get_root_page(self):
"""
Returns the page that is used when the `&child_of=root` filter is used.
"""
return Site.find_for_request(self.request).root_page | [
"def",
"get_root_page",
"(",
"self",
")",
":",
"return",
"Site",
".",
"find_for_request",
"(",
"self",
".",
"request",
")",
".",
"root_page"
] | [
429,
4
] | [
433,
60
] | python | en | ['en', 'error', 'th'] | False |
PagesAPIViewSet.get_base_queryset | (self) |
Returns a queryset containing all pages that can be seen by this user.
This is used as the base for get_queryset and is also used to find the
parent pages when using the child_of and descendant_of filters as well.
|
Returns a queryset containing all pages that can be seen by this user. | def get_base_queryset(self):
"""
Returns a queryset containing all pages that can be seen by this user.
This is used as the base for get_queryset and is also used to find the
parent pages when using the child_of and descendant_of filters as well.
"""
# Get live pages tha... | [
"def",
"get_base_queryset",
"(",
"self",
")",
":",
"# Get live pages that are not in a private section",
"queryset",
"=",
"Page",
".",
"objects",
".",
"all",
"(",
")",
".",
"public",
"(",
")",
".",
"live",
"(",
")",
"# Filter by site",
"site",
"=",
"Site",
"."... | [
435,
4
] | [
460,
23
] | python | en | ['en', 'error', 'th'] | False |
PagesAPIViewSet.get_serializer_context | (self) |
The serialization context differs between listing and detail views.
|
The serialization context differs between listing and detail views.
| def get_serializer_context(self):
"""
The serialization context differs between listing and detail views.
"""
context = super().get_serializer_context()
context['base_queryset'] = self.get_base_queryset()
return context | [
"def",
"get_serializer_context",
"(",
"self",
")",
":",
"context",
"=",
"super",
"(",
")",
".",
"get_serializer_context",
"(",
")",
"context",
"[",
"'base_queryset'",
"]",
"=",
"self",
".",
"get_base_queryset",
"(",
")",
"return",
"context"
] | [
502,
4
] | [
508,
22
] | python | en | ['en', 'error', 'th'] | False |
backport_makefile | (
self, mode="r", buffering=None, encoding=None, errors=None, newline=None
) |
Backport of ``socket.makefile`` from Python 3.5.
|
Backport of ``socket.makefile`` from Python 3.5.
| def backport_makefile(
self, mode="r", buffering=None, encoding=None, errors=None, newline=None
):
"""
Backport of ``socket.makefile`` from Python 3.5.
"""
if not set(mode) <= {"r", "w", "b"}:
raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
writing = "w" in mode
... | [
"def",
"backport_makefile",
"(",
"self",
",",
"mode",
"=",
"\"r\"",
",",
"buffering",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"if",
"not",
"set",
"(",
"mode",
")",
"<=",
"{",
"\"... | [
12,
0
] | [
50,
15
] | python | en | ['en', 'error', 'th'] | False |
HostManager.active_count | (self) | Return count of active, unique hosts for licensing.
Construction of query involves:
- remove any ordering specified in model's Meta
- Exclude hosts sourced from another Tower
- Restrict the query to only return the name column
- Only consider results that are unique
... | Return count of active, unique hosts for licensing.
Construction of query involves:
- remove any ordering specified in model's Meta
- Exclude hosts sourced from another Tower
- Restrict the query to only return the name column
- Only consider results that are unique
... | def active_count(self):
"""Return count of active, unique hosts for licensing.
Construction of query involves:
- remove any ordering specified in model's Meta
- Exclude hosts sourced from another Tower
- Restrict the query to only return the name column
- Only conside... | [
"def",
"active_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"order_by",
"(",
")",
".",
"exclude",
"(",
"inventory_sources__source",
"=",
"'controller'",
")",
".",
"values",
"(",
"'name'",
")",
".",
"distinct",
"(",
")",
".",
"count",
"(",
")"
] | [
27,
4
] | [
36,
112
] | python | en | ['en', 'en', 'en'] | True |
HostManager.org_active_count | (self, org_id) | Return count of active, unique hosts used by an organization.
Construction of query involves:
- remove any ordering specified in model's Meta
- Exclude hosts sourced from another Tower
- Consider only hosts where the canonical inventory is owned by the organization
- Restrict... | Return count of active, unique hosts used by an organization.
Construction of query involves:
- remove any ordering specified in model's Meta
- Exclude hosts sourced from another Tower
- Consider only hosts where the canonical inventory is owned by the organization
- Restrict... | def org_active_count(self, org_id):
"""Return count of active, unique hosts used by an organization.
Construction of query involves:
- remove any ordering specified in model's Meta
- Exclude hosts sourced from another Tower
- Consider only hosts where the canonical inventory i... | [
"def",
"org_active_count",
"(",
"self",
",",
"org_id",
")",
":",
"return",
"self",
".",
"order_by",
"(",
")",
".",
"exclude",
"(",
"inventory_sources__source",
"=",
"'controller'",
")",
".",
"filter",
"(",
"inventory__organization",
"=",
"org_id",
")",
".",
... | [
38,
4
] | [
48,
151
] | python | en | ['en', 'en', 'en'] | True |
HostManager.get_queryset | (self) | When the parent instance of the host query set has a `kind=smart` and a `host_filter`
set. Use the `host_filter` to generate the queryset for the hosts.
| When the parent instance of the host query set has a `kind=smart` and a `host_filter`
set. Use the `host_filter` to generate the queryset for the hosts.
| def get_queryset(self):
"""When the parent instance of the host query set has a `kind=smart` and a `host_filter`
set. Use the `host_filter` to generate the queryset for the hosts.
"""
qs = (
super(HostManager, self)
.get_queryset()
.defer(
... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"(",
"super",
"(",
"HostManager",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
".",
"defer",
"(",
"'last_job__extra_vars'",
",",
"'last_job_host_summary__job__extra_vars'",
",",
"'last_job__artifacts'",
... | [
50,
4
] | [
80,
17
] | python | en | ['en', 'en', 'en'] | True |
InstanceManager.me | (self) | Return the currently active instance. | Return the currently active instance. | def me(self):
"""Return the currently active instance."""
# If we are running unit tests, return a stub record.
if settings.IS_TESTING(sys.argv) or hasattr(sys, '_called_from_test'):
return self.model(id=1, hostname=settings.CLUSTER_HOST_ID, uuid='00000000-0000-0000-0000-000000000000... | [
"def",
"me",
"(",
"self",
")",
":",
"# If we are running unit tests, return a stub record.",
"if",
"settings",
".",
"IS_TESTING",
"(",
"sys",
".",
"argv",
")",
"or",
"hasattr",
"(",
"sys",
",",
"'_called_from_test'",
")",
":",
"return",
"self",
".",
"model",
"... | [
103,
4
] | [
112,
80
] | python | en | ['en', 'en', 'en'] | True |
InstanceManager.active_count | (self) | Return count of active Tower nodes for licensing. | Return count of active Tower nodes for licensing. | def active_count(self):
"""Return count of active Tower nodes for licensing."""
return self.all().count() | [
"def",
"active_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"all",
"(",
")",
".",
"count",
"(",
")"
] | [
173,
4
] | [
175,
33
] | python | en | ['en', 'en', 'en'] | True |
InstanceGroupManager.capacity_mapping | (self, qs=None) |
Another entry-point to Instance manager method by same name
|
Another entry-point to Instance manager method by same name
| def capacity_mapping(self, qs=None):
"""
Another entry-point to Instance manager method by same name
"""
if qs is None:
qs = self.all().prefetch_related('instances')
instance_ig_mapping = {}
ig_instance_mapping = {}
# Create dictionaries that represent... | [
"def",
"capacity_mapping",
"(",
"self",
",",
"qs",
"=",
"None",
")",
":",
"if",
"qs",
"is",
"None",
":",
"qs",
"=",
"self",
".",
"all",
"(",
")",
".",
"prefetch_related",
"(",
"'instances'",
")",
"instance_ig_mapping",
"=",
"{",
"}",
"ig_instance_mapping... | [
184,
4
] | [
203,
49
] | python | en | ['en', 'error', 'th'] | False |
InstanceGroupManager.capacity_values | (self, qs=None, tasks=None, breakdown=False, graph=None) |
Returns a dictionary of capacity values for all IGs
|
Returns a dictionary of capacity values for all IGs
| def capacity_values(self, qs=None, tasks=None, breakdown=False, graph=None):
"""
Returns a dictionary of capacity values for all IGs
"""
if qs is None: # Optionally BYOQS - bring your own queryset
qs = self.all().prefetch_related('instances')
instance_ig_mapping, ig_... | [
"def",
"capacity_values",
"(",
"self",
",",
"qs",
"=",
"None",
",",
"tasks",
"=",
"None",
",",
"breakdown",
"=",
"False",
",",
"graph",
"=",
"None",
")",
":",
"if",
"qs",
"is",
"None",
":",
"# Optionally BYOQS - bring your own queryset",
"qs",
"=",
"self",... | [
216,
4
] | [
272,
20
] | python | en | ['en', 'error', 'th'] | False |
openapi_test_function | (endpoint: str) | This decorator is used to register an OpenAPI test function with
its endpoint. Example usage:
@openapi_test_function("/messages/render:post")
def ...
| This decorator is used to register an OpenAPI test function with
its endpoint. Example usage: | def openapi_test_function(endpoint: str) -> Callable[[FuncT], FuncT]:
"""This decorator is used to register an OpenAPI test function with
its endpoint. Example usage:
@openapi_test_function("/messages/render:post")
def ...
"""
def wrapper(test_func: FuncT) -> FuncT:
@wraps(test_func)
... | [
"def",
"openapi_test_function",
"(",
"endpoint",
":",
"str",
")",
"->",
"Callable",
"[",
"[",
"FuncT",
"]",
",",
"FuncT",
"]",
":",
"def",
"wrapper",
"(",
"test_func",
":",
"FuncT",
")",
"->",
"FuncT",
":",
"@",
"wraps",
"(",
"test_func",
")",
"def",
... | [
35,
0
] | [
54,
18
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.