id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
171,310
from contextlib import contextmanager import errno from io import BytesIO import json import mimetypes from pathlib import Path import random import sys import signal import socket import threading try: import tornado except ImportError as err: raise RuntimeError("The WebAgg backend requires Tornado.") from err...
null
171,311
import uuid import weakref from contextlib import contextmanager import logging import math import os.path import sys import tkinter as tk import tkinter.filedialog import tkinter.font import tkinter.messagebox from tkinter.simpledialog import SimpleDialog import numpy as np from PIL import Image, ImageTk import matplo...
null
171,312
import copy import datetime import logging from numbers import Integral, Real from matplotlib import _api, colors as mcolors from matplotlib.backends.qt_compat import ( QtGui, QtWidgets, QtCore, _enum, _to_int) The provided code snippet includes necessary dependencies for implementing the `to_qcolor` function. Wri...
Create a QColor from a matplotlib color
171,313
import copy import datetime import logging from numbers import Integral, Real from matplotlib import _api, colors as mcolors from matplotlib.backends.qt_compat import ( QtGui, QtWidgets, QtCore, _enum, _to_int) def font_is_installed(font): """Check if font is installed""" return [fam for fam in QtGui.QFontD...
Create a QFont from tuple: (family [string], size [int], italic [bool], bold [bool])
171,314
import copy import datetime import logging from numbers import Integral, Real from matplotlib import _api, colors as mcolors from matplotlib.backends.qt_compat import ( QtGui, QtWidgets, QtCore, _enum, _to_int) def qfont_to_tuple(font): return (str(font.family()), int(font.pointSize()), font.italic...
null
171,315
import copy import datetime import logging from numbers import Integral, Real from matplotlib import _api, colors as mcolors from matplotlib.backends.qt_compat import ( QtGui, QtWidgets, QtCore, _enum, _to_int) def _enum(name): # foo.bar.Enum.Entry (PyQt6) <=> foo.bar.Entry (non-PyQt6). return operator.att...
null
171,316
import copy import datetime import logging from numbers import Integral, Real from matplotlib import _api, colors as mcolors from matplotlib.backends.qt_compat import ( QtGui, QtWidgets, QtCore, _enum, _to_int) def create_datagroup_example(): datalist = create_datalist_example() return ((datalist, ...
null
171,317
import copy import datetime import logging from numbers import Integral, Real from matplotlib import _api, colors as mcolors from matplotlib.backends.qt_compat import ( QtGui, QtWidgets, QtCore, _enum, _to_int) def apply_test(data): print("data:", data)
null
171,318
from itertools import chain from matplotlib import cbook, cm, colors as mcolors, markers, image as mimage from matplotlib.backends.qt_compat import QtGui from matplotlib.backends.qt_editor import _formlayout from matplotlib.dates import DateConverter, num2date LINESTYLES = {'-': 'Solid', '--': 'Dashed', ...
Edit matplotlib figure options
171,319
import asyncio import datetime from io import BytesIO, StringIO import json import logging import os from pathlib import Path import numpy as np from PIL import Image from matplotlib import _api, backend_bases, backend_tools from matplotlib.backends import backend_agg from matplotlib.backend_bases import ( _Backend...
Handle key values
171,320
import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import ( ...
null
171,321
import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import ( ...
null
171,322
import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import ( ...
null
171,323
import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import ( ...
null
171,324
import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import ( ...
null
171,325
import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import ( ...
null
171,326
import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import ( ...
null
171,327
import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import ( ...
null
171,328
import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import ( ...
null
171,329
import functools import os import sys import traceback import matplotlib as mpl from matplotlib import _api, backend_tools, cbook from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase, cursors, ToolContainerB...
null
171,330
import codecs import datetime import functools from io import BytesIO import logging import math import os import pathlib import re import shutil import subprocess from tempfile import TemporaryDirectory import weakref from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm...
Build fontspec preamble from rc.
171,331
import codecs import datetime import functools from io import BytesIO import logging import math import os import pathlib import re import shutil import subprocess from tempfile import TemporaryDirectory import weakref from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm...
Get LaTeX preamble from rc.
171,332
import codecs import datetime import functools from io import BytesIO import logging import math import os import pathlib import re import shutil import subprocess from tempfile import TemporaryDirectory import weakref from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm...
null
171,333
import codecs import datetime import functools from io import BytesIO import logging import math import os import pathlib import re import shutil import subprocess from tempfile import TemporaryDirectory import weakref from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm...
null
171,334
import codecs import datetime import functools from io import BytesIO import logging import math import os import pathlib import re import shutil import subprocess from tempfile import TemporaryDirectory import weakref from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm...
Generate a TeX string that renders string *s* with font properties *prop*, also applying any required escapes to *s*.
171,335
import codecs import datetime import functools from io import BytesIO import logging import math import os import pathlib import re import shutil import subprocess from tempfile import TemporaryDirectory import weakref from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm...
Convert metadata key/value to a form that hyperref accepts.
171,336
import codecs import datetime import functools from io import BytesIO import logging import math import os import pathlib import re import shutil import subprocess from tempfile import TemporaryDirectory import weakref from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm...
Return a function that converts a pdf file to a png file.
171,337
import codecs import datetime import functools from io import BytesIO import logging import math import os import pathlib import re import shutil import subprocess from tempfile import TemporaryDirectory import weakref from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm...
null
171,338
import copy from collections import namedtuple import enum import functools import logging import os import re import types import unicodedata import numpy as np from pyparsing import ( Empty, Forward, Literal, NotAny, oneOf, OneOrMore, Optional, ParseBaseException, ParseException, ParseExpression, ParseFatalEx...
r""" Return the integer index (from the Unicode table) of *symbol*. Parameters ---------- symbol : str A single (Unicode) character, a TeX command (e.g. r'\pi') or a Type1 symbol name (e.g. 'phi'). math : bool, default: False If True (deprecated), replace ASCII hyphen-minus by Unicode minus.
171,339
import copy from collections import namedtuple import enum import functools import logging import os import re import types import unicodedata import numpy as np from pyparsing import ( Empty, Forward, Literal, NotAny, oneOf, OneOrMore, Optional, ParseBaseException, ParseException, ParseExpression, ParseFatalEx...
null
171,340
import copy from collections import namedtuple import enum import functools import logging import os import re import types import unicodedata import numpy as np from pyparsing import ( Empty, Forward, Literal, NotAny, oneOf, OneOrMore, Optional, ParseBaseException, ParseException, ParseExpression, ParseFatalEx...
Ship out *box* at offset *xy*, converting it to an `Output`. Since boxes can be inside of boxes inside of boxes, the main work of `ship` is done by two mutually recursive routines, `hlist_out` and `vlist_out`, which traverse the `Hlist` nodes and `Vlist` nodes inside of horizontal and vertical boxes. The global variabl...
171,341
import copy from collections import namedtuple import enum import functools import logging import os import re import types import unicodedata import numpy as np from pyparsing import ( Empty, Forward, Literal, NotAny, oneOf, OneOrMore, Optional, ParseBaseException, ParseException, ParseExpression, ParseFatalEx...
r""" Helper to define TeX commands. ``cmd("\cmd", args)`` is equivalent to ``"\cmd" - (args | Error("Expected \cmd{arg}{...}"))`` where the names in the error message are taken from element names in *args*. If *expr* already includes arguments (e.g. "\cmd{arg}{...}"), then they are stripped when constructing the parse ...
171,342
import dataclasses from . import _api from .ft2font import KERNING_DEFAULT, LOAD_NO_HINTING def warn_on_missing_glyph(codepoint): _api.warn_external( "Glyph {} ({}) missing from current font.".format( codepoint, chr(codepoint).encode("ascii", "namereplace").decode("ascii"))) blo...
null
171,343
import dataclasses from . import _api from .ft2font import KERNING_DEFAULT, LOAD_NO_HINTING LayoutItem = dataclasses.make_dataclass( "LayoutItem", ["ft_object", "char", "glyph_idx", "x", "prev_kern"]) The provided code snippet includes necessary dependencies for implementing the `layout` function. Write a Python f...
Render *string* with *font*. For each character in *string*, yield a (glyph-index, x-position) pair. When such a pair is yielded, the font's glyph is set to the corresponding character. Parameters ---------- string : str The string to be rendered. font : FT2Font The font. kern_mode : int A FreeType kerning mode. Yields...
171,344
import os import sys import time from collections import OrderedDict from datetime import timedelta from ._internal_utils import to_native_string from .adapters import HTTPAdapter from .auth import _basic_auth_str from .compat import Mapping, cookielib, urljoin, urlparse from .cookies import ( RequestsCookieJar, ...
Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely.
171,354
import codecs import contextlib import io import os import re import socket import struct import sys import tempfile import warnings import zipfile from collections import OrderedDict from urllib3.util import make_headers, parse_url from . import certs from .__version__ import __version__ from ._internal_utils import H...
Returns the Requests tuple auth for a given url from netrc.
171,357
import codecs import contextlib import io import os import re import socket import struct import sys import tempfile import warnings import zipfile from collections import OrderedDict from urllib3.util import make_headers, parse_url from . import certs from .__version__ import __version__ from ._internal_utils import H...
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode object...
171,389
import hashlib import os import re import threading import time import warnings from base64 import b64encode from ._internal_utils import to_native_string from .compat import basestring, str, urlparse from .cookies import extract_cookies_to_jar from .utils import parse_dict_header import warnings warnings...
Returns a Basic Auth string.
171,390
import json version_json = ''' { "date": "2022-06-23T17:03:26-0700", "dirty": false, "error": null, "full-revisionid": "d8c6624e9547587d6c57d27c97fb7fea717455e7", "version": "1.8.2.2" } ''' def get_versions(): return json.loads(version_json)
null
171,391
from __future__ import division from itertools import tee from operator import itemgetter from collections import defaultdict from math import log def score(count_bigram, count1, count2, n_words): def pairwise(iterable): def process_tokens(words, normalize_plurals=True): def unigrams_and_bigrams(words, stopwords, norm...
null
171,392
from __future__ import absolute_import import sys import textwrap import io import re import argparse import wordcloud as wc import numpy as np from PIL import Image from . import __version__ def make_parser(): description = 'A simple command line interface for wordcloud module.' parser = argparse.ArgumentParse...
null
171,393
CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Operating System :: Microsoft :: Windows Operating System :: POSIX :: Linux Programming Language :: Python Programming Language :: Python :: 3 Pro...
null
171,394
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def standardErrorHandler(connection, cursor, errorclass, errorvalue): err = (errorclass, errorvalue) try: connection.messages.append(err) except: pass if cursor is not None: try:...
null
171,395
import datetime import decimal import numbers import sys import time from . import ado_consts as adc StringTypes = str class DataError(DatabaseError): pass typeMap = { memoryViewType: adc.adVarBinary, float: adc.adDouble, type(None): adc.adEmpty, str: adc.adBSTR, bool: adc.adBoolean, # v2.1 Col...
null
171,396
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def variantConvertDate(v): from . import dateconverter # this function only called when adodbapi is running return dateconverter.DateObjectFromCOMDate(v)
null
171,397
import datetime import decimal import numbers import sys import time from . import ado_consts as adc onIronPython = sys.platform == "cli" if onIronPython: # we need type definitions for odd data we may need to convert # noinspection PyUnresolvedReferences from System import DateTime, DBNull NullTypes = (ty...
null
171,398
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def cvtDecimal(variant): # better name return _convertNumberWithCulture(variant, decimal.Decimal) def cvtNumeric(variant): # older name - don't break old code return cvtDecimal(variant)
null
171,399
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def _convertNumberWithCulture(variant, f): try: return f(variant) except (ValueError, TypeError, decimal.InvalidOperation): try: europeVsUS = str(variant).replace(",", ".") ...
null
171,400
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def cvtInt(variant): return int(variant)
null
171,401
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def cvtLong(variant): # only important in old versions where long and int differ return int(variant)
null
171,402
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def cvtBuffer(variant): return bytes(variant)
null
171,403
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def cvtUnicode(variant): return str(variant)
null
171,404
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def identity(x): return x
null
171,405
import datetime import decimal import numbers import sys import time from . import ado_consts as adc verbose = False def cvtUnusual(variant): if verbose > 1: sys.stderr.write("Conversion called for Unusual data=%s\n" % repr(variant)) if isinstance(variant, DateTime): # COMdate or System.Date f...
null
171,406
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def convert_to_python(variant, func): # convert DB value into Python value if isinstance(variant, NullTypes): # IronPython Null or None return None return func(variant) # call the appropriate convers...
null
171,407
import datetime import decimal import numbers import sys import time from . import ado_consts as adc def changeNamedToQmark( op, ): # convert from 'named' paramstyle to ADO required '?'mark parameters outOp = "" outparms = [] chunks = op.split( "'" ) # quote all literals -- odd numbered l...
null
171,408
import datetime import decimal import numbers import sys import time from . import ado_consts as adc class ProgrammingError(DatabaseError): def changeFormatToQmark( op, ): # convert from 'format' paramstyle to ADO required '?'mark parameters outOp = "" outparams = [] chunks = op.split( "'" ...
null
171,409
from . import adodbapi def names(connection_object): ado = connection_object.adoConn schema = ado.OpenSchema(20) # constant = adSchemaTables tables = [] while not schema.EOF: name = adodbapi.getIndexedValue(schema.Fields, "TABLE_NAME").Value tables.append(name) schema.MoveNext...
null
171,410
import array import datetime import os import sys import time import adodbapi import adodbapi.apibase as api import adodbapi.process_connect_string from adodbapi.apibase import ProgrammingError def Date(year, month, day): # dateconverter.Date(year,month,day) def DateFromTicks(ticks): return Date(*time.gmtime(tick...
null
171,411
import array import datetime import os import sys import time import adodbapi import adodbapi.apibase as api import adodbapi.process_connect_string from adodbapi.apibase import ProgrammingError def Time(hour, minute, second): return datetime.time(hour, minute, second) # dateconverter.Time(hour,minute,second) def ...
null
171,412
import array import datetime import os import sys import time import adodbapi import adodbapi.apibase as api import adodbapi.process_connect_string from adodbapi.apibase import ProgrammingError def Timestamp(year, month, day, hour, minute, second): return datetime.datetime(year, month, day, hour, minute, second) d...
null
171,413
import array import datetime import os import sys import time try: import Pyro4 except ImportError: print('* * * Sorry, server operation requires Pyro4. Please "pip import" it.') exit(11) import adodbapi import adodbapi.apibase as api import adodbapi.process_connect_string from adodbapi.apibase import Progr...
Create and open a remote db-api database connection object
171,414
import array import datetime import os import sys import time import adodbapi import adodbapi.apibase as api import adodbapi.process_connect_string from adodbapi.apibase import ProgrammingError memoryViewType = memoryview The provided code snippet includes necessary dependencies for implementing the `fixpickle` functi...
pickle barfs on buffer(x) so we pass as array.array(x) then restore to original form for .execute()
171,415
import copy import decimal import os import sys import weakref from . import ado_consts as adc, apibase as api, process_connect_string onWin32 = False if api.onIronPython: from clr import Reference from System import ( Activator, Array, Byte, DateTime, DBNull, De...
null
171,416
import copy import decimal import os import sys import weakref from . import ado_consts as adc, apibase as api, process_connect_string if api.onIronPython: from clr import Reference from System import ( Activator, Array, Byte, DateTime, DBNull, Decimal as SystemDe...
Connect to a database. call using: :connection_string -- An ADODB formatted connection string, see: * http://www.connectionstrings.com * http://www.asp101.com/articles/john/connstring/default.asp :timeout -- A command timeout value, in seconds (default 30 seconds)
171,417
import copy import decimal import os import sys import weakref from . import ado_consts as adc, apibase as api, process_connect_string from collections.abc import Mapping The provided code snippet includes necessary dependencies for implementing the `format_parameters` function. Write a Python function `def format_par...
Format a collection of ADO Command Parameters. Used by error reporting in _execute_command.
171,418
import copy import decimal import os import sys import weakref from . import ado_consts as adc, apibase as api, process_connect_string if api.onIronPython: from clr import Reference from System import ( Activator, Array, Byte, DateTime, DBNull, Decimal as SystemDe...
Configure the given ADO Parameter 'p' with the Python 'value'.
171,419
directions = { 0: "Unknown", 1: "Input", 2: "Output", 3: "InputOutput", 4: "Return", } def ado_direction_name(ado_dir): try: return "adParam" + directions[ado_dir] except: return "unknown direction (" + str(ado_dir) + ")"
null
171,420
adTypeNames = { adBSTR: "adBSTR", adBigInt: "adBigInt", adBinary: "adBinary", adBoolean: "adBoolean", adChapter: "adChapter", adChar: "adChar", adCurrency: "adCurrency", adDBDate: "adDBDate", adDBTime: "adDBTime", adDBTimeStamp: "adDBTimeStamp", adDate: "adDate", adDecima...
null
171,421
from __future__ import absolute_import import re def prepare_child(next, token): tag = token[1] def select(result): for elem in result: for e in elem.iterchildren(tag): yield e return select
null
171,422
from __future__ import absolute_import import re def prepare_star(next, token): def select(result): for elem in result: for e in elem.iterchildren('*'): yield e return select
null
171,423
from __future__ import absolute_import import re def prepare_self(next, token): def select(result): return result return select
null
171,424
from __future__ import absolute_import import re def prepare_descendant(next, token): token = next() if token[0] == "*": tag = "*" elif not token[0]: tag = token[1] else: raise SyntaxError("invalid descendant") def select(result): for elem in result: for ...
null
171,425
from __future__ import absolute_import import re def prepare_parent(next, token): def select(result): for elem in result: parent = elem.getparent() if parent is not None: yield parent return select
null
171,426
from __future__ import absolute_import import re def prepare_predicate(next, token): # FIXME: replace with real parser!!! refs: # http://effbot.org/zone/simple-iterator-parser.htm # http://javascript.crockford.com/tdop/tdop.html signature = '' predicate = [] while 1: token = next() ...
null
171,427
from __future__ import absolute_import import re def find(elem, path, namespaces=None): it = iterfind(elem, path, namespaces) try: return next(it) except StopIteration: return None def findtext(elem, path, default=None, namespaces=None): el = find(elem, path, namespaces) if el is No...
null
171,428
from __future__ import absolute_import import difflib from lxml import etree from lxml.html import fragment_fromstring import re def default_markup(text, version): return '<span title="%s">%s</span>' % ( html_escape(_unicode(version), 1), text) def tokenize_annotated(doc, annotation): """Tokenize a doc...
doclist should be ordered from oldest to newest, like:: >>> version1 = 'Hello World' >>> version2 = 'Goodbye World' >>> print(html_annotate([(version1, 'version 1'), ... (version2, 'version 2')])) <span title="version 2">Goodbye</span> <span title="version 1">World</span> The documents must be *fragments* (str/UTF8 or ...
171,429
from __future__ import absolute_import import difflib from lxml import etree from lxml.html import fragment_fromstring import re def htmldiff_tokens(html1_tokens, html2_tokens): """ Does a diff on the tokens themselves, returning a list of text chunks (not tokens). """ # There are several passes as we d...
Do a diff of the old and new document. The documents are HTML *fragments* (str/UTF8 or unicode), they are not complete documents (i.e., no <html> tag). Returns HTML with <ins> and <del> tags added around the appropriate text. Markup is generally ignored, with the markup from new_html preserved, and possibly some markup...
171,430
from __future__ import absolute_import import difflib from lxml import etree from lxml.html import fragment_fromstring import re The provided code snippet includes necessary dependencies for implementing the `_merge_element_contents` function. Write a Python function `def _merge_element_contents(el)` to solve the foll...
Removes an element, but merges its contents into its place, e.g., given <p>Hi <i>there!</i></p>, if you remove the <i> element you get <p>Hi there!</p>
171,431
from lxml.etree import XPath, ElementBase from lxml.html import fromstring, XHTML_NAMESPACE from lxml.html import _forms_xpath, _options_xpath, _nons, _transform_result from lxml.html import defs import copy try: basestring except NameError: # Python 3 basestring = str def fill_form( el, values, ...
null
171,432
from lxml.etree import XPath, ElementBase from lxml.html import fromstring, XHTML_NAMESPACE from lxml.html import _forms_xpath, _options_xpath, _nons, _transform_result from lxml.html import defs import copy try: basestring except NameError: # Python 3 basestring = str def insert_errors( el, errors,...
null
171,433
from __future__ import absolute_import import copy import re import sys from lxml import etree from lxml.html import defs from lxml.html import fromstring, XHTML_NAMESPACE from lxml.html import xhtml_to_html, _transform_result _find_image_dataurls = re.compile( r'data:image/(.+);base64,', re.I).findall _possibly_ma...
null
171,434
from __future__ import absolute_import import copy import re import sys from lxml import etree from lxml.html import defs from lxml.html import fromstring, XHTML_NAMESPACE from lxml.html import xhtml_to_html, _transform_result try: basestring except NameError: basestring = (str, bytes) def autolink(el, link_reg...
null
171,435
from __future__ import absolute_import import copy import re import sys from lxml import etree from lxml.html import defs from lxml.html import fromstring, XHTML_NAMESPACE from lxml.html import xhtml_to_html, _transform_result def word_break(el, max_width=40, avoid_elements=_avoid_word_break_elements, ...
null
171,436
from .soupparser import convert_tree, parse as _parse def parse(file, beautifulsoup=None, makeelement=None): root = _parse(file, beautifulsoup=beautifulsoup, makeelement=makeelement) return root.getroot()
null
171,437
import sys import string from html5lib import HTMLParser as _HTMLParser from html5lib.treebuilders.etree_lxml import TreeBuilder from lxml import etree from lxml.html import Element, XHTML_NAMESPACE, _contains_block_level_tag try: _strings = basestring except NameError: _strings = (bytes, str) def fragments_fro...
Parses a single HTML element; it is an error if there is more than one element, or if anything but whitespace precedes or follows the element. If 'create_parent' is true (or is a tag name) then a parent node will be created to encapsulate the HTML in a single element. In this case, leading or trailing text is allowed. ...
171,438
import sys import string from html5lib import HTMLParser as _HTMLParser from html5lib.treebuilders.etree_lxml import TreeBuilder from lxml import etree from lxml.html import Element, XHTML_NAMESPACE, _contains_block_level_tag try: _strings = basestring except NameError: _strings = (bytes, str) def _find_tag(tre...
Parse the html, returning a single element/document. This tries to minimally parse the chunk of text, without knowing if it is a fragment or a document. 'base_url' will set the document's base_url attribute (and the tree's docinfo.URL) If `guess_charset` is true, or if the input is not Unicode but a byte string, the `c...
171,439
from __future__ import absolute_import import optparse import sys import re import os from .diff import htmldiff def read_file(filename): if filename == '-': c = sys.stdin.read() elif not os.path.exists(filename): raise OSError( "Input file %s does not exist" % filename) else: ...
null
171,440
from __future__ import absolute_import import optparse import sys import re import os from .diff import htmldiff body_start_re = re.compile( r"<body.*?>", re.I|re.S) body_end_re = re.compile( r"</body.*?>", re.I|re.S) def split_body(html): pre = post = '' match = body_start_re.search(html) if match...
null
171,441
from __future__ import absolute_import import optparse import sys import re import os from .diff import htmldiff def annotate(options, args): print("Not yet implemented") sys.exit(1)
null
171,442
from lxml.builder import ElementMaker from lxml.html import html_parser def CLASS(v): return {'class': v}
null
171,443
from lxml.builder import ElementMaker from lxml.html import html_parser def FOR(v): return {'for': v}
null
171,444
import re from lxml import etree, html def _parse(source, beautifulsoup, makeelement, **bsargs): if beautifulsoup is None: beautifulsoup = BeautifulSoup if hasattr(beautifulsoup, "HTML_ENTITIES"): # bs3 if 'convertEntities' not in bsargs: bsargs['convertEntities'] = 'html' if ha...
Parse a string of HTML data into an Element tree using the BeautifulSoup parser. Returns the root ``<html>`` Element of the tree. You can pass a different BeautifulSoup parser through the `beautifulsoup` keyword, and a diffent Element factory function through the `makeelement` keyword. By default, the standard ``Beauti...
171,445
import re from lxml import etree, html def _parse(source, beautifulsoup, makeelement, **bsargs): if beautifulsoup is None: beautifulsoup = BeautifulSoup if hasattr(beautifulsoup, "HTML_ENTITIES"): # bs3 if 'convertEntities' not in bsargs: bsargs['convertEntities'] = 'html' if ha...
Parse a file into an ElemenTree using the BeautifulSoup parser. You can pass a different BeautifulSoup parser through the `beautifulsoup` keyword, and a diffent Element factory function through the `makeelement` keyword. By default, the standard ``BeautifulSoup`` class and the default factory of `lxml.html` are used.
171,446
import re from lxml import etree, html def _convert_tree(beautiful_soup_tree, makeelement): if makeelement is None: makeelement = html.html_parser.makeelement # Split the tree into three parts: # i) everything before the root element: document type # declaration, comments, processing instruction...
Convert a BeautifulSoup tree to a list of Element trees. Returns a list instead of a single root Element to support HTML-like soup with more than one root element. You can pass a different Element factory through the `makeelement` keyword.
171,447
from lxml import etree def default_loader(href, parse, encoding=None): file = open(href, 'rb') if parse == "xml": data = etree.parse(file).getroot() else: data = file.read() if not encoding: encoding = 'utf-8' data = data.decode(encoding) file.close() ret...
null
171,448
from lxml import etree DEFAULT_MAX_INCLUSION_DEPTH = 6 def _include(elem, loader=None, base_url=None, max_depth=DEFAULT_MAX_INCLUSION_DEPTH, _parent_hrefs=None): if loader is not None: load_include = _wrap_et_loader(loader) else: load_include = _lxml_default_loader if _parent_hr...
null
171,449
from __future__ import absolute_import from xml.sax.handler import ContentHandler from lxml import etree from lxml.etree import ElementTree, SubElement from lxml.etree import Comment, ProcessingInstruction def _getNsTag(tag): if tag[0] == '{': return tuple(tag[1:].split('}', 1)) else: return No...
null
171,450
from __future__ import absolute_import from xml.sax.handler import ContentHandler from lxml import etree from lxml.etree import ElementTree, SubElement from lxml.etree import Comment, ProcessingInstruction class ElementTreeProducer(object): """Produces SAX events for an element and children. """ def __init_...
One-shot helper to generate SAX events from an XML tree and fire them against a SAX ContentHandler.
171,451
from __future__ import absolute_import from . import etree def _make_lower_case(context, s): return s.lower()
null