id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,800 | BlueBrain/NeuroM | examples/radius_of_gyration.py | neurite_centre_of_mass | def neurite_centre_of_mass(neurite):
'''Calculate and return centre of mass of a neurite.'''
centre_of_mass = np.zeros(3)
total_volume = 0
seg_vol = np.array(map(mm.segment_volume, nm.iter_segments(neurite)))
seg_centre_of_mass = np.array(map(segment_centre_of_mass, nm.iter_segments(neurite)))
# multiply array of scalars with array of arrays
# http://stackoverflow.com/questions/5795700/multiply-numpy-array-of-scalars-by-array-of-vectors
seg_centre_of_mass = seg_centre_of_mass * seg_vol[:, np.newaxis]
centre_of_mass = np.sum(seg_centre_of_mass, axis=0)
total_volume = np.sum(seg_vol)
return centre_of_mass / total_volume | python | def neurite_centre_of_mass(neurite):
'''Calculate and return centre of mass of a neurite.'''
centre_of_mass = np.zeros(3)
total_volume = 0
seg_vol = np.array(map(mm.segment_volume, nm.iter_segments(neurite)))
seg_centre_of_mass = np.array(map(segment_centre_of_mass, nm.iter_segments(neurite)))
# multiply array of scalars with array of arrays
# http://stackoverflow.com/questions/5795700/multiply-numpy-array-of-scalars-by-array-of-vectors
seg_centre_of_mass = seg_centre_of_mass * seg_vol[:, np.newaxis]
centre_of_mass = np.sum(seg_centre_of_mass, axis=0)
total_volume = np.sum(seg_vol)
return centre_of_mass / total_volume | [
"def",
"neurite_centre_of_mass",
"(",
"neurite",
")",
":",
"centre_of_mass",
"=",
"np",
".",
"zeros",
"(",
"3",
")",
"total_volume",
"=",
"0",
"seg_vol",
"=",
"np",
".",
"array",
"(",
"map",
"(",
"mm",
".",
"segment_volume",
",",
"nm",
".",
"iter_segments",
"(",
"neurite",
")",
")",
")",
"seg_centre_of_mass",
"=",
"np",
".",
"array",
"(",
"map",
"(",
"segment_centre_of_mass",
",",
"nm",
".",
"iter_segments",
"(",
"neurite",
")",
")",
")",
"# multiply array of scalars with array of arrays",
"# http://stackoverflow.com/questions/5795700/multiply-numpy-array-of-scalars-by-array-of-vectors",
"seg_centre_of_mass",
"=",
"seg_centre_of_mass",
"*",
"seg_vol",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"centre_of_mass",
"=",
"np",
".",
"sum",
"(",
"seg_centre_of_mass",
",",
"axis",
"=",
"0",
")",
"total_volume",
"=",
"np",
".",
"sum",
"(",
"seg_vol",
")",
"return",
"centre_of_mass",
"/",
"total_volume"
] | Calculate and return centre of mass of a neurite. | [
"Calculate",
"and",
"return",
"centre",
"of",
"mass",
"of",
"a",
"neurite",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/radius_of_gyration.py#L51-L64 |
2,801 | BlueBrain/NeuroM | examples/radius_of_gyration.py | distance_sqr | def distance_sqr(point, seg):
'''Calculate and return square Euclidian distance from given point to
centre of mass of given segment.'''
centre_of_mass = segment_centre_of_mass(seg)
return sum(pow(np.subtract(point, centre_of_mass), 2)) | python | def distance_sqr(point, seg):
'''Calculate and return square Euclidian distance from given point to
centre of mass of given segment.'''
centre_of_mass = segment_centre_of_mass(seg)
return sum(pow(np.subtract(point, centre_of_mass), 2)) | [
"def",
"distance_sqr",
"(",
"point",
",",
"seg",
")",
":",
"centre_of_mass",
"=",
"segment_centre_of_mass",
"(",
"seg",
")",
"return",
"sum",
"(",
"pow",
"(",
"np",
".",
"subtract",
"(",
"point",
",",
"centre_of_mass",
")",
",",
"2",
")",
")"
] | Calculate and return square Euclidian distance from given point to
centre of mass of given segment. | [
"Calculate",
"and",
"return",
"square",
"Euclidian",
"distance",
"from",
"given",
"point",
"to",
"centre",
"of",
"mass",
"of",
"given",
"segment",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/radius_of_gyration.py#L67-L71 |
2,802 | BlueBrain/NeuroM | examples/radius_of_gyration.py | radius_of_gyration | def radius_of_gyration(neurite):
'''Calculate and return radius of gyration of a given neurite.'''
centre_mass = neurite_centre_of_mass(neurite)
sum_sqr_distance = 0
N = 0
dist_sqr = [distance_sqr(centre_mass, s) for s in nm.iter_segments(neurite)]
sum_sqr_distance = np.sum(dist_sqr)
N = len(dist_sqr)
return np.sqrt(sum_sqr_distance / N) | python | def radius_of_gyration(neurite):
'''Calculate and return radius of gyration of a given neurite.'''
centre_mass = neurite_centre_of_mass(neurite)
sum_sqr_distance = 0
N = 0
dist_sqr = [distance_sqr(centre_mass, s) for s in nm.iter_segments(neurite)]
sum_sqr_distance = np.sum(dist_sqr)
N = len(dist_sqr)
return np.sqrt(sum_sqr_distance / N) | [
"def",
"radius_of_gyration",
"(",
"neurite",
")",
":",
"centre_mass",
"=",
"neurite_centre_of_mass",
"(",
"neurite",
")",
"sum_sqr_distance",
"=",
"0",
"N",
"=",
"0",
"dist_sqr",
"=",
"[",
"distance_sqr",
"(",
"centre_mass",
",",
"s",
")",
"for",
"s",
"in",
"nm",
".",
"iter_segments",
"(",
"neurite",
")",
"]",
"sum_sqr_distance",
"=",
"np",
".",
"sum",
"(",
"dist_sqr",
")",
"N",
"=",
"len",
"(",
"dist_sqr",
")",
"return",
"np",
".",
"sqrt",
"(",
"sum_sqr_distance",
"/",
"N",
")"
] | Calculate and return radius of gyration of a given neurite. | [
"Calculate",
"and",
"return",
"radius",
"of",
"gyration",
"of",
"a",
"given",
"neurite",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/radius_of_gyration.py#L74-L82 |
2,803 | BlueBrain/NeuroM | apps/__main__.py | view | def view(input_file, plane, backend):
'''A simple neuron viewer'''
if backend == 'matplotlib':
from neurom.viewer import draw
kwargs = {
'mode': '3d' if plane == '3d' else '2d',
}
if plane != '3d':
kwargs['plane'] = plane
draw(load_neuron(input_file), **kwargs)
else:
from neurom.view.plotly import draw
draw(load_neuron(input_file), plane=plane)
if backend == 'matplotlib':
import matplotlib.pyplot as plt
plt.show() | python | def view(input_file, plane, backend):
'''A simple neuron viewer'''
if backend == 'matplotlib':
from neurom.viewer import draw
kwargs = {
'mode': '3d' if plane == '3d' else '2d',
}
if plane != '3d':
kwargs['plane'] = plane
draw(load_neuron(input_file), **kwargs)
else:
from neurom.view.plotly import draw
draw(load_neuron(input_file), plane=plane)
if backend == 'matplotlib':
import matplotlib.pyplot as plt
plt.show() | [
"def",
"view",
"(",
"input_file",
",",
"plane",
",",
"backend",
")",
":",
"if",
"backend",
"==",
"'matplotlib'",
":",
"from",
"neurom",
".",
"viewer",
"import",
"draw",
"kwargs",
"=",
"{",
"'mode'",
":",
"'3d'",
"if",
"plane",
"==",
"'3d'",
"else",
"'2d'",
",",
"}",
"if",
"plane",
"!=",
"'3d'",
":",
"kwargs",
"[",
"'plane'",
"]",
"=",
"plane",
"draw",
"(",
"load_neuron",
"(",
"input_file",
")",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"from",
"neurom",
".",
"view",
".",
"plotly",
"import",
"draw",
"draw",
"(",
"load_neuron",
"(",
"input_file",
")",
",",
"plane",
"=",
"plane",
")",
"if",
"backend",
"==",
"'matplotlib'",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"plt",
".",
"show",
"(",
")"
] | A simple neuron viewer | [
"A",
"simple",
"neuron",
"viewer"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/apps/__main__.py#L23-L39 |
2,804 | BlueBrain/NeuroM | neurom/apps/annotate.py | generate_annotation | def generate_annotation(result, settings):
'''Generate the annotation for a given checker
Arguments
neuron(Neuron): The neuron object
checker: A tuple where the first item is the checking function (usually from neuron_checks)
and the second item is a dictionary of settings for the annotation. It must
contain the keys name, label and color
Returns
An S-expression-like string representing the annotation
'''
if result.status:
return ""
header = ("\n\n"
"({label} ; MUK_ANNOTATION\n"
" (Color {color}) ; MUK_ANNOTATION\n"
" (Name \"{name}\") ; MUK_ANNOTATION").format(**settings)
points = [p for _, _points in result.info for p in _points]
annotations = (" ({0} {1} {2} 0.50) ; MUK_ANNOTATION".format(
p[COLS.X], p[COLS.Y], p[COLS.Z]) for p in points)
footer = ") ; MUK_ANNOTATION\n"
return '\n'.join(chain.from_iterable(([header], annotations, [footer]))) | python | def generate_annotation(result, settings):
'''Generate the annotation for a given checker
Arguments
neuron(Neuron): The neuron object
checker: A tuple where the first item is the checking function (usually from neuron_checks)
and the second item is a dictionary of settings for the annotation. It must
contain the keys name, label and color
Returns
An S-expression-like string representing the annotation
'''
if result.status:
return ""
header = ("\n\n"
"({label} ; MUK_ANNOTATION\n"
" (Color {color}) ; MUK_ANNOTATION\n"
" (Name \"{name}\") ; MUK_ANNOTATION").format(**settings)
points = [p for _, _points in result.info for p in _points]
annotations = (" ({0} {1} {2} 0.50) ; MUK_ANNOTATION".format(
p[COLS.X], p[COLS.Y], p[COLS.Z]) for p in points)
footer = ") ; MUK_ANNOTATION\n"
return '\n'.join(chain.from_iterable(([header], annotations, [footer]))) | [
"def",
"generate_annotation",
"(",
"result",
",",
"settings",
")",
":",
"if",
"result",
".",
"status",
":",
"return",
"\"\"",
"header",
"=",
"(",
"\"\\n\\n\"",
"\"({label} ; MUK_ANNOTATION\\n\"",
"\" (Color {color}) ; MUK_ANNOTATION\\n\"",
"\" (Name \\\"{name}\\\") ; MUK_ANNOTATION\"",
")",
".",
"format",
"(",
"*",
"*",
"settings",
")",
"points",
"=",
"[",
"p",
"for",
"_",
",",
"_points",
"in",
"result",
".",
"info",
"for",
"p",
"in",
"_points",
"]",
"annotations",
"=",
"(",
"\" ({0} {1} {2} 0.50) ; MUK_ANNOTATION\"",
".",
"format",
"(",
"p",
"[",
"COLS",
".",
"X",
"]",
",",
"p",
"[",
"COLS",
".",
"Y",
"]",
",",
"p",
"[",
"COLS",
".",
"Z",
"]",
")",
"for",
"p",
"in",
"points",
")",
"footer",
"=",
"\") ; MUK_ANNOTATION\\n\"",
"return",
"'\\n'",
".",
"join",
"(",
"chain",
".",
"from_iterable",
"(",
"(",
"[",
"header",
"]",
",",
"annotations",
",",
"[",
"footer",
"]",
")",
")",
")"
] | Generate the annotation for a given checker
Arguments
neuron(Neuron): The neuron object
checker: A tuple where the first item is the checking function (usually from neuron_checks)
and the second item is a dictionary of settings for the annotation. It must
contain the keys name, label and color
Returns
An S-expression-like string representing the annotation | [
"Generate",
"the",
"annotation",
"for",
"a",
"given",
"checker"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/apps/annotate.py#L37-L62 |
2,805 | BlueBrain/NeuroM | neurom/apps/annotate.py | annotate | def annotate(results, settings):
'''Concatenate the annotations of all checkers'''
annotations = (generate_annotation(result, setting)
for result, setting in zip(results, settings))
return '\n'.join(annot for annot in annotations if annot) | python | def annotate(results, settings):
'''Concatenate the annotations of all checkers'''
annotations = (generate_annotation(result, setting)
for result, setting in zip(results, settings))
return '\n'.join(annot for annot in annotations if annot) | [
"def",
"annotate",
"(",
"results",
",",
"settings",
")",
":",
"annotations",
"=",
"(",
"generate_annotation",
"(",
"result",
",",
"setting",
")",
"for",
"result",
",",
"setting",
"in",
"zip",
"(",
"results",
",",
"settings",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"annot",
"for",
"annot",
"in",
"annotations",
"if",
"annot",
")"
] | Concatenate the annotations of all checkers | [
"Concatenate",
"the",
"annotations",
"of",
"all",
"checkers"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/apps/annotate.py#L65-L69 |
2,806 | BlueBrain/NeuroM | neurom/core/point.py | as_point | def as_point(row):
'''Create a Point from a data block row'''
return Point(row[COLS.X], row[COLS.Y], row[COLS.Z],
row[COLS.R], int(row[COLS.TYPE])) | python | def as_point(row):
'''Create a Point from a data block row'''
return Point(row[COLS.X], row[COLS.Y], row[COLS.Z],
row[COLS.R], int(row[COLS.TYPE])) | [
"def",
"as_point",
"(",
"row",
")",
":",
"return",
"Point",
"(",
"row",
"[",
"COLS",
".",
"X",
"]",
",",
"row",
"[",
"COLS",
".",
"Y",
"]",
",",
"row",
"[",
"COLS",
".",
"Z",
"]",
",",
"row",
"[",
"COLS",
".",
"R",
"]",
",",
"int",
"(",
"row",
"[",
"COLS",
".",
"TYPE",
"]",
")",
")"
] | Create a Point from a data block row | [
"Create",
"a",
"Point",
"from",
"a",
"data",
"block",
"row"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/point.py#L38-L41 |
2,807 | jambonsw/django-improved-user | src/improved_user/managers.py | UserManager.create_superuser | def create_superuser(self, email, password, **extra_fields):
"""Save new User with is_staff and is_superuser set to True"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields) | python | def create_superuser(self, email, password, **extra_fields):
"""Save new User with is_staff and is_superuser set to True"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields) | [
"def",
"create_superuser",
"(",
"self",
",",
"email",
",",
"password",
",",
"*",
"*",
"extra_fields",
")",
":",
"extra_fields",
".",
"setdefault",
"(",
"'is_staff'",
",",
"True",
")",
"extra_fields",
".",
"setdefault",
"(",
"'is_superuser'",
",",
"True",
")",
"if",
"extra_fields",
".",
"get",
"(",
"'is_staff'",
")",
"is",
"not",
"True",
":",
"raise",
"ValueError",
"(",
"'Superuser must have is_staff=True.'",
")",
"if",
"extra_fields",
".",
"get",
"(",
"'is_superuser'",
")",
"is",
"not",
"True",
":",
"raise",
"ValueError",
"(",
"'Superuser must have is_superuser=True.'",
")",
"return",
"self",
".",
"_create_user",
"(",
"email",
",",
"password",
",",
"*",
"*",
"extra_fields",
")"
] | Save new User with is_staff and is_superuser set to True | [
"Save",
"new",
"User",
"with",
"is_staff",
"and",
"is_superuser",
"set",
"to",
"True"
] | e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4 | https://github.com/jambonsw/django-improved-user/blob/e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4/src/improved_user/managers.py#L43-L51 |
2,808 | jambonsw/django-improved-user | setup.py | load_file_contents | def load_file_contents(file_path, as_list=True):
"""Load file as string or list"""
abs_file_path = join(HERE, file_path)
with open(abs_file_path, encoding='utf-8') as file_pointer:
if as_list:
return file_pointer.read().splitlines()
return file_pointer.read() | python | def load_file_contents(file_path, as_list=True):
"""Load file as string or list"""
abs_file_path = join(HERE, file_path)
with open(abs_file_path, encoding='utf-8') as file_pointer:
if as_list:
return file_pointer.read().splitlines()
return file_pointer.read() | [
"def",
"load_file_contents",
"(",
"file_path",
",",
"as_list",
"=",
"True",
")",
":",
"abs_file_path",
"=",
"join",
"(",
"HERE",
",",
"file_path",
")",
"with",
"open",
"(",
"abs_file_path",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"file_pointer",
":",
"if",
"as_list",
":",
"return",
"file_pointer",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"return",
"file_pointer",
".",
"read",
"(",
")"
] | Load file as string or list | [
"Load",
"file",
"as",
"string",
"or",
"list"
] | e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4 | https://github.com/jambonsw/django-improved-user/blob/e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4/setup.py#L22-L28 |
2,809 | jambonsw/django-improved-user | src/improved_user/forms.py | AbstractUserCreationForm.clean_password2 | def clean_password2(self):
"""
Check wether password 1 and password 2 are equivalent
While ideally this would be done in clean, there is a chance a
superclass could declare clean and forget to call super. We
therefore opt to run this password mismatch check in password2
clean, but to show the error above password1 (as we are unsure
whether password 1 or password 2 contains the typo, and putting
it above password 2 may lead some users to believe the typo is
in just one).
"""
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
self.add_error(
'password1',
forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
))
return password2 | python | def clean_password2(self):
"""
Check wether password 1 and password 2 are equivalent
While ideally this would be done in clean, there is a chance a
superclass could declare clean and forget to call super. We
therefore opt to run this password mismatch check in password2
clean, but to show the error above password1 (as we are unsure
whether password 1 or password 2 contains the typo, and putting
it above password 2 may lead some users to believe the typo is
in just one).
"""
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
self.add_error(
'password1',
forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
))
return password2 | [
"def",
"clean_password2",
"(",
"self",
")",
":",
"password1",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'password1'",
")",
"password2",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'password2'",
")",
"if",
"password1",
"and",
"password2",
"and",
"password1",
"!=",
"password2",
":",
"self",
".",
"add_error",
"(",
"'password1'",
",",
"forms",
".",
"ValidationError",
"(",
"self",
".",
"error_messages",
"[",
"'password_mismatch'",
"]",
",",
"code",
"=",
"'password_mismatch'",
",",
")",
")",
"return",
"password2"
] | Check wether password 1 and password 2 are equivalent
While ideally this would be done in clean, there is a chance a
superclass could declare clean and forget to call super. We
therefore opt to run this password mismatch check in password2
clean, but to show the error above password1 (as we are unsure
whether password 1 or password 2 contains the typo, and putting
it above password 2 may lead some users to believe the typo is
in just one). | [
"Check",
"wether",
"password",
"1",
"and",
"password",
"2",
"are",
"equivalent"
] | e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4 | https://github.com/jambonsw/django-improved-user/blob/e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4/src/improved_user/forms.py#L62-L84 |
2,810 | jambonsw/django-improved-user | src/improved_user/forms.py | AbstractUserCreationForm._post_clean | def _post_clean(self):
"""Run password validaton after clean methods
When clean methods are run, the user instance does not yet
exist. To properly compare model values agains the password (in
the UserAttributeSimilarityValidator), we wait until we have an
instance to compare against.
https://code.djangoproject.com/ticket/28127
https://github.com/django/django/pull/8408
Has no effect in Django prior to 1.9
May become unnecessary in Django 2.0 (if this superclass changes)
"""
super()._post_clean() # updates self.instance with form data
password = self.cleaned_data.get('password1')
if password:
try:
password_validation.validate_password(password, self.instance)
except ValidationError as error:
self.add_error('password1', error) | python | def _post_clean(self):
"""Run password validaton after clean methods
When clean methods are run, the user instance does not yet
exist. To properly compare model values agains the password (in
the UserAttributeSimilarityValidator), we wait until we have an
instance to compare against.
https://code.djangoproject.com/ticket/28127
https://github.com/django/django/pull/8408
Has no effect in Django prior to 1.9
May become unnecessary in Django 2.0 (if this superclass changes)
"""
super()._post_clean() # updates self.instance with form data
password = self.cleaned_data.get('password1')
if password:
try:
password_validation.validate_password(password, self.instance)
except ValidationError as error:
self.add_error('password1', error) | [
"def",
"_post_clean",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_post_clean",
"(",
")",
"# updates self.instance with form data",
"password",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'password1'",
")",
"if",
"password",
":",
"try",
":",
"password_validation",
".",
"validate_password",
"(",
"password",
",",
"self",
".",
"instance",
")",
"except",
"ValidationError",
"as",
"error",
":",
"self",
".",
"add_error",
"(",
"'password1'",
",",
"error",
")"
] | Run password validaton after clean methods
When clean methods are run, the user instance does not yet
exist. To properly compare model values agains the password (in
the UserAttributeSimilarityValidator), we wait until we have an
instance to compare against.
https://code.djangoproject.com/ticket/28127
https://github.com/django/django/pull/8408
Has no effect in Django prior to 1.9
May become unnecessary in Django 2.0 (if this superclass changes) | [
"Run",
"password",
"validaton",
"after",
"clean",
"methods"
] | e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4 | https://github.com/jambonsw/django-improved-user/blob/e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4/src/improved_user/forms.py#L86-L107 |
2,811 | jambonsw/django-improved-user | src/improved_user/model_mixins.py | EmailAuthMixin.clean | def clean(self):
"""Override default clean method to normalize email.
Call :code:`super().clean()` if overriding.
"""
super().clean()
self.email = self.__class__.objects.normalize_email(self.email) | python | def clean(self):
"""Override default clean method to normalize email.
Call :code:`super().clean()` if overriding.
"""
super().clean()
self.email = self.__class__.objects.normalize_email(self.email) | [
"def",
"clean",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"clean",
"(",
")",
"self",
".",
"email",
"=",
"self",
".",
"__class__",
".",
"objects",
".",
"normalize_email",
"(",
"self",
".",
"email",
")"
] | Override default clean method to normalize email.
Call :code:`super().clean()` if overriding. | [
"Override",
"default",
"clean",
"method",
"to",
"normalize",
"email",
"."
] | e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4 | https://github.com/jambonsw/django-improved-user/blob/e5fbb4f0d5f7491b9f06f7eb2812127b5e4616d4/src/improved_user/model_mixins.py#L69-L76 |
2,812 | mapbox/cligj | cligj/features.py | normalize_feature_inputs | def normalize_feature_inputs(ctx, param, value):
"""Click callback that normalizes feature input values.
Returns a generator over features from the input value.
Parameters
----------
ctx: a Click context
param: the name of the argument or option
value: object
The value argument may be one of the following:
1. A list of paths to files containing GeoJSON feature
collections or feature sequences.
2. A list of string-encoded coordinate pairs of the form
"[lng, lat]", or "lng, lat", or "lng lat".
If no value is provided, features will be read from stdin.
"""
for feature_like in value or ('-',):
try:
with click.open_file(feature_like) as src:
for feature in iter_features(iter(src)):
yield feature
except IOError:
coords = list(coords_from_query(feature_like))
yield {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'Point',
'coordinates': coords}} | python | def normalize_feature_inputs(ctx, param, value):
"""Click callback that normalizes feature input values.
Returns a generator over features from the input value.
Parameters
----------
ctx: a Click context
param: the name of the argument or option
value: object
The value argument may be one of the following:
1. A list of paths to files containing GeoJSON feature
collections or feature sequences.
2. A list of string-encoded coordinate pairs of the form
"[lng, lat]", or "lng, lat", or "lng lat".
If no value is provided, features will be read from stdin.
"""
for feature_like in value or ('-',):
try:
with click.open_file(feature_like) as src:
for feature in iter_features(iter(src)):
yield feature
except IOError:
coords = list(coords_from_query(feature_like))
yield {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'Point',
'coordinates': coords}} | [
"def",
"normalize_feature_inputs",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"for",
"feature_like",
"in",
"value",
"or",
"(",
"'-'",
",",
")",
":",
"try",
":",
"with",
"click",
".",
"open_file",
"(",
"feature_like",
")",
"as",
"src",
":",
"for",
"feature",
"in",
"iter_features",
"(",
"iter",
"(",
"src",
")",
")",
":",
"yield",
"feature",
"except",
"IOError",
":",
"coords",
"=",
"list",
"(",
"coords_from_query",
"(",
"feature_like",
")",
")",
"yield",
"{",
"'type'",
":",
"'Feature'",
",",
"'properties'",
":",
"{",
"}",
",",
"'geometry'",
":",
"{",
"'type'",
":",
"'Point'",
",",
"'coordinates'",
":",
"coords",
"}",
"}"
] | Click callback that normalizes feature input values.
Returns a generator over features from the input value.
Parameters
----------
ctx: a Click context
param: the name of the argument or option
value: object
The value argument may be one of the following:
1. A list of paths to files containing GeoJSON feature
collections or feature sequences.
2. A list of string-encoded coordinate pairs of the form
"[lng, lat]", or "lng, lat", or "lng lat".
If no value is provided, features will be read from stdin. | [
"Click",
"callback",
"that",
"normalizes",
"feature",
"input",
"values",
"."
] | 1815692d99abfb4bc4b2d0411f67fa568f112c05 | https://github.com/mapbox/cligj/blob/1815692d99abfb4bc4b2d0411f67fa568f112c05/cligj/features.py#L8-L39 |
2,813 | mapbox/cligj | cligj/features.py | iter_features | def iter_features(geojsonfile, func=None):
"""Extract GeoJSON features from a text file object.
Given a file-like object containing a single GeoJSON feature
collection text or a sequence of GeoJSON features, iter_features()
iterates over lines of the file and yields GeoJSON features.
Parameters
----------
geojsonfile: a file-like object
The geojsonfile implements the iterator protocol and yields
lines of JSON text.
func: function, optional
A function that will be applied to each extracted feature. It
takes a feature object and may return a replacement feature or
None -- in which case iter_features does not yield.
"""
func = func or (lambda x: x)
first_line = next(geojsonfile)
# Does the geojsonfile contain RS-delimited JSON sequences?
if first_line.startswith(u'\x1e'):
text_buffer = first_line.strip(u'\x1e')
for line in geojsonfile:
if line.startswith(u'\x1e'):
if text_buffer:
obj = json.loads(text_buffer)
if 'coordinates' in obj:
obj = to_feature(obj)
newfeat = func(obj)
if newfeat:
yield newfeat
text_buffer = line.strip(u'\x1e')
else:
text_buffer += line
# complete our parsing with a for-else clause.
else:
obj = json.loads(text_buffer)
if 'coordinates' in obj:
obj = to_feature(obj)
newfeat = func(obj)
if newfeat:
yield newfeat
# If not, it may contains LF-delimited GeoJSON objects or a single
# multi-line pretty-printed GeoJSON object.
else:
# Try to parse LF-delimited sequences of features or feature
# collections produced by, e.g., `jq -c ...`.
try:
obj = json.loads(first_line)
if obj['type'] == 'Feature':
newfeat = func(obj)
if newfeat:
yield newfeat
for line in geojsonfile:
newfeat = func(json.loads(line))
if newfeat:
yield newfeat
elif obj['type'] == 'FeatureCollection':
for feat in obj['features']:
newfeat = func(feat)
if newfeat:
yield newfeat
elif 'coordinates' in obj:
newfeat = func(to_feature(obj))
if newfeat:
yield newfeat
for line in geojsonfile:
newfeat = func(to_feature(json.loads(line)))
if newfeat:
yield newfeat
# Indented or pretty-printed GeoJSON features or feature
# collections will fail out of the try clause above since
# they'll have no complete JSON object on their first line.
# To handle these, we slurp in the entire file and parse its
# text.
except ValueError:
text = "".join(chain([first_line], geojsonfile))
obj = json.loads(text)
if obj['type'] == 'Feature':
newfeat = func(obj)
if newfeat:
yield newfeat
elif obj['type'] == 'FeatureCollection':
for feat in obj['features']:
newfeat = func(feat)
if newfeat:
yield newfeat
elif 'coordinates' in obj:
newfeat = func(to_feature(obj))
if newfeat:
yield newfeat | python | def iter_features(geojsonfile, func=None):
"""Extract GeoJSON features from a text file object.
Given a file-like object containing a single GeoJSON feature
collection text or a sequence of GeoJSON features, iter_features()
iterates over lines of the file and yields GeoJSON features.
Parameters
----------
geojsonfile: a file-like object
The geojsonfile implements the iterator protocol and yields
lines of JSON text.
func: function, optional
A function that will be applied to each extracted feature. It
takes a feature object and may return a replacement feature or
None -- in which case iter_features does not yield.
"""
func = func or (lambda x: x)
first_line = next(geojsonfile)
# Does the geojsonfile contain RS-delimited JSON sequences?
if first_line.startswith(u'\x1e'):
text_buffer = first_line.strip(u'\x1e')
for line in geojsonfile:
if line.startswith(u'\x1e'):
if text_buffer:
obj = json.loads(text_buffer)
if 'coordinates' in obj:
obj = to_feature(obj)
newfeat = func(obj)
if newfeat:
yield newfeat
text_buffer = line.strip(u'\x1e')
else:
text_buffer += line
# complete our parsing with a for-else clause.
else:
obj = json.loads(text_buffer)
if 'coordinates' in obj:
obj = to_feature(obj)
newfeat = func(obj)
if newfeat:
yield newfeat
# If not, it may contains LF-delimited GeoJSON objects or a single
# multi-line pretty-printed GeoJSON object.
else:
# Try to parse LF-delimited sequences of features or feature
# collections produced by, e.g., `jq -c ...`.
try:
obj = json.loads(first_line)
if obj['type'] == 'Feature':
newfeat = func(obj)
if newfeat:
yield newfeat
for line in geojsonfile:
newfeat = func(json.loads(line))
if newfeat:
yield newfeat
elif obj['type'] == 'FeatureCollection':
for feat in obj['features']:
newfeat = func(feat)
if newfeat:
yield newfeat
elif 'coordinates' in obj:
newfeat = func(to_feature(obj))
if newfeat:
yield newfeat
for line in geojsonfile:
newfeat = func(to_feature(json.loads(line)))
if newfeat:
yield newfeat
# Indented or pretty-printed GeoJSON features or feature
# collections will fail out of the try clause above since
# they'll have no complete JSON object on their first line.
# To handle these, we slurp in the entire file and parse its
# text.
except ValueError:
text = "".join(chain([first_line], geojsonfile))
obj = json.loads(text)
if obj['type'] == 'Feature':
newfeat = func(obj)
if newfeat:
yield newfeat
elif obj['type'] == 'FeatureCollection':
for feat in obj['features']:
newfeat = func(feat)
if newfeat:
yield newfeat
elif 'coordinates' in obj:
newfeat = func(to_feature(obj))
if newfeat:
yield newfeat | [
"def",
"iter_features",
"(",
"geojsonfile",
",",
"func",
"=",
"None",
")",
":",
"func",
"=",
"func",
"or",
"(",
"lambda",
"x",
":",
"x",
")",
"first_line",
"=",
"next",
"(",
"geojsonfile",
")",
"# Does the geojsonfile contain RS-delimited JSON sequences?",
"if",
"first_line",
".",
"startswith",
"(",
"u'\\x1e'",
")",
":",
"text_buffer",
"=",
"first_line",
".",
"strip",
"(",
"u'\\x1e'",
")",
"for",
"line",
"in",
"geojsonfile",
":",
"if",
"line",
".",
"startswith",
"(",
"u'\\x1e'",
")",
":",
"if",
"text_buffer",
":",
"obj",
"=",
"json",
".",
"loads",
"(",
"text_buffer",
")",
"if",
"'coordinates'",
"in",
"obj",
":",
"obj",
"=",
"to_feature",
"(",
"obj",
")",
"newfeat",
"=",
"func",
"(",
"obj",
")",
"if",
"newfeat",
":",
"yield",
"newfeat",
"text_buffer",
"=",
"line",
".",
"strip",
"(",
"u'\\x1e'",
")",
"else",
":",
"text_buffer",
"+=",
"line",
"# complete our parsing with a for-else clause.",
"else",
":",
"obj",
"=",
"json",
".",
"loads",
"(",
"text_buffer",
")",
"if",
"'coordinates'",
"in",
"obj",
":",
"obj",
"=",
"to_feature",
"(",
"obj",
")",
"newfeat",
"=",
"func",
"(",
"obj",
")",
"if",
"newfeat",
":",
"yield",
"newfeat",
"# If not, it may contains LF-delimited GeoJSON objects or a single",
"# multi-line pretty-printed GeoJSON object.",
"else",
":",
"# Try to parse LF-delimited sequences of features or feature",
"# collections produced by, e.g., `jq -c ...`.",
"try",
":",
"obj",
"=",
"json",
".",
"loads",
"(",
"first_line",
")",
"if",
"obj",
"[",
"'type'",
"]",
"==",
"'Feature'",
":",
"newfeat",
"=",
"func",
"(",
"obj",
")",
"if",
"newfeat",
":",
"yield",
"newfeat",
"for",
"line",
"in",
"geojsonfile",
":",
"newfeat",
"=",
"func",
"(",
"json",
".",
"loads",
"(",
"line",
")",
")",
"if",
"newfeat",
":",
"yield",
"newfeat",
"elif",
"obj",
"[",
"'type'",
"]",
"==",
"'FeatureCollection'",
":",
"for",
"feat",
"in",
"obj",
"[",
"'features'",
"]",
":",
"newfeat",
"=",
"func",
"(",
"feat",
")",
"if",
"newfeat",
":",
"yield",
"newfeat",
"elif",
"'coordinates'",
"in",
"obj",
":",
"newfeat",
"=",
"func",
"(",
"to_feature",
"(",
"obj",
")",
")",
"if",
"newfeat",
":",
"yield",
"newfeat",
"for",
"line",
"in",
"geojsonfile",
":",
"newfeat",
"=",
"func",
"(",
"to_feature",
"(",
"json",
".",
"loads",
"(",
"line",
")",
")",
")",
"if",
"newfeat",
":",
"yield",
"newfeat",
"# Indented or pretty-printed GeoJSON features or feature",
"# collections will fail out of the try clause above since",
"# they'll have no complete JSON object on their first line.",
"# To handle these, we slurp in the entire file and parse its",
"# text.",
"except",
"ValueError",
":",
"text",
"=",
"\"\"",
".",
"join",
"(",
"chain",
"(",
"[",
"first_line",
"]",
",",
"geojsonfile",
")",
")",
"obj",
"=",
"json",
".",
"loads",
"(",
"text",
")",
"if",
"obj",
"[",
"'type'",
"]",
"==",
"'Feature'",
":",
"newfeat",
"=",
"func",
"(",
"obj",
")",
"if",
"newfeat",
":",
"yield",
"newfeat",
"elif",
"obj",
"[",
"'type'",
"]",
"==",
"'FeatureCollection'",
":",
"for",
"feat",
"in",
"obj",
"[",
"'features'",
"]",
":",
"newfeat",
"=",
"func",
"(",
"feat",
")",
"if",
"newfeat",
":",
"yield",
"newfeat",
"elif",
"'coordinates'",
"in",
"obj",
":",
"newfeat",
"=",
"func",
"(",
"to_feature",
"(",
"obj",
")",
")",
"if",
"newfeat",
":",
"yield",
"newfeat"
] | Extract GeoJSON features from a text file object.
Given a file-like object containing a single GeoJSON feature
collection text or a sequence of GeoJSON features, iter_features()
iterates over lines of the file and yields GeoJSON features.
Parameters
----------
geojsonfile: a file-like object
The geojsonfile implements the iterator protocol and yields
lines of JSON text.
func: function, optional
A function that will be applied to each extracted feature. It
takes a feature object and may return a replacement feature or
None -- in which case iter_features does not yield. | [
"Extract",
"GeoJSON",
"features",
"from",
"a",
"text",
"file",
"object",
"."
] | 1815692d99abfb4bc4b2d0411f67fa568f112c05 | https://github.com/mapbox/cligj/blob/1815692d99abfb4bc4b2d0411f67fa568f112c05/cligj/features.py#L42-L135 |
2,814 | mapbox/cligj | cligj/features.py | iter_query | def iter_query(query):
"""Accept a filename, stream, or string.
Returns an iterator over lines of the query."""
try:
itr = click.open_file(query).readlines()
except IOError:
itr = [query]
return itr | python | def iter_query(query):
"""Accept a filename, stream, or string.
Returns an iterator over lines of the query."""
try:
itr = click.open_file(query).readlines()
except IOError:
itr = [query]
return itr | [
"def",
"iter_query",
"(",
"query",
")",
":",
"try",
":",
"itr",
"=",
"click",
".",
"open_file",
"(",
"query",
")",
".",
"readlines",
"(",
")",
"except",
"IOError",
":",
"itr",
"=",
"[",
"query",
"]",
"return",
"itr"
] | Accept a filename, stream, or string.
Returns an iterator over lines of the query. | [
"Accept",
"a",
"filename",
"stream",
"or",
"string",
".",
"Returns",
"an",
"iterator",
"over",
"lines",
"of",
"the",
"query",
"."
] | 1815692d99abfb4bc4b2d0411f67fa568f112c05 | https://github.com/mapbox/cligj/blob/1815692d99abfb4bc4b2d0411f67fa568f112c05/cligj/features.py#L154-L161 |
2,815 | mapbox/cligj | cligj/features.py | normalize_feature_objects | def normalize_feature_objects(feature_objs):
"""Takes an iterable of GeoJSON-like Feature mappings or
an iterable of objects with a geo interface and
normalizes it to the former."""
for obj in feature_objs:
if hasattr(obj, "__geo_interface__") and \
'type' in obj.__geo_interface__.keys() and \
obj.__geo_interface__['type'] == 'Feature':
yield obj.__geo_interface__
elif isinstance(obj, dict) and 'type' in obj and \
obj['type'] == 'Feature':
yield obj
else:
raise ValueError("Did not recognize object {0}"
"as GeoJSON Feature".format(obj)) | python | def normalize_feature_objects(feature_objs):
"""Takes an iterable of GeoJSON-like Feature mappings or
an iterable of objects with a geo interface and
normalizes it to the former."""
for obj in feature_objs:
if hasattr(obj, "__geo_interface__") and \
'type' in obj.__geo_interface__.keys() and \
obj.__geo_interface__['type'] == 'Feature':
yield obj.__geo_interface__
elif isinstance(obj, dict) and 'type' in obj and \
obj['type'] == 'Feature':
yield obj
else:
raise ValueError("Did not recognize object {0}"
"as GeoJSON Feature".format(obj)) | [
"def",
"normalize_feature_objects",
"(",
"feature_objs",
")",
":",
"for",
"obj",
"in",
"feature_objs",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"__geo_interface__\"",
")",
"and",
"'type'",
"in",
"obj",
".",
"__geo_interface__",
".",
"keys",
"(",
")",
"and",
"obj",
".",
"__geo_interface__",
"[",
"'type'",
"]",
"==",
"'Feature'",
":",
"yield",
"obj",
".",
"__geo_interface__",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
"and",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"==",
"'Feature'",
":",
"yield",
"obj",
"else",
":",
"raise",
"ValueError",
"(",
"\"Did not recognize object {0}\"",
"\"as GeoJSON Feature\"",
".",
"format",
"(",
"obj",
")",
")"
] | Takes an iterable of GeoJSON-like Feature mappings or
an iterable of objects with a geo interface and
normalizes it to the former. | [
"Takes",
"an",
"iterable",
"of",
"GeoJSON",
"-",
"like",
"Feature",
"mappings",
"or",
"an",
"iterable",
"of",
"objects",
"with",
"a",
"geo",
"interface",
"and",
"normalizes",
"it",
"to",
"the",
"former",
"."
] | 1815692d99abfb4bc4b2d0411f67fa568f112c05 | https://github.com/mapbox/cligj/blob/1815692d99abfb4bc4b2d0411f67fa568f112c05/cligj/features.py#L175-L189 |
2,816 | ludeeus/pytraccar | pytraccar/api.py | API.api | async def api(self, endpoint, params=None, test=False):
"""Comunicate with the API."""
data = {}
url = "{}/{}".format(self._api, endpoint)
try:
async with async_timeout.timeout(8, loop=self._loop):
response = await self._session.get(
url, auth=self._auth, headers=HEADERS, params=params
)
if response.status == 200:
self._authenticated = True
self._connected = True
if not test:
data = await response.json()
elif response.status == 401:
self._authenticated = False
self._connected = True
except asyncio.TimeoutError as error:
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Timeouterror connecting to Traccar, %s", error)
except aiohttp.ClientError as error:
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Error connecting to Traccar, %s", error)
except socket.gaierror as error:
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Error connecting to Traccar, %s", error)
except TypeError as error:
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Error connecting to Traccar, %s", error)
except Exception as error: # pylint: disable=broad-except
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Error connecting to Traccar, %s", error)
return data | python | async def api(self, endpoint, params=None, test=False):
"""Comunicate with the API."""
data = {}
url = "{}/{}".format(self._api, endpoint)
try:
async with async_timeout.timeout(8, loop=self._loop):
response = await self._session.get(
url, auth=self._auth, headers=HEADERS, params=params
)
if response.status == 200:
self._authenticated = True
self._connected = True
if not test:
data = await response.json()
elif response.status == 401:
self._authenticated = False
self._connected = True
except asyncio.TimeoutError as error:
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Timeouterror connecting to Traccar, %s", error)
except aiohttp.ClientError as error:
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Error connecting to Traccar, %s", error)
except socket.gaierror as error:
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Error connecting to Traccar, %s", error)
except TypeError as error:
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Error connecting to Traccar, %s", error)
except Exception as error: # pylint: disable=broad-except
self._authenticated, self._connected = False, False
if not test:
_LOGGER.warning("Error connecting to Traccar, %s", error)
return data | [
"async",
"def",
"api",
"(",
"self",
",",
"endpoint",
",",
"params",
"=",
"None",
",",
"test",
"=",
"False",
")",
":",
"data",
"=",
"{",
"}",
"url",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"self",
".",
"_api",
",",
"endpoint",
")",
"try",
":",
"async",
"with",
"async_timeout",
".",
"timeout",
"(",
"8",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
":",
"response",
"=",
"await",
"self",
".",
"_session",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"self",
".",
"_auth",
",",
"headers",
"=",
"HEADERS",
",",
"params",
"=",
"params",
")",
"if",
"response",
".",
"status",
"==",
"200",
":",
"self",
".",
"_authenticated",
"=",
"True",
"self",
".",
"_connected",
"=",
"True",
"if",
"not",
"test",
":",
"data",
"=",
"await",
"response",
".",
"json",
"(",
")",
"elif",
"response",
".",
"status",
"==",
"401",
":",
"self",
".",
"_authenticated",
"=",
"False",
"self",
".",
"_connected",
"=",
"True",
"except",
"asyncio",
".",
"TimeoutError",
"as",
"error",
":",
"self",
".",
"_authenticated",
",",
"self",
".",
"_connected",
"=",
"False",
",",
"False",
"if",
"not",
"test",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Timeouterror connecting to Traccar, %s\"",
",",
"error",
")",
"except",
"aiohttp",
".",
"ClientError",
"as",
"error",
":",
"self",
".",
"_authenticated",
",",
"self",
".",
"_connected",
"=",
"False",
",",
"False",
"if",
"not",
"test",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Error connecting to Traccar, %s\"",
",",
"error",
")",
"except",
"socket",
".",
"gaierror",
"as",
"error",
":",
"self",
".",
"_authenticated",
",",
"self",
".",
"_connected",
"=",
"False",
",",
"False",
"if",
"not",
"test",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Error connecting to Traccar, %s\"",
",",
"error",
")",
"except",
"TypeError",
"as",
"error",
":",
"self",
".",
"_authenticated",
",",
"self",
".",
"_connected",
"=",
"False",
",",
"False",
"if",
"not",
"test",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Error connecting to Traccar, %s\"",
",",
"error",
")",
"except",
"Exception",
"as",
"error",
":",
"# pylint: disable=broad-except",
"self",
".",
"_authenticated",
",",
"self",
".",
"_connected",
"=",
"False",
",",
"False",
"if",
"not",
"test",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Error connecting to Traccar, %s\"",
",",
"error",
")",
"return",
"data"
] | Comunicate with the API. | [
"Comunicate",
"with",
"the",
"API",
"."
] | c7c635c334cc193c2da351a9fc8213d5095f77d6 | https://github.com/ludeeus/pytraccar/blob/c7c635c334cc193c2da351a9fc8213d5095f77d6/pytraccar/api.py#L39-L79 |
2,817 | ludeeus/pytraccar | pytraccar/cli.py | runcli | async def runcli():
"""Debug of pytraccar."""
async with aiohttp.ClientSession() as session:
host = input("IP: ")
username = input("Username: ")
password = input("Password: ")
print("\n\n\n")
data = API(LOOP, session, username, password, host)
await data.test_connection()
print("Authenticated:", data.authenticated)
if data.authenticated:
await data.get_device_info()
print("Authentication:", data.authenticated)
print("Geofences:", data.geofences)
print("Devices:", data.devices)
print("Positions:", data.positions)
print("Device info:", data.device_info) | python | async def runcli():
"""Debug of pytraccar."""
async with aiohttp.ClientSession() as session:
host = input("IP: ")
username = input("Username: ")
password = input("Password: ")
print("\n\n\n")
data = API(LOOP, session, username, password, host)
await data.test_connection()
print("Authenticated:", data.authenticated)
if data.authenticated:
await data.get_device_info()
print("Authentication:", data.authenticated)
print("Geofences:", data.geofences)
print("Devices:", data.devices)
print("Positions:", data.positions)
print("Device info:", data.device_info) | [
"async",
"def",
"runcli",
"(",
")",
":",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"host",
"=",
"input",
"(",
"\"IP: \"",
")",
"username",
"=",
"input",
"(",
"\"Username: \"",
")",
"password",
"=",
"input",
"(",
"\"Password: \"",
")",
"print",
"(",
"\"\\n\\n\\n\"",
")",
"data",
"=",
"API",
"(",
"LOOP",
",",
"session",
",",
"username",
",",
"password",
",",
"host",
")",
"await",
"data",
".",
"test_connection",
"(",
")",
"print",
"(",
"\"Authenticated:\"",
",",
"data",
".",
"authenticated",
")",
"if",
"data",
".",
"authenticated",
":",
"await",
"data",
".",
"get_device_info",
"(",
")",
"print",
"(",
"\"Authentication:\"",
",",
"data",
".",
"authenticated",
")",
"print",
"(",
"\"Geofences:\"",
",",
"data",
".",
"geofences",
")",
"print",
"(",
"\"Devices:\"",
",",
"data",
".",
"devices",
")",
"print",
"(",
"\"Positions:\"",
",",
"data",
".",
"positions",
")",
"print",
"(",
"\"Device info:\"",
",",
"data",
".",
"device_info",
")"
] | Debug of pytraccar. | [
"Debug",
"of",
"pytraccar",
"."
] | c7c635c334cc193c2da351a9fc8213d5095f77d6 | https://github.com/ludeeus/pytraccar/blob/c7c635c334cc193c2da351a9fc8213d5095f77d6/pytraccar/cli.py#L9-L25 |
2,818 | alexdej/puzpy | puz.py | restore | def restore(s, t):
"""
s is the source string, it can contain '.'
t is the target, it's smaller than s by the number of '.'s in s
Each char in s is replaced by the corresponding
char in t, jumping over '.'s in s.
>>> restore('ABC.DEF', 'XYZABC')
'XYZ.ABC'
"""
t = (c for c in t)
return ''.join(next(t) if not is_blacksquare(c) else c for c in s) | python | def restore(s, t):
"""
s is the source string, it can contain '.'
t is the target, it's smaller than s by the number of '.'s in s
Each char in s is replaced by the corresponding
char in t, jumping over '.'s in s.
>>> restore('ABC.DEF', 'XYZABC')
'XYZ.ABC'
"""
t = (c for c in t)
return ''.join(next(t) if not is_blacksquare(c) else c for c in s) | [
"def",
"restore",
"(",
"s",
",",
"t",
")",
":",
"t",
"=",
"(",
"c",
"for",
"c",
"in",
"t",
")",
"return",
"''",
".",
"join",
"(",
"next",
"(",
"t",
")",
"if",
"not",
"is_blacksquare",
"(",
"c",
")",
"else",
"c",
"for",
"c",
"in",
"s",
")"
] | s is the source string, it can contain '.'
t is the target, it's smaller than s by the number of '.'s in s
Each char in s is replaced by the corresponding
char in t, jumping over '.'s in s.
>>> restore('ABC.DEF', 'XYZABC')
'XYZ.ABC' | [
"s",
"is",
"the",
"source",
"string",
"it",
"can",
"contain",
".",
"t",
"is",
"the",
"target",
"it",
"s",
"smaller",
"than",
"s",
"by",
"the",
"number",
"of",
".",
"s",
"in",
"s"
] | 8906ab899845d1200ac3411b4c2a2067cffa15d7 | https://github.com/alexdej/puzpy/blob/8906ab899845d1200ac3411b4c2a2067cffa15d7/puz.py#L696-L708 |
2,819 | instacart/ahab | ahab/__init__.py | Ahab.default | def default(event, data):
"""The default handler prints basic event info."""
messages = defaultdict(lambda: 'Avast:')
messages['start'] = 'Thar she blows!'
messages['tag'] = 'Thar she blows!'
messages['stop'] = 'Away into the depths:'
messages['destroy'] = 'Away into the depths:'
messages['delete'] = 'Away into the depths:'
status = get_status(event)
message = messages[status] + ' %s/%s'
log.info(message, status, get_id(event))
log.debug('"data": %s', form_json(data)) | python | def default(event, data):
"""The default handler prints basic event info."""
messages = defaultdict(lambda: 'Avast:')
messages['start'] = 'Thar she blows!'
messages['tag'] = 'Thar she blows!'
messages['stop'] = 'Away into the depths:'
messages['destroy'] = 'Away into the depths:'
messages['delete'] = 'Away into the depths:'
status = get_status(event)
message = messages[status] + ' %s/%s'
log.info(message, status, get_id(event))
log.debug('"data": %s', form_json(data)) | [
"def",
"default",
"(",
"event",
",",
"data",
")",
":",
"messages",
"=",
"defaultdict",
"(",
"lambda",
":",
"'Avast:'",
")",
"messages",
"[",
"'start'",
"]",
"=",
"'Thar she blows!'",
"messages",
"[",
"'tag'",
"]",
"=",
"'Thar she blows!'",
"messages",
"[",
"'stop'",
"]",
"=",
"'Away into the depths:'",
"messages",
"[",
"'destroy'",
"]",
"=",
"'Away into the depths:'",
"messages",
"[",
"'delete'",
"]",
"=",
"'Away into the depths:'",
"status",
"=",
"get_status",
"(",
"event",
")",
"message",
"=",
"messages",
"[",
"status",
"]",
"+",
"' %s/%s'",
"log",
".",
"info",
"(",
"message",
",",
"status",
",",
"get_id",
"(",
"event",
")",
")",
"log",
".",
"debug",
"(",
"'\"data\": %s'",
",",
"form_json",
"(",
"data",
")",
")"
] | The default handler prints basic event info. | [
"The",
"default",
"handler",
"prints",
"basic",
"event",
"info",
"."
] | da85dc6d89f5d0c49d3a26a25ea3710c7881b150 | https://github.com/instacart/ahab/blob/da85dc6d89f5d0c49d3a26a25ea3710c7881b150/ahab/__init__.py#L58-L69 |
2,820 | instacart/ahab | examples/nathook.py | table | def table(tab):
"""Access IPTables transactionally in a uniform way.
Ensures all access is done without autocommit and that only the outer
most task commits, and also ensures we refresh once and commit once.
"""
global open_tables
if tab in open_tables:
yield open_tables[tab]
else:
open_tables[tab] = iptc.Table(tab)
open_tables[tab].refresh()
open_tables[tab].autocommit = False
yield open_tables[tab]
open_tables[tab].commit()
del open_tables[tab] | python | def table(tab):
"""Access IPTables transactionally in a uniform way.
Ensures all access is done without autocommit and that only the outer
most task commits, and also ensures we refresh once and commit once.
"""
global open_tables
if tab in open_tables:
yield open_tables[tab]
else:
open_tables[tab] = iptc.Table(tab)
open_tables[tab].refresh()
open_tables[tab].autocommit = False
yield open_tables[tab]
open_tables[tab].commit()
del open_tables[tab] | [
"def",
"table",
"(",
"tab",
")",
":",
"global",
"open_tables",
"if",
"tab",
"in",
"open_tables",
":",
"yield",
"open_tables",
"[",
"tab",
"]",
"else",
":",
"open_tables",
"[",
"tab",
"]",
"=",
"iptc",
".",
"Table",
"(",
"tab",
")",
"open_tables",
"[",
"tab",
"]",
".",
"refresh",
"(",
")",
"open_tables",
"[",
"tab",
"]",
".",
"autocommit",
"=",
"False",
"yield",
"open_tables",
"[",
"tab",
"]",
"open_tables",
"[",
"tab",
"]",
".",
"commit",
"(",
")",
"del",
"open_tables",
"[",
"tab",
"]"
] | Access IPTables transactionally in a uniform way.
Ensures all access is done without autocommit and that only the outer
most task commits, and also ensures we refresh once and commit once. | [
"Access",
"IPTables",
"transactionally",
"in",
"a",
"uniform",
"way",
"."
] | da85dc6d89f5d0c49d3a26a25ea3710c7881b150 | https://github.com/instacart/ahab/blob/da85dc6d89f5d0c49d3a26a25ea3710c7881b150/examples/nathook.py#L124-L139 |
2,821 | hotdoc/hotdoc | hotdoc/core/formatter.py | Formatter.format_symbol | def format_symbol(self, symbol, link_resolver):
"""
Format a symbols.Symbol
"""
if not symbol:
return ''
if isinstance(symbol, FieldSymbol):
return ''
# pylint: disable=unused-variable
out = self._format_symbol(symbol)
template = self.get_template('symbol_wrapper.html')
return template.render(
{'symbol': symbol,
'formatted_doc': out}) | python | def format_symbol(self, symbol, link_resolver):
"""
Format a symbols.Symbol
"""
if not symbol:
return ''
if isinstance(symbol, FieldSymbol):
return ''
# pylint: disable=unused-variable
out = self._format_symbol(symbol)
template = self.get_template('symbol_wrapper.html')
return template.render(
{'symbol': symbol,
'formatted_doc': out}) | [
"def",
"format_symbol",
"(",
"self",
",",
"symbol",
",",
"link_resolver",
")",
":",
"if",
"not",
"symbol",
":",
"return",
"''",
"if",
"isinstance",
"(",
"symbol",
",",
"FieldSymbol",
")",
":",
"return",
"''",
"# pylint: disable=unused-variable",
"out",
"=",
"self",
".",
"_format_symbol",
"(",
"symbol",
")",
"template",
"=",
"self",
".",
"get_template",
"(",
"'symbol_wrapper.html'",
")",
"return",
"template",
".",
"render",
"(",
"{",
"'symbol'",
":",
"symbol",
",",
"'formatted_doc'",
":",
"out",
"}",
")"
] | Format a symbols.Symbol | [
"Format",
"a",
"symbols",
".",
"Symbol"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L219-L235 |
2,822 | hotdoc/hotdoc | hotdoc/core/database.py | Database.add_comment | def add_comment(self, comment):
"""
Add a comment to the database.
Args:
comment (hotdoc.core.Comment): comment to add
"""
if not comment:
return
self.__comments[comment.name] = comment
self.comment_added_signal(self, comment) | python | def add_comment(self, comment):
"""
Add a comment to the database.
Args:
comment (hotdoc.core.Comment): comment to add
"""
if not comment:
return
self.__comments[comment.name] = comment
self.comment_added_signal(self, comment) | [
"def",
"add_comment",
"(",
"self",
",",
"comment",
")",
":",
"if",
"not",
"comment",
":",
"return",
"self",
".",
"__comments",
"[",
"comment",
".",
"name",
"]",
"=",
"comment",
"self",
".",
"comment_added_signal",
"(",
"self",
",",
"comment",
")"
] | Add a comment to the database.
Args:
comment (hotdoc.core.Comment): comment to add | [
"Add",
"a",
"comment",
"to",
"the",
"database",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/database.py#L77-L88 |
2,823 | hotdoc/hotdoc | hotdoc/utils/utils.py | touch | def touch(fname):
"""
Mimics the `touch` command
Busy loops until the mtime has actually been changed, use for tests only
"""
orig_mtime = get_mtime(fname)
while get_mtime(fname) == orig_mtime:
pathlib.Path(fname).touch() | python | def touch(fname):
"""
Mimics the `touch` command
Busy loops until the mtime has actually been changed, use for tests only
"""
orig_mtime = get_mtime(fname)
while get_mtime(fname) == orig_mtime:
pathlib.Path(fname).touch() | [
"def",
"touch",
"(",
"fname",
")",
":",
"orig_mtime",
"=",
"get_mtime",
"(",
"fname",
")",
"while",
"get_mtime",
"(",
"fname",
")",
"==",
"orig_mtime",
":",
"pathlib",
".",
"Path",
"(",
"fname",
")",
".",
"touch",
"(",
")"
] | Mimics the `touch` command
Busy loops until the mtime has actually been changed, use for tests only | [
"Mimics",
"the",
"touch",
"command"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L306-L314 |
2,824 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.debug | def debug(self, message, domain=None):
"""
Shortcut function for `utils.loggable.debug`
Args:
message: see `utils.loggable.debug`
domain: see `utils.loggable.debug`
"""
if domain is None:
domain = self.extension_name
debug(message, domain) | python | def debug(self, message, domain=None):
"""
Shortcut function for `utils.loggable.debug`
Args:
message: see `utils.loggable.debug`
domain: see `utils.loggable.debug`
"""
if domain is None:
domain = self.extension_name
debug(message, domain) | [
"def",
"debug",
"(",
"self",
",",
"message",
",",
"domain",
"=",
"None",
")",
":",
"if",
"domain",
"is",
"None",
":",
"domain",
"=",
"self",
".",
"extension_name",
"debug",
"(",
"message",
",",
"domain",
")"
] | Shortcut function for `utils.loggable.debug`
Args:
message: see `utils.loggable.debug`
domain: see `utils.loggable.debug` | [
"Shortcut",
"function",
"for",
"utils",
".",
"loggable",
".",
"debug"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L148-L158 |
2,825 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.info | def info(self, message, domain=None):
"""
Shortcut function for `utils.loggable.info`
Args:
message: see `utils.loggable.info`
domain: see `utils.loggable.info`
"""
if domain is None:
domain = self.extension_name
info(message, domain) | python | def info(self, message, domain=None):
"""
Shortcut function for `utils.loggable.info`
Args:
message: see `utils.loggable.info`
domain: see `utils.loggable.info`
"""
if domain is None:
domain = self.extension_name
info(message, domain) | [
"def",
"info",
"(",
"self",
",",
"message",
",",
"domain",
"=",
"None",
")",
":",
"if",
"domain",
"is",
"None",
":",
"domain",
"=",
"self",
".",
"extension_name",
"info",
"(",
"message",
",",
"domain",
")"
] | Shortcut function for `utils.loggable.info`
Args:
message: see `utils.loggable.info`
domain: see `utils.loggable.info` | [
"Shortcut",
"function",
"for",
"utils",
".",
"loggable",
".",
"info"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L160-L170 |
2,826 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.parse_config | def parse_config(self, config):
"""
Override this, making sure to chain up first, if your extension adds
its own custom command line arguments, or you want to do any further
processing on the automatically added arguments.
The default implementation will set attributes on the extension:
- 'sources': a set of absolute paths to source files for this extension
- 'index': absolute path to the index for this extension
Additionally, it will set an attribute for each argument added with
`Extension.add_path_argument` or `Extension.add_paths_argument`, with
the extension's `Extension.argument_prefix` stripped, and dashes
changed to underscores.
Args:
config: a `config.Config` instance
"""
prefix = self.argument_prefix
self.sources = config.get_sources(prefix)
self.smart_sources = [
self._get_smart_filename(s) for s in self.sources]
self.index = config.get_index(prefix)
self.source_roots = OrderedSet(
config.get_paths('%s_source_roots' % prefix))
for arg, dest in list(self.paths_arguments.items()):
val = config.get_paths(arg)
setattr(self, dest, val)
for arg, dest in list(self.path_arguments.items()):
val = config.get_path(arg)
setattr(self, dest, val)
self.formatter.parse_config(config) | python | def parse_config(self, config):
"""
Override this, making sure to chain up first, if your extension adds
its own custom command line arguments, or you want to do any further
processing on the automatically added arguments.
The default implementation will set attributes on the extension:
- 'sources': a set of absolute paths to source files for this extension
- 'index': absolute path to the index for this extension
Additionally, it will set an attribute for each argument added with
`Extension.add_path_argument` or `Extension.add_paths_argument`, with
the extension's `Extension.argument_prefix` stripped, and dashes
changed to underscores.
Args:
config: a `config.Config` instance
"""
prefix = self.argument_prefix
self.sources = config.get_sources(prefix)
self.smart_sources = [
self._get_smart_filename(s) for s in self.sources]
self.index = config.get_index(prefix)
self.source_roots = OrderedSet(
config.get_paths('%s_source_roots' % prefix))
for arg, dest in list(self.paths_arguments.items()):
val = config.get_paths(arg)
setattr(self, dest, val)
for arg, dest in list(self.path_arguments.items()):
val = config.get_path(arg)
setattr(self, dest, val)
self.formatter.parse_config(config) | [
"def",
"parse_config",
"(",
"self",
",",
"config",
")",
":",
"prefix",
"=",
"self",
".",
"argument_prefix",
"self",
".",
"sources",
"=",
"config",
".",
"get_sources",
"(",
"prefix",
")",
"self",
".",
"smart_sources",
"=",
"[",
"self",
".",
"_get_smart_filename",
"(",
"s",
")",
"for",
"s",
"in",
"self",
".",
"sources",
"]",
"self",
".",
"index",
"=",
"config",
".",
"get_index",
"(",
"prefix",
")",
"self",
".",
"source_roots",
"=",
"OrderedSet",
"(",
"config",
".",
"get_paths",
"(",
"'%s_source_roots'",
"%",
"prefix",
")",
")",
"for",
"arg",
",",
"dest",
"in",
"list",
"(",
"self",
".",
"paths_arguments",
".",
"items",
"(",
")",
")",
":",
"val",
"=",
"config",
".",
"get_paths",
"(",
"arg",
")",
"setattr",
"(",
"self",
",",
"dest",
",",
"val",
")",
"for",
"arg",
",",
"dest",
"in",
"list",
"(",
"self",
".",
"path_arguments",
".",
"items",
"(",
")",
")",
":",
"val",
"=",
"config",
".",
"get_path",
"(",
"arg",
")",
"setattr",
"(",
"self",
",",
"dest",
",",
"val",
")",
"self",
".",
"formatter",
".",
"parse_config",
"(",
"config",
")"
] | Override this, making sure to chain up first, if your extension adds
its own custom command line arguments, or you want to do any further
processing on the automatically added arguments.
The default implementation will set attributes on the extension:
- 'sources': a set of absolute paths to source files for this extension
- 'index': absolute path to the index for this extension
Additionally, it will set an attribute for each argument added with
`Extension.add_path_argument` or `Extension.add_paths_argument`, with
the extension's `Extension.argument_prefix` stripped, and dashes
changed to underscores.
Args:
config: a `config.Config` instance | [
"Override",
"this",
"making",
"sure",
"to",
"chain",
"up",
"first",
"if",
"your",
"extension",
"adds",
"its",
"own",
"custom",
"command",
"line",
"arguments",
"or",
"you",
"want",
"to",
"do",
"any",
"further",
"processing",
"on",
"the",
"automatically",
"added",
"arguments",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L403-L437 |
2,827 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.add_attrs | def add_attrs(self, symbol, **kwargs):
"""
Helper for setting symbol extension attributes
"""
for key, val in kwargs.items():
symbol.add_extension_attribute(self.extension_name, key, val) | python | def add_attrs(self, symbol, **kwargs):
"""
Helper for setting symbol extension attributes
"""
for key, val in kwargs.items():
symbol.add_extension_attribute(self.extension_name, key, val) | [
"def",
"add_attrs",
"(",
"self",
",",
"symbol",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"symbol",
".",
"add_extension_attribute",
"(",
"self",
".",
"extension_name",
",",
"key",
",",
"val",
")"
] | Helper for setting symbol extension attributes | [
"Helper",
"for",
"setting",
"symbol",
"extension",
"attributes"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L439-L444 |
2,828 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.get_attr | def get_attr(self, symbol, attrname):
"""
Helper for getting symbol extension attributes
"""
return symbol.extension_attributes.get(self.extension_name, {}).get(
attrname, None) | python | def get_attr(self, symbol, attrname):
"""
Helper for getting symbol extension attributes
"""
return symbol.extension_attributes.get(self.extension_name, {}).get(
attrname, None) | [
"def",
"get_attr",
"(",
"self",
",",
"symbol",
",",
"attrname",
")",
":",
"return",
"symbol",
".",
"extension_attributes",
".",
"get",
"(",
"self",
".",
"extension_name",
",",
"{",
"}",
")",
".",
"get",
"(",
"attrname",
",",
"None",
")"
] | Helper for getting symbol extension attributes | [
"Helper",
"for",
"getting",
"symbol",
"extension",
"attributes"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L446-L451 |
2,829 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.add_index_argument | def add_index_argument(cls, group):
"""
Subclasses may call this to add an index argument.
Args:
group: arparse.ArgumentGroup, the extension argument group
prefix: str, arguments have to be namespaced
"""
prefix = cls.argument_prefix
group.add_argument(
'--%s-index' % prefix, action="store",
dest="%s_index" % prefix,
help=("Name of the %s root markdown file, can be None" % (
cls.extension_name))) | python | def add_index_argument(cls, group):
"""
Subclasses may call this to add an index argument.
Args:
group: arparse.ArgumentGroup, the extension argument group
prefix: str, arguments have to be namespaced
"""
prefix = cls.argument_prefix
group.add_argument(
'--%s-index' % prefix, action="store",
dest="%s_index" % prefix,
help=("Name of the %s root markdown file, can be None" % (
cls.extension_name))) | [
"def",
"add_index_argument",
"(",
"cls",
",",
"group",
")",
":",
"prefix",
"=",
"cls",
".",
"argument_prefix",
"group",
".",
"add_argument",
"(",
"'--%s-index'",
"%",
"prefix",
",",
"action",
"=",
"\"store\"",
",",
"dest",
"=",
"\"%s_index\"",
"%",
"prefix",
",",
"help",
"=",
"(",
"\"Name of the %s root markdown file, can be None\"",
"%",
"(",
"cls",
".",
"extension_name",
")",
")",
")"
] | Subclasses may call this to add an index argument.
Args:
group: arparse.ArgumentGroup, the extension argument group
prefix: str, arguments have to be namespaced | [
"Subclasses",
"may",
"call",
"this",
"to",
"add",
"an",
"index",
"argument",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L479-L493 |
2,830 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.add_sources_argument | def add_sources_argument(cls, group, allow_filters=True, prefix=None, add_root_paths=False):
"""
Subclasses may call this to add sources and source_filters arguments.
Args:
group: arparse.ArgumentGroup, the extension argument group
allow_filters: bool, Whether the extension wishes to expose a
source_filters argument.
prefix: str, arguments have to be namespaced.
"""
prefix = prefix or cls.argument_prefix
group.add_argument("--%s-sources" % prefix,
action="store", nargs="+",
dest="%s_sources" % prefix.replace('-', '_'),
help="%s source files to parse" % prefix)
if allow_filters:
group.add_argument("--%s-source-filters" % prefix,
action="store", nargs="+",
dest="%s_source_filters" % prefix.replace(
'-', '_'),
help="%s source files to ignore" % prefix)
if add_root_paths:
group.add_argument("--%s-source-roots" % prefix,
action="store", nargs="+",
dest="%s_source_roots" % prefix.replace(
'-', '_'),
help="%s source root directories allowing files "
"to be referenced relatively to those" % prefix) | python | def add_sources_argument(cls, group, allow_filters=True, prefix=None, add_root_paths=False):
"""
Subclasses may call this to add sources and source_filters arguments.
Args:
group: arparse.ArgumentGroup, the extension argument group
allow_filters: bool, Whether the extension wishes to expose a
source_filters argument.
prefix: str, arguments have to be namespaced.
"""
prefix = prefix or cls.argument_prefix
group.add_argument("--%s-sources" % prefix,
action="store", nargs="+",
dest="%s_sources" % prefix.replace('-', '_'),
help="%s source files to parse" % prefix)
if allow_filters:
group.add_argument("--%s-source-filters" % prefix,
action="store", nargs="+",
dest="%s_source_filters" % prefix.replace(
'-', '_'),
help="%s source files to ignore" % prefix)
if add_root_paths:
group.add_argument("--%s-source-roots" % prefix,
action="store", nargs="+",
dest="%s_source_roots" % prefix.replace(
'-', '_'),
help="%s source root directories allowing files "
"to be referenced relatively to those" % prefix) | [
"def",
"add_sources_argument",
"(",
"cls",
",",
"group",
",",
"allow_filters",
"=",
"True",
",",
"prefix",
"=",
"None",
",",
"add_root_paths",
"=",
"False",
")",
":",
"prefix",
"=",
"prefix",
"or",
"cls",
".",
"argument_prefix",
"group",
".",
"add_argument",
"(",
"\"--%s-sources\"",
"%",
"prefix",
",",
"action",
"=",
"\"store\"",
",",
"nargs",
"=",
"\"+\"",
",",
"dest",
"=",
"\"%s_sources\"",
"%",
"prefix",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
",",
"help",
"=",
"\"%s source files to parse\"",
"%",
"prefix",
")",
"if",
"allow_filters",
":",
"group",
".",
"add_argument",
"(",
"\"--%s-source-filters\"",
"%",
"prefix",
",",
"action",
"=",
"\"store\"",
",",
"nargs",
"=",
"\"+\"",
",",
"dest",
"=",
"\"%s_source_filters\"",
"%",
"prefix",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
",",
"help",
"=",
"\"%s source files to ignore\"",
"%",
"prefix",
")",
"if",
"add_root_paths",
":",
"group",
".",
"add_argument",
"(",
"\"--%s-source-roots\"",
"%",
"prefix",
",",
"action",
"=",
"\"store\"",
",",
"nargs",
"=",
"\"+\"",
",",
"dest",
"=",
"\"%s_source_roots\"",
"%",
"prefix",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
",",
"help",
"=",
"\"%s source root directories allowing files \"",
"\"to be referenced relatively to those\"",
"%",
"prefix",
")"
] | Subclasses may call this to add sources and source_filters arguments.
Args:
group: arparse.ArgumentGroup, the extension argument group
allow_filters: bool, Whether the extension wishes to expose a
source_filters argument.
prefix: str, arguments have to be namespaced. | [
"Subclasses",
"may",
"call",
"this",
"to",
"add",
"sources",
"and",
"source_filters",
"arguments",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L496-L526 |
2,831 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.add_path_argument | def add_path_argument(cls, group, argname, dest=None, help_=None):
"""
Subclasses may call this to expose a path argument.
Args:
group: arparse.ArgumentGroup, the extension argument group
argname: str, the name of the argument, will be namespaced.
dest: str, similar to the `dest` argument of
`argparse.ArgumentParser.add_argument`, will be namespaced.
help_: str, similar to the `help` argument of
`argparse.ArgumentParser.add_argument`.
"""
prefixed = '%s-%s' % (cls.argument_prefix, argname)
if dest is None:
dest = prefixed.replace('-', '_')
final_dest = dest[len(cls.argument_prefix) + 1:]
else:
final_dest = dest
dest = '%s_%s' % (cls.argument_prefix, dest)
group.add_argument('--%s' % prefixed, action='store',
dest=dest, help=help_)
cls.path_arguments[dest] = final_dest | python | def add_path_argument(cls, group, argname, dest=None, help_=None):
"""
Subclasses may call this to expose a path argument.
Args:
group: arparse.ArgumentGroup, the extension argument group
argname: str, the name of the argument, will be namespaced.
dest: str, similar to the `dest` argument of
`argparse.ArgumentParser.add_argument`, will be namespaced.
help_: str, similar to the `help` argument of
`argparse.ArgumentParser.add_argument`.
"""
prefixed = '%s-%s' % (cls.argument_prefix, argname)
if dest is None:
dest = prefixed.replace('-', '_')
final_dest = dest[len(cls.argument_prefix) + 1:]
else:
final_dest = dest
dest = '%s_%s' % (cls.argument_prefix, dest)
group.add_argument('--%s' % prefixed, action='store',
dest=dest, help=help_)
cls.path_arguments[dest] = final_dest | [
"def",
"add_path_argument",
"(",
"cls",
",",
"group",
",",
"argname",
",",
"dest",
"=",
"None",
",",
"help_",
"=",
"None",
")",
":",
"prefixed",
"=",
"'%s-%s'",
"%",
"(",
"cls",
".",
"argument_prefix",
",",
"argname",
")",
"if",
"dest",
"is",
"None",
":",
"dest",
"=",
"prefixed",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"final_dest",
"=",
"dest",
"[",
"len",
"(",
"cls",
".",
"argument_prefix",
")",
"+",
"1",
":",
"]",
"else",
":",
"final_dest",
"=",
"dest",
"dest",
"=",
"'%s_%s'",
"%",
"(",
"cls",
".",
"argument_prefix",
",",
"dest",
")",
"group",
".",
"add_argument",
"(",
"'--%s'",
"%",
"prefixed",
",",
"action",
"=",
"'store'",
",",
"dest",
"=",
"dest",
",",
"help",
"=",
"help_",
")",
"cls",
".",
"path_arguments",
"[",
"dest",
"]",
"=",
"final_dest"
] | Subclasses may call this to expose a path argument.
Args:
group: arparse.ArgumentGroup, the extension argument group
argname: str, the name of the argument, will be namespaced.
dest: str, similar to the `dest` argument of
`argparse.ArgumentParser.add_argument`, will be namespaced.
help_: str, similar to the `help` argument of
`argparse.ArgumentParser.add_argument`. | [
"Subclasses",
"may",
"call",
"this",
"to",
"expose",
"a",
"path",
"argument",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L529-L551 |
2,832 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.add_paths_argument | def add_paths_argument(cls, group, argname, dest=None, help_=None):
"""
Subclasses may call this to expose a paths argument.
Args:
group: arparse.ArgumentGroup, the extension argument group
argname: str, the name of the argument, will be namespaced.
dest: str, similar to the `dest` argument of
`argparse.ArgumentParser.add_argument`, will be namespaced.
help_: str, similar to the `help` argument of
`argparse.ArgumentParser.add_argument`.
"""
prefixed = '%s-%s' % (cls.argument_prefix, argname)
if dest is None:
dest = prefixed.replace('-', '_')
final_dest = dest[len(cls.argument_prefix) + 1:]
else:
final_dest = dest
dest = '%s_%s' % (cls.argument_prefix, dest)
group.add_argument('--%s' % prefixed, action='store', nargs='+',
dest=dest, help=help_)
cls.paths_arguments[dest] = final_dest | python | def add_paths_argument(cls, group, argname, dest=None, help_=None):
"""
Subclasses may call this to expose a paths argument.
Args:
group: arparse.ArgumentGroup, the extension argument group
argname: str, the name of the argument, will be namespaced.
dest: str, similar to the `dest` argument of
`argparse.ArgumentParser.add_argument`, will be namespaced.
help_: str, similar to the `help` argument of
`argparse.ArgumentParser.add_argument`.
"""
prefixed = '%s-%s' % (cls.argument_prefix, argname)
if dest is None:
dest = prefixed.replace('-', '_')
final_dest = dest[len(cls.argument_prefix) + 1:]
else:
final_dest = dest
dest = '%s_%s' % (cls.argument_prefix, dest)
group.add_argument('--%s' % prefixed, action='store', nargs='+',
dest=dest, help=help_)
cls.paths_arguments[dest] = final_dest | [
"def",
"add_paths_argument",
"(",
"cls",
",",
"group",
",",
"argname",
",",
"dest",
"=",
"None",
",",
"help_",
"=",
"None",
")",
":",
"prefixed",
"=",
"'%s-%s'",
"%",
"(",
"cls",
".",
"argument_prefix",
",",
"argname",
")",
"if",
"dest",
"is",
"None",
":",
"dest",
"=",
"prefixed",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"final_dest",
"=",
"dest",
"[",
"len",
"(",
"cls",
".",
"argument_prefix",
")",
"+",
"1",
":",
"]",
"else",
":",
"final_dest",
"=",
"dest",
"dest",
"=",
"'%s_%s'",
"%",
"(",
"cls",
".",
"argument_prefix",
",",
"dest",
")",
"group",
".",
"add_argument",
"(",
"'--%s'",
"%",
"prefixed",
",",
"action",
"=",
"'store'",
",",
"nargs",
"=",
"'+'",
",",
"dest",
"=",
"dest",
",",
"help",
"=",
"help_",
")",
"cls",
".",
"paths_arguments",
"[",
"dest",
"]",
"=",
"final_dest"
] | Subclasses may call this to expose a paths argument.
Args:
group: arparse.ArgumentGroup, the extension argument group
argname: str, the name of the argument, will be namespaced.
dest: str, similar to the `dest` argument of
`argparse.ArgumentParser.add_argument`, will be namespaced.
help_: str, similar to the `help` argument of
`argparse.ArgumentParser.add_argument`. | [
"Subclasses",
"may",
"call",
"this",
"to",
"expose",
"a",
"paths",
"argument",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L554-L576 |
2,833 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.create_symbol | def create_symbol(self, *args, **kwargs):
"""
Extensions that discover and create instances of `symbols.Symbol`
should do this through this method, as it will keep an index
of these which can be used when generating a "naive index".
See `database.Database.create_symbol` for more
information.
Args:
args: see `database.Database.create_symbol`
kwargs: see `database.Database.create_symbol`
Returns:
symbols.Symbol: the created symbol, or `None`.
"""
if not kwargs.get('project_name'):
kwargs['project_name'] = self.project.project_name
sym = self.app.database.create_symbol(*args, **kwargs)
if sym:
# pylint: disable=unidiomatic-typecheck
if type(sym) != Symbol:
self._created_symbols[sym.filename].add(sym.unique_name)
return sym | python | def create_symbol(self, *args, **kwargs):
"""
Extensions that discover and create instances of `symbols.Symbol`
should do this through this method, as it will keep an index
of these which can be used when generating a "naive index".
See `database.Database.create_symbol` for more
information.
Args:
args: see `database.Database.create_symbol`
kwargs: see `database.Database.create_symbol`
Returns:
symbols.Symbol: the created symbol, or `None`.
"""
if not kwargs.get('project_name'):
kwargs['project_name'] = self.project.project_name
sym = self.app.database.create_symbol(*args, **kwargs)
if sym:
# pylint: disable=unidiomatic-typecheck
if type(sym) != Symbol:
self._created_symbols[sym.filename].add(sym.unique_name)
return sym | [
"def",
"create_symbol",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"get",
"(",
"'project_name'",
")",
":",
"kwargs",
"[",
"'project_name'",
"]",
"=",
"self",
".",
"project",
".",
"project_name",
"sym",
"=",
"self",
".",
"app",
".",
"database",
".",
"create_symbol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"sym",
":",
"# pylint: disable=unidiomatic-typecheck",
"if",
"type",
"(",
"sym",
")",
"!=",
"Symbol",
":",
"self",
".",
"_created_symbols",
"[",
"sym",
".",
"filename",
"]",
".",
"add",
"(",
"sym",
".",
"unique_name",
")",
"return",
"sym"
] | Extensions that discover and create instances of `symbols.Symbol`
should do this through this method, as it will keep an index
of these which can be used when generating a "naive index".
See `database.Database.create_symbol` for more
information.
Args:
args: see `database.Database.create_symbol`
kwargs: see `database.Database.create_symbol`
Returns:
symbols.Symbol: the created symbol, or `None`. | [
"Extensions",
"that",
"discover",
"and",
"create",
"instances",
"of",
"symbols",
".",
"Symbol",
"should",
"do",
"this",
"through",
"this",
"method",
"as",
"it",
"will",
"keep",
"an",
"index",
"of",
"these",
"which",
"can",
"be",
"used",
"when",
"generating",
"a",
"naive",
"index",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L584-L609 |
2,834 | hotdoc/hotdoc | hotdoc/core/extension.py | Extension.format_page | def format_page(self, page, link_resolver, output):
"""
Called by `project.Project.format_page`, to leave full control
to extensions over the formatting of the pages they are
responsible of.
Args:
page: tree.Page, the page to format.
link_resolver: links.LinkResolver, object responsible
for resolving links potentially mentioned in `page`
output: str, path to the output directory.
"""
debug('Formatting page %s' % page.link.ref, 'formatting')
if output:
actual_output = os.path.join(output,
'html')
if not os.path.exists(actual_output):
os.makedirs(actual_output)
else:
actual_output = None
page.format(self.formatter, link_resolver, actual_output) | python | def format_page(self, page, link_resolver, output):
"""
Called by `project.Project.format_page`, to leave full control
to extensions over the formatting of the pages they are
responsible of.
Args:
page: tree.Page, the page to format.
link_resolver: links.LinkResolver, object responsible
for resolving links potentially mentioned in `page`
output: str, path to the output directory.
"""
debug('Formatting page %s' % page.link.ref, 'formatting')
if output:
actual_output = os.path.join(output,
'html')
if not os.path.exists(actual_output):
os.makedirs(actual_output)
else:
actual_output = None
page.format(self.formatter, link_resolver, actual_output) | [
"def",
"format_page",
"(",
"self",
",",
"page",
",",
"link_resolver",
",",
"output",
")",
":",
"debug",
"(",
"'Formatting page %s'",
"%",
"page",
".",
"link",
".",
"ref",
",",
"'formatting'",
")",
"if",
"output",
":",
"actual_output",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output",
",",
"'html'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"actual_output",
")",
":",
"os",
".",
"makedirs",
"(",
"actual_output",
")",
"else",
":",
"actual_output",
"=",
"None",
"page",
".",
"format",
"(",
"self",
".",
"formatter",
",",
"link_resolver",
",",
"actual_output",
")"
] | Called by `project.Project.format_page`, to leave full control
to extensions over the formatting of the pages they are
responsible of.
Args:
page: tree.Page, the page to format.
link_resolver: links.LinkResolver, object responsible
for resolving links potentially mentioned in `page`
output: str, path to the output directory. | [
"Called",
"by",
"project",
".",
"Project",
".",
"format_page",
"to",
"leave",
"full",
"control",
"to",
"extensions",
"over",
"the",
"formatting",
"of",
"the",
"pages",
"they",
"are",
"responsible",
"of",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L646-L668 |
2,835 | hotdoc/hotdoc | hotdoc/core/project.py | Project.add_subproject | def add_subproject(self, fname, conf_path):
"""Creates and adds a new subproject."""
config = Config(conf_file=conf_path)
proj = Project(self.app,
dependency_map=self.dependency_map)
proj.parse_name_from_config(config)
proj.parse_config(config)
proj.setup()
self.subprojects[fname] = proj | python | def add_subproject(self, fname, conf_path):
"""Creates and adds a new subproject."""
config = Config(conf_file=conf_path)
proj = Project(self.app,
dependency_map=self.dependency_map)
proj.parse_name_from_config(config)
proj.parse_config(config)
proj.setup()
self.subprojects[fname] = proj | [
"def",
"add_subproject",
"(",
"self",
",",
"fname",
",",
"conf_path",
")",
":",
"config",
"=",
"Config",
"(",
"conf_file",
"=",
"conf_path",
")",
"proj",
"=",
"Project",
"(",
"self",
".",
"app",
",",
"dependency_map",
"=",
"self",
".",
"dependency_map",
")",
"proj",
".",
"parse_name_from_config",
"(",
"config",
")",
"proj",
".",
"parse_config",
"(",
"config",
")",
"proj",
".",
"setup",
"(",
")",
"self",
".",
"subprojects",
"[",
"fname",
"]",
"=",
"proj"
] | Creates and adds a new subproject. | [
"Creates",
"and",
"adds",
"a",
"new",
"subproject",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L226-L234 |
2,836 | hotdoc/hotdoc | hotdoc/core/tree.py | _no_duplicates_constructor | def _no_duplicates_constructor(loader, node, deep=False):
"""Check for duplicate keys."""
mapping = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
value = loader.construct_object(value_node, deep=deep)
if key in mapping:
raise ConstructorError("while constructing a mapping",
node.start_mark,
"found duplicate key (%s)" % key,
key_node.start_mark)
mapping[key] = value
return loader.construct_mapping(node, deep) | python | def _no_duplicates_constructor(loader, node, deep=False):
"""Check for duplicate keys."""
mapping = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
value = loader.construct_object(value_node, deep=deep)
if key in mapping:
raise ConstructorError("while constructing a mapping",
node.start_mark,
"found duplicate key (%s)" % key,
key_node.start_mark)
mapping[key] = value
return loader.construct_mapping(node, deep) | [
"def",
"_no_duplicates_constructor",
"(",
"loader",
",",
"node",
",",
"deep",
"=",
"False",
")",
":",
"mapping",
"=",
"{",
"}",
"for",
"key_node",
",",
"value_node",
"in",
"node",
".",
"value",
":",
"key",
"=",
"loader",
".",
"construct_object",
"(",
"key_node",
",",
"deep",
"=",
"deep",
")",
"value",
"=",
"loader",
".",
"construct_object",
"(",
"value_node",
",",
"deep",
"=",
"deep",
")",
"if",
"key",
"in",
"mapping",
":",
"raise",
"ConstructorError",
"(",
"\"while constructing a mapping\"",
",",
"node",
".",
"start_mark",
",",
"\"found duplicate key (%s)\"",
"%",
"key",
",",
"key_node",
".",
"start_mark",
")",
"mapping",
"[",
"key",
"]",
"=",
"value",
"return",
"loader",
".",
"construct_mapping",
"(",
"node",
",",
"deep",
")"
] | Check for duplicate keys. | [
"Check",
"for",
"duplicate",
"keys",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L49-L63 |
2,837 | hotdoc/hotdoc | hotdoc/core/tree.py | Page.resolve_symbols | def resolve_symbols(self, tree, database, link_resolver):
"""
When this method is called, the page's symbol names are queried
from `database`, and added to lists of actual symbols, sorted
by symbol class.
"""
self.typed_symbols = self.__get_empty_typed_symbols()
all_syms = OrderedSet()
for sym_name in self.symbol_names:
sym = database.get_symbol(sym_name)
self.__query_extra_symbols(
sym, all_syms, tree, link_resolver, database)
if tree.project.is_toplevel:
page_path = self.link.ref
else:
page_path = self.project_name + '/' + self.link.ref
if self.meta.get("auto-sort", True):
all_syms = sorted(all_syms, key=lambda x: x.unique_name)
for sym in all_syms:
sym.update_children_comments()
self.__resolve_symbol(sym, link_resolver, page_path)
self.symbol_names.add(sym.unique_name)
# Always put symbols with no parent at the end
no_parent_syms = self.by_parent_symbols.pop(None, None)
if no_parent_syms:
self.by_parent_symbols[None] = no_parent_syms
for sym_type in [ClassSymbol, AliasSymbol, InterfaceSymbol,
StructSymbol]:
syms = self.typed_symbols[sym_type].symbols
if not syms:
continue
if self.title is None:
self.title = syms[0].display_name
if self.comment is None:
self.comment = Comment(name=self.name)
self.comment.short_description = syms[
0].comment.short_description
self.comment.title = syms[0].comment.title
break | python | def resolve_symbols(self, tree, database, link_resolver):
"""
When this method is called, the page's symbol names are queried
from `database`, and added to lists of actual symbols, sorted
by symbol class.
"""
self.typed_symbols = self.__get_empty_typed_symbols()
all_syms = OrderedSet()
for sym_name in self.symbol_names:
sym = database.get_symbol(sym_name)
self.__query_extra_symbols(
sym, all_syms, tree, link_resolver, database)
if tree.project.is_toplevel:
page_path = self.link.ref
else:
page_path = self.project_name + '/' + self.link.ref
if self.meta.get("auto-sort", True):
all_syms = sorted(all_syms, key=lambda x: x.unique_name)
for sym in all_syms:
sym.update_children_comments()
self.__resolve_symbol(sym, link_resolver, page_path)
self.symbol_names.add(sym.unique_name)
# Always put symbols with no parent at the end
no_parent_syms = self.by_parent_symbols.pop(None, None)
if no_parent_syms:
self.by_parent_symbols[None] = no_parent_syms
for sym_type in [ClassSymbol, AliasSymbol, InterfaceSymbol,
StructSymbol]:
syms = self.typed_symbols[sym_type].symbols
if not syms:
continue
if self.title is None:
self.title = syms[0].display_name
if self.comment is None:
self.comment = Comment(name=self.name)
self.comment.short_description = syms[
0].comment.short_description
self.comment.title = syms[0].comment.title
break | [
"def",
"resolve_symbols",
"(",
"self",
",",
"tree",
",",
"database",
",",
"link_resolver",
")",
":",
"self",
".",
"typed_symbols",
"=",
"self",
".",
"__get_empty_typed_symbols",
"(",
")",
"all_syms",
"=",
"OrderedSet",
"(",
")",
"for",
"sym_name",
"in",
"self",
".",
"symbol_names",
":",
"sym",
"=",
"database",
".",
"get_symbol",
"(",
"sym_name",
")",
"self",
".",
"__query_extra_symbols",
"(",
"sym",
",",
"all_syms",
",",
"tree",
",",
"link_resolver",
",",
"database",
")",
"if",
"tree",
".",
"project",
".",
"is_toplevel",
":",
"page_path",
"=",
"self",
".",
"link",
".",
"ref",
"else",
":",
"page_path",
"=",
"self",
".",
"project_name",
"+",
"'/'",
"+",
"self",
".",
"link",
".",
"ref",
"if",
"self",
".",
"meta",
".",
"get",
"(",
"\"auto-sort\"",
",",
"True",
")",
":",
"all_syms",
"=",
"sorted",
"(",
"all_syms",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"unique_name",
")",
"for",
"sym",
"in",
"all_syms",
":",
"sym",
".",
"update_children_comments",
"(",
")",
"self",
".",
"__resolve_symbol",
"(",
"sym",
",",
"link_resolver",
",",
"page_path",
")",
"self",
".",
"symbol_names",
".",
"add",
"(",
"sym",
".",
"unique_name",
")",
"# Always put symbols with no parent at the end",
"no_parent_syms",
"=",
"self",
".",
"by_parent_symbols",
".",
"pop",
"(",
"None",
",",
"None",
")",
"if",
"no_parent_syms",
":",
"self",
".",
"by_parent_symbols",
"[",
"None",
"]",
"=",
"no_parent_syms",
"for",
"sym_type",
"in",
"[",
"ClassSymbol",
",",
"AliasSymbol",
",",
"InterfaceSymbol",
",",
"StructSymbol",
"]",
":",
"syms",
"=",
"self",
".",
"typed_symbols",
"[",
"sym_type",
"]",
".",
"symbols",
"if",
"not",
"syms",
":",
"continue",
"if",
"self",
".",
"title",
"is",
"None",
":",
"self",
".",
"title",
"=",
"syms",
"[",
"0",
"]",
".",
"display_name",
"if",
"self",
".",
"comment",
"is",
"None",
":",
"self",
".",
"comment",
"=",
"Comment",
"(",
"name",
"=",
"self",
".",
"name",
")",
"self",
".",
"comment",
".",
"short_description",
"=",
"syms",
"[",
"0",
"]",
".",
"comment",
".",
"short_description",
"self",
".",
"comment",
".",
"title",
"=",
"syms",
"[",
"0",
"]",
".",
"comment",
".",
"title",
"break"
] | When this method is called, the page's symbol names are queried
from `database`, and added to lists of actual symbols, sorted
by symbol class. | [
"When",
"this",
"method",
"is",
"called",
"the",
"page",
"s",
"symbol",
"names",
"are",
"queried",
"from",
"database",
"and",
"added",
"to",
"lists",
"of",
"actual",
"symbols",
"sorted",
"by",
"symbol",
"class",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L196-L240 |
2,838 | hotdoc/hotdoc | hotdoc/core/tree.py | Tree.walk | def walk(self, parent=None):
"""Generator that yields pages in infix order
Args:
parent: hotdoc.core.tree.Page, optional, the page to start
traversal from. If None, defaults to the root of the tree.
Yields:
hotdoc.core.tree.Page: the next page
"""
if parent is None:
yield self.root
parent = self.root
for cpage_name in parent.subpages:
cpage = self.__all_pages[cpage_name]
yield cpage
for page in self.walk(parent=cpage):
yield page | python | def walk(self, parent=None):
"""Generator that yields pages in infix order
Args:
parent: hotdoc.core.tree.Page, optional, the page to start
traversal from. If None, defaults to the root of the tree.
Yields:
hotdoc.core.tree.Page: the next page
"""
if parent is None:
yield self.root
parent = self.root
for cpage_name in parent.subpages:
cpage = self.__all_pages[cpage_name]
yield cpage
for page in self.walk(parent=cpage):
yield page | [
"def",
"walk",
"(",
"self",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"is",
"None",
":",
"yield",
"self",
".",
"root",
"parent",
"=",
"self",
".",
"root",
"for",
"cpage_name",
"in",
"parent",
".",
"subpages",
":",
"cpage",
"=",
"self",
".",
"__all_pages",
"[",
"cpage_name",
"]",
"yield",
"cpage",
"for",
"page",
"in",
"self",
".",
"walk",
"(",
"parent",
"=",
"cpage",
")",
":",
"yield",
"page"
] | Generator that yields pages in infix order
Args:
parent: hotdoc.core.tree.Page, optional, the page to start
traversal from. If None, defaults to the root of the tree.
Yields:
hotdoc.core.tree.Page: the next page | [
"Generator",
"that",
"yields",
"pages",
"in",
"infix",
"order"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L514-L532 |
2,839 | hotdoc/hotdoc | hotdoc/extensions/__init__.py | get_extension_classes | def get_extension_classes():
"""
Hotdoc's setuptools entry point
"""
res = [SyntaxHighlightingExtension, SearchExtension, TagExtension,
DevhelpExtension, LicenseExtension, GitUploadExtension,
EditOnGitHubExtension]
if sys.version_info[1] >= 5:
res += [DBusExtension]
try:
from hotdoc.extensions.c.c_extension import CExtension
res += [CExtension]
except ImportError:
pass
try:
from hotdoc.extensions.gi.gi_extension import GIExtension
res += [GIExtension]
except ImportError:
pass
return res | python | def get_extension_classes():
"""
Hotdoc's setuptools entry point
"""
res = [SyntaxHighlightingExtension, SearchExtension, TagExtension,
DevhelpExtension, LicenseExtension, GitUploadExtension,
EditOnGitHubExtension]
if sys.version_info[1] >= 5:
res += [DBusExtension]
try:
from hotdoc.extensions.c.c_extension import CExtension
res += [CExtension]
except ImportError:
pass
try:
from hotdoc.extensions.gi.gi_extension import GIExtension
res += [GIExtension]
except ImportError:
pass
return res | [
"def",
"get_extension_classes",
"(",
")",
":",
"res",
"=",
"[",
"SyntaxHighlightingExtension",
",",
"SearchExtension",
",",
"TagExtension",
",",
"DevhelpExtension",
",",
"LicenseExtension",
",",
"GitUploadExtension",
",",
"EditOnGitHubExtension",
"]",
"if",
"sys",
".",
"version_info",
"[",
"1",
"]",
">=",
"5",
":",
"res",
"+=",
"[",
"DBusExtension",
"]",
"try",
":",
"from",
"hotdoc",
".",
"extensions",
".",
"c",
".",
"c_extension",
"import",
"CExtension",
"res",
"+=",
"[",
"CExtension",
"]",
"except",
"ImportError",
":",
"pass",
"try",
":",
"from",
"hotdoc",
".",
"extensions",
".",
"gi",
".",
"gi_extension",
"import",
"GIExtension",
"res",
"+=",
"[",
"GIExtension",
"]",
"except",
"ImportError",
":",
"pass",
"return",
"res"
] | Hotdoc's setuptools entry point | [
"Hotdoc",
"s",
"setuptools",
"entry",
"point"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/__init__.py#L40-L63 |
2,840 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | register_functions | def register_functions(lib, ignore_errors):
"""Register function prototypes with a libclang library instance.
This must be called as part of library instantiation so Python knows how
to call out to the shared library.
"""
def register(item):
return register_function(lib, item, ignore_errors)
for f in functionList:
register(f) | python | def register_functions(lib, ignore_errors):
"""Register function prototypes with a libclang library instance.
This must be called as part of library instantiation so Python knows how
to call out to the shared library.
"""
def register(item):
return register_function(lib, item, ignore_errors)
for f in functionList:
register(f) | [
"def",
"register_functions",
"(",
"lib",
",",
"ignore_errors",
")",
":",
"def",
"register",
"(",
"item",
")",
":",
"return",
"register_function",
"(",
"lib",
",",
"item",
",",
"ignore_errors",
")",
"for",
"f",
"in",
"functionList",
":",
"register",
"(",
"f",
")"
] | Register function prototypes with a libclang library instance.
This must be called as part of library instantiation so Python knows how
to call out to the shared library. | [
"Register",
"function",
"prototypes",
"with",
"a",
"libclang",
"library",
"instance",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L3814-L3825 |
2,841 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | SourceLocation.from_offset | def from_offset(tu, file, offset):
"""Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file
"""
return conf.lib.clang_getLocationForOffset(tu, file, offset) | python | def from_offset(tu, file, offset):
"""Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file
"""
return conf.lib.clang_getLocationForOffset(tu, file, offset) | [
"def",
"from_offset",
"(",
"tu",
",",
"file",
",",
"offset",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getLocationForOffset",
"(",
"tu",
",",
"file",
",",
"offset",
")"
] | Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file | [
"Retrieve",
"a",
"SourceLocation",
"from",
"a",
"given",
"character",
"offset",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L217-L224 |
2,842 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TokenGroup.get_tokens | def get_tokens(tu, extent):
"""Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place.
"""
tokens_memory = POINTER(Token)()
tokens_count = c_uint()
conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
byref(tokens_count))
count = int(tokens_count.value)
# If we get no tokens, no memory was allocated. Be sure not to return
# anything and potentially call a destructor on nothing.
if count < 1:
return
tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
token_group = TokenGroup(tu, tokens_memory, tokens_count)
for i in xrange(0, count):
token = Token()
token.int_data = tokens_array[i].int_data
token.ptr_data = tokens_array[i].ptr_data
token._tu = tu
token._group = token_group
yield token | python | def get_tokens(tu, extent):
"""Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place.
"""
tokens_memory = POINTER(Token)()
tokens_count = c_uint()
conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
byref(tokens_count))
count = int(tokens_count.value)
# If we get no tokens, no memory was allocated. Be sure not to return
# anything and potentially call a destructor on nothing.
if count < 1:
return
tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
token_group = TokenGroup(tu, tokens_memory, tokens_count)
for i in xrange(0, count):
token = Token()
token.int_data = tokens_array[i].int_data
token.ptr_data = tokens_array[i].ptr_data
token._tu = tu
token._group = token_group
yield token | [
"def",
"get_tokens",
"(",
"tu",
",",
"extent",
")",
":",
"tokens_memory",
"=",
"POINTER",
"(",
"Token",
")",
"(",
")",
"tokens_count",
"=",
"c_uint",
"(",
")",
"conf",
".",
"lib",
".",
"clang_tokenize",
"(",
"tu",
",",
"extent",
",",
"byref",
"(",
"tokens_memory",
")",
",",
"byref",
"(",
"tokens_count",
")",
")",
"count",
"=",
"int",
"(",
"tokens_count",
".",
"value",
")",
"# If we get no tokens, no memory was allocated. Be sure not to return",
"# anything and potentially call a destructor on nothing.",
"if",
"count",
"<",
"1",
":",
"return",
"tokens_array",
"=",
"cast",
"(",
"tokens_memory",
",",
"POINTER",
"(",
"Token",
"*",
"count",
")",
")",
".",
"contents",
"token_group",
"=",
"TokenGroup",
"(",
"tu",
",",
"tokens_memory",
",",
"tokens_count",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"count",
")",
":",
"token",
"=",
"Token",
"(",
")",
"token",
".",
"int_data",
"=",
"tokens_array",
"[",
"i",
"]",
".",
"int_data",
"token",
".",
"ptr_data",
"=",
"tokens_array",
"[",
"i",
"]",
".",
"ptr_data",
"token",
".",
"_tu",
"=",
"tu",
"token",
".",
"_group",
"=",
"token_group",
"yield",
"token"
] | Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place. | [
"Helper",
"method",
"to",
"return",
"all",
"tokens",
"in",
"an",
"extent",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L500-L530 |
2,843 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TokenKind.from_value | def from_value(value):
"""Obtain a registered TokenKind instance from its value."""
result = TokenKind._value_map.get(value, None)
if result is None:
raise ValueError('Unknown TokenKind: %d' % value)
return result | python | def from_value(value):
"""Obtain a registered TokenKind instance from its value."""
result = TokenKind._value_map.get(value, None)
if result is None:
raise ValueError('Unknown TokenKind: %d' % value)
return result | [
"def",
"from_value",
"(",
"value",
")",
":",
"result",
"=",
"TokenKind",
".",
"_value_map",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"result",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unknown TokenKind: %d'",
"%",
"value",
")",
"return",
"result"
] | Obtain a registered TokenKind instance from its value. | [
"Obtain",
"a",
"registered",
"TokenKind",
"instance",
"from",
"its",
"value",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L546-L553 |
2,844 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TokenKind.register | def register(value, name):
"""Register a new TokenKind enumeration.
This should only be called at module load time by code within this
package.
"""
if value in TokenKind._value_map:
raise ValueError('TokenKind already registered: %d' % value)
kind = TokenKind(value, name)
TokenKind._value_map[value] = kind
setattr(TokenKind, name, kind) | python | def register(value, name):
"""Register a new TokenKind enumeration.
This should only be called at module load time by code within this
package.
"""
if value in TokenKind._value_map:
raise ValueError('TokenKind already registered: %d' % value)
kind = TokenKind(value, name)
TokenKind._value_map[value] = kind
setattr(TokenKind, name, kind) | [
"def",
"register",
"(",
"value",
",",
"name",
")",
":",
"if",
"value",
"in",
"TokenKind",
".",
"_value_map",
":",
"raise",
"ValueError",
"(",
"'TokenKind already registered: %d'",
"%",
"value",
")",
"kind",
"=",
"TokenKind",
"(",
"value",
",",
"name",
")",
"TokenKind",
".",
"_value_map",
"[",
"value",
"]",
"=",
"kind",
"setattr",
"(",
"TokenKind",
",",
"name",
",",
"kind",
")"
] | Register a new TokenKind enumeration.
This should only be called at module load time by code within this
package. | [
"Register",
"a",
"new",
"TokenKind",
"enumeration",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L556-L567 |
2,845 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.canonical | def canonical(self):
"""Return the canonical Cursor corresponding to this Cursor.
The canonical cursor is the cursor which is representative for the
underlying entity. For example, if you have multiple forward
declarations for the same class, the canonical cursor for the forward
declarations will be identical.
"""
if not hasattr(self, '_canonical'):
self._canonical = conf.lib.clang_getCanonicalCursor(self)
return self._canonical | python | def canonical(self):
"""Return the canonical Cursor corresponding to this Cursor.
The canonical cursor is the cursor which is representative for the
underlying entity. For example, if you have multiple forward
declarations for the same class, the canonical cursor for the forward
declarations will be identical.
"""
if not hasattr(self, '_canonical'):
self._canonical = conf.lib.clang_getCanonicalCursor(self)
return self._canonical | [
"def",
"canonical",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_canonical'",
")",
":",
"self",
".",
"_canonical",
"=",
"conf",
".",
"lib",
".",
"clang_getCanonicalCursor",
"(",
"self",
")",
"return",
"self",
".",
"_canonical"
] | Return the canonical Cursor corresponding to this Cursor.
The canonical cursor is the cursor which is representative for the
underlying entity. For example, if you have multiple forward
declarations for the same class, the canonical cursor for the forward
declarations will be identical. | [
"Return",
"the",
"canonical",
"Cursor",
"corresponding",
"to",
"this",
"Cursor",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1542-L1553 |
2,846 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.result_type | def result_type(self):
"""Retrieve the Type of the result for this Cursor."""
if not hasattr(self, '_result_type'):
self._result_type = conf.lib.clang_getResultType(self.type)
return self._result_type | python | def result_type(self):
"""Retrieve the Type of the result for this Cursor."""
if not hasattr(self, '_result_type'):
self._result_type = conf.lib.clang_getResultType(self.type)
return self._result_type | [
"def",
"result_type",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_result_type'",
")",
":",
"self",
".",
"_result_type",
"=",
"conf",
".",
"lib",
".",
"clang_getResultType",
"(",
"self",
".",
"type",
")",
"return",
"self",
".",
"_result_type"
] | Retrieve the Type of the result for this Cursor. | [
"Retrieve",
"the",
"Type",
"of",
"the",
"result",
"for",
"this",
"Cursor",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1556-L1561 |
2,847 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.underlying_typedef_type | def underlying_typedef_type(self):
"""Return the underlying type of a typedef declaration.
Returns a Type for the typedef this cursor is a declaration for. If
the current cursor is not a typedef, this raises.
"""
if not hasattr(self, '_underlying_type'):
assert self.kind.is_declaration()
self._underlying_type = \
conf.lib.clang_getTypedefDeclUnderlyingType(self)
return self._underlying_type | python | def underlying_typedef_type(self):
"""Return the underlying type of a typedef declaration.
Returns a Type for the typedef this cursor is a declaration for. If
the current cursor is not a typedef, this raises.
"""
if not hasattr(self, '_underlying_type'):
assert self.kind.is_declaration()
self._underlying_type = \
conf.lib.clang_getTypedefDeclUnderlyingType(self)
return self._underlying_type | [
"def",
"underlying_typedef_type",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_underlying_type'",
")",
":",
"assert",
"self",
".",
"kind",
".",
"is_declaration",
"(",
")",
"self",
".",
"_underlying_type",
"=",
"conf",
".",
"lib",
".",
"clang_getTypedefDeclUnderlyingType",
"(",
"self",
")",
"return",
"self",
".",
"_underlying_type"
] | Return the underlying type of a typedef declaration.
Returns a Type for the typedef this cursor is a declaration for. If
the current cursor is not a typedef, this raises. | [
"Return",
"the",
"underlying",
"type",
"of",
"a",
"typedef",
"declaration",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1564-L1575 |
2,848 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.enum_type | def enum_type(self):
"""Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises.
"""
if not hasattr(self, '_enum_type'):
assert self.kind == CursorKind.ENUM_DECL
self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
return self._enum_type | python | def enum_type(self):
"""Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises.
"""
if not hasattr(self, '_enum_type'):
assert self.kind == CursorKind.ENUM_DECL
self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
return self._enum_type | [
"def",
"enum_type",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_enum_type'",
")",
":",
"assert",
"self",
".",
"kind",
"==",
"CursorKind",
".",
"ENUM_DECL",
"self",
".",
"_enum_type",
"=",
"conf",
".",
"lib",
".",
"clang_getEnumDeclIntegerType",
"(",
"self",
")",
"return",
"self",
".",
"_enum_type"
] | Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises. | [
"Return",
"the",
"integer",
"type",
"of",
"an",
"enum",
"declaration",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1578-L1588 |
2,849 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.enum_value | def enum_value(self):
"""Return the value of an enum constant."""
if not hasattr(self, '_enum_value'):
assert self.kind == CursorKind.ENUM_CONSTANT_DECL
# Figure out the underlying type of the enum to know if it
# is a signed or unsigned quantity.
underlying_type = self.type
if underlying_type.kind == TypeKind.ENUM:
underlying_type = underlying_type.get_declaration().enum_type
if underlying_type.kind in (TypeKind.CHAR_U,
TypeKind.UCHAR,
TypeKind.CHAR16,
TypeKind.CHAR32,
TypeKind.USHORT,
TypeKind.UINT,
TypeKind.ULONG,
TypeKind.ULONGLONG,
TypeKind.UINT128):
self._enum_value = \
conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
else:
self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
return self._enum_value | python | def enum_value(self):
"""Return the value of an enum constant."""
if not hasattr(self, '_enum_value'):
assert self.kind == CursorKind.ENUM_CONSTANT_DECL
# Figure out the underlying type of the enum to know if it
# is a signed or unsigned quantity.
underlying_type = self.type
if underlying_type.kind == TypeKind.ENUM:
underlying_type = underlying_type.get_declaration().enum_type
if underlying_type.kind in (TypeKind.CHAR_U,
TypeKind.UCHAR,
TypeKind.CHAR16,
TypeKind.CHAR32,
TypeKind.USHORT,
TypeKind.UINT,
TypeKind.ULONG,
TypeKind.ULONGLONG,
TypeKind.UINT128):
self._enum_value = \
conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
else:
self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
return self._enum_value | [
"def",
"enum_value",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_enum_value'",
")",
":",
"assert",
"self",
".",
"kind",
"==",
"CursorKind",
".",
"ENUM_CONSTANT_DECL",
"# Figure out the underlying type of the enum to know if it",
"# is a signed or unsigned quantity.",
"underlying_type",
"=",
"self",
".",
"type",
"if",
"underlying_type",
".",
"kind",
"==",
"TypeKind",
".",
"ENUM",
":",
"underlying_type",
"=",
"underlying_type",
".",
"get_declaration",
"(",
")",
".",
"enum_type",
"if",
"underlying_type",
".",
"kind",
"in",
"(",
"TypeKind",
".",
"CHAR_U",
",",
"TypeKind",
".",
"UCHAR",
",",
"TypeKind",
".",
"CHAR16",
",",
"TypeKind",
".",
"CHAR32",
",",
"TypeKind",
".",
"USHORT",
",",
"TypeKind",
".",
"UINT",
",",
"TypeKind",
".",
"ULONG",
",",
"TypeKind",
".",
"ULONGLONG",
",",
"TypeKind",
".",
"UINT128",
")",
":",
"self",
".",
"_enum_value",
"=",
"conf",
".",
"lib",
".",
"clang_getEnumConstantDeclUnsignedValue",
"(",
"self",
")",
"else",
":",
"self",
".",
"_enum_value",
"=",
"conf",
".",
"lib",
".",
"clang_getEnumConstantDeclValue",
"(",
"self",
")",
"return",
"self",
".",
"_enum_value"
] | Return the value of an enum constant. | [
"Return",
"the",
"value",
"of",
"an",
"enum",
"constant",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1591-L1613 |
2,850 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.hash | def hash(self):
"""Returns a hash of the cursor as an int."""
if not hasattr(self, '_hash'):
self._hash = conf.lib.clang_hashCursor(self)
return self._hash | python | def hash(self):
"""Returns a hash of the cursor as an int."""
if not hasattr(self, '_hash'):
self._hash = conf.lib.clang_hashCursor(self)
return self._hash | [
"def",
"hash",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_hash'",
")",
":",
"self",
".",
"_hash",
"=",
"conf",
".",
"lib",
".",
"clang_hashCursor",
"(",
"self",
")",
"return",
"self",
".",
"_hash"
] | Returns a hash of the cursor as an int. | [
"Returns",
"a",
"hash",
"of",
"the",
"cursor",
"as",
"an",
"int",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1625-L1630 |
2,851 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.semantic_parent | def semantic_parent(self):
"""Return the semantic parent for this cursor."""
if not hasattr(self, '_semantic_parent'):
self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
return self._semantic_parent | python | def semantic_parent(self):
"""Return the semantic parent for this cursor."""
if not hasattr(self, '_semantic_parent'):
self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
return self._semantic_parent | [
"def",
"semantic_parent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_semantic_parent'",
")",
":",
"self",
".",
"_semantic_parent",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorSemanticParent",
"(",
"self",
")",
"return",
"self",
".",
"_semantic_parent"
] | Return the semantic parent for this cursor. | [
"Return",
"the",
"semantic",
"parent",
"for",
"this",
"cursor",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1633-L1638 |
2,852 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.lexical_parent | def lexical_parent(self):
"""Return the lexical parent for this cursor."""
if not hasattr(self, '_lexical_parent'):
self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
return self._lexical_parent | python | def lexical_parent(self):
"""Return the lexical parent for this cursor."""
if not hasattr(self, '_lexical_parent'):
self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
return self._lexical_parent | [
"def",
"lexical_parent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_lexical_parent'",
")",
":",
"self",
".",
"_lexical_parent",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorLexicalParent",
"(",
"self",
")",
"return",
"self",
".",
"_lexical_parent"
] | Return the lexical parent for this cursor. | [
"Return",
"the",
"lexical",
"parent",
"for",
"this",
"cursor",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1641-L1646 |
2,853 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.referenced | def referenced(self):
"""
For a cursor that is a reference, returns a cursor
representing the entity that it references.
"""
if not hasattr(self, '_referenced'):
self._referenced = conf.lib.clang_getCursorReferenced(self)
return self._referenced | python | def referenced(self):
"""
For a cursor that is a reference, returns a cursor
representing the entity that it references.
"""
if not hasattr(self, '_referenced'):
self._referenced = conf.lib.clang_getCursorReferenced(self)
return self._referenced | [
"def",
"referenced",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_referenced'",
")",
":",
"self",
".",
"_referenced",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorReferenced",
"(",
"self",
")",
"return",
"self",
".",
"_referenced"
] | For a cursor that is a reference, returns a cursor
representing the entity that it references. | [
"For",
"a",
"cursor",
"that",
"is",
"a",
"reference",
"returns",
"a",
"cursor",
"representing",
"the",
"entity",
"that",
"it",
"references",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1656-L1664 |
2,854 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.brief_comment | def brief_comment(self):
"""Returns the brief comment text associated with that Cursor"""
r = conf.lib.clang_Cursor_getBriefCommentText(self)
if not r:
return None
return str(r) | python | def brief_comment(self):
"""Returns the brief comment text associated with that Cursor"""
r = conf.lib.clang_Cursor_getBriefCommentText(self)
if not r:
return None
return str(r) | [
"def",
"brief_comment",
"(",
"self",
")",
":",
"r",
"=",
"conf",
".",
"lib",
".",
"clang_Cursor_getBriefCommentText",
"(",
"self",
")",
"if",
"not",
"r",
":",
"return",
"None",
"return",
"str",
"(",
"r",
")"
] | Returns the brief comment text associated with that Cursor | [
"Returns",
"the",
"brief",
"comment",
"text",
"associated",
"with",
"that",
"Cursor"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1667-L1672 |
2,855 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.raw_comment | def raw_comment(self):
"""Returns the raw comment text associated with that Cursor"""
r = conf.lib.clang_Cursor_getRawCommentText(self)
if not r:
return None
return str(r) | python | def raw_comment(self):
"""Returns the raw comment text associated with that Cursor"""
r = conf.lib.clang_Cursor_getRawCommentText(self)
if not r:
return None
return str(r) | [
"def",
"raw_comment",
"(",
"self",
")",
":",
"r",
"=",
"conf",
".",
"lib",
".",
"clang_Cursor_getRawCommentText",
"(",
"self",
")",
"if",
"not",
"r",
":",
"return",
"None",
"return",
"str",
"(",
"r",
")"
] | Returns the raw comment text associated with that Cursor | [
"Returns",
"the",
"raw",
"comment",
"text",
"associated",
"with",
"that",
"Cursor"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1675-L1680 |
2,856 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.get_arguments | def get_arguments(self):
"""Return an iterator for accessing the arguments of this cursor."""
num_args = conf.lib.clang_Cursor_getNumArguments(self)
for i in xrange(0, num_args):
yield conf.lib.clang_Cursor_getArgument(self, i) | python | def get_arguments(self):
"""Return an iterator for accessing the arguments of this cursor."""
num_args = conf.lib.clang_Cursor_getNumArguments(self)
for i in xrange(0, num_args):
yield conf.lib.clang_Cursor_getArgument(self, i) | [
"def",
"get_arguments",
"(",
"self",
")",
":",
"num_args",
"=",
"conf",
".",
"lib",
".",
"clang_Cursor_getNumArguments",
"(",
"self",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"num_args",
")",
":",
"yield",
"conf",
".",
"lib",
".",
"clang_Cursor_getArgument",
"(",
"self",
",",
"i",
")"
] | Return an iterator for accessing the arguments of this cursor. | [
"Return",
"an",
"iterator",
"for",
"accessing",
"the",
"arguments",
"of",
"this",
"cursor",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1682-L1686 |
2,857 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.get_children | def get_children(self):
"""Return an iterator for accessing the children of this cursor."""
# FIXME: Expose iteration from CIndex, PR6125.
def visitor(child, parent, children):
# FIXME: Document this assertion in API.
# FIXME: There should just be an isNull method.
assert child != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
child._tu = self._tu
children.append(child)
return 1 # continue
children = []
conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
children)
return iter(children) | python | def get_children(self):
"""Return an iterator for accessing the children of this cursor."""
# FIXME: Expose iteration from CIndex, PR6125.
def visitor(child, parent, children):
# FIXME: Document this assertion in API.
# FIXME: There should just be an isNull method.
assert child != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
child._tu = self._tu
children.append(child)
return 1 # continue
children = []
conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
children)
return iter(children) | [
"def",
"get_children",
"(",
"self",
")",
":",
"# FIXME: Expose iteration from CIndex, PR6125.",
"def",
"visitor",
"(",
"child",
",",
"parent",
",",
"children",
")",
":",
"# FIXME: Document this assertion in API.",
"# FIXME: There should just be an isNull method.",
"assert",
"child",
"!=",
"conf",
".",
"lib",
".",
"clang_getNullCursor",
"(",
")",
"# Create reference to TU so it isn't GC'd before Cursor.",
"child",
".",
"_tu",
"=",
"self",
".",
"_tu",
"children",
".",
"append",
"(",
"child",
")",
"return",
"1",
"# continue",
"children",
"=",
"[",
"]",
"conf",
".",
"lib",
".",
"clang_visitChildren",
"(",
"self",
",",
"callbacks",
"[",
"'cursor_visit'",
"]",
"(",
"visitor",
")",
",",
"children",
")",
"return",
"iter",
"(",
"children",
")"
] | Return an iterator for accessing the children of this cursor. | [
"Return",
"an",
"iterator",
"for",
"accessing",
"the",
"children",
"of",
"this",
"cursor",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1709-L1725 |
2,858 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.walk_preorder | def walk_preorder(self):
"""Depth-first preorder walk over the cursor and its descendants.
Yields cursors.
"""
yield self
for child in self.get_children():
for descendant in child.walk_preorder():
yield descendant | python | def walk_preorder(self):
"""Depth-first preorder walk over the cursor and its descendants.
Yields cursors.
"""
yield self
for child in self.get_children():
for descendant in child.walk_preorder():
yield descendant | [
"def",
"walk_preorder",
"(",
"self",
")",
":",
"yield",
"self",
"for",
"child",
"in",
"self",
".",
"get_children",
"(",
")",
":",
"for",
"descendant",
"in",
"child",
".",
"walk_preorder",
"(",
")",
":",
"yield",
"descendant"
] | Depth-first preorder walk over the cursor and its descendants.
Yields cursors. | [
"Depth",
"-",
"first",
"preorder",
"walk",
"over",
"the",
"cursor",
"and",
"its",
"descendants",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1727-L1735 |
2,859 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Cursor.is_anonymous | def is_anonymous(self):
"""
Check if the record is anonymous.
"""
if self.kind == CursorKind.FIELD_DECL:
return self.type.get_declaration().is_anonymous()
return conf.lib.clang_Cursor_isAnonymous(self) | python | def is_anonymous(self):
"""
Check if the record is anonymous.
"""
if self.kind == CursorKind.FIELD_DECL:
return self.type.get_declaration().is_anonymous()
return conf.lib.clang_Cursor_isAnonymous(self) | [
"def",
"is_anonymous",
"(",
"self",
")",
":",
"if",
"self",
".",
"kind",
"==",
"CursorKind",
".",
"FIELD_DECL",
":",
"return",
"self",
".",
"type",
".",
"get_declaration",
"(",
")",
".",
"is_anonymous",
"(",
")",
"return",
"conf",
".",
"lib",
".",
"clang_Cursor_isAnonymous",
"(",
"self",
")"
] | Check if the record is anonymous. | [
"Check",
"if",
"the",
"record",
"is",
"anonymous",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1749-L1755 |
2,860 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Type.argument_types | def argument_types(self):
"""Retrieve a container for the non-variadic arguments for this type.
The returned object is iterable and indexable. Each item in the
container is a Type instance.
"""
class ArgumentsIterator(collections.Sequence):
def __init__(self, parent):
self.parent = parent
self.length = None
def __len__(self):
if self.length is None:
self.length = conf.lib.clang_getNumArgTypes(self.parent)
return self.length
def __getitem__(self, key):
# FIXME Support slice objects.
if not isinstance(key, int):
raise TypeError("Must supply a non-negative int.")
if key < 0:
raise IndexError("Only non-negative indexes are accepted.")
if key >= len(self):
raise IndexError("Index greater than container length: "
"%d > %d" % ( key, len(self) ))
result = conf.lib.clang_getArgType(self.parent, key)
if result.kind == TypeKind.INVALID:
raise IndexError("Argument could not be retrieved.")
return result
assert self.kind == TypeKind.FUNCTIONPROTO
return ArgumentsIterator(self) | python | def argument_types(self):
"""Retrieve a container for the non-variadic arguments for this type.
The returned object is iterable and indexable. Each item in the
container is a Type instance.
"""
class ArgumentsIterator(collections.Sequence):
def __init__(self, parent):
self.parent = parent
self.length = None
def __len__(self):
if self.length is None:
self.length = conf.lib.clang_getNumArgTypes(self.parent)
return self.length
def __getitem__(self, key):
# FIXME Support slice objects.
if not isinstance(key, int):
raise TypeError("Must supply a non-negative int.")
if key < 0:
raise IndexError("Only non-negative indexes are accepted.")
if key >= len(self):
raise IndexError("Index greater than container length: "
"%d > %d" % ( key, len(self) ))
result = conf.lib.clang_getArgType(self.parent, key)
if result.kind == TypeKind.INVALID:
raise IndexError("Argument could not be retrieved.")
return result
assert self.kind == TypeKind.FUNCTIONPROTO
return ArgumentsIterator(self) | [
"def",
"argument_types",
"(",
"self",
")",
":",
"class",
"ArgumentsIterator",
"(",
"collections",
".",
"Sequence",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"parent",
")",
":",
"self",
".",
"parent",
"=",
"parent",
"self",
".",
"length",
"=",
"None",
"def",
"__len__",
"(",
"self",
")",
":",
"if",
"self",
".",
"length",
"is",
"None",
":",
"self",
".",
"length",
"=",
"conf",
".",
"lib",
".",
"clang_getNumArgTypes",
"(",
"self",
".",
"parent",
")",
"return",
"self",
".",
"length",
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"# FIXME Support slice objects.",
"if",
"not",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Must supply a non-negative int.\"",
")",
"if",
"key",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"\"Only non-negative indexes are accepted.\"",
")",
"if",
"key",
">=",
"len",
"(",
"self",
")",
":",
"raise",
"IndexError",
"(",
"\"Index greater than container length: \"",
"\"%d > %d\"",
"%",
"(",
"key",
",",
"len",
"(",
"self",
")",
")",
")",
"result",
"=",
"conf",
".",
"lib",
".",
"clang_getArgType",
"(",
"self",
".",
"parent",
",",
"key",
")",
"if",
"result",
".",
"kind",
"==",
"TypeKind",
".",
"INVALID",
":",
"raise",
"IndexError",
"(",
"\"Argument could not be retrieved.\"",
")",
"return",
"result",
"assert",
"self",
".",
"kind",
"==",
"TypeKind",
".",
"FUNCTIONPROTO",
"return",
"ArgumentsIterator",
"(",
"self",
")"
] | Retrieve a container for the non-variadic arguments for this type.
The returned object is iterable and indexable. Each item in the
container is a Type instance. | [
"Retrieve",
"a",
"container",
"for",
"the",
"non",
"-",
"variadic",
"arguments",
"for",
"this",
"type",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1974-L2010 |
2,861 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Type.element_type | def element_type(self):
"""Retrieve the Type of elements within this Type.
If accessed on a type that is not an array, complex, or vector type, an
exception will be raised.
"""
result = conf.lib.clang_getElementType(self)
if result.kind == TypeKind.INVALID:
raise Exception('Element type not available on this type.')
return result | python | def element_type(self):
"""Retrieve the Type of elements within this Type.
If accessed on a type that is not an array, complex, or vector type, an
exception will be raised.
"""
result = conf.lib.clang_getElementType(self)
if result.kind == TypeKind.INVALID:
raise Exception('Element type not available on this type.')
return result | [
"def",
"element_type",
"(",
"self",
")",
":",
"result",
"=",
"conf",
".",
"lib",
".",
"clang_getElementType",
"(",
"self",
")",
"if",
"result",
".",
"kind",
"==",
"TypeKind",
".",
"INVALID",
":",
"raise",
"Exception",
"(",
"'Element type not available on this type.'",
")",
"return",
"result"
] | Retrieve the Type of elements within this Type.
If accessed on a type that is not an array, complex, or vector type, an
exception will be raised. | [
"Retrieve",
"the",
"Type",
"of",
"elements",
"within",
"this",
"Type",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2013-L2023 |
2,862 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Type.element_count | def element_count(self):
"""Retrieve the number of elements in this type.
Returns an int.
If the Type is not an array or vector, this raises.
"""
result = conf.lib.clang_getNumElements(self)
if result < 0:
raise Exception('Type does not have elements.')
return result | python | def element_count(self):
"""Retrieve the number of elements in this type.
Returns an int.
If the Type is not an array or vector, this raises.
"""
result = conf.lib.clang_getNumElements(self)
if result < 0:
raise Exception('Type does not have elements.')
return result | [
"def",
"element_count",
"(",
"self",
")",
":",
"result",
"=",
"conf",
".",
"lib",
".",
"clang_getNumElements",
"(",
"self",
")",
"if",
"result",
"<",
"0",
":",
"raise",
"Exception",
"(",
"'Type does not have elements.'",
")",
"return",
"result"
] | Retrieve the number of elements in this type.
Returns an int.
If the Type is not an array or vector, this raises. | [
"Retrieve",
"the",
"number",
"of",
"elements",
"in",
"this",
"type",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2026-L2037 |
2,863 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Type.is_function_variadic | def is_function_variadic(self):
"""Determine whether this function Type is a variadic function type."""
assert self.kind == TypeKind.FUNCTIONPROTO
return conf.lib.clang_isFunctionTypeVariadic(self) | python | def is_function_variadic(self):
"""Determine whether this function Type is a variadic function type."""
assert self.kind == TypeKind.FUNCTIONPROTO
return conf.lib.clang_isFunctionTypeVariadic(self) | [
"def",
"is_function_variadic",
"(",
"self",
")",
":",
"assert",
"self",
".",
"kind",
"==",
"TypeKind",
".",
"FUNCTIONPROTO",
"return",
"conf",
".",
"lib",
".",
"clang_isFunctionTypeVariadic",
"(",
"self",
")"
] | Determine whether this function Type is a variadic function type. | [
"Determine",
"whether",
"this",
"function",
"Type",
"is",
"a",
"variadic",
"function",
"type",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2097-L2101 |
2,864 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Type.get_fields | def get_fields(self):
"""Return an iterator for accessing the fields of this type."""
def visitor(field, children):
assert field != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
field._tu = self._tu
fields.append(field)
return 1 # continue
fields = []
conf.lib.clang_Type_visitFields(self,
callbacks['fields_visit'](visitor), fields)
return iter(fields) | python | def get_fields(self):
"""Return an iterator for accessing the fields of this type."""
def visitor(field, children):
assert field != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
field._tu = self._tu
fields.append(field)
return 1 # continue
fields = []
conf.lib.clang_Type_visitFields(self,
callbacks['fields_visit'](visitor), fields)
return iter(fields) | [
"def",
"get_fields",
"(",
"self",
")",
":",
"def",
"visitor",
"(",
"field",
",",
"children",
")",
":",
"assert",
"field",
"!=",
"conf",
".",
"lib",
".",
"clang_getNullCursor",
"(",
")",
"# Create reference to TU so it isn't GC'd before Cursor.",
"field",
".",
"_tu",
"=",
"self",
".",
"_tu",
"fields",
".",
"append",
"(",
"field",
")",
"return",
"1",
"# continue",
"fields",
"=",
"[",
"]",
"conf",
".",
"lib",
".",
"clang_Type_visitFields",
"(",
"self",
",",
"callbacks",
"[",
"'fields_visit'",
"]",
"(",
"visitor",
")",
",",
"fields",
")",
"return",
"iter",
"(",
"fields",
")"
] | Return an iterator for accessing the fields of this type. | [
"Return",
"an",
"iterator",
"for",
"accessing",
"the",
"fields",
"of",
"this",
"type",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2174-L2187 |
2,865 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | Index.parse | def parse(self, path, args=None, unsaved_files=None, options = 0):
"""Load the translation unit from the given source code file by running
clang and generating the AST before loading. Additional command line
parameters can be passed to clang via the args parameter.
In-memory contents for files can be provided by passing a list of pairs
to as unsaved_files, the first item should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
If an error was encountered during parsing, a TranslationUnitLoadError
will be raised.
"""
return TranslationUnit.from_source(path, args, unsaved_files, options,
self) | python | def parse(self, path, args=None, unsaved_files=None, options = 0):
"""Load the translation unit from the given source code file by running
clang and generating the AST before loading. Additional command line
parameters can be passed to clang via the args parameter.
In-memory contents for files can be provided by passing a list of pairs
to as unsaved_files, the first item should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
If an error was encountered during parsing, a TranslationUnitLoadError
will be raised.
"""
return TranslationUnit.from_source(path, args, unsaved_files, options,
self) | [
"def",
"parse",
"(",
"self",
",",
"path",
",",
"args",
"=",
"None",
",",
"unsaved_files",
"=",
"None",
",",
"options",
"=",
"0",
")",
":",
"return",
"TranslationUnit",
".",
"from_source",
"(",
"path",
",",
"args",
",",
"unsaved_files",
",",
"options",
",",
"self",
")"
] | Load the translation unit from the given source code file by running
clang and generating the AST before loading. Additional command line
parameters can be passed to clang via the args parameter.
In-memory contents for files can be provided by passing a list of pairs
to as unsaved_files, the first item should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
If an error was encountered during parsing, a TranslationUnitLoadError
will be raised. | [
"Load",
"the",
"translation",
"unit",
"from",
"the",
"given",
"source",
"code",
"file",
"by",
"running",
"clang",
"and",
"generating",
"the",
"AST",
"before",
"loading",
".",
"Additional",
"command",
"line",
"parameters",
"can",
"be",
"passed",
"to",
"clang",
"via",
"the",
"args",
"parameter",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2471-L2485 |
2,866 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TranslationUnit.from_ast_file | def from_ast_file(cls, filename, index=None):
"""Create a TranslationUnit instance from a saved AST file.
A previously-saved AST file (provided with -emit-ast or
TranslationUnit.save()) is loaded from the filename specified.
If the file cannot be loaded, a TranslationUnitLoadError will be
raised.
index is optional and is the Index instance to use. If not provided,
a default Index will be created.
"""
if index is None:
index = Index.create()
ptr = conf.lib.clang_createTranslationUnit(index, filename)
if not ptr:
raise TranslationUnitLoadError(filename)
return cls(ptr=ptr, index=index) | python | def from_ast_file(cls, filename, index=None):
"""Create a TranslationUnit instance from a saved AST file.
A previously-saved AST file (provided with -emit-ast or
TranslationUnit.save()) is loaded from the filename specified.
If the file cannot be loaded, a TranslationUnitLoadError will be
raised.
index is optional and is the Index instance to use. If not provided,
a default Index will be created.
"""
if index is None:
index = Index.create()
ptr = conf.lib.clang_createTranslationUnit(index, filename)
if not ptr:
raise TranslationUnitLoadError(filename)
return cls(ptr=ptr, index=index) | [
"def",
"from_ast_file",
"(",
"cls",
",",
"filename",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"Index",
".",
"create",
"(",
")",
"ptr",
"=",
"conf",
".",
"lib",
".",
"clang_createTranslationUnit",
"(",
"index",
",",
"filename",
")",
"if",
"not",
"ptr",
":",
"raise",
"TranslationUnitLoadError",
"(",
"filename",
")",
"return",
"cls",
"(",
"ptr",
"=",
"ptr",
",",
"index",
"=",
"index",
")"
] | Create a TranslationUnit instance from a saved AST file.
A previously-saved AST file (provided with -emit-ast or
TranslationUnit.save()) is loaded from the filename specified.
If the file cannot be loaded, a TranslationUnitLoadError will be
raised.
index is optional and is the Index instance to use. If not provided,
a default Index will be created. | [
"Create",
"a",
"TranslationUnit",
"instance",
"from",
"a",
"saved",
"AST",
"file",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2604-L2623 |
2,867 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TranslationUnit.get_includes | def get_includes(self):
"""
Return an iterable sequence of FileInclusion objects that describe the
sequence of inclusions in a translation unit. The first object in
this sequence is always the input file. Note that this method will not
recursively iterate over header files included through precompiled
headers.
"""
def visitor(fobj, lptr, depth, includes):
if depth > 0:
loc = lptr.contents
includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
# Automatically adapt CIndex/ctype pointers to python objects
includes = []
conf.lib.clang_getInclusions(self,
callbacks['translation_unit_includes'](visitor), includes)
return iter(includes) | python | def get_includes(self):
"""
Return an iterable sequence of FileInclusion objects that describe the
sequence of inclusions in a translation unit. The first object in
this sequence is always the input file. Note that this method will not
recursively iterate over header files included through precompiled
headers.
"""
def visitor(fobj, lptr, depth, includes):
if depth > 0:
loc = lptr.contents
includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
# Automatically adapt CIndex/ctype pointers to python objects
includes = []
conf.lib.clang_getInclusions(self,
callbacks['translation_unit_includes'](visitor), includes)
return iter(includes) | [
"def",
"get_includes",
"(",
"self",
")",
":",
"def",
"visitor",
"(",
"fobj",
",",
"lptr",
",",
"depth",
",",
"includes",
")",
":",
"if",
"depth",
">",
"0",
":",
"loc",
"=",
"lptr",
".",
"contents",
"includes",
".",
"append",
"(",
"FileInclusion",
"(",
"loc",
".",
"file",
",",
"File",
"(",
"fobj",
")",
",",
"loc",
",",
"depth",
")",
")",
"# Automatically adapt CIndex/ctype pointers to python objects",
"includes",
"=",
"[",
"]",
"conf",
".",
"lib",
".",
"clang_getInclusions",
"(",
"self",
",",
"callbacks",
"[",
"'translation_unit_includes'",
"]",
"(",
"visitor",
")",
",",
"includes",
")",
"return",
"iter",
"(",
"includes",
")"
] | Return an iterable sequence of FileInclusion objects that describe the
sequence of inclusions in a translation unit. The first object in
this sequence is always the input file. Note that this method will not
recursively iterate over header files included through precompiled
headers. | [
"Return",
"an",
"iterable",
"sequence",
"of",
"FileInclusion",
"objects",
"that",
"describe",
"the",
"sequence",
"of",
"inclusions",
"in",
"a",
"translation",
"unit",
".",
"The",
"first",
"object",
"in",
"this",
"sequence",
"is",
"always",
"the",
"input",
"file",
".",
"Note",
"that",
"this",
"method",
"will",
"not",
"recursively",
"iterate",
"over",
"header",
"files",
"included",
"through",
"precompiled",
"headers",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2648-L2666 |
2,868 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TranslationUnit.get_location | def get_location(self, filename, position):
"""Obtain a SourceLocation for a file in this translation unit.
The position can be specified by passing:
- Integer file offset. Initial file offset is 0.
- 2-tuple of (line number, column number). Initial file position is
(0, 0)
"""
f = self.get_file(filename)
if isinstance(position, int):
return SourceLocation.from_offset(self, f, position)
return SourceLocation.from_position(self, f, position[0], position[1]) | python | def get_location(self, filename, position):
"""Obtain a SourceLocation for a file in this translation unit.
The position can be specified by passing:
- Integer file offset. Initial file offset is 0.
- 2-tuple of (line number, column number). Initial file position is
(0, 0)
"""
f = self.get_file(filename)
if isinstance(position, int):
return SourceLocation.from_offset(self, f, position)
return SourceLocation.from_position(self, f, position[0], position[1]) | [
"def",
"get_location",
"(",
"self",
",",
"filename",
",",
"position",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"filename",
")",
"if",
"isinstance",
"(",
"position",
",",
"int",
")",
":",
"return",
"SourceLocation",
".",
"from_offset",
"(",
"self",
",",
"f",
",",
"position",
")",
"return",
"SourceLocation",
".",
"from_position",
"(",
"self",
",",
"f",
",",
"position",
"[",
"0",
"]",
",",
"position",
"[",
"1",
"]",
")"
] | Obtain a SourceLocation for a file in this translation unit.
The position can be specified by passing:
- Integer file offset. Initial file offset is 0.
- 2-tuple of (line number, column number). Initial file position is
(0, 0) | [
"Obtain",
"a",
"SourceLocation",
"for",
"a",
"file",
"in",
"this",
"translation",
"unit",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2673-L2687 |
2,869 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TranslationUnit.get_extent | def get_extent(self, filename, locations):
"""Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15)))
"""
f = self.get_file(filename)
if len(locations) < 2:
raise Exception('Must pass object with at least 2 elements')
start_location, end_location = locations
if hasattr(start_location, '__len__'):
start_location = SourceLocation.from_position(self, f,
start_location[0], start_location[1])
elif isinstance(start_location, int):
start_location = SourceLocation.from_offset(self, f,
start_location)
if hasattr(end_location, '__len__'):
end_location = SourceLocation.from_position(self, f,
end_location[0], end_location[1])
elif isinstance(end_location, int):
end_location = SourceLocation.from_offset(self, f, end_location)
assert isinstance(start_location, SourceLocation)
assert isinstance(end_location, SourceLocation)
return SourceRange.from_locations(start_location, end_location) | python | def get_extent(self, filename, locations):
"""Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15)))
"""
f = self.get_file(filename)
if len(locations) < 2:
raise Exception('Must pass object with at least 2 elements')
start_location, end_location = locations
if hasattr(start_location, '__len__'):
start_location = SourceLocation.from_position(self, f,
start_location[0], start_location[1])
elif isinstance(start_location, int):
start_location = SourceLocation.from_offset(self, f,
start_location)
if hasattr(end_location, '__len__'):
end_location = SourceLocation.from_position(self, f,
end_location[0], end_location[1])
elif isinstance(end_location, int):
end_location = SourceLocation.from_offset(self, f, end_location)
assert isinstance(start_location, SourceLocation)
assert isinstance(end_location, SourceLocation)
return SourceRange.from_locations(start_location, end_location) | [
"def",
"get_extent",
"(",
"self",
",",
"filename",
",",
"locations",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"filename",
")",
"if",
"len",
"(",
"locations",
")",
"<",
"2",
":",
"raise",
"Exception",
"(",
"'Must pass object with at least 2 elements'",
")",
"start_location",
",",
"end_location",
"=",
"locations",
"if",
"hasattr",
"(",
"start_location",
",",
"'__len__'",
")",
":",
"start_location",
"=",
"SourceLocation",
".",
"from_position",
"(",
"self",
",",
"f",
",",
"start_location",
"[",
"0",
"]",
",",
"start_location",
"[",
"1",
"]",
")",
"elif",
"isinstance",
"(",
"start_location",
",",
"int",
")",
":",
"start_location",
"=",
"SourceLocation",
".",
"from_offset",
"(",
"self",
",",
"f",
",",
"start_location",
")",
"if",
"hasattr",
"(",
"end_location",
",",
"'__len__'",
")",
":",
"end_location",
"=",
"SourceLocation",
".",
"from_position",
"(",
"self",
",",
"f",
",",
"end_location",
"[",
"0",
"]",
",",
"end_location",
"[",
"1",
"]",
")",
"elif",
"isinstance",
"(",
"end_location",
",",
"int",
")",
":",
"end_location",
"=",
"SourceLocation",
".",
"from_offset",
"(",
"self",
",",
"f",
",",
"end_location",
")",
"assert",
"isinstance",
"(",
"start_location",
",",
"SourceLocation",
")",
"assert",
"isinstance",
"(",
"end_location",
",",
"SourceLocation",
")",
"return",
"SourceRange",
".",
"from_locations",
"(",
"start_location",
",",
"end_location",
")"
] | Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15))) | [
"Obtain",
"a",
"SourceRange",
"from",
"this",
"translation",
"unit",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2689-L2727 |
2,870 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TranslationUnit.reparse | def reparse(self, unsaved_files=None, options=0):
"""
Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print(value)
if not isinstance(value, str):
raise TypeError('Unexpected unsaved file contents.')
unsaved_files_array[i].name = name
unsaved_files_array[i].contents = value
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
unsaved_files_array, options) | python | def reparse(self, unsaved_files=None, options=0):
"""
Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print(value)
if not isinstance(value, str):
raise TypeError('Unexpected unsaved file contents.')
unsaved_files_array[i].name = name
unsaved_files_array[i].contents = value
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
unsaved_files_array, options) | [
"def",
"reparse",
"(",
"self",
",",
"unsaved_files",
"=",
"None",
",",
"options",
"=",
"0",
")",
":",
"if",
"unsaved_files",
"is",
"None",
":",
"unsaved_files",
"=",
"[",
"]",
"unsaved_files_array",
"=",
"0",
"if",
"len",
"(",
"unsaved_files",
")",
":",
"unsaved_files_array",
"=",
"(",
"_CXUnsavedFile",
"*",
"len",
"(",
"unsaved_files",
")",
")",
"(",
")",
"for",
"i",
",",
"(",
"name",
",",
"value",
")",
"in",
"enumerate",
"(",
"unsaved_files",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"# FIXME: It would be great to support an efficient version",
"# of this, one day.",
"value",
"=",
"value",
".",
"read",
"(",
")",
"print",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Unexpected unsaved file contents.'",
")",
"unsaved_files_array",
"[",
"i",
"]",
".",
"name",
"=",
"name",
"unsaved_files_array",
"[",
"i",
"]",
".",
"contents",
"=",
"value",
"unsaved_files_array",
"[",
"i",
"]",
".",
"length",
"=",
"len",
"(",
"value",
")",
"ptr",
"=",
"conf",
".",
"lib",
".",
"clang_reparseTranslationUnit",
"(",
"self",
",",
"len",
"(",
"unsaved_files",
")",
",",
"unsaved_files_array",
",",
"options",
")"
] | Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects. | [
"Reparse",
"an",
"already",
"parsed",
"translation",
"unit",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2749-L2776 |
2,871 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TranslationUnit.save | def save(self, filename):
"""Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to.
"""
options = conf.lib.clang_defaultSaveOptions(self)
result = int(conf.lib.clang_saveTranslationUnit(self, filename,
options))
if result != 0:
raise TranslationUnitSaveError(result,
'Error saving TranslationUnit.') | python | def save(self, filename):
"""Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to.
"""
options = conf.lib.clang_defaultSaveOptions(self)
result = int(conf.lib.clang_saveTranslationUnit(self, filename,
options))
if result != 0:
raise TranslationUnitSaveError(result,
'Error saving TranslationUnit.') | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"options",
"=",
"conf",
".",
"lib",
".",
"clang_defaultSaveOptions",
"(",
"self",
")",
"result",
"=",
"int",
"(",
"conf",
".",
"lib",
".",
"clang_saveTranslationUnit",
"(",
"self",
",",
"filename",
",",
"options",
")",
")",
"if",
"result",
"!=",
"0",
":",
"raise",
"TranslationUnitSaveError",
"(",
"result",
",",
"'Error saving TranslationUnit.'",
")"
] | Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to. | [
"Saves",
"the",
"TranslationUnit",
"to",
"a",
"file",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2778-L2798 |
2,872 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TranslationUnit.codeComplete | def codeComplete(self, path, line, column, unsaved_files=None,
include_macros=False, include_code_patterns=False,
include_brief_comments=False):
"""
Code complete in this translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
options = 0
if include_macros:
options += 1
if include_code_patterns:
options += 2
if include_brief_comments:
options += 4
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print(value)
if not isinstance(value, str):
raise TypeError('Unexpected unsaved file contents.')
unsaved_files_array[i].name = c_string_p(name)
unsaved_files_array[i].contents = c_string_p(value)
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
unsaved_files_array, len(unsaved_files), options)
if ptr:
return CodeCompletionResults(ptr)
return None | python | def codeComplete(self, path, line, column, unsaved_files=None,
include_macros=False, include_code_patterns=False,
include_brief_comments=False):
"""
Code complete in this translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
options = 0
if include_macros:
options += 1
if include_code_patterns:
options += 2
if include_brief_comments:
options += 4
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print(value)
if not isinstance(value, str):
raise TypeError('Unexpected unsaved file contents.')
unsaved_files_array[i].name = c_string_p(name)
unsaved_files_array[i].contents = c_string_p(value)
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
unsaved_files_array, len(unsaved_files), options)
if ptr:
return CodeCompletionResults(ptr)
return None | [
"def",
"codeComplete",
"(",
"self",
",",
"path",
",",
"line",
",",
"column",
",",
"unsaved_files",
"=",
"None",
",",
"include_macros",
"=",
"False",
",",
"include_code_patterns",
"=",
"False",
",",
"include_brief_comments",
"=",
"False",
")",
":",
"options",
"=",
"0",
"if",
"include_macros",
":",
"options",
"+=",
"1",
"if",
"include_code_patterns",
":",
"options",
"+=",
"2",
"if",
"include_brief_comments",
":",
"options",
"+=",
"4",
"if",
"unsaved_files",
"is",
"None",
":",
"unsaved_files",
"=",
"[",
"]",
"unsaved_files_array",
"=",
"0",
"if",
"len",
"(",
"unsaved_files",
")",
":",
"unsaved_files_array",
"=",
"(",
"_CXUnsavedFile",
"*",
"len",
"(",
"unsaved_files",
")",
")",
"(",
")",
"for",
"i",
",",
"(",
"name",
",",
"value",
")",
"in",
"enumerate",
"(",
"unsaved_files",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"# FIXME: It would be great to support an efficient version",
"# of this, one day.",
"value",
"=",
"value",
".",
"read",
"(",
")",
"print",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Unexpected unsaved file contents.'",
")",
"unsaved_files_array",
"[",
"i",
"]",
".",
"name",
"=",
"c_string_p",
"(",
"name",
")",
"unsaved_files_array",
"[",
"i",
"]",
".",
"contents",
"=",
"c_string_p",
"(",
"value",
")",
"unsaved_files_array",
"[",
"i",
"]",
".",
"length",
"=",
"len",
"(",
"value",
")",
"ptr",
"=",
"conf",
".",
"lib",
".",
"clang_codeCompleteAt",
"(",
"self",
",",
"path",
",",
"line",
",",
"column",
",",
"unsaved_files_array",
",",
"len",
"(",
"unsaved_files",
")",
",",
"options",
")",
"if",
"ptr",
":",
"return",
"CodeCompletionResults",
"(",
"ptr",
")",
"return",
"None"
] | Code complete in this translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects. | [
"Code",
"complete",
"in",
"this",
"translation",
"unit",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2800-L2843 |
2,873 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | TranslationUnit.get_tokens | def get_tokens(self, locations=None, extent=None):
"""Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined.
"""
if locations is not None:
extent = SourceRange(start=locations[0], end=locations[1])
return TokenGroup.get_tokens(self, extent) | python | def get_tokens(self, locations=None, extent=None):
"""Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined.
"""
if locations is not None:
extent = SourceRange(start=locations[0], end=locations[1])
return TokenGroup.get_tokens(self, extent) | [
"def",
"get_tokens",
"(",
"self",
",",
"locations",
"=",
"None",
",",
"extent",
"=",
"None",
")",
":",
"if",
"locations",
"is",
"not",
"None",
":",
"extent",
"=",
"SourceRange",
"(",
"start",
"=",
"locations",
"[",
"0",
"]",
",",
"end",
"=",
"locations",
"[",
"1",
"]",
")",
"return",
"TokenGroup",
".",
"get_tokens",
"(",
"self",
",",
"extent",
")"
] | Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined. | [
"Obtain",
"tokens",
"in",
"this",
"translation",
"unit",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2845-L2856 |
2,874 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | File.name | def name(self):
"""Return the complete file and path name of the file."""
return str(conf.lib.clang_getCString(conf.lib.clang_getFileName(self))) | python | def name(self):
"""Return the complete file and path name of the file."""
return str(conf.lib.clang_getCString(conf.lib.clang_getFileName(self))) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"str",
"(",
"conf",
".",
"lib",
".",
"clang_getCString",
"(",
"conf",
".",
"lib",
".",
"clang_getFileName",
"(",
"self",
")",
")",
")"
] | Return the complete file and path name of the file. | [
"Return",
"the",
"complete",
"file",
"and",
"path",
"name",
"of",
"the",
"file",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2870-L2872 |
2,875 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | CompileCommand.arguments | def arguments(self):
"""
Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString.
Invariant : the first argument is the compiler executable
"""
length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
for i in xrange(length):
yield str(conf.lib.clang_CompileCommand_getArg(self.cmd, i)) | python | def arguments(self):
"""
Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString.
Invariant : the first argument is the compiler executable
"""
length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
for i in xrange(length):
yield str(conf.lib.clang_CompileCommand_getArg(self.cmd, i)) | [
"def",
"arguments",
"(",
"self",
")",
":",
"length",
"=",
"conf",
".",
"lib",
".",
"clang_CompileCommand_getNumArgs",
"(",
"self",
".",
"cmd",
")",
"for",
"i",
"in",
"xrange",
"(",
"length",
")",
":",
"yield",
"str",
"(",
"conf",
".",
"lib",
".",
"clang_CompileCommand_getArg",
"(",
"self",
".",
"cmd",
",",
"i",
")",
")"
] | Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString.
Invariant : the first argument is the compiler executable | [
"Get",
"an",
"iterable",
"object",
"providing",
"each",
"argument",
"in",
"the",
"command",
"line",
"for",
"the",
"compiler",
"invocation",
"as",
"a",
"_CXString",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2957-L2966 |
2,876 | hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | CompilationDatabase.fromDirectory | def fromDirectory(buildDir):
"""Builds a CompilationDatabase from the database found in buildDir"""
errorCode = c_uint()
try:
cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
byref(errorCode))
except CompilationDatabaseError as e:
raise CompilationDatabaseError(int(errorCode.value),
"CompilationDatabase loading failed")
return cdb | python | def fromDirectory(buildDir):
"""Builds a CompilationDatabase from the database found in buildDir"""
errorCode = c_uint()
try:
cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
byref(errorCode))
except CompilationDatabaseError as e:
raise CompilationDatabaseError(int(errorCode.value),
"CompilationDatabase loading failed")
return cdb | [
"def",
"fromDirectory",
"(",
"buildDir",
")",
":",
"errorCode",
"=",
"c_uint",
"(",
")",
"try",
":",
"cdb",
"=",
"conf",
".",
"lib",
".",
"clang_CompilationDatabase_fromDirectory",
"(",
"buildDir",
",",
"byref",
"(",
"errorCode",
")",
")",
"except",
"CompilationDatabaseError",
"as",
"e",
":",
"raise",
"CompilationDatabaseError",
"(",
"int",
"(",
"errorCode",
".",
"value",
")",
",",
"\"CompilationDatabase loading failed\"",
")",
"return",
"cdb"
] | Builds a CompilationDatabase from the database found in buildDir | [
"Builds",
"a",
"CompilationDatabase",
"from",
"the",
"database",
"found",
"in",
"buildDir"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L3013-L3022 |
2,877 | hotdoc/hotdoc | hotdoc/extensions/gi/node_cache.py | get_klass_parents | def get_klass_parents(gi_name):
'''
Returns a sorted list of qualified symbols representing
the parents of the klass-like symbol named gi_name
'''
res = []
parents = __HIERARCHY_GRAPH.predecessors(gi_name)
if not parents:
return []
__get_parent_link_recurse(parents[0], res)
return res | python | def get_klass_parents(gi_name):
'''
Returns a sorted list of qualified symbols representing
the parents of the klass-like symbol named gi_name
'''
res = []
parents = __HIERARCHY_GRAPH.predecessors(gi_name)
if not parents:
return []
__get_parent_link_recurse(parents[0], res)
return res | [
"def",
"get_klass_parents",
"(",
"gi_name",
")",
":",
"res",
"=",
"[",
"]",
"parents",
"=",
"__HIERARCHY_GRAPH",
".",
"predecessors",
"(",
"gi_name",
")",
"if",
"not",
"parents",
":",
"return",
"[",
"]",
"__get_parent_link_recurse",
"(",
"parents",
"[",
"0",
"]",
",",
"res",
")",
"return",
"res"
] | Returns a sorted list of qualified symbols representing
the parents of the klass-like symbol named gi_name | [
"Returns",
"a",
"sorted",
"list",
"of",
"qualified",
"symbols",
"representing",
"the",
"parents",
"of",
"the",
"klass",
"-",
"like",
"symbol",
"named",
"gi_name"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L173-L183 |
2,878 | hotdoc/hotdoc | hotdoc/extensions/gi/node_cache.py | get_klass_children | def get_klass_children(gi_name):
'''
Returns a dict of qualified symbols representing
the children of the klass-like symbol named gi_name
'''
res = {}
children = __HIERARCHY_GRAPH.successors(gi_name)
for gi_name in children:
ctype_name = ALL_GI_TYPES[gi_name]
qs = QualifiedSymbol(type_tokens=[Link(None, ctype_name, ctype_name)])
qs.add_extension_attribute ('gi-extension', 'type_desc',
SymbolTypeDesc([], gi_name, ctype_name, 0))
res[ctype_name] = qs
return res | python | def get_klass_children(gi_name):
'''
Returns a dict of qualified symbols representing
the children of the klass-like symbol named gi_name
'''
res = {}
children = __HIERARCHY_GRAPH.successors(gi_name)
for gi_name in children:
ctype_name = ALL_GI_TYPES[gi_name]
qs = QualifiedSymbol(type_tokens=[Link(None, ctype_name, ctype_name)])
qs.add_extension_attribute ('gi-extension', 'type_desc',
SymbolTypeDesc([], gi_name, ctype_name, 0))
res[ctype_name] = qs
return res | [
"def",
"get_klass_children",
"(",
"gi_name",
")",
":",
"res",
"=",
"{",
"}",
"children",
"=",
"__HIERARCHY_GRAPH",
".",
"successors",
"(",
"gi_name",
")",
"for",
"gi_name",
"in",
"children",
":",
"ctype_name",
"=",
"ALL_GI_TYPES",
"[",
"gi_name",
"]",
"qs",
"=",
"QualifiedSymbol",
"(",
"type_tokens",
"=",
"[",
"Link",
"(",
"None",
",",
"ctype_name",
",",
"ctype_name",
")",
"]",
")",
"qs",
".",
"add_extension_attribute",
"(",
"'gi-extension'",
",",
"'type_desc'",
",",
"SymbolTypeDesc",
"(",
"[",
"]",
",",
"gi_name",
",",
"ctype_name",
",",
"0",
")",
")",
"res",
"[",
"ctype_name",
"]",
"=",
"qs",
"return",
"res"
] | Returns a dict of qualified symbols representing
the children of the klass-like symbol named gi_name | [
"Returns",
"a",
"dict",
"of",
"qualified",
"symbols",
"representing",
"the",
"children",
"of",
"the",
"klass",
"-",
"like",
"symbol",
"named",
"gi_name"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L186-L199 |
2,879 | hotdoc/hotdoc | hotdoc/extensions/gi/node_cache.py | cache_nodes | def cache_nodes(gir_root, all_girs):
'''
Identify and store all the gir symbols the symbols we will document
may link to, or be typed with
'''
ns_node = gir_root.find('./{%s}namespace' % NS_MAP['core'])
id_prefixes = ns_node.attrib['{%s}identifier-prefixes' % NS_MAP['c']]
sym_prefixes = ns_node.attrib['{%s}symbol-prefixes' % NS_MAP['c']]
id_key = '{%s}identifier' % NS_MAP['c']
for node in gir_root.xpath(
'.//*[@c:identifier]',
namespaces=NS_MAP):
make_translations (node.attrib[id_key], node)
id_type = c_ns('type')
glib_type = glib_ns('type-name')
class_tag = core_ns('class')
callback_tag = core_ns('callback')
interface_tag = core_ns('interface')
for node in gir_root.xpath('.//*[not(self::core:type) and not (self::core:array)][@c:type or @glib:type-name]',
namespaces=NS_MAP):
try:
name = node.attrib[id_type]
except KeyError:
name = node.attrib[glib_type]
make_translations (name, node)
gi_name = '.'.join(get_gi_name_components(node))
ALL_GI_TYPES[gi_name] = get_klass_name(node)
if node.tag in (class_tag, interface_tag):
__update_hierarchies (ns_node.attrib.get('name'), node, gi_name)
make_translations('%s::%s' % (name, name), node)
__generate_smart_filters(id_prefixes, sym_prefixes, node)
elif node.tag in (callback_tag,):
ALL_CALLBACK_TYPES.add(node.attrib[c_ns('type')])
for field in gir_root.xpath('.//self::core:field', namespaces=NS_MAP):
unique_name = get_field_c_name(field)
make_translations(unique_name, field)
for node in gir_root.xpath(
'.//core:property',
namespaces=NS_MAP):
name = '%s:%s' % (get_klass_name(node.getparent()),
node.attrib['name'])
make_translations (name, node)
for node in gir_root.xpath(
'.//glib:signal',
namespaces=NS_MAP):
name = '%s::%s' % (get_klass_name(node.getparent()),
node.attrib['name'])
make_translations (name, node)
for node in gir_root.xpath(
'.//core:virtual-method',
namespaces=NS_MAP):
name = get_symbol_names(node)[0]
make_translations (name, node)
for inc in gir_root.findall('./core:include',
namespaces = NS_MAP):
inc_name = inc.attrib["name"]
inc_version = inc.attrib["version"]
gir_file = __find_gir_file('%s-%s.gir' % (inc_name, inc_version), all_girs)
if not gir_file:
warn('missing-gir-include', "Couldn't find a gir for %s-%s.gir" %
(inc_name, inc_version))
continue
if gir_file in __PARSED_GIRS:
continue
__PARSED_GIRS.add(gir_file)
inc_gir_root = etree.parse(gir_file).getroot()
cache_nodes(inc_gir_root, all_girs) | python | def cache_nodes(gir_root, all_girs):
'''
Identify and store all the gir symbols the symbols we will document
may link to, or be typed with
'''
ns_node = gir_root.find('./{%s}namespace' % NS_MAP['core'])
id_prefixes = ns_node.attrib['{%s}identifier-prefixes' % NS_MAP['c']]
sym_prefixes = ns_node.attrib['{%s}symbol-prefixes' % NS_MAP['c']]
id_key = '{%s}identifier' % NS_MAP['c']
for node in gir_root.xpath(
'.//*[@c:identifier]',
namespaces=NS_MAP):
make_translations (node.attrib[id_key], node)
id_type = c_ns('type')
glib_type = glib_ns('type-name')
class_tag = core_ns('class')
callback_tag = core_ns('callback')
interface_tag = core_ns('interface')
for node in gir_root.xpath('.//*[not(self::core:type) and not (self::core:array)][@c:type or @glib:type-name]',
namespaces=NS_MAP):
try:
name = node.attrib[id_type]
except KeyError:
name = node.attrib[glib_type]
make_translations (name, node)
gi_name = '.'.join(get_gi_name_components(node))
ALL_GI_TYPES[gi_name] = get_klass_name(node)
if node.tag in (class_tag, interface_tag):
__update_hierarchies (ns_node.attrib.get('name'), node, gi_name)
make_translations('%s::%s' % (name, name), node)
__generate_smart_filters(id_prefixes, sym_prefixes, node)
elif node.tag in (callback_tag,):
ALL_CALLBACK_TYPES.add(node.attrib[c_ns('type')])
for field in gir_root.xpath('.//self::core:field', namespaces=NS_MAP):
unique_name = get_field_c_name(field)
make_translations(unique_name, field)
for node in gir_root.xpath(
'.//core:property',
namespaces=NS_MAP):
name = '%s:%s' % (get_klass_name(node.getparent()),
node.attrib['name'])
make_translations (name, node)
for node in gir_root.xpath(
'.//glib:signal',
namespaces=NS_MAP):
name = '%s::%s' % (get_klass_name(node.getparent()),
node.attrib['name'])
make_translations (name, node)
for node in gir_root.xpath(
'.//core:virtual-method',
namespaces=NS_MAP):
name = get_symbol_names(node)[0]
make_translations (name, node)
for inc in gir_root.findall('./core:include',
namespaces = NS_MAP):
inc_name = inc.attrib["name"]
inc_version = inc.attrib["version"]
gir_file = __find_gir_file('%s-%s.gir' % (inc_name, inc_version), all_girs)
if not gir_file:
warn('missing-gir-include', "Couldn't find a gir for %s-%s.gir" %
(inc_name, inc_version))
continue
if gir_file in __PARSED_GIRS:
continue
__PARSED_GIRS.add(gir_file)
inc_gir_root = etree.parse(gir_file).getroot()
cache_nodes(inc_gir_root, all_girs) | [
"def",
"cache_nodes",
"(",
"gir_root",
",",
"all_girs",
")",
":",
"ns_node",
"=",
"gir_root",
".",
"find",
"(",
"'./{%s}namespace'",
"%",
"NS_MAP",
"[",
"'core'",
"]",
")",
"id_prefixes",
"=",
"ns_node",
".",
"attrib",
"[",
"'{%s}identifier-prefixes'",
"%",
"NS_MAP",
"[",
"'c'",
"]",
"]",
"sym_prefixes",
"=",
"ns_node",
".",
"attrib",
"[",
"'{%s}symbol-prefixes'",
"%",
"NS_MAP",
"[",
"'c'",
"]",
"]",
"id_key",
"=",
"'{%s}identifier'",
"%",
"NS_MAP",
"[",
"'c'",
"]",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//*[@c:identifier]'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"make_translations",
"(",
"node",
".",
"attrib",
"[",
"id_key",
"]",
",",
"node",
")",
"id_type",
"=",
"c_ns",
"(",
"'type'",
")",
"glib_type",
"=",
"glib_ns",
"(",
"'type-name'",
")",
"class_tag",
"=",
"core_ns",
"(",
"'class'",
")",
"callback_tag",
"=",
"core_ns",
"(",
"'callback'",
")",
"interface_tag",
"=",
"core_ns",
"(",
"'interface'",
")",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//*[not(self::core:type) and not (self::core:array)][@c:type or @glib:type-name]'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"try",
":",
"name",
"=",
"node",
".",
"attrib",
"[",
"id_type",
"]",
"except",
"KeyError",
":",
"name",
"=",
"node",
".",
"attrib",
"[",
"glib_type",
"]",
"make_translations",
"(",
"name",
",",
"node",
")",
"gi_name",
"=",
"'.'",
".",
"join",
"(",
"get_gi_name_components",
"(",
"node",
")",
")",
"ALL_GI_TYPES",
"[",
"gi_name",
"]",
"=",
"get_klass_name",
"(",
"node",
")",
"if",
"node",
".",
"tag",
"in",
"(",
"class_tag",
",",
"interface_tag",
")",
":",
"__update_hierarchies",
"(",
"ns_node",
".",
"attrib",
".",
"get",
"(",
"'name'",
")",
",",
"node",
",",
"gi_name",
")",
"make_translations",
"(",
"'%s::%s'",
"%",
"(",
"name",
",",
"name",
")",
",",
"node",
")",
"__generate_smart_filters",
"(",
"id_prefixes",
",",
"sym_prefixes",
",",
"node",
")",
"elif",
"node",
".",
"tag",
"in",
"(",
"callback_tag",
",",
")",
":",
"ALL_CALLBACK_TYPES",
".",
"add",
"(",
"node",
".",
"attrib",
"[",
"c_ns",
"(",
"'type'",
")",
"]",
")",
"for",
"field",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//self::core:field'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"unique_name",
"=",
"get_field_c_name",
"(",
"field",
")",
"make_translations",
"(",
"unique_name",
",",
"field",
")",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//core:property'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"name",
"=",
"'%s:%s'",
"%",
"(",
"get_klass_name",
"(",
"node",
".",
"getparent",
"(",
")",
")",
",",
"node",
".",
"attrib",
"[",
"'name'",
"]",
")",
"make_translations",
"(",
"name",
",",
"node",
")",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//glib:signal'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"name",
"=",
"'%s::%s'",
"%",
"(",
"get_klass_name",
"(",
"node",
".",
"getparent",
"(",
")",
")",
",",
"node",
".",
"attrib",
"[",
"'name'",
"]",
")",
"make_translations",
"(",
"name",
",",
"node",
")",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//core:virtual-method'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"name",
"=",
"get_symbol_names",
"(",
"node",
")",
"[",
"0",
"]",
"make_translations",
"(",
"name",
",",
"node",
")",
"for",
"inc",
"in",
"gir_root",
".",
"findall",
"(",
"'./core:include'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"inc_name",
"=",
"inc",
".",
"attrib",
"[",
"\"name\"",
"]",
"inc_version",
"=",
"inc",
".",
"attrib",
"[",
"\"version\"",
"]",
"gir_file",
"=",
"__find_gir_file",
"(",
"'%s-%s.gir'",
"%",
"(",
"inc_name",
",",
"inc_version",
")",
",",
"all_girs",
")",
"if",
"not",
"gir_file",
":",
"warn",
"(",
"'missing-gir-include'",
",",
"\"Couldn't find a gir for %s-%s.gir\"",
"%",
"(",
"inc_name",
",",
"inc_version",
")",
")",
"continue",
"if",
"gir_file",
"in",
"__PARSED_GIRS",
":",
"continue",
"__PARSED_GIRS",
".",
"add",
"(",
"gir_file",
")",
"inc_gir_root",
"=",
"etree",
".",
"parse",
"(",
"gir_file",
")",
".",
"getroot",
"(",
")",
"cache_nodes",
"(",
"inc_gir_root",
",",
"all_girs",
")"
] | Identify and store all the gir symbols the symbols we will document
may link to, or be typed with | [
"Identify",
"and",
"store",
"all",
"the",
"gir",
"symbols",
"the",
"symbols",
"we",
"will",
"document",
"may",
"link",
"to",
"or",
"be",
"typed",
"with"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L202-L277 |
2,880 | hotdoc/hotdoc | hotdoc/extensions/gi/node_cache.py | type_description_from_node | def type_description_from_node(gi_node):
'''
Parse a typed node, returns a usable description
'''
ctype_name, gi_name, array_nesting = unnest_type (gi_node)
cur_ns = get_namespace(gi_node)
if ctype_name is not None:
type_tokens = __type_tokens_from_cdecl (ctype_name)
else:
type_tokens = __type_tokens_from_gitype (cur_ns, gi_name)
namespaced = '%s.%s' % (cur_ns, gi_name)
if namespaced in ALL_GI_TYPES:
gi_name = namespaced
return SymbolTypeDesc(type_tokens, gi_name, ctype_name, array_nesting) | python | def type_description_from_node(gi_node):
'''
Parse a typed node, returns a usable description
'''
ctype_name, gi_name, array_nesting = unnest_type (gi_node)
cur_ns = get_namespace(gi_node)
if ctype_name is not None:
type_tokens = __type_tokens_from_cdecl (ctype_name)
else:
type_tokens = __type_tokens_from_gitype (cur_ns, gi_name)
namespaced = '%s.%s' % (cur_ns, gi_name)
if namespaced in ALL_GI_TYPES:
gi_name = namespaced
return SymbolTypeDesc(type_tokens, gi_name, ctype_name, array_nesting) | [
"def",
"type_description_from_node",
"(",
"gi_node",
")",
":",
"ctype_name",
",",
"gi_name",
",",
"array_nesting",
"=",
"unnest_type",
"(",
"gi_node",
")",
"cur_ns",
"=",
"get_namespace",
"(",
"gi_node",
")",
"if",
"ctype_name",
"is",
"not",
"None",
":",
"type_tokens",
"=",
"__type_tokens_from_cdecl",
"(",
"ctype_name",
")",
"else",
":",
"type_tokens",
"=",
"__type_tokens_from_gitype",
"(",
"cur_ns",
",",
"gi_name",
")",
"namespaced",
"=",
"'%s.%s'",
"%",
"(",
"cur_ns",
",",
"gi_name",
")",
"if",
"namespaced",
"in",
"ALL_GI_TYPES",
":",
"gi_name",
"=",
"namespaced",
"return",
"SymbolTypeDesc",
"(",
"type_tokens",
",",
"gi_name",
",",
"ctype_name",
",",
"array_nesting",
")"
] | Parse a typed node, returns a usable description | [
"Parse",
"a",
"typed",
"node",
"returns",
"a",
"usable",
"description"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L318-L335 |
2,881 | hotdoc/hotdoc | hotdoc/extensions/gi/node_cache.py | is_introspectable | def is_introspectable(name, language):
'''
Do not call this before caching the nodes
'''
if name in FUNDAMENTALS[language]:
return True
if name not in __TRANSLATED_NAMES[language]:
return False
return True | python | def is_introspectable(name, language):
'''
Do not call this before caching the nodes
'''
if name in FUNDAMENTALS[language]:
return True
if name not in __TRANSLATED_NAMES[language]:
return False
return True | [
"def",
"is_introspectable",
"(",
"name",
",",
"language",
")",
":",
"if",
"name",
"in",
"FUNDAMENTALS",
"[",
"language",
"]",
":",
"return",
"True",
"if",
"name",
"not",
"in",
"__TRANSLATED_NAMES",
"[",
"language",
"]",
":",
"return",
"False",
"return",
"True"
] | Do not call this before caching the nodes | [
"Do",
"not",
"call",
"this",
"before",
"caching",
"the",
"nodes"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L338-L348 |
2,882 | hotdoc/hotdoc | hotdoc/core/config.py | Config.get_markdown_files | def get_markdown_files(self, dir_):
"""
Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk.
"""
md_files = OrderedSet()
for root, _, files in os.walk(dir_):
for name in files:
split = os.path.splitext(name)
if len(split) == 1:
continue
if split[1] in ('.markdown', '.md', '.yaml'):
md_files.add(os.path.join(root, name))
return md_files | python | def get_markdown_files(self, dir_):
"""
Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk.
"""
md_files = OrderedSet()
for root, _, files in os.walk(dir_):
for name in files:
split = os.path.splitext(name)
if len(split) == 1:
continue
if split[1] in ('.markdown', '.md', '.yaml'):
md_files.add(os.path.join(root, name))
return md_files | [
"def",
"get_markdown_files",
"(",
"self",
",",
"dir_",
")",
":",
"md_files",
"=",
"OrderedSet",
"(",
")",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir_",
")",
":",
"for",
"name",
"in",
"files",
":",
"split",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"if",
"len",
"(",
"split",
")",
"==",
"1",
":",
"continue",
"if",
"split",
"[",
"1",
"]",
"in",
"(",
"'.markdown'",
",",
"'.md'",
",",
"'.yaml'",
")",
":",
"md_files",
".",
"add",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"name",
")",
")",
"return",
"md_files"
] | Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk. | [
"Get",
"all",
"the",
"markdown",
"files",
"in",
"a",
"folder",
"recursively"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L164-L179 |
2,883 | hotdoc/hotdoc | hotdoc/core/config.py | Config.get | def get(self, key, default=None):
"""
Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key`
"""
if key in self.__cli:
return self.__cli[key]
if key in self.__config:
return self.__config.get(key)
if key in self.__defaults:
return self.__defaults.get(key)
return default | python | def get(self, key, default=None):
"""
Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key`
"""
if key in self.__cli:
return self.__cli[key]
if key in self.__config:
return self.__config.get(key)
if key in self.__defaults:
return self.__defaults.get(key)
return default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"return",
"self",
".",
"__cli",
"[",
"key",
"]",
"if",
"key",
"in",
"self",
".",
"__config",
":",
"return",
"self",
".",
"__config",
".",
"get",
"(",
"key",
")",
"if",
"key",
"in",
"self",
".",
"__defaults",
":",
"return",
"self",
".",
"__defaults",
".",
"get",
"(",
"key",
")",
"return",
"default"
] | Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key` | [
"Get",
"the",
"value",
"for",
"key",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L187-L205 |
2,884 | hotdoc/hotdoc | hotdoc/core/config.py | Config.get_index | def get_index(self, prefix=''):
"""
Retrieve the absolute path to an index, according to
`prefix`.
Args:
prefix: str, the desired prefix or `None`.
Returns:
str: An absolute path, or `None`
"""
if prefix:
prefixed = '%s_index' % prefix
else:
prefixed = 'index'
if prefixed in self.__cli and self.__cli[prefixed]:
index = self.__cli.get(prefixed)
from_conf = False
else:
index = self.__config.get(prefixed)
from_conf = True
return self.__abspath(index, from_conf) | python | def get_index(self, prefix=''):
"""
Retrieve the absolute path to an index, according to
`prefix`.
Args:
prefix: str, the desired prefix or `None`.
Returns:
str: An absolute path, or `None`
"""
if prefix:
prefixed = '%s_index' % prefix
else:
prefixed = 'index'
if prefixed in self.__cli and self.__cli[prefixed]:
index = self.__cli.get(prefixed)
from_conf = False
else:
index = self.__config.get(prefixed)
from_conf = True
return self.__abspath(index, from_conf) | [
"def",
"get_index",
"(",
"self",
",",
"prefix",
"=",
"''",
")",
":",
"if",
"prefix",
":",
"prefixed",
"=",
"'%s_index'",
"%",
"prefix",
"else",
":",
"prefixed",
"=",
"'index'",
"if",
"prefixed",
"in",
"self",
".",
"__cli",
"and",
"self",
".",
"__cli",
"[",
"prefixed",
"]",
":",
"index",
"=",
"self",
".",
"__cli",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"False",
"else",
":",
"index",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"True",
"return",
"self",
".",
"__abspath",
"(",
"index",
",",
"from_conf",
")"
] | Retrieve the absolute path to an index, according to
`prefix`.
Args:
prefix: str, the desired prefix or `None`.
Returns:
str: An absolute path, or `None` | [
"Retrieve",
"the",
"absolute",
"path",
"to",
"an",
"index",
"according",
"to",
"prefix",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L207-L230 |
2,885 | hotdoc/hotdoc | hotdoc/core/config.py | Config.get_path | def get_path(self, key, rel_to_cwd=False, rel_to_conf=False):
"""
Retrieve a path from the config, resolving it against
the invokation directory or the configuration file directory,
depending on whether it was passed through the command-line
or the configuration file.
Args:
key: str, the key to lookup the path with
Returns:
str: The path, or `None`
"""
if key in self.__cli:
path = self.__cli[key]
from_conf = False
else:
path = self.__config.get(key)
from_conf = True
if not isinstance(path, str):
return None
res = self.__abspath(path, from_conf)
if rel_to_cwd:
return os.path.relpath(res, self.__invoke_dir)
if rel_to_conf:
return os.path.relpath(res, self.__conf_dir)
return self.__abspath(path, from_conf) | python | def get_path(self, key, rel_to_cwd=False, rel_to_conf=False):
"""
Retrieve a path from the config, resolving it against
the invokation directory or the configuration file directory,
depending on whether it was passed through the command-line
or the configuration file.
Args:
key: str, the key to lookup the path with
Returns:
str: The path, or `None`
"""
if key in self.__cli:
path = self.__cli[key]
from_conf = False
else:
path = self.__config.get(key)
from_conf = True
if not isinstance(path, str):
return None
res = self.__abspath(path, from_conf)
if rel_to_cwd:
return os.path.relpath(res, self.__invoke_dir)
if rel_to_conf:
return os.path.relpath(res, self.__conf_dir)
return self.__abspath(path, from_conf) | [
"def",
"get_path",
"(",
"self",
",",
"key",
",",
"rel_to_cwd",
"=",
"False",
",",
"rel_to_conf",
"=",
"False",
")",
":",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"path",
"=",
"self",
".",
"__cli",
"[",
"key",
"]",
"from_conf",
"=",
"False",
"else",
":",
"path",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"key",
")",
"from_conf",
"=",
"True",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"None",
"res",
"=",
"self",
".",
"__abspath",
"(",
"path",
",",
"from_conf",
")",
"if",
"rel_to_cwd",
":",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"res",
",",
"self",
".",
"__invoke_dir",
")",
"if",
"rel_to_conf",
":",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"res",
",",
"self",
".",
"__conf_dir",
")",
"return",
"self",
".",
"__abspath",
"(",
"path",
",",
"from_conf",
")"
] | Retrieve a path from the config, resolving it against
the invokation directory or the configuration file directory,
depending on whether it was passed through the command-line
or the configuration file.
Args:
key: str, the key to lookup the path with
Returns:
str: The path, or `None` | [
"Retrieve",
"a",
"path",
"from",
"the",
"config",
"resolving",
"it",
"against",
"the",
"invokation",
"directory",
"or",
"the",
"configuration",
"file",
"directory",
"depending",
"on",
"whether",
"it",
"was",
"passed",
"through",
"the",
"command",
"-",
"line",
"or",
"the",
"configuration",
"file",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L232-L262 |
2,886 | hotdoc/hotdoc | hotdoc/core/config.py | Config.get_paths | def get_paths(self, key):
"""
Same as `ConfigParser.get_path` for a list of paths.
Args:
key: str, the key to lookup the paths with
Returns:
list: The paths.
"""
final_paths = []
if key in self.__cli:
paths = self.__cli[key] or []
from_conf = False
else:
paths = self.__config.get(key) or []
from_conf = True
for path in flatten_list(paths):
final_path = self.__abspath(path, from_conf)
if final_path:
final_paths.append(final_path)
return final_paths | python | def get_paths(self, key):
"""
Same as `ConfigParser.get_path` for a list of paths.
Args:
key: str, the key to lookup the paths with
Returns:
list: The paths.
"""
final_paths = []
if key in self.__cli:
paths = self.__cli[key] or []
from_conf = False
else:
paths = self.__config.get(key) or []
from_conf = True
for path in flatten_list(paths):
final_path = self.__abspath(path, from_conf)
if final_path:
final_paths.append(final_path)
return final_paths | [
"def",
"get_paths",
"(",
"self",
",",
"key",
")",
":",
"final_paths",
"=",
"[",
"]",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"paths",
"=",
"self",
".",
"__cli",
"[",
"key",
"]",
"or",
"[",
"]",
"from_conf",
"=",
"False",
"else",
":",
"paths",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"key",
")",
"or",
"[",
"]",
"from_conf",
"=",
"True",
"for",
"path",
"in",
"flatten_list",
"(",
"paths",
")",
":",
"final_path",
"=",
"self",
".",
"__abspath",
"(",
"path",
",",
"from_conf",
")",
"if",
"final_path",
":",
"final_paths",
".",
"append",
"(",
"final_path",
")",
"return",
"final_paths"
] | Same as `ConfigParser.get_path` for a list of paths.
Args:
key: str, the key to lookup the paths with
Returns:
list: The paths. | [
"Same",
"as",
"ConfigParser",
".",
"get_path",
"for",
"a",
"list",
"of",
"paths",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L264-L288 |
2,887 | hotdoc/hotdoc | hotdoc/core/config.py | Config.get_sources | def get_sources(self, prefix=''):
"""
Retrieve a set of absolute paths to sources, according to `prefix`
`ConfigParser` will perform wildcard expansion and
filtering.
Args:
prefix: str, the desired prefix.
Returns:
utils.utils.OrderedSet: The set of sources for the given
`prefix`.
"""
prefix = prefix.replace('-', '_')
prefixed = '%s_sources' % prefix
if prefixed in self.__cli:
sources = self.__cli.get(prefixed)
from_conf = False
else:
sources = self.__config.get(prefixed)
from_conf = True
if sources is None:
return OrderedSet()
sources = self.__resolve_patterns(sources, from_conf)
prefixed = '%s_source_filters' % prefix
if prefixed in self.__cli:
filters = self.__cli.get(prefixed)
from_conf = False
else:
filters = self.__config.get(prefixed)
from_conf = True
if filters is None:
return sources
sources -= self.__resolve_patterns(filters, from_conf)
return sources | python | def get_sources(self, prefix=''):
"""
Retrieve a set of absolute paths to sources, according to `prefix`
`ConfigParser` will perform wildcard expansion and
filtering.
Args:
prefix: str, the desired prefix.
Returns:
utils.utils.OrderedSet: The set of sources for the given
`prefix`.
"""
prefix = prefix.replace('-', '_')
prefixed = '%s_sources' % prefix
if prefixed in self.__cli:
sources = self.__cli.get(prefixed)
from_conf = False
else:
sources = self.__config.get(prefixed)
from_conf = True
if sources is None:
return OrderedSet()
sources = self.__resolve_patterns(sources, from_conf)
prefixed = '%s_source_filters' % prefix
if prefixed in self.__cli:
filters = self.__cli.get(prefixed)
from_conf = False
else:
filters = self.__config.get(prefixed)
from_conf = True
if filters is None:
return sources
sources -= self.__resolve_patterns(filters, from_conf)
return sources | [
"def",
"get_sources",
"(",
"self",
",",
"prefix",
"=",
"''",
")",
":",
"prefix",
"=",
"prefix",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"prefixed",
"=",
"'%s_sources'",
"%",
"prefix",
"if",
"prefixed",
"in",
"self",
".",
"__cli",
":",
"sources",
"=",
"self",
".",
"__cli",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"False",
"else",
":",
"sources",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"True",
"if",
"sources",
"is",
"None",
":",
"return",
"OrderedSet",
"(",
")",
"sources",
"=",
"self",
".",
"__resolve_patterns",
"(",
"sources",
",",
"from_conf",
")",
"prefixed",
"=",
"'%s_source_filters'",
"%",
"prefix",
"if",
"prefixed",
"in",
"self",
".",
"__cli",
":",
"filters",
"=",
"self",
".",
"__cli",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"False",
"else",
":",
"filters",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"True",
"if",
"filters",
"is",
"None",
":",
"return",
"sources",
"sources",
"-=",
"self",
".",
"__resolve_patterns",
"(",
"filters",
",",
"from_conf",
")",
"return",
"sources"
] | Retrieve a set of absolute paths to sources, according to `prefix`
`ConfigParser` will perform wildcard expansion and
filtering.
Args:
prefix: str, the desired prefix.
Returns:
utils.utils.OrderedSet: The set of sources for the given
`prefix`. | [
"Retrieve",
"a",
"set",
"of",
"absolute",
"paths",
"to",
"sources",
"according",
"to",
"prefix"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L290-L332 |
2,888 | hotdoc/hotdoc | hotdoc/core/config.py | Config.get_dependencies | def get_dependencies(self):
"""
Retrieve the set of all dependencies for a given configuration.
Returns:
utils.utils.OrderedSet: The set of all dependencies for the
tracked configuration.
"""
all_deps = OrderedSet()
for key, _ in list(self.__config.items()):
if key in self.__cli:
continue
if key.endswith('sources'):
all_deps |= self.get_sources(key[:len('sources') * -1 - 1])
for key, _ in list(self.__cli.items()):
if key.endswith('sources'):
all_deps |= self.get_sources(key[:len('sources') * -1 - 1])
if self.conf_file is not None:
all_deps.add(self.conf_file)
all_deps.add(self.get_path("sitemap", rel_to_cwd=True))
cwd = os.getcwd()
return [os.path.relpath(fname, cwd) for fname in all_deps if fname] | python | def get_dependencies(self):
"""
Retrieve the set of all dependencies for a given configuration.
Returns:
utils.utils.OrderedSet: The set of all dependencies for the
tracked configuration.
"""
all_deps = OrderedSet()
for key, _ in list(self.__config.items()):
if key in self.__cli:
continue
if key.endswith('sources'):
all_deps |= self.get_sources(key[:len('sources') * -1 - 1])
for key, _ in list(self.__cli.items()):
if key.endswith('sources'):
all_deps |= self.get_sources(key[:len('sources') * -1 - 1])
if self.conf_file is not None:
all_deps.add(self.conf_file)
all_deps.add(self.get_path("sitemap", rel_to_cwd=True))
cwd = os.getcwd()
return [os.path.relpath(fname, cwd) for fname in all_deps if fname] | [
"def",
"get_dependencies",
"(",
"self",
")",
":",
"all_deps",
"=",
"OrderedSet",
"(",
")",
"for",
"key",
",",
"_",
"in",
"list",
"(",
"self",
".",
"__config",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"continue",
"if",
"key",
".",
"endswith",
"(",
"'sources'",
")",
":",
"all_deps",
"|=",
"self",
".",
"get_sources",
"(",
"key",
"[",
":",
"len",
"(",
"'sources'",
")",
"*",
"-",
"1",
"-",
"1",
"]",
")",
"for",
"key",
",",
"_",
"in",
"list",
"(",
"self",
".",
"__cli",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
".",
"endswith",
"(",
"'sources'",
")",
":",
"all_deps",
"|=",
"self",
".",
"get_sources",
"(",
"key",
"[",
":",
"len",
"(",
"'sources'",
")",
"*",
"-",
"1",
"-",
"1",
"]",
")",
"if",
"self",
".",
"conf_file",
"is",
"not",
"None",
":",
"all_deps",
".",
"add",
"(",
"self",
".",
"conf_file",
")",
"all_deps",
".",
"add",
"(",
"self",
".",
"get_path",
"(",
"\"sitemap\"",
",",
"rel_to_cwd",
"=",
"True",
")",
")",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"return",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"fname",
",",
"cwd",
")",
"for",
"fname",
"in",
"all_deps",
"if",
"fname",
"]"
] | Retrieve the set of all dependencies for a given configuration.
Returns:
utils.utils.OrderedSet: The set of all dependencies for the
tracked configuration. | [
"Retrieve",
"the",
"set",
"of",
"all",
"dependencies",
"for",
"a",
"given",
"configuration",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L334-L360 |
2,889 | hotdoc/hotdoc | hotdoc/core/config.py | Config.dump | def dump(self, conf_file=None):
"""
Dump the possibly updated config to a file.
Args:
conf_file: str, the destination, or None to overwrite the
existing configuration.
"""
if conf_file:
conf_dir = os.path.dirname(conf_file)
if not conf_dir:
conf_dir = self.__invoke_dir
elif not os.path.exists(conf_dir):
os.makedirs(conf_dir)
else:
conf_dir = self.__conf_dir
final_conf = {}
for key, value in list(self.__config.items()):
if key in self.__cli:
continue
final_conf[key] = value
for key, value in list(self.__cli.items()):
if key.endswith('index') or key in ['sitemap', 'output']:
path = self.__abspath(value, from_conf=False)
if path:
relpath = os.path.relpath(path, conf_dir)
final_conf[key] = relpath
elif key.endswith('sources') or key.endswith('source_filters'):
new_list = []
for path in value:
path = self.__abspath(path, from_conf=False)
if path:
relpath = os.path.relpath(path, conf_dir)
new_list.append(relpath)
final_conf[key] = new_list
elif key not in ['command', 'output_conf_file']:
final_conf[key] = value
with open(conf_file or self.conf_file or 'hotdoc.json', 'w') as _:
_.write(json.dumps(final_conf, sort_keys=True, indent=4)) | python | def dump(self, conf_file=None):
"""
Dump the possibly updated config to a file.
Args:
conf_file: str, the destination, or None to overwrite the
existing configuration.
"""
if conf_file:
conf_dir = os.path.dirname(conf_file)
if not conf_dir:
conf_dir = self.__invoke_dir
elif not os.path.exists(conf_dir):
os.makedirs(conf_dir)
else:
conf_dir = self.__conf_dir
final_conf = {}
for key, value in list(self.__config.items()):
if key in self.__cli:
continue
final_conf[key] = value
for key, value in list(self.__cli.items()):
if key.endswith('index') or key in ['sitemap', 'output']:
path = self.__abspath(value, from_conf=False)
if path:
relpath = os.path.relpath(path, conf_dir)
final_conf[key] = relpath
elif key.endswith('sources') or key.endswith('source_filters'):
new_list = []
for path in value:
path = self.__abspath(path, from_conf=False)
if path:
relpath = os.path.relpath(path, conf_dir)
new_list.append(relpath)
final_conf[key] = new_list
elif key not in ['command', 'output_conf_file']:
final_conf[key] = value
with open(conf_file or self.conf_file or 'hotdoc.json', 'w') as _:
_.write(json.dumps(final_conf, sort_keys=True, indent=4)) | [
"def",
"dump",
"(",
"self",
",",
"conf_file",
"=",
"None",
")",
":",
"if",
"conf_file",
":",
"conf_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"conf_file",
")",
"if",
"not",
"conf_dir",
":",
"conf_dir",
"=",
"self",
".",
"__invoke_dir",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"conf_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"conf_dir",
")",
"else",
":",
"conf_dir",
"=",
"self",
".",
"__conf_dir",
"final_conf",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"self",
".",
"__config",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"continue",
"final_conf",
"[",
"key",
"]",
"=",
"value",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"self",
".",
"__cli",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
".",
"endswith",
"(",
"'index'",
")",
"or",
"key",
"in",
"[",
"'sitemap'",
",",
"'output'",
"]",
":",
"path",
"=",
"self",
".",
"__abspath",
"(",
"value",
",",
"from_conf",
"=",
"False",
")",
"if",
"path",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"conf_dir",
")",
"final_conf",
"[",
"key",
"]",
"=",
"relpath",
"elif",
"key",
".",
"endswith",
"(",
"'sources'",
")",
"or",
"key",
".",
"endswith",
"(",
"'source_filters'",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"path",
"in",
"value",
":",
"path",
"=",
"self",
".",
"__abspath",
"(",
"path",
",",
"from_conf",
"=",
"False",
")",
"if",
"path",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"conf_dir",
")",
"new_list",
".",
"append",
"(",
"relpath",
")",
"final_conf",
"[",
"key",
"]",
"=",
"new_list",
"elif",
"key",
"not",
"in",
"[",
"'command'",
",",
"'output_conf_file'",
"]",
":",
"final_conf",
"[",
"key",
"]",
"=",
"value",
"with",
"open",
"(",
"conf_file",
"or",
"self",
".",
"conf_file",
"or",
"'hotdoc.json'",
",",
"'w'",
")",
"as",
"_",
":",
"_",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"final_conf",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",
")"
] | Dump the possibly updated config to a file.
Args:
conf_file: str, the destination, or None to overwrite the
existing configuration. | [
"Dump",
"the",
"possibly",
"updated",
"config",
"to",
"a",
"file",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L363-L405 |
2,890 | hotdoc/hotdoc | hotdoc/utils/setup_utils.py | _update_submodules | def _update_submodules(repo_dir):
"""update submodules in a repo"""
subprocess.check_call("git submodule init", cwd=repo_dir, shell=True)
subprocess.check_call(
"git submodule update --recursive", cwd=repo_dir, shell=True) | python | def _update_submodules(repo_dir):
"""update submodules in a repo"""
subprocess.check_call("git submodule init", cwd=repo_dir, shell=True)
subprocess.check_call(
"git submodule update --recursive", cwd=repo_dir, shell=True) | [
"def",
"_update_submodules",
"(",
"repo_dir",
")",
":",
"subprocess",
".",
"check_call",
"(",
"\"git submodule init\"",
",",
"cwd",
"=",
"repo_dir",
",",
"shell",
"=",
"True",
")",
"subprocess",
".",
"check_call",
"(",
"\"git submodule update --recursive\"",
",",
"cwd",
"=",
"repo_dir",
",",
"shell",
"=",
"True",
")"
] | update submodules in a repo | [
"update",
"submodules",
"in",
"a",
"repo"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L75-L79 |
2,891 | hotdoc/hotdoc | hotdoc/utils/setup_utils.py | require_clean_submodules | def require_clean_submodules(repo_root, submodules):
"""Check on git submodules before distutils can do anything
Since distutils cannot be trusted to update the tree
after everything has been set in motion,
this is not a distutils command.
"""
# PACKAGERS: Add a return here to skip checks for git submodules
# don't do anything if nothing is actually supposed to happen
for do_nothing in (
'-h', '--help', '--help-commands', 'clean', 'submodule'):
if do_nothing in sys.argv:
return
status = _check_submodule_status(repo_root, submodules)
if status == "missing":
print("checking out submodules for the first time")
_update_submodules(repo_root)
elif status == "unclean":
print(UNCLEAN_SUBMODULES_MSG) | python | def require_clean_submodules(repo_root, submodules):
"""Check on git submodules before distutils can do anything
Since distutils cannot be trusted to update the tree
after everything has been set in motion,
this is not a distutils command.
"""
# PACKAGERS: Add a return here to skip checks for git submodules
# don't do anything if nothing is actually supposed to happen
for do_nothing in (
'-h', '--help', '--help-commands', 'clean', 'submodule'):
if do_nothing in sys.argv:
return
status = _check_submodule_status(repo_root, submodules)
if status == "missing":
print("checking out submodules for the first time")
_update_submodules(repo_root)
elif status == "unclean":
print(UNCLEAN_SUBMODULES_MSG) | [
"def",
"require_clean_submodules",
"(",
"repo_root",
",",
"submodules",
")",
":",
"# PACKAGERS: Add a return here to skip checks for git submodules",
"# don't do anything if nothing is actually supposed to happen",
"for",
"do_nothing",
"in",
"(",
"'-h'",
",",
"'--help'",
",",
"'--help-commands'",
",",
"'clean'",
",",
"'submodule'",
")",
":",
"if",
"do_nothing",
"in",
"sys",
".",
"argv",
":",
"return",
"status",
"=",
"_check_submodule_status",
"(",
"repo_root",
",",
"submodules",
")",
"if",
"status",
"==",
"\"missing\"",
":",
"print",
"(",
"\"checking out submodules for the first time\"",
")",
"_update_submodules",
"(",
"repo_root",
")",
"elif",
"status",
"==",
"\"unclean\"",
":",
"print",
"(",
"UNCLEAN_SUBMODULES_MSG",
")"
] | Check on git submodules before distutils can do anything
Since distutils cannot be trusted to update the tree
after everything has been set in motion,
this is not a distutils command. | [
"Check",
"on",
"git",
"submodules",
"before",
"distutils",
"can",
"do",
"anything",
"Since",
"distutils",
"cannot",
"be",
"trusted",
"to",
"update",
"the",
"tree",
"after",
"everything",
"has",
"been",
"set",
"in",
"motion",
"this",
"is",
"not",
"a",
"distutils",
"command",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L93-L113 |
2,892 | hotdoc/hotdoc | hotdoc/utils/setup_utils.py | symlink | def symlink(source, link_name):
"""
Method to allow creating symlinks on Windows
"""
if os.path.islink(link_name) and os.readlink(link_name) == source:
return
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, link_name)
else:
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
flags = 1 if os.path.isdir(source) else 0
if csl(link_name, source, flags) == 0:
raise ctypes.WinError() | python | def symlink(source, link_name):
"""
Method to allow creating symlinks on Windows
"""
if os.path.islink(link_name) and os.readlink(link_name) == source:
return
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, link_name)
else:
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
flags = 1 if os.path.isdir(source) else 0
if csl(link_name, source, flags) == 0:
raise ctypes.WinError() | [
"def",
"symlink",
"(",
"source",
",",
"link_name",
")",
":",
"if",
"os",
".",
"path",
".",
"islink",
"(",
"link_name",
")",
"and",
"os",
".",
"readlink",
"(",
"link_name",
")",
"==",
"source",
":",
"return",
"os_symlink",
"=",
"getattr",
"(",
"os",
",",
"\"symlink\"",
",",
"None",
")",
"if",
"callable",
"(",
"os_symlink",
")",
":",
"os_symlink",
"(",
"source",
",",
"link_name",
")",
"else",
":",
"import",
"ctypes",
"csl",
"=",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"CreateSymbolicLinkW",
"csl",
".",
"argtypes",
"=",
"(",
"ctypes",
".",
"c_wchar_p",
",",
"ctypes",
".",
"c_wchar_p",
",",
"ctypes",
".",
"c_uint32",
")",
"csl",
".",
"restype",
"=",
"ctypes",
".",
"c_ubyte",
"flags",
"=",
"1",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"source",
")",
"else",
"0",
"if",
"csl",
"(",
"link_name",
",",
"source",
",",
"flags",
")",
"==",
"0",
":",
"raise",
"ctypes",
".",
"WinError",
"(",
")"
] | Method to allow creating symlinks on Windows | [
"Method",
"to",
"allow",
"creating",
"symlinks",
"on",
"Windows"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L116-L133 |
2,893 | hotdoc/hotdoc | hotdoc/utils/setup_utils.py | pkgconfig | def pkgconfig(*packages, **kw):
"""
Query pkg-config for library compile and linking options. Return configuration in distutils
Extension format.
Usage:
pkgconfig('opencv')
pkgconfig('opencv', 'libavformat')
pkgconfig('opencv', optional='--static')
pkgconfig('opencv', config=c)
returns e.g.
{'extra_compile_args': [],
'extra_link_args': [],
'include_dirs': ['/usr/include/ffmpeg'],
'libraries': ['avformat'],
'library_dirs': []}
Intended use:
distutils.core.Extension('pyextension', sources=['source.cpp'], **c)
Set PKG_CONFIG_PATH environment variable for nonstandard library locations.
based on work of Micah Dowty (http://code.activestate.com/recipes/502261-python-distutils-pkg-config/)
"""
config = kw.setdefault('config', {})
optional_args = kw.setdefault('optional', '')
# { <distutils Extension arg>: [<pkg config option>, <prefix length to strip>], ...}
flag_map = {'include_dirs': ['--cflags-only-I', 2],
'library_dirs': ['--libs-only-L', 2],
'libraries': ['--libs-only-l', 2],
'extra_compile_args': ['--cflags-only-other', 0],
'extra_link_args': ['--libs-only-other', 0],
}
for package in packages:
for distutils_key, (pkg_option, n) in flag_map.items():
items = subprocess.check_output(['pkg-config', optional_args, pkg_option, package]).decode('utf8').split()
config.setdefault(distutils_key, []).extend([i[n:] for i in items])
return config | python | def pkgconfig(*packages, **kw):
"""
Query pkg-config for library compile and linking options. Return configuration in distutils
Extension format.
Usage:
pkgconfig('opencv')
pkgconfig('opencv', 'libavformat')
pkgconfig('opencv', optional='--static')
pkgconfig('opencv', config=c)
returns e.g.
{'extra_compile_args': [],
'extra_link_args': [],
'include_dirs': ['/usr/include/ffmpeg'],
'libraries': ['avformat'],
'library_dirs': []}
Intended use:
distutils.core.Extension('pyextension', sources=['source.cpp'], **c)
Set PKG_CONFIG_PATH environment variable for nonstandard library locations.
based on work of Micah Dowty (http://code.activestate.com/recipes/502261-python-distutils-pkg-config/)
"""
config = kw.setdefault('config', {})
optional_args = kw.setdefault('optional', '')
# { <distutils Extension arg>: [<pkg config option>, <prefix length to strip>], ...}
flag_map = {'include_dirs': ['--cflags-only-I', 2],
'library_dirs': ['--libs-only-L', 2],
'libraries': ['--libs-only-l', 2],
'extra_compile_args': ['--cflags-only-other', 0],
'extra_link_args': ['--libs-only-other', 0],
}
for package in packages:
for distutils_key, (pkg_option, n) in flag_map.items():
items = subprocess.check_output(['pkg-config', optional_args, pkg_option, package]).decode('utf8').split()
config.setdefault(distutils_key, []).extend([i[n:] for i in items])
return config | [
"def",
"pkgconfig",
"(",
"*",
"packages",
",",
"*",
"*",
"kw",
")",
":",
"config",
"=",
"kw",
".",
"setdefault",
"(",
"'config'",
",",
"{",
"}",
")",
"optional_args",
"=",
"kw",
".",
"setdefault",
"(",
"'optional'",
",",
"''",
")",
"# { <distutils Extension arg>: [<pkg config option>, <prefix length to strip>], ...}",
"flag_map",
"=",
"{",
"'include_dirs'",
":",
"[",
"'--cflags-only-I'",
",",
"2",
"]",
",",
"'library_dirs'",
":",
"[",
"'--libs-only-L'",
",",
"2",
"]",
",",
"'libraries'",
":",
"[",
"'--libs-only-l'",
",",
"2",
"]",
",",
"'extra_compile_args'",
":",
"[",
"'--cflags-only-other'",
",",
"0",
"]",
",",
"'extra_link_args'",
":",
"[",
"'--libs-only-other'",
",",
"0",
"]",
",",
"}",
"for",
"package",
"in",
"packages",
":",
"for",
"distutils_key",
",",
"(",
"pkg_option",
",",
"n",
")",
"in",
"flag_map",
".",
"items",
"(",
")",
":",
"items",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'pkg-config'",
",",
"optional_args",
",",
"pkg_option",
",",
"package",
"]",
")",
".",
"decode",
"(",
"'utf8'",
")",
".",
"split",
"(",
")",
"config",
".",
"setdefault",
"(",
"distutils_key",
",",
"[",
"]",
")",
".",
"extend",
"(",
"[",
"i",
"[",
"n",
":",
"]",
"for",
"i",
"in",
"items",
"]",
")",
"return",
"config"
] | Query pkg-config for library compile and linking options. Return configuration in distutils
Extension format.
Usage:
pkgconfig('opencv')
pkgconfig('opencv', 'libavformat')
pkgconfig('opencv', optional='--static')
pkgconfig('opencv', config=c)
returns e.g.
{'extra_compile_args': [],
'extra_link_args': [],
'include_dirs': ['/usr/include/ffmpeg'],
'libraries': ['avformat'],
'library_dirs': []}
Intended use:
distutils.core.Extension('pyextension', sources=['source.cpp'], **c)
Set PKG_CONFIG_PATH environment variable for nonstandard library locations.
based on work of Micah Dowty (http://code.activestate.com/recipes/502261-python-distutils-pkg-config/) | [
"Query",
"pkg",
"-",
"config",
"for",
"library",
"compile",
"and",
"linking",
"options",
".",
"Return",
"configuration",
"in",
"distutils",
"Extension",
"format",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L135-L180 |
2,894 | hotdoc/hotdoc | hotdoc/utils/loggable.py | Logger.register_error_code | def register_error_code(code, exception_type, domain='core'):
"""Register a new error code"""
Logger._error_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code) | python | def register_error_code(code, exception_type, domain='core'):
"""Register a new error code"""
Logger._error_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code) | [
"def",
"register_error_code",
"(",
"code",
",",
"exception_type",
",",
"domain",
"=",
"'core'",
")",
":",
"Logger",
".",
"_error_code_to_exception",
"[",
"code",
"]",
"=",
"(",
"exception_type",
",",
"domain",
")",
"Logger",
".",
"_domain_codes",
"[",
"domain",
"]",
".",
"add",
"(",
"code",
")"
] | Register a new error code | [
"Register",
"a",
"new",
"error",
"code"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L201-L204 |
2,895 | hotdoc/hotdoc | hotdoc/utils/loggable.py | Logger.register_warning_code | def register_warning_code(code, exception_type, domain='core'):
"""Register a new warning code"""
Logger._warning_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code) | python | def register_warning_code(code, exception_type, domain='core'):
"""Register a new warning code"""
Logger._warning_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code) | [
"def",
"register_warning_code",
"(",
"code",
",",
"exception_type",
",",
"domain",
"=",
"'core'",
")",
":",
"Logger",
".",
"_warning_code_to_exception",
"[",
"code",
"]",
"=",
"(",
"exception_type",
",",
"domain",
")",
"Logger",
".",
"_domain_codes",
"[",
"domain",
"]",
".",
"add",
"(",
"code",
")"
] | Register a new warning code | [
"Register",
"a",
"new",
"warning",
"code"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L207-L210 |
2,896 | hotdoc/hotdoc | hotdoc/utils/loggable.py | Logger._log | def _log(code, message, level, domain):
"""Call this to add an entry in the journal"""
entry = LogEntry(level, domain, code, message)
Logger.journal.append(entry)
if Logger.silent:
return
if level >= Logger._verbosity:
_print_entry(entry) | python | def _log(code, message, level, domain):
"""Call this to add an entry in the journal"""
entry = LogEntry(level, domain, code, message)
Logger.journal.append(entry)
if Logger.silent:
return
if level >= Logger._verbosity:
_print_entry(entry) | [
"def",
"_log",
"(",
"code",
",",
"message",
",",
"level",
",",
"domain",
")",
":",
"entry",
"=",
"LogEntry",
"(",
"level",
",",
"domain",
",",
"code",
",",
"message",
")",
"Logger",
".",
"journal",
".",
"append",
"(",
"entry",
")",
"if",
"Logger",
".",
"silent",
":",
"return",
"if",
"level",
">=",
"Logger",
".",
"_verbosity",
":",
"_print_entry",
"(",
"entry",
")"
] | Call this to add an entry in the journal | [
"Call",
"this",
"to",
"add",
"an",
"entry",
"in",
"the",
"journal"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L213-L222 |
2,897 | hotdoc/hotdoc | hotdoc/utils/loggable.py | Logger.error | def error(code, message, **kwargs):
"""Call this to raise an exception and have it stored in the journal"""
assert code in Logger._error_code_to_exception
exc_type, domain = Logger._error_code_to_exception[code]
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, ERROR, domain)
raise exc | python | def error(code, message, **kwargs):
"""Call this to raise an exception and have it stored in the journal"""
assert code in Logger._error_code_to_exception
exc_type, domain = Logger._error_code_to_exception[code]
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, ERROR, domain)
raise exc | [
"def",
"error",
"(",
"code",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"code",
"in",
"Logger",
".",
"_error_code_to_exception",
"exc_type",
",",
"domain",
"=",
"Logger",
".",
"_error_code_to_exception",
"[",
"code",
"]",
"exc",
"=",
"exc_type",
"(",
"message",
",",
"*",
"*",
"kwargs",
")",
"Logger",
".",
"_log",
"(",
"code",
",",
"exc",
".",
"message",
",",
"ERROR",
",",
"domain",
")",
"raise",
"exc"
] | Call this to raise an exception and have it stored in the journal | [
"Call",
"this",
"to",
"raise",
"an",
"exception",
"and",
"have",
"it",
"stored",
"in",
"the",
"journal"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L225-L231 |
2,898 | hotdoc/hotdoc | hotdoc/utils/loggable.py | Logger.warn | def warn(code, message, **kwargs):
"""
Call this to store a warning in the journal.
Will raise if `Logger.fatal_warnings` is set to True.
"""
if code in Logger._ignored_codes:
return
assert code in Logger._warning_code_to_exception
exc_type, domain = Logger._warning_code_to_exception[code]
if domain in Logger._ignored_domains:
return
level = WARNING
if Logger.fatal_warnings:
level = ERROR
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, level, domain)
if Logger.fatal_warnings:
raise exc | python | def warn(code, message, **kwargs):
"""
Call this to store a warning in the journal.
Will raise if `Logger.fatal_warnings` is set to True.
"""
if code in Logger._ignored_codes:
return
assert code in Logger._warning_code_to_exception
exc_type, domain = Logger._warning_code_to_exception[code]
if domain in Logger._ignored_domains:
return
level = WARNING
if Logger.fatal_warnings:
level = ERROR
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, level, domain)
if Logger.fatal_warnings:
raise exc | [
"def",
"warn",
"(",
"code",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"code",
"in",
"Logger",
".",
"_ignored_codes",
":",
"return",
"assert",
"code",
"in",
"Logger",
".",
"_warning_code_to_exception",
"exc_type",
",",
"domain",
"=",
"Logger",
".",
"_warning_code_to_exception",
"[",
"code",
"]",
"if",
"domain",
"in",
"Logger",
".",
"_ignored_domains",
":",
"return",
"level",
"=",
"WARNING",
"if",
"Logger",
".",
"fatal_warnings",
":",
"level",
"=",
"ERROR",
"exc",
"=",
"exc_type",
"(",
"message",
",",
"*",
"*",
"kwargs",
")",
"Logger",
".",
"_log",
"(",
"code",
",",
"exc",
".",
"message",
",",
"level",
",",
"domain",
")",
"if",
"Logger",
".",
"fatal_warnings",
":",
"raise",
"exc"
] | Call this to store a warning in the journal.
Will raise if `Logger.fatal_warnings` is set to True. | [
"Call",
"this",
"to",
"store",
"a",
"warning",
"in",
"the",
"journal",
"."
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L234-L259 |
2,899 | hotdoc/hotdoc | hotdoc/utils/loggable.py | Logger.debug | def debug(message, domain):
"""Log debugging information"""
if domain in Logger._ignored_domains:
return
Logger._log(None, message, DEBUG, domain) | python | def debug(message, domain):
"""Log debugging information"""
if domain in Logger._ignored_domains:
return
Logger._log(None, message, DEBUG, domain) | [
"def",
"debug",
"(",
"message",
",",
"domain",
")",
":",
"if",
"domain",
"in",
"Logger",
".",
"_ignored_domains",
":",
"return",
"Logger",
".",
"_log",
"(",
"None",
",",
"message",
",",
"DEBUG",
",",
"domain",
")"
] | Log debugging information | [
"Log",
"debugging",
"information"
] | 1067cdc8482b585b364a38fb52ca5d904e486280 | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L262-L267 |
Subsets and Splits