code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
for (name, order) in iteritems(appsettings.FLUENT_DASHBOARD_CMS_MODEL_ORDER):
if name in model_name:
return order
return 999
|
def get_cms_model_order(model_name)
|
Return a numeric ordering for a model name.
| 5.57496
| 5.004251
| 1.114045
|
site_name = get_admin_site_name(context)
self.children += [
items.MenuItem(_('Dashboard'), reverse('{0}:index'.format(site_name))),
items.Bookmarks(),
]
for title, kwargs in get_application_groups():
if kwargs.get('enabled', True):
self.children.append(CmsModelList(title, **kwargs))
self.children += [
ReturnToSiteItem()
]
|
def init_with_context(self, context)
|
Initialize the menu items.
| 6.95943
| 6.383672
| 1.090192
|
super(PersonalModule, self).init_with_context(context)
current_user = context['request'].user
if django.VERSION < (1, 5):
current_username = current_user.first_name or current_user.username
else:
current_username = current_user.get_short_name() or current_user.get_username()
site_name = get_admin_site_name(context)
# Personalize
self.title = _('Welcome,') + ' ' + (current_username)
# Expose links
self.pages_link = None
self.pages_title = None
self.password_link = reverse('{0}:password_change'.format(site_name))
self.logout_link = reverse('{0}:logout'.format(site_name))
if self.cms_page_model:
try:
app_label, model_name = self.cms_page_model
model = apps.get_model(app_label, model_name)
pages_title = model._meta.verbose_name_plural.lower()
pages_link = reverse('{site}:{app}_{model}_changelist'.format(site=site_name, app=app_label.lower(), model=model_name.lower()))
except AttributeError:
raise ImproperlyConfigured("The value {0} of FLUENT_DASHBOARD_CMS_PAGE_MODEL setting (or cms_page_model value) does not reffer to an existing model.".format(self.cms_page_model))
except NoReverseMatch:
pass
else:
# Also check if the user has permission to view the module.
# TODO: When there are modules that use Django 1.8's has_module_permission, add the support here.
permission_name = 'change_{0}'.format(model._meta.model_name.lower())
if current_user.has_perm('{0}.{1}'.format(model._meta.app_label, permission_name)):
self.pages_title = pages_title
self.pages_link = pages_link
|
def init_with_context(self, context)
|
Initializes the link list.
| 3.172046
| 3.177809
| 0.998186
|
super(AppIconList, self).init_with_context(context)
apps = self.children
# Standard model only has a title, change_url and add_url.
# Restore the app_name and name, so icons can be matched.
for app in apps:
app_name = self._get_app_name(app)
app['name'] = app_name
for model in app['models']:
try:
model_name = self._get_model_name(model)
model['name'] = model_name
model['icon'] = self.get_icon_for_model(app_name, model_name) or appsettings.FLUENT_DASHBOARD_DEFAULT_ICON
except ValueError:
model['icon'] = appsettings.FLUENT_DASHBOARD_DEFAULT_ICON
# Automatically add STATIC_URL before relative icon paths.
model['icon'] = self.get_icon_url(model['icon'])
model['app_name'] = app_name
|
def init_with_context(self, context)
|
Initializes the icon list.
| 4.464128
| 4.321305
| 1.033051
|
if 'change_url' in modeldata:
return modeldata['change_url'].strip('/').split('/')[-1] # /foo/admin/appname/modelname
elif 'add_url' in modeldata:
return modeldata['add_url'].strip('/').split('/')[-2] # /foo/admin/appname/modelname/add
else:
raise ValueError("Missing attributes in modeldata to find the model name!")
|
def _get_model_name(self, modeldata)
|
Extract the model name from the ``modeldata`` that *django-admin-tools* provides.
| 3.964528
| 3.285852
| 1.206545
|
key = "{0}/{1}".format(app_name, model_name)
return appsettings.FLUENT_DASHBOARD_APP_ICONS.get(key, default)
|
def get_icon_for_model(self, app_name, model_name, default=None)
|
Return the icon for the given model.
It reads the :ref:`FLUENT_DASHBOARD_APP_ICONS` setting.
| 4.496424
| 2.793141
| 1.609809
|
if not icon.startswith('/') \
and not icon.startswith('http://') \
and not icon.startswith('https://'):
if '/' in icon:
return self.icon_static_root + icon
else:
return self.icon_theme_root + icon
else:
return icon
|
def get_icon_url(self, icon)
|
Replaces the "icon name" with a full usable URL.
* When the icon is an absolute URL, it is used as-is.
* When the icon contains a slash, it is relative from the ``STATIC_URL``.
* Otherwise, it's relative to the theme url folder.
| 2.963868
| 2.871329
| 1.032229
|
super(CmsAppIconList, self).init_with_context(context)
apps = self.children
cms_apps = [a for a in apps if is_cms_app(a['name'])]
non_cms_apps = [a for a in apps if a not in cms_apps]
if cms_apps:
# Group the models of all CMS apps in one group.
cms_models = []
for app in cms_apps:
cms_models += app['models']
sort_cms_models(cms_models)
single_cms_app = {'name': "Modules", 'title': "Modules", 'url': "", 'models': cms_models}
# Put remaining groups after the first CMS group.
self.children = [single_cms_app] + non_cms_apps
|
def init_with_context(self, context)
|
Initializes the icon list.
| 3.992007
| 3.812755
| 1.047014
|
super(CacheStatusGroup, self).init_with_context(context)
if 'dashboardmods' in settings.INSTALLED_APPS:
import dashboardmods
memcache_mods = dashboardmods.get_memcache_dash_modules()
try:
varnish_mods = dashboardmods.get_varnish_dash_modules()
except (socket.error, KeyError) as e:
# dashboardmods 2.2 throws KeyError for 'cache_misses' when the Varnish cache is empty.
# Socket errors are also ignored, to work similar to the memcache stats.
logger.exception("Unable to request Varnish stats: {0}".format(str(e)))
varnish_mods = []
except ImportError:
varnish_mods = []
self.children = memcache_mods + varnish_mods
|
def init_with_context(self, context)
|
Initializes the status list.
| 5.832057
| 5.694176
| 1.024214
|
path = os.path.join(os.path.dirname(__file__), 'soupsieve')
fp, pathname, desc = imp.find_module('__meta__', [path])
try:
meta = imp.load_module('__meta__', fp, pathname, desc)
return meta.__version__, meta.__version_info__._get_dev_status()
finally:
fp.close()
|
def get_version()
|
Get version and version_info without importing the entire module.
| 3.249981
| 2.856403
| 1.137788
|
with open("requirements/project.txt") as f:
requirements = []
for line in f.readlines():
line = line.strip()
if line and not line.startswith('#'):
requirements.append(line)
return requirements
|
def get_requirements()
|
Get the dependencies.
| 2.782873
| 2.654299
| 1.04844
|
custom_selectors = process_custom(custom)
return cm.SoupSieve(
pattern,
CSSParser(pattern, custom=custom_selectors, flags=flags).process_selectors(),
namespaces,
custom,
flags
)
|
def _cached_css_compile(pattern, namespaces, custom, flags)
|
Cached CSS compile.
| 12.141662
| 12.375255
| 0.981124
|
custom_selectors = {}
if custom is not None:
for key, value in custom.items():
name = util.lower(key)
if RE_CUSTOM.match(name) is None:
raise SelectorSyntaxError("The name '{}' is not a valid custom pseudo-class name".format(name))
if name in custom_selectors:
raise KeyError("The custom selector '{}' has already been registered".format(name))
custom_selectors[css_unescape(name)] = value
return custom_selectors
|
def process_custom(custom)
|
Process custom.
| 4.098372
| 3.97375
| 1.031361
|
def replace(m):
if m.group(1):
codepoint = int(m.group(1)[1:], 16)
if codepoint == 0:
codepoint = UNICODE_REPLACEMENT_CHAR
value = util.uchr(codepoint)
elif m.group(2):
value = m.group(2)[1:]
elif m.group(3):
value = '\ufffd'
else:
value = ''
return value
return (RE_CSS_ESC if not string else RE_CSS_STR_ESC).sub(replace, content)
|
def css_unescape(content, string=False)
|
Unescape CSS value.
Strings allow for spanning the value on multiple strings by escaping a new line.
| 3.410717
| 3.460138
| 0.985717
|
string = []
length = len(ident)
start_dash = length > 0 and ident[0] == '-'
if length == 1 and start_dash:
# Need to escape identifier that is a single `-` with no other characters
string.append('\\{}'.format(ident))
else:
for index, c in enumerate(ident):
codepoint = util.uord(c)
if codepoint == 0x00:
string.append('\ufffd')
elif (0x01 <= codepoint <= 0x1F) or codepoint == 0x7F:
string.append('\\{:x} '.format(codepoint))
elif (index == 0 or (start_dash and index == 1)) and (0x30 <= codepoint <= 0x39):
string.append('\\{:x} '.format(codepoint))
elif (
codepoint in (0x2D, 0x5F) or codepoint >= 0x80 or (0x30 <= codepoint <= 0x39) or
(0x30 <= codepoint <= 0x39) or (0x41 <= codepoint <= 0x5A) or (0x61 <= codepoint <= 0x7A)
):
string.append(c)
else:
string.append('\\{}'.format(c))
return ''.join(string)
|
def escape(ident)
|
Escape identifier.
| 2.486201
| 2.442711
| 1.017804
|
pseudo = None
m = self.re_pseudo_name.match(selector, index)
if m:
name = util.lower(css_unescape(m.group('name')))
pattern = self.patterns.get(name)
if pattern:
pseudo = pattern.match(selector, index)
if pseudo:
self.matched_name = pattern
return pseudo
|
def match(self, selector, index)
|
Match the selector.
| 4.821815
| 4.732815
| 1.018805
|
if relations:
sel = relations[0]
sel.relations.extend(relations[1:])
return ct.SelectorList([sel.freeze()])
else:
return ct.SelectorList()
|
def _freeze_relations(self, relations)
|
Freeze relation.
| 7.33579
| 6.581553
| 1.114599
|
if self.no_match:
return ct.SelectorNull()
else:
return ct.Selector(
self.tag,
tuple(self.ids),
tuple(self.classes),
tuple(self.attributes),
tuple(self.nth),
tuple(self.selectors),
self._freeze_relations(self.relations),
self.rel_type,
tuple(self.contains),
tuple(self.lang),
self.flags
)
|
def freeze(self)
|
Freeze self.
| 6.130332
| 5.686028
| 1.07814
|
inverse = False
op = m.group('cmp')
case = util.lower(m.group('case')) if m.group('case') else None
parts = [css_unescape(a) for a in m.group('ns_attr').split('|')]
ns = ''
is_type = False
pattern2 = None
if len(parts) > 1:
ns = parts[0]
attr = parts[1]
else:
attr = parts[0]
if case:
flags = re.I if case == 'i' else 0
elif util.lower(attr) == 'type':
flags = re.I
is_type = True
else:
flags = 0
if op:
if m.group('value').startswith(('"', "'")) and not quirks:
value = css_unescape(m.group('value')[1:-1], True)
else:
value = css_unescape(m.group('value'))
else:
value = None
if not op:
# Attribute name
pattern = None
elif op.startswith('^'):
# Value start with
pattern = re.compile(r'^%s.*' % re.escape(value), flags)
elif op.startswith('$'):
# Value ends with
pattern = re.compile(r'.*?%s$' % re.escape(value), flags)
elif op.startswith('*'):
# Value contains
pattern = re.compile(r'.*?%s.*' % re.escape(value), flags)
elif op.startswith('~'):
# Value contains word within space separated list
# `~=` should match nothing if it is empty or contains whitespace,
# so if either of these cases is present, use `[^\s\S]` which cannot be matched.
value = r'[^\s\S]' if not value or RE_WS.search(value) else re.escape(value)
pattern = re.compile(r'.*?(?:(?<=^)|(?<=[ \t\r\n\f]))%s(?=(?:[ \t\r\n\f]|$)).*' % value, flags)
elif op.startswith('|'):
# Value starts with word in dash separated list
pattern = re.compile(r'^%s(?:-.*)?$' % re.escape(value), flags)
elif op.startswith('!'):
# Equivalent to `:not([attr=value])`
pattern = re.compile(r'^%s(?:-.*)?$' % re.escape(value), flags)
inverse = True
else:
# Value matches
pattern = re.compile(r'^%s$' % re.escape(value), flags)
if is_type and pattern:
pattern2 = re.compile(pattern.pattern)
# Append the attribute selector
sel_attr = ct.SelectorAttribute(attr, ns, pattern, pattern2)
if inverse:
# If we are using `!=`, we need to nest the pattern under a `:not()`.
sub_sel = _Selector()
sub_sel.attributes.append(sel_attr)
not_list = ct.SelectorList([sub_sel.freeze()], True, False)
sel.selectors.append(not_list)
else:
sel.attributes.append(sel_attr)
has_selector = True
return has_selector
|
def parse_attribute_selector(self, sel, m, has_selector, quirks)
|
Create attribute selector from the returned regex match.
| 3.077309
| 3.056513
| 1.006804
|
parts = [css_unescape(x) for x in m.group(0).split('|')]
if len(parts) > 1:
prefix = parts[0]
tag = parts[1]
else:
tag = parts[0]
prefix = None
sel.tag = ct.SelectorTag(tag, prefix)
has_selector = True
return has_selector
|
def parse_tag_pattern(self, sel, m, has_selector)
|
Parse tag pattern from regex match.
| 3.315692
| 3.175302
| 1.044213
|
pseudo = util.lower(css_unescape(m.group('name')))
selector = self.custom.get(pseudo)
if selector is None:
raise SelectorSyntaxError(
"Undefined custom selector '{}' found at postion {}".format(pseudo, m.end(0)),
self.pattern,
m.end(0)
)
if not isinstance(selector, ct.SelectorList):
self.custom[pseudo] = None
selector = CSSParser(
selector, custom=self.custom, flags=self.flags
).process_selectors(flags=FLG_PSEUDO)
self.custom[pseudo] = selector
sel.selectors.append(selector)
has_selector = True
return has_selector
|
def parse_pseudo_class_custom(self, sel, m, has_selector)
|
Parse custom pseudo class alias.
Compile custom selectors as we need them. When compiling a custom selector,
set it to `None` in the dictionary so we can avoid an infinite loop.
| 5.184515
| 4.865182
| 1.065636
|
complex_pseudo = False
pseudo = util.lower(css_unescape(m.group('name')))
if m.group('open'):
complex_pseudo = True
if complex_pseudo and pseudo in PSEUDO_COMPLEX:
has_selector = self.parse_pseudo_open(sel, pseudo, has_selector, iselector, m.end(0))
elif not complex_pseudo and pseudo in PSEUDO_SIMPLE:
if pseudo == ':root':
sel.flags |= ct.SEL_ROOT
elif pseudo == ':defined':
sel.flags |= ct.SEL_DEFINED
is_html = True
elif pseudo == ':scope':
sel.flags |= ct.SEL_SCOPE
elif pseudo == ':empty':
sel.flags |= ct.SEL_EMPTY
elif pseudo in (':link', ':any-link'):
sel.selectors.append(CSS_LINK)
elif pseudo == ':checked':
sel.selectors.append(CSS_CHECKED)
elif pseudo == ':default':
sel.selectors.append(CSS_DEFAULT)
elif pseudo == ':indeterminate':
sel.selectors.append(CSS_INDETERMINATE)
elif pseudo == ":disabled":
sel.selectors.append(CSS_DISABLED)
elif pseudo == ":enabled":
sel.selectors.append(CSS_ENABLED)
elif pseudo == ":required":
sel.selectors.append(CSS_REQUIRED)
elif pseudo == ":optional":
sel.selectors.append(CSS_OPTIONAL)
elif pseudo == ":read-only":
sel.selectors.append(CSS_READ_ONLY)
elif pseudo == ":read-write":
sel.selectors.append(CSS_READ_WRITE)
elif pseudo == ":in-range":
sel.selectors.append(CSS_IN_RANGE)
elif pseudo == ":out-of-range":
sel.selectors.append(CSS_OUT_OF_RANGE)
elif pseudo == ":placeholder-shown":
sel.selectors.append(CSS_PLACEHOLDER_SHOWN)
elif pseudo == ':first-child':
sel.nth.append(ct.SelectorNth(1, False, 0, False, False, ct.SelectorList()))
elif pseudo == ':last-child':
sel.nth.append(ct.SelectorNth(1, False, 0, False, True, ct.SelectorList()))
elif pseudo == ':first-of-type':
sel.nth.append(ct.SelectorNth(1, False, 0, True, False, ct.SelectorList()))
elif pseudo == ':last-of-type':
sel.nth.append(ct.SelectorNth(1, False, 0, True, True, ct.SelectorList()))
elif pseudo == ':only-child':
sel.nth.extend(
[
ct.SelectorNth(1, False, 0, False, False, ct.SelectorList()),
ct.SelectorNth(1, False, 0, False, True, ct.SelectorList())
]
)
elif pseudo == ':only-of-type':
sel.nth.extend(
[
ct.SelectorNth(1, False, 0, True, False, ct.SelectorList()),
ct.SelectorNth(1, False, 0, True, True, ct.SelectorList())
]
)
has_selector = True
elif complex_pseudo and pseudo in PSEUDO_COMPLEX_NO_MATCH:
self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN)
sel.no_match = True
has_selector = True
elif not complex_pseudo and pseudo in PSEUDO_SIMPLE_NO_MATCH:
sel.no_match = True
has_selector = True
elif pseudo in PSEUDO_SUPPORTED:
raise SelectorSyntaxError(
"Invalid syntax for pseudo class '{}'".format(pseudo),
self.pattern,
m.start(0)
)
else:
raise NotImplementedError(
"'{}' pseudo-class is not implemented at this time".format(pseudo)
)
return has_selector, is_html
|
def parse_pseudo_class(self, sel, m, has_selector, iselector, is_html)
|
Parse pseudo class.
| 1.892315
| 1.890534
| 1.000942
|
mdict = m.groupdict()
if mdict.get('pseudo_nth_child'):
postfix = '_child'
else:
postfix = '_type'
mdict['name'] = util.lower(css_unescape(mdict['name']))
content = util.lower(mdict.get('nth' + postfix))
if content == 'even':
# 2n
s1 = 2
s2 = 0
var = True
elif content == 'odd':
# 2n+1
s1 = 2
s2 = 1
var = True
else:
nth_parts = RE_NTH.match(content)
s1 = '-' if nth_parts.group('s1') and nth_parts.group('s1') == '-' else ''
a = nth_parts.group('a')
var = a.endswith('n')
if a.startswith('n'):
s1 += '1'
elif var:
s1 += a[:-1]
else:
s1 += a
s2 = '-' if nth_parts.group('s2') and nth_parts.group('s2') == '-' else ''
if nth_parts.group('b'):
s2 += nth_parts.group('b')
else:
s2 = '0'
s1 = int(s1, 10)
s2 = int(s2, 10)
pseudo_sel = mdict['name']
if postfix == '_child':
if m.group('of'):
# Parse the rest of `of S`.
nth_sel = self.parse_selectors(iselector, m.end(0), FLG_PSEUDO | FLG_OPEN)
else:
# Use default `*|*` for `of S`.
nth_sel = CSS_NTH_OF_S_DEFAULT
if pseudo_sel == ':nth-child':
sel.nth.append(ct.SelectorNth(s1, var, s2, False, False, nth_sel))
elif pseudo_sel == ':nth-last-child':
sel.nth.append(ct.SelectorNth(s1, var, s2, False, True, nth_sel))
else:
if pseudo_sel == ':nth-of-type':
sel.nth.append(ct.SelectorNth(s1, var, s2, True, False, ct.SelectorList()))
elif pseudo_sel == ':nth-last-of-type':
sel.nth.append(ct.SelectorNth(s1, var, s2, True, True, ct.SelectorList()))
has_selector = True
return has_selector
|
def parse_pseudo_nth(self, sel, m, has_selector, iselector)
|
Parse `nth` pseudo.
| 2.875005
| 2.853676
| 1.007474
|
flags = FLG_PSEUDO | FLG_OPEN
if name == ':not':
flags |= FLG_NOT
if name == ':has':
flags |= FLG_RELATIVE
sel.selectors.append(self.parse_selectors(iselector, index, flags))
has_selector = True
return has_selector
|
def parse_pseudo_open(self, sel, name, has_selector, iselector, index)
|
Parse pseudo with opening bracket.
| 5.094254
| 5.033452
| 1.01208
|
combinator = m.group('relation').strip()
if not combinator:
combinator = WS_COMBINATOR
if combinator == COMMA_COMBINATOR:
if not has_selector:
# If we've not captured any selector parts, the comma is either at the beginning of the pattern
# or following another comma, both of which are unexpected. Commas must split selectors.
raise SelectorSyntaxError(
"The combinator '{}' at postion {}, must have a selector before it".format(combinator, index),
self.pattern,
index
)
sel.rel_type = rel_type
selectors[-1].relations.append(sel)
rel_type = ":" + WS_COMBINATOR
selectors.append(_Selector())
else:
if has_selector:
# End the current selector and associate the leading combinator with this selector.
sel.rel_type = rel_type
selectors[-1].relations.append(sel)
elif rel_type[1:] != WS_COMBINATOR:
# It's impossible to have two whitespace combinators after each other as the patterns
# will gobble up trailing whitespace. It is also impossible to have a whitespace
# combinator after any other kind for the same reason. But we could have
# multiple non-whitespace combinators. So if the current combinator is not a whitespace,
# then we've hit the multiple combinator case, so we should fail.
raise SelectorSyntaxError(
'The multiple combinators at position {}'.format(index),
self.pattern,
index
)
# Set the leading combinator for the next selector.
rel_type = ':' + combinator
sel = _Selector()
has_selector = False
return has_selector, sel, rel_type
|
def parse_has_combinator(self, sel, m, has_selector, selectors, rel_type, index)
|
Parse combinator tokens.
| 5.385429
| 5.290143
| 1.018012
|
combinator = m.group('relation').strip()
if not combinator:
combinator = WS_COMBINATOR
if not has_selector:
# The only way we don't fail is if we are at the root level and quirks mode is enabled,
# and we've found no other selectors yet in this compound selector.
if (not self.quirks or is_pseudo or combinator == COMMA_COMBINATOR or relations):
raise SelectorSyntaxError(
"The combinator '{}' at postion {}, must have a selector before it".format(combinator, index),
self.pattern,
index
)
util.warn_quirks(
'You have attempted to use a combinator without a selector before it at position {}.'.format(index),
'the :scope pseudo class (or another appropriate selector) should be placed before the combinator.',
self.pattern,
index
)
sel.flags |= ct.SEL_SCOPE
if combinator == COMMA_COMBINATOR:
if not sel.tag and not is_pseudo:
# Implied `*`
sel.tag = ct.SelectorTag('*', None)
sel.relations.extend(relations)
selectors.append(sel)
del relations[:]
else:
sel.relations.extend(relations)
sel.rel_type = combinator
del relations[:]
relations.append(sel)
sel = _Selector()
has_selector = False
return has_selector, sel
|
def parse_combinator(self, sel, m, has_selector, selectors, relations, is_pseudo, index)
|
Parse combinator tokens.
| 6.027544
| 5.884726
| 1.024269
|
selector = m.group(0)
if selector.startswith('.'):
sel.classes.append(css_unescape(selector[1:]))
else:
sel.ids.append(css_unescape(selector[1:]))
has_selector = True
return has_selector
|
def parse_class_id(self, sel, m, has_selector)
|
Parse HTML classes and ids.
| 2.960413
| 2.486229
| 1.190724
|
values = m.group('values')
patterns = []
for token in RE_VALUES.finditer(values):
if token.group('split'):
continue
value = token.group('value')
if value.startswith(("'", '"')):
value = css_unescape(value[1:-1], True)
else:
value = css_unescape(value)
patterns.append(value)
sel.contains.append(ct.SelectorContains(tuple(patterns)))
has_selector = True
return has_selector
|
def parse_pseudo_contains(self, sel, m, has_selector)
|
Parse contains.
| 4.069114
| 3.815512
| 1.066466
|
values = m.group('values')
patterns = []
for token in RE_VALUES.finditer(values):
if token.group('split'):
continue
value = token.group('value')
if value.startswith(('"', "'")):
parts = css_unescape(value[1:-1], True).split('-')
else:
parts = css_unescape(value).split('-')
new_parts = []
first = True
for part in parts:
if part == '*' and first:
new_parts.append('(?!x\b)[a-z0-9]+?')
elif part != '*':
new_parts.append(('' if first else '(-(?!x\b)[a-z0-9]+)*?\\-') + re.escape(part))
if first:
first = False
patterns.append(re.compile(r'^{}(?:-.*)?$'.format(''.join(new_parts)), re.I))
sel.lang.append(ct.SelectorLang(patterns))
has_selector = True
return has_selector
|
def parse_pseudo_lang(self, sel, m, has_selector)
|
Parse pseudo language.
| 4.068581
| 3.953016
| 1.029235
|
value = ct.SEL_DIR_LTR if util.lower(m.group('dir')) == 'ltr' else ct.SEL_DIR_RTL
sel.flags |= value
has_selector = True
return has_selector
|
def parse_pseudo_dir(self, sel, m, has_selector)
|
Parse pseudo direction.
| 7.11588
| 5.730907
| 1.241667
|
# Ignore whitespace and comments at start and end of pattern
m = RE_WS_BEGIN.search(pattern)
index = m.end(0) if m else 0
m = RE_WS_END.search(pattern)
end = (m.start(0) - 1) if m else (len(pattern) - 1)
if self.debug: # pragma: no cover
if self.quirks:
print('## QUIRKS MODE: Throwing out the spec!')
print('## PARSING: {!r}'.format(pattern))
while index <= end:
m = None
for v in self.css_tokens:
if not v.enabled(self.flags): # pragma: no cover
continue
m = v.match(pattern, index)
if m:
name = v.get_name()
if self.debug: # pragma: no cover
print("TOKEN: '{}' --> {!r} at position {}".format(name, m.group(0), m.start(0)))
index = m.end(0)
yield name, m
break
if m is None:
c = pattern[index]
# If the character represents the start of one of the known selector types,
# throw an exception mentioning that the known selector type is in error;
# otherwise, report the invalid character.
if c == '[':
msg = "Malformed attribute selector at position {}".format(index)
elif c == '.':
msg = "Malformed class selector at position {}".format(index)
elif c == '#':
msg = "Malformed id selector at position {}".format(index)
elif c == ':':
msg = "Malformed pseudo-class selector at position {}".format(index)
else:
msg = "Invalid character {!r} position {}".format(c, index)
raise SelectorSyntaxError(msg, self.pattern, index)
if self.debug: # pragma: no cover
print('## END PARSING')
|
def selector_iter(self, pattern)
|
Iterate selector tokens.
| 3.374916
| 3.304499
| 1.021309
|
return self.parse_selectors(self.selector_iter(self.pattern), index, flags)
|
def process_selectors(self, index=0, flags=0)
|
Process selectors.
We do our own selectors as BeautifulSoup4 has some annoying quirks,
and we don't really need to do nth selectors or siblings or
descendants etc.
| 11.810998
| 9.798994
| 1.205328
|
edit = None
for name, values in label_list.items():
color, description = values
if isinstance(name, tuple):
old_name = name[0]
new_name = name[1]
else:
old_name = name
new_name = name
if label.lower() == old_name.lower():
edit = LabelEdit(old_name, new_name, color, description)
break
return edit
|
def find_label(label, label_color, label_description)
|
Find label.
| 2.680322
| 2.653534
| 1.010095
|
updated = set()
for label in repo.get_labels():
edit = find_label(label.name, label.color, label.description)
if edit is not None:
print(' Updating {}: #{} "{}"'.format(edit.new, edit.color, edit.description))
label.edit(edit.new, edit.color, edit.description)
updated.add(edit.old)
updated.add(edit.new)
else:
if DELETE_UNSPECIFIED:
print(' Deleting {}: #{} "{}"'.format(label.name, label.color, label.description))
label.delete()
else:
print(' Skipping {}: #{} "{}"'.format(label.name, label.color, label.description))
updated.add(label.name)
for name, values in label_list.items():
color, description = values
if isinstance(name, tuple):
new_name = name[1]
else:
new_name = name
if new_name not in updated:
print(' Creating {}: #{} "{}"'.format(new_name, color, description))
repo.create_label(new_name, color, description)
|
def update_labels(repo)
|
Update labels.
| 2.193489
| 2.163813
| 1.013714
|
import getpass
user = input("User Name: ") # noqa
pswd = getpass.getpass('Password: ')
return Github(user, pswd)
|
def get_auth()
|
Get authentication.
| 5.045118
| 4.873763
| 1.035159
|
if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
try:
with open(sys.argv[1], 'r') as f:
user_name, password = f.read().strip().split(':')
git = Github(user_name, password)
password = None
except Exception:
git = get_auth()
else:
git = get_auth()
user = git.get_user()
print('Finding repo...')
for repo in user.get_repos():
if repo.owner.name == user.name:
if repo.name == REPO_NAME:
print(repo.name)
update_labels(repo)
break
|
def main()
|
Main.
| 2.889318
| 2.955536
| 0.977595
|
m = RE_VER.match(ver)
# Handle major, minor, micro
major = int(m.group('major'))
minor = int(m.group('minor')) if m.group('minor') else 0
micro = int(m.group('micro')) if m.group('micro') else 0
# Handle pre releases
if m.group('type'):
release = PRE_REL_MAP[m.group('type')]
pre = int(m.group('pre'))
else:
release = "final"
pre = 0
# Handle development releases
dev = m.group('dev') if m.group('dev') else 0
if m.group('dev'):
dev = int(m.group('dev'))
release = '.dev-' + release if pre else '.dev'
else:
dev = 0
# Handle post
post = int(m.group('post')) if m.group('post') else 0
return Version(major, minor, micro, release, pre, post, dev)
|
def parse_version(ver, pre=False)
|
Parse version into a comparable Version tuple.
| 2.24915
| 2.166104
| 1.038339
|
# Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed..
if self.micro == 0:
ver = "{}.{}".format(self.major, self.minor)
else:
ver = "{}.{}.{}".format(self.major, self.minor, self.micro)
if self._is_pre():
ver += '{}{}'.format(REL_MAP[self.release], self.pre)
if self._is_post():
ver += ".post{}".format(self.post)
if self._is_dev():
ver += ".dev{}".format(self.dev)
return ver
|
def _get_canonical(self)
|
Get the canonical output string.
| 3.333762
| 3.244327
| 1.027567
|
# Fail on unexpected types.
if not cls.is_tag(tag):
raise TypeError("Expected a BeautifulSoup 'Tag', but instead recieved type {}".format(type(tag)))
|
def assert_valid_input(cls, tag)
|
Check if valid input tag or document.
| 10.128628
| 8.929666
| 1.134267
|
import bs4
return isinstance(obj, (bs4.Comment, bs4.Declaration, bs4.CData, bs4.ProcessingInstruction))
|
def is_special_string(obj)
|
Is special string.
| 5.646356
| 4.947763
| 1.141194
|
return ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == 'iframe') and self.is_html_tag(el)
|
def is_iframe(self, el)
|
Check if element is an `iframe`.
| 7.655076
| 7.327609
| 1.044689
|
root = self.root and self.root is el
if not root:
parent = self.get_parent(el)
root = parent is not None and self.is_html and self.is_iframe(parent)
return root
|
def is_root(self, el)
|
Return whether element is a root element.
We check that the element is the root of the tree (which we have already pre-calculated),
and we check if it is the root element under an `iframe`.
| 5.749985
| 3.979209
| 1.445007
|
if not no_iframe or not self.is_iframe(el):
for content in el.contents:
yield content
|
def get_contents(self, el, no_iframe=False)
|
Get contents or contents in reverse.
| 4.37772
| 3.826323
| 1.144106
|
if not no_iframe or not self.is_iframe(el):
last = len(el.contents) - 1
if start is None:
index = last if reverse else 0
else:
index = start
end = -1 if reverse else last + 1
incr = -1 if reverse else 1
if 0 <= index <= last:
while index != end:
node = el.contents[index]
index += incr
if not tags or self.is_tag(node):
yield node
|
def get_children(self, el, start=None, reverse=False, tags=True, no_iframe=False)
|
Get children.
| 3.000698
| 2.991842
| 1.00296
|
if not no_iframe or not self.is_iframe(el):
next_good = None
for child in el.descendants:
if next_good is not None:
if child is not next_good:
continue
next_good = None
is_tag = self.is_tag(child)
if no_iframe and is_tag and self.is_iframe(child):
if child.next_sibling is not None:
next_good = child.next_sibling
else:
last_child = child
while self.is_tag(last_child) and last_child.contents:
last_child = last_child.contents[-1]
next_good = last_child.next_element
yield child
if next_good is None:
break
# Coverage isn't seeing this even though it's executed
continue # pragma: no cover
if not tags or is_tag:
yield child
|
def get_descendants(self, el, tags=True, no_iframe=False)
|
Get descendants.
| 3.19757
| 3.181231
| 1.005136
|
parent = el.parent
if no_iframe and parent is not None and self.is_iframe(parent):
parent = None
return parent
|
def get_parent(self, el, no_iframe=False)
|
Get parent.
| 3.336184
| 3.121232
| 1.068867
|
sibling = el.next_sibling
while not cls.is_tag(sibling) and sibling is not None:
sibling = sibling.next_sibling
return sibling
|
def get_next_tag(cls, el)
|
Get next sibling tag.
| 3.661618
| 2.966142
| 1.234472
|
sibling = el.previous_sibling
while not cls.is_tag(sibling) and sibling is not None:
sibling = sibling.previous_sibling
return sibling
|
def get_previous_tag(cls, el)
|
Get previous sibling tag.
| 3.589844
| 3.064833
| 1.171302
|
value = default
if el._is_xml:
try:
value = el.attrs[name]
except KeyError:
pass
else:
for k, v in el.attrs.items():
if util.lower(k) == name:
value = v
break
return value
|
def get_attribute_by_name(el, name, default=None)
|
Get attribute by name.
| 3.555025
| 3.347672
| 1.06194
|
classes = cls.get_attribute_by_name(el, 'class', [])
if isinstance(classes, util.ustr):
classes = RE_NOT_WS.findall(classes)
return classes
|
def get_classes(cls, el)
|
Get classes.
| 8.735995
| 7.893437
| 1.106742
|
return ''.join(
[node for node in self.get_descendants(el, tags=False, no_iframe=no_iframe) if self.is_content_string(node)]
)
|
def get_text(self, el, no_iframe=False)
|
Get text.
| 5.612234
| 5.659024
| 0.991732
|
max_days = LONG_MONTH
if month == FEB:
max_days = FEB_LEAP_MONTH if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0) else FEB_MONTH
elif month in MONTHS_30:
max_days = SHORT_MONTH
return 1 <= day <= max_days
|
def validate_day(year, month, day)
|
Validate day.
| 3.153016
| 2.93545
| 1.074117
|
max_week = datetime.strptime("{}-{}-{}".format(12, 31, year), "%m-%d-%Y").isocalendar()[1]
if max_week == 1:
max_week = 53
return 1 <= week <= max_week
|
def validate_week(year, week)
|
Validate week.
| 3.891196
| 3.4765
| 1.119285
|
parsed = None
if itype == "date":
m = RE_DATE.match(value)
if m:
year = int(m.group('year'), 10)
month = int(m.group('month'), 10)
day = int(m.group('day'), 10)
if cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day):
parsed = (year, month, day)
elif itype == "month":
m = RE_MONTH.match(value)
if m:
year = int(m.group('year'), 10)
month = int(m.group('month'), 10)
if cls.validate_year(year) and cls.validate_month(month):
parsed = (year, month)
elif itype == "week":
m = RE_WEEK.match(value)
if m:
year = int(m.group('year'), 10)
week = int(m.group('week'), 10)
if cls.validate_year(year) and cls.validate_week(year, week):
parsed = (year, week)
elif itype == "time":
m = RE_TIME.match(value)
if m:
hour = int(m.group('hour'), 10)
minutes = int(m.group('minutes'), 10)
if cls.validate_hour(hour) and cls.validate_minutes(minutes):
parsed = (hour, minutes)
elif itype == "datetime-local":
m = RE_DATETIME.match(value)
if m:
year = int(m.group('year'), 10)
month = int(m.group('month'), 10)
day = int(m.group('day'), 10)
hour = int(m.group('hour'), 10)
minutes = int(m.group('minutes'), 10)
if (
cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day) and
cls.validate_hour(hour) and cls.validate_minutes(minutes)
):
parsed = (year, month, day, hour, minutes)
elif itype in ("number", "range"):
m = RE_NUM.match(value)
if m:
parsed = float(m.group('value'))
return parsed
|
def parse_value(cls, itype, value)
|
Parse the input value.
| 1.317309
| 1.298387
| 1.014573
|
if self.supports_namespaces():
namespace = ''
ns = el.namespace
if ns:
namespace = ns
else:
namespace = NS_XHTML
return namespace
|
def get_tag_ns(self, el)
|
Get tag namespace.
| 6.853922
| 5.572846
| 1.229878
|
name = self.get_tag_name(el)
return util.lower(name) if name is not None and not self.is_xml else name
|
def get_tag(self, el)
|
Get tag.
| 8.263759
| 7.393437
| 1.117715
|
prefix = self.get_prefix_name(el)
return util.lower(prefix) if prefix is not None and not self.is_xml else prefix
|
def get_prefix(self, el)
|
Get prefix.
| 9.405027
| 8.161655
| 1.152343
|
for node in self.get_children(el, tags=False):
# Analyze child text nodes
if self.is_tag(node):
# Avoid analyzing certain elements specified in the specification.
direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(node, 'dir', '')), None)
if (
self.get_tag(node) in ('bdi', 'script', 'style', 'textarea', 'iframe') or
not self.is_html_tag(node) or
direction is not None
):
continue # pragma: no cover
# Check directionality of this node's text
value = self.find_bidi(node)
if value is not None:
return value
# Direction could not be determined
continue # pragma: no cover
# Skip `doctype` comments, etc.
if self.is_special_string(node):
continue
# Analyze text nodes for directionality.
for c in node:
bidi = unicodedata.bidirectional(c)
if bidi in ('AL', 'R', 'L'):
return ct.SEL_DIR_LTR if bidi == 'L' else ct.SEL_DIR_RTL
return None
|
def find_bidi(self, el)
|
Get directionality from element text.
| 5.396224
| 5.162448
| 1.045284
|
value = None
if self.supports_namespaces():
value = None
# If we have not defined namespaces, we can't very well find them, so don't bother trying.
if prefix:
ns = self.namespaces.get(prefix)
if ns is None and prefix != '*':
return None
else:
ns = None
for k, v in self.iter_attributes(el):
# Get attribute parts
namespace, name = self.split_namespace(el, k)
# Can't match a prefix attribute as we haven't specified one to match
# Try to match it normally as a whole `p:a` as selector may be trying `p\:a`.
if ns is None:
if (self.is_xml and attr == k) or (not self.is_xml and util.lower(attr) == util.lower(k)):
value = v
break
# Coverage is not finding this even though it is executed.
# Adding a print statement before this (and erasing coverage) causes coverage to find the line.
# Ignore the false positive message.
continue # pragma: no cover
# We can't match our desired prefix attribute as the attribute doesn't have a prefix
if namespace is None or ns != namespace and prefix != '*':
continue
# The attribute doesn't match.
if (util.lower(attr) != util.lower(name)) if not self.is_xml else (attr != name):
continue
value = v
break
else:
for k, v in self.iter_attributes(el):
if util.lower(attr) != util.lower(k):
continue
value = v
break
return value
|
def match_attribute_name(self, el, attr, prefix)
|
Match attribute name and return value if it exists.
| 6.117806
| 5.911597
| 1.034882
|
match = True
namespace = self.get_tag_ns(el)
default_namespace = self.namespaces.get('')
tag_ns = '' if tag.prefix is None else self.namespaces.get(tag.prefix, None)
# We must match the default namespace if one is not provided
if tag.prefix is None and (default_namespace is not None and namespace != default_namespace):
match = False
# If we specified `|tag`, we must not have a namespace.
elif (tag.prefix is not None and tag.prefix == '' and namespace):
match = False
# Verify prefix matches
elif (
tag.prefix and
tag.prefix != '*' and (tag_ns is None or namespace != tag_ns)
):
match = False
return match
|
def match_namespace(self, el, tag)
|
Match the namespace of the element.
| 4.508564
| 4.384207
| 1.028365
|
match = True
if attributes:
for a in attributes:
value = self.match_attribute_name(el, a.attribute, a.prefix)
pattern = a.xml_type_pattern if self.is_xml and a.xml_type_pattern else a.pattern
if isinstance(value, list):
value = ' '.join(value)
if value is None:
match = False
break
elif pattern is None:
continue
elif pattern.match(value) is None:
match = False
break
return match
|
def match_attributes(self, el, attributes)
|
Match attributes.
| 3.309111
| 3.114988
| 1.062319
|
name = (util.lower(tag.name) if not self.is_xml and tag.name is not None else tag.name)
return not (
name is not None and
name not in (self.get_tag(el), '*')
)
|
def match_tagname(self, el, tag)
|
Match tag name.
| 7.785077
| 6.481961
| 1.201037
|
match = True
if tag is not None:
# Verify namespace
if not self.match_namespace(el, tag):
match = False
if not self.match_tagname(el, tag):
match = False
return match
|
def match_tag(self, el, tag)
|
Match the tag.
| 3.812284
| 3.356091
| 1.13593
|
found = False
if relation[0].rel_type == REL_PARENT:
parent = self.get_parent(el, no_iframe=self.iframe_restrict)
while not found and parent:
found = self.match_selectors(parent, relation)
parent = self.get_parent(parent, no_iframe=self.iframe_restrict)
elif relation[0].rel_type == REL_CLOSE_PARENT:
parent = self.get_parent(el, no_iframe=self.iframe_restrict)
if parent:
found = self.match_selectors(parent, relation)
elif relation[0].rel_type == REL_SIBLING:
sibling = self.get_previous_tag(el)
while not found and sibling:
found = self.match_selectors(sibling, relation)
sibling = self.get_previous_tag(sibling)
elif relation[0].rel_type == REL_CLOSE_SIBLING:
sibling = self.get_previous_tag(el)
if sibling and self.is_tag(sibling):
found = self.match_selectors(sibling, relation)
return found
|
def match_past_relations(self, el, relation)
|
Match past relationship.
| 2.121911
| 2.098878
| 1.010974
|
match = False
children = self.get_descendants if recursive else self.get_children
for child in children(parent, no_iframe=self.iframe_restrict):
match = self.match_selectors(child, relation)
if match:
break
return match
|
def match_future_child(self, parent, relation, recursive=False)
|
Match future child.
| 5.689409
| 5.575224
| 1.020481
|
found = False
if relation[0].rel_type == REL_HAS_PARENT:
found = self.match_future_child(el, relation, True)
elif relation[0].rel_type == REL_HAS_CLOSE_PARENT:
found = self.match_future_child(el, relation)
elif relation[0].rel_type == REL_HAS_SIBLING:
sibling = self.get_next_tag(el)
while not found and sibling:
found = self.match_selectors(sibling, relation)
sibling = self.get_next_tag(sibling)
elif relation[0].rel_type == REL_HAS_CLOSE_SIBLING:
sibling = self.get_next_tag(el)
if sibling and self.is_tag(sibling):
found = self.match_selectors(sibling, relation)
return found
|
def match_future_relations(self, el, relation)
|
Match future relationship.
| 2.389908
| 2.338819
| 1.021844
|
found = False
if relation[0].rel_type.startswith(':'):
found = self.match_future_relations(el, relation)
else:
found = self.match_past_relations(el, relation)
return found
|
def match_relations(self, el, relation)
|
Match relationship to other elements.
| 4.452347
| 4.316449
| 1.031484
|
found = True
for i in ids:
if i != self.get_attribute_by_name(el, 'id', ''):
found = False
break
return found
|
def match_id(self, el, ids)
|
Match element's ID.
| 5.006849
| 4.250157
| 1.178038
|
current_classes = self.get_classes(el)
found = True
for c in classes:
if c not in current_classes:
found = False
break
return found
|
def match_classes(self, el, classes)
|
Match element's classes.
| 3.118884
| 2.610764
| 1.194625
|
return(
(self.get_tag(child) == self.get_tag(el)) and
(self.get_tag_ns(child) == self.get_tag_ns(el))
)
|
def match_nth_tag_type(self, el, child)
|
Match tag type for `nth` matches.
| 3.262023
| 3.181597
| 1.025279
|
matched = True
for n in nth:
matched = False
if n.selectors and not self.match_selectors(el, n.selectors):
break
parent = self.get_parent(el)
if parent is None:
parent = self.create_fake_parent(el)
last = n.last
last_index = len(parent) - 1
index = last_index if last else 0
relative_index = 0
a = n.a
b = n.b
var = n.n
count = 0
count_incr = 1
factor = -1 if last else 1
idx = last_idx = a * count + b if var else a
# We can only adjust bounds within a variable index
if var:
# Abort if our nth index is out of bounds and only getting further out of bounds as we increment.
# Otherwise, increment to try to get in bounds.
adjust = None
while idx < 1 or idx > last_index:
if idx < 0:
diff_low = 0 - idx
if adjust is not None and adjust == 1:
break
adjust = -1
count += count_incr
idx = last_idx = a * count + b if var else a
diff = 0 - idx
if diff >= diff_low:
break
else:
diff_high = idx - last_index
if adjust is not None and adjust == -1:
break
adjust = 1
count += count_incr
idx = last_idx = a * count + b if var else a
diff = idx - last_index
if diff >= diff_high:
break
diff_high = diff
# If a < 0, our count is working backwards, so floor the index by increasing the count.
# Find the count that yields the lowest, in bound value and use that.
# Lastly reverse count increment so that we'll increase our index.
lowest = count
if a < 0:
while idx >= 1:
lowest = count
count += count_incr
idx = last_idx = a * count + b if var else a
count_incr = -1
count = lowest
idx = last_idx = a * count + b if var else a
# Evaluate elements while our calculated nth index is still in range
while 1 <= idx <= last_index + 1:
child = None
# Evaluate while our child index is still in range.
for child in self.get_children(parent, start=index, reverse=factor < 0, tags=False):
index += factor
if not self.is_tag(child):
continue
# Handle `of S` in `nth-child`
if n.selectors and not self.match_selectors(child, n.selectors):
continue
# Handle `of-type`
if n.of_type and not self.match_nth_tag_type(el, child):
continue
relative_index += 1
if relative_index == idx:
if child is el:
matched = True
else:
break
if child is el:
break
if child is el:
break
last_idx = idx
count += count_incr
if count < 0:
# Count is counting down and has now ventured into invalid territory.
break
idx = a * count + b if var else a
if last_idx == idx:
break
if not matched:
break
return matched
|
def match_nth(self, el, nth)
|
Match `nth` elements.
| 4.537304
| 4.507852
| 1.006533
|
is_empty = True
for child in self.get_children(el, tags=False):
if self.is_tag(child):
is_empty = False
break
elif self.is_content_string(child) and RE_NOT_EMPTY.search(child):
is_empty = False
break
return is_empty
|
def match_empty(self, el)
|
Check if element is empty (if requested).
| 3.933377
| 3.449668
| 1.140219
|
match = True
for sel in selectors:
if not self.match_selectors(el, sel):
match = False
return match
|
def match_subselectors(self, el, selectors)
|
Match selectors.
| 3.694434
| 3.051526
| 1.210684
|
match = True
content = None
for contain_list in contains:
if content is None:
content = self.get_text(el, no_iframe=self.is_html)
found = False
for text in contain_list.text:
if text in content:
found = True
break
if not found:
match = False
return match
|
def match_contains(self, el, contains)
|
Match element if it contains text.
| 4.529285
| 4.104909
| 1.103383
|
match = False
# Find this input's form
form = None
parent = self.get_parent(el, no_iframe=True)
while parent and form is None:
if self.get_tag(parent) == 'form' and self.is_html_tag(parent):
form = parent
else:
parent = self.get_parent(parent, no_iframe=True)
# Look in form cache to see if we've already located its default button
found_form = False
for f, t in self.cached_default_forms:
if f is form:
found_form = True
if t is el:
match = True
break
# We didn't have the form cached, so look for its default button
if not found_form:
for child in self.get_descendants(form, no_iframe=True):
name = self.get_tag(child)
# Can't do nested forms (haven't figured out why we never hit this)
if name == 'form': # pragma: no cover
break
if name in ('input', 'button'):
v = self.get_attribute_by_name(child, 'type', '')
if v and util.lower(v) == 'submit':
self.cached_default_forms.append([form, child])
if el is child:
match = True
break
return match
|
def match_default(self, el)
|
Match default.
| 3.74838
| 3.691196
| 1.015492
|
match = False
name = self.get_attribute_by_name(el, 'name')
def get_parent_form(el):
form = None
parent = self.get_parent(el, no_iframe=True)
while form is None:
if self.get_tag(parent) == 'form' and self.is_html_tag(parent):
form = parent
break
last_parent = parent
parent = self.get_parent(parent, no_iframe=True)
if parent is None:
form = last_parent
break
return form
form = get_parent_form(el)
# Look in form cache to see if we've already evaluated that its fellow radio buttons are indeterminate
found_form = False
for f, n, i in self.cached_indeterminate_forms:
if f is form and n == name:
found_form = True
if i is True:
match = True
break
# We didn't have the form cached, so validate that the radio button is indeterminate
if not found_form:
checked = False
for child in self.get_descendants(form, no_iframe=True):
if child is el:
continue
tag_name = self.get_tag(child)
if tag_name == 'input':
is_radio = False
check = False
has_name = False
for k, v in self.iter_attributes(child):
if util.lower(k) == 'type' and util.lower(v) == 'radio':
is_radio = True
elif util.lower(k) == 'name' and v == name:
has_name = True
elif util.lower(k) == 'checked':
check = True
if is_radio and check and has_name and get_parent_form(child) is form:
checked = True
break
if checked:
break
if not checked:
match = True
self.cached_indeterminate_forms.append([form, name, match])
return match
|
def match_indeterminate(self, el)
|
Match default.
| 2.757062
| 2.734687
| 1.008182
|
match = False
has_ns = self.supports_namespaces()
root = self.root
has_html_namespace = self.has_html_namespace
# Walk parents looking for `lang` (HTML) or `xml:lang` XML property.
parent = el
found_lang = None
last = None
while not found_lang:
has_html_ns = self.has_html_ns(parent)
for k, v in self.iter_attributes(parent):
attr_ns, attr = self.split_namespace(parent, k)
if (
((not has_ns or has_html_ns) and (util.lower(k) if not self.is_xml else k) == 'lang') or
(
has_ns and not has_html_ns and attr_ns == NS_XML and
(util.lower(attr) if not self.is_xml and attr is not None else attr) == 'lang'
)
):
found_lang = v
break
last = parent
parent = self.get_parent(parent, no_iframe=self.is_html)
if parent is None:
root = last
has_html_namespace = self.has_html_ns(root)
parent = last
break
# Use cached meta language.
if not found_lang and self.cached_meta_lang:
for cache in self.cached_meta_lang:
if root is cache[0]:
found_lang = cache[1]
# If we couldn't find a language, and the document is HTML, look to meta to determine language.
if found_lang is None and (not self.is_xml or (has_html_namespace and root.name == 'html')):
# Find head
found = False
for tag in ('html', 'head'):
found = False
for child in self.get_children(parent, no_iframe=self.is_html):
if self.get_tag(child) == tag and self.is_html_tag(child):
found = True
parent = child
break
if not found: # pragma: no cover
break
# Search meta tags
if found:
for child in parent:
if self.is_tag(child) and self.get_tag(child) == 'meta' and self.is_html_tag(parent):
c_lang = False
content = None
for k, v in self.iter_attributes(child):
if util.lower(k) == 'http-equiv' and util.lower(v) == 'content-language':
c_lang = True
if util.lower(k) == 'content':
content = v
if c_lang and content:
found_lang = content
self.cached_meta_lang.append((root, found_lang))
break
if found_lang:
break
if not found_lang:
self.cached_meta_lang.append((root, False))
# If we determined a language, compare.
if found_lang:
for patterns in langs:
match = False
for pattern in patterns:
if pattern.match(found_lang):
match = True
if not match:
break
return match
|
def match_lang(self, el, langs)
|
Match languages.
| 3.018803
| 2.987338
| 1.010533
|
# If we have to match both left and right, we can't match either.
if directionality & ct.SEL_DIR_LTR and directionality & ct.SEL_DIR_RTL:
return False
if el is None or not self.is_html_tag(el):
return False
# Element has defined direction of left to right or right to left
direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(el, 'dir', '')), None)
if direction not in (None, 0):
return direction == directionality
# Element is the document element (the root) and no direction assigned, assume left to right.
is_root = self.is_root(el)
if is_root and direction is None:
return ct.SEL_DIR_LTR == directionality
# If `input[type=telephone]` and no direction is assigned, assume left to right.
name = self.get_tag(el)
is_input = name == 'input'
is_textarea = name == 'textarea'
is_bdi = name == 'bdi'
itype = util.lower(self.get_attribute_by_name(el, 'type', '')) if is_input else ''
if is_input and itype == 'tel' and direction is None:
return ct.SEL_DIR_LTR == directionality
# Auto handling for text inputs
if ((is_input and itype in ('text', 'search', 'tel', 'url', 'email')) or is_textarea) and direction == 0:
if is_textarea:
value = []
for node in self.get_contents(el, no_iframe=True):
if self.is_content_string(node):
value.append(node)
value = ''.join(value)
else:
value = self.get_attribute_by_name(el, 'value', '')
if value:
for c in value:
bidi = unicodedata.bidirectional(c)
if bidi in ('AL', 'R', 'L'):
direction = ct.SEL_DIR_LTR if bidi == 'L' else ct.SEL_DIR_RTL
return direction == directionality
# Assume left to right
return ct.SEL_DIR_LTR == directionality
elif is_root:
return ct.SEL_DIR_LTR == directionality
return self.match_dir(self.get_parent(el, no_iframe=True), directionality)
# Auto handling for `bdi` and other non text inputs.
if (is_bdi and direction is None) or direction == 0:
direction = self.find_bidi(el)
if direction is not None:
return direction == directionality
elif is_root:
return ct.SEL_DIR_LTR == directionality
return self.match_dir(self.get_parent(el, no_iframe=True), directionality)
# Match parents direction
return self.match_dir(self.get_parent(el, no_iframe=True), directionality)
|
def match_dir(self, el, directionality)
|
Check directionality.
| 2.88703
| 2.863652
| 1.008164
|
out_of_range = False
itype = self.get_attribute_by_name(el, 'type').lower()
mn = self.get_attribute_by_name(el, 'min', None)
if mn is not None:
mn = Inputs.parse_value(itype, mn)
mx = self.get_attribute_by_name(el, 'max', None)
if mx is not None:
mx = Inputs.parse_value(itype, mx)
# There is no valid min or max, so we cannot evaluate a range
if mn is None and mx is None:
return False
value = self.get_attribute_by_name(el, 'value', None)
if value is not None:
value = Inputs.parse_value(itype, value)
if value is not None:
if itype in ("date", "datetime-local", "month", "week", "number", "range"):
if mn is not None and value < mn:
out_of_range = True
if not out_of_range and mx is not None and value > mx:
out_of_range = True
elif itype == "time":
if mn is not None and mx is not None and mn > mx:
# Time is periodic, so this is a reversed/discontinuous range
if value < mn and value > mx:
out_of_range = True
else:
if mn is not None and value < mn:
out_of_range = True
if not out_of_range and mx is not None and value > mx:
out_of_range = True
return not out_of_range if condition & ct.SEL_IN_RANGE else out_of_range
|
def match_range(self, el, condition)
|
Match range.
Behavior is modeled after what we see in browsers. Browsers seem to evaluate
if the value is out of range, and if not, it is in range. So a missing value
will not evaluate out of range; therefore, value is in range. Personally, I
feel like this should evaluate as neither in or out of range.
| 2.505399
| 2.447089
| 1.023828
|
name = self.get_tag(el)
return (
name.find('-') == -1 or
name.find(':') != -1 or
self.get_prefix(el) is not None
)
|
def match_defined(self, el)
|
Match defined.
`:defined` is related to custom elements in a browser.
- If the document is XML (not XHTML), all tags will match.
- Tags that are not custom (don't have a hyphen) are marked defined.
- If the tag has a prefix (without or without a namespace), it will not match.
This is of course requires the parser to provide us with the proper prefix and namespace info,
if it doesn't, there is nothing we can do.
| 5.786547
| 4.045404
| 1.4304
|
match = False
is_not = selectors.is_not
is_html = selectors.is_html
# Internal selector lists that use the HTML flag, will automatically get the `html` namespace.
if is_html:
namespaces = self.namespaces
iframe_restrict = self.iframe_restrict
self.namespaces = {'html': NS_XHTML}
self.iframe_restrict = True
if not is_html or self.is_html:
for selector in selectors:
match = is_not
# We have a un-matchable situation (like `:focus` as you can focus an element in this environment)
if isinstance(selector, ct.SelectorNull):
continue
# Verify tag matches
if not self.match_tag(el, selector.tag):
continue
# Verify tag is defined
if selector.flags & ct.SEL_DEFINED and not self.match_defined(el):
continue
# Verify element is root
if selector.flags & ct.SEL_ROOT and not self.match_root(el):
continue
# Verify element is scope
if selector.flags & ct.SEL_SCOPE and not self.match_scope(el):
continue
# Verify `nth` matches
if not self.match_nth(el, selector.nth):
continue
if selector.flags & ct.SEL_EMPTY and not self.match_empty(el):
continue
# Verify id matches
if selector.ids and not self.match_id(el, selector.ids):
continue
# Verify classes match
if selector.classes and not self.match_classes(el, selector.classes):
continue
# Verify attribute(s) match
if not self.match_attributes(el, selector.attributes):
continue
# Verify ranges
if selector.flags & RANGES and not self.match_range(el, selector.flags & RANGES):
continue
# Verify language patterns
if selector.lang and not self.match_lang(el, selector.lang):
continue
# Verify pseudo selector patterns
if selector.selectors and not self.match_subselectors(el, selector.selectors):
continue
# Verify relationship selectors
if selector.relation and not self.match_relations(el, selector.relation):
continue
# Validate that the current default selector match corresponds to the first submit button in the form
if selector.flags & ct.SEL_DEFAULT and not self.match_default(el):
continue
# Validate that the unset radio button is among radio buttons with the same name in a form that are
# also not set.
if selector.flags & ct.SEL_INDETERMINATE and not self.match_indeterminate(el):
continue
# Validate element directionality
if selector.flags & DIR_FLAGS and not self.match_dir(el, selector.flags & DIR_FLAGS):
continue
# Validate that the tag contains the specified text.
if not self.match_contains(el, selector.contains):
continue
match = not is_not
break
# Restore actual namespaces being used for external selector lists
if is_html:
self.namespaces = namespaces
self.iframe_restrict = iframe_restrict
return match
|
def match_selectors(self, el, selectors)
|
Check if element matches one of the selectors.
| 3.548921
| 3.54455
| 1.001233
|
if limit < 1:
limit = None
for child in self.get_descendants(self.tag):
if self.match(child):
yield child
if limit is not None:
limit -= 1
if limit < 1:
break
|
def select(self, limit=0)
|
Match all tags under the targeted tag.
| 4.118438
| 3.277686
| 1.256508
|
current = self.tag
closest = None
while closest is None and current is not None:
if self.match(current):
closest = current
else:
current = self.get_parent(current)
return closest
|
def closest(self)
|
Match closest ancestor.
| 4.356379
| 3.618756
| 1.203833
|
def filter(self): # noqa A001
return [tag for tag in self.get_contents(self.tag) if not self.is_navigable_string(tag) and self.match(tag)]
|
Filter tag's children.
| null | null | null |
|
return not self.is_doc(el) and self.is_tag(el) and self.match_selectors(el, self.selectors)
|
def match(self, el)
|
Match.
| 6.369496
| 6.154245
| 1.034976
|
if limit < 1:
limit = None
for child in self.get_descendants(self.tag, tags=False):
if self.is_comment(child):
yield child
if limit is not None:
limit -= 1
if limit < 1:
break
|
def get_comments(self, limit=0)
|
Get comments.
| 4.114154
| 3.908249
| 1.052685
|
return CSSMatch(self.selectors, tag, self.namespaces, self.flags).match(tag)
|
def match(self, tag)
|
Match.
| 18.249794
| 14.185442
| 1.286516
|
return CSSMatch(self.selectors, tag, self.namespaces, self.flags).closest()
|
def closest(self, tag)
|
Match closest ancestor.
| 28.698742
| 19.111601
| 1.50164
|
return CSSMatch(self.selectors, iterable, self.namespaces, self.flags).filter()
else:
return [node for node in iterable if not CSSMatch.is_navigable_string(node) and self.match(node)]
|
def filter(self, iterable): # noqa A001
if CSSMatch.is_tag(iterable)
|
Filter.
`CSSMatch` can cache certain searches for tags of the same document,
so if we are given a tag, all tags are from the same document,
and we can take advantage of the optimization.
Any other kind of iterable could have tags from different documents or detached tags,
so for those, we use a new `CSSMatch` for each item in the iterable.
| 6.024602
| 6.85924
| 0.878319
|
return [comment for comment in CommentsMatch(tag).get_comments(limit)]
|
def comments(self, tag, limit=0)
|
Get comments only.
| 19.325962
| 17.212065
| 1.122815
|
for comment in CommentsMatch(tag).get_comments(limit):
yield comment
|
def icomments(self, tag, limit=0)
|
Iterate comments only.
| 19.198608
| 15.066796
| 1.274233
|
tags = self.select(tag, limit=1)
return tags[0] if tags else None
|
def select_one(self, tag)
|
Select a single tag.
| 5.64672
| 4.356817
| 1.296065
|
for el in CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit):
yield el
|
def iselect(self, tag, limit=0)
|
Iterate the specified tags.
| 17.47974
| 14.84416
| 1.17755
|
new_string = []
for c in string:
o = ord(c)
new_string.append(chr(o + 32) if UC_A <= o <= UC_Z else c)
return ''.join(new_string)
|
def lower(string)
|
Lower.
| 3.526256
| 3.110875
| 1.133525
|
o = ord(c)
new_string.append(chr(o - 32) if LC_A <= o <= LC_Z else c)
return ''.join(new_string)
|
def upper(string): # pragma: no cover
new_string = []
for c in string
|
Lower.
| 5.689211
| 5.748389
| 0.989705
|
if len(c) == 2: # pragma: no cover
high, low = [ord(p) for p in c]
ordinal = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000
else:
ordinal = ord(c)
return ordinal
|
def uord(c)
|
Get Unicode ordinal.
| 2.719096
| 2.323659
| 1.170178
|
@wraps(func)
def _func(*args, **kwargs):
warnings.warn(
"'{}' is deprecated. {}".format(func.__name__, message),
category=DeprecationWarning,
stacklevel=stacklevel
)
return func(*args, **kwargs)
return _func
return _decorator
|
def deprecated(message, stacklevel=2): # pragma: no cover
def _decorator(func)
|
Raise a `DeprecationWarning` when wrapped function/method is called.
Borrowed from https://stackoverflow.com/a/48632082/866026
| 1.972821
| 2.037551
| 0.968231
|
def warn_deprecated(message, stacklevel=2): # pragma: no cover
warnings.warn(
message,
category=DeprecationWarning,
stacklevel=stacklevel
)
|
Warn deprecated.
| null | null | null |
|
last = 0
current_line = 1
col = 1
text = []
line = 1
# Split pattern by newline and handle the text before the newline
for m in RE_PATTERN_LINE_SPLIT.finditer(pattern):
linetext = pattern[last:m.start(0)]
if not len(m.group(0)) and not len(text):
indent = ''
offset = -1
col = index - last + 1
elif last <= index < m.end(0):
indent = '--> '
offset = (-1 if index > m.start(0) else 0) + 3
col = index - last + 1
else:
indent = ' '
offset = None
if len(text):
# Regardless of whether we are presented with `\r\n`, `\r`, or `\n`,
# we will render the output with just `\n`. We will still log the column
# correctly though.
text.append('\n')
text.append('{}{}'.format(indent, linetext))
if offset is not None:
text.append('\n')
text.append(' ' * (col + offset) + '^')
line = current_line
current_line += 1
last = m.end(0)
return ''.join(text), line, col
|
def get_pattern_context(pattern, index)
|
Get the pattern context.
| 4.329061
| 4.313479
| 1.003612
|
import traceback
import bs4 # noqa: F401
# Acquire source code line context
paths = (MODULE, sys.modules['bs4'].__path__[0])
tb = traceback.extract_stack()
previous = None
filename = None
lineno = None
for entry in tb:
if (PY35 and entry.filename.startswith(paths)) or (not PY35 and entry[0].startswith(paths)):
break
previous = entry
if previous:
filename = previous.filename if PY35 else previous[0]
lineno = previous.lineno if PY35 else previous[1]
# Format pattern to show line and column position
context, line = get_pattern_context(pattern, index)[0:2]
# Display warning
warnings.warn_explicit(
"\nCSS selector pattern:\n" +
" {}\n".format(message) +
" This behavior is only allowed temporarily for Beautiful Soup's transition to Soup Sieve.\n" +
" In order to confrom to the CSS spec, {}\n".format(recommend) +
" It is strongly recommended the selector be altered to conform to the CSS spec " +
"as an exception will be raised for this case in the future.\n" +
"pattern line {}:\n{}".format(line, context),
QuirksWarning,
filename,
lineno
)
|
def warn_quirks(message, recommend, pattern, index)
|
Warn quirks.
| 6.167274
| 6.184664
| 0.997188
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.