repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ArchiveTeam/wpull | wpull/protocol/ftp/command.py | Commander.read_stream | def read_stream(self, file: IO, data_stream: DataStream) -> Reply:
'''Read from the data stream.
Args:
file: A destination file object or a stream writer.
data_stream: The stream of which to read from.
Coroutine.
Returns:
Reply: The final reply.
'''
yield from data_stream.read_file(file=file)
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'End stream',
ReplyCodes.closing_data_connection,
reply
)
data_stream.close()
return reply | python | def read_stream(self, file: IO, data_stream: DataStream) -> Reply:
'''Read from the data stream.
Args:
file: A destination file object or a stream writer.
data_stream: The stream of which to read from.
Coroutine.
Returns:
Reply: The final reply.
'''
yield from data_stream.read_file(file=file)
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'End stream',
ReplyCodes.closing_data_connection,
reply
)
data_stream.close()
return reply | [
"def",
"read_stream",
"(",
"self",
",",
"file",
":",
"IO",
",",
"data_stream",
":",
"DataStream",
")",
"->",
"Reply",
":",
"yield",
"from",
"data_stream",
".",
"read_file",
"(",
"file",
"=",
"file",
")",
"reply",
"=",
"yield",
"from",
"self",
".",
"_co... | Read from the data stream.
Args:
file: A destination file object or a stream writer.
data_stream: The stream of which to read from.
Coroutine.
Returns:
Reply: The final reply. | [
"Read",
"from",
"the",
"data",
"stream",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/command.py#L178-L203 | train | 201,400 |
ArchiveTeam/wpull | wpull/protocol/ftp/command.py | Commander.restart | def restart(self, offset: int):
'''Send restart command.
Coroutine.
'''
yield from self._control_stream.write_command(Command('REST', str(offset)))
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match('Restart', ReplyCodes.requested_file_action_pending_further_information, reply) | python | def restart(self, offset: int):
'''Send restart command.
Coroutine.
'''
yield from self._control_stream.write_command(Command('REST', str(offset)))
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match('Restart', ReplyCodes.requested_file_action_pending_further_information, reply) | [
"def",
"restart",
"(",
"self",
",",
"offset",
":",
"int",
")",
":",
"yield",
"from",
"self",
".",
"_control_stream",
".",
"write_command",
"(",
"Command",
"(",
"'REST'",
",",
"str",
"(",
"offset",
")",
")",
")",
"reply",
"=",
"yield",
"from",
"self",
... | Send restart command.
Coroutine. | [
"Send",
"restart",
"command",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/command.py#L223-L232 | train | 201,401 |
ArchiveTeam/wpull | wpull/processor/coprocessor/youtubedl.py | get_version | def get_version(exe_path='youtube-dl'):
'''Get the version string of youtube-dl.'''
process = subprocess.Popen(
[exe_path, '--version'],
stdout=subprocess.PIPE
)
version_string = process.communicate()[0]
version_string = version_string.decode().strip()
assert ' ' not in version_string, version_string
return version_string | python | def get_version(exe_path='youtube-dl'):
'''Get the version string of youtube-dl.'''
process = subprocess.Popen(
[exe_path, '--version'],
stdout=subprocess.PIPE
)
version_string = process.communicate()[0]
version_string = version_string.decode().strip()
assert ' ' not in version_string, version_string
return version_string | [
"def",
"get_version",
"(",
"exe_path",
"=",
"'youtube-dl'",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"exe_path",
",",
"'--version'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"version_string",
"=",
"process",
".",
"com... | Get the version string of youtube-dl. | [
"Get",
"the",
"version",
"string",
"of",
"youtube",
"-",
"dl",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/youtubedl.py#L174-L185 | train | 201,402 |
ArchiveTeam/wpull | wpull/processor/coprocessor/youtubedl.py | Session._get_output_template | def _get_output_template(self):
'''Return the path prefix and output template.'''
path = self._file_writer_session.extra_resource_path('.youtube-dl')
if not path:
self._temp_dir = tempfile.TemporaryDirectory(
dir=self._root_path, prefix='tmp-wpull-youtubedl'
)
path = '{}/tmp'.format(self._temp_dir.name)
return path, '{}.%(id)s.%(format_id)s.%(ext)s'.format(path) | python | def _get_output_template(self):
'''Return the path prefix and output template.'''
path = self._file_writer_session.extra_resource_path('.youtube-dl')
if not path:
self._temp_dir = tempfile.TemporaryDirectory(
dir=self._root_path, prefix='tmp-wpull-youtubedl'
)
path = '{}/tmp'.format(self._temp_dir.name)
return path, '{}.%(id)s.%(format_id)s.%(ext)s'.format(path) | [
"def",
"_get_output_template",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"_file_writer_session",
".",
"extra_resource_path",
"(",
"'.youtube-dl'",
")",
"if",
"not",
"path",
":",
"self",
".",
"_temp_dir",
"=",
"tempfile",
".",
"TemporaryDirectory",
"(",
... | Return the path prefix and output template. | [
"Return",
"the",
"path",
"prefix",
"and",
"output",
"template",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/youtubedl.py#L124-L134 | train | 201,403 |
ArchiveTeam/wpull | wpull/processor/coprocessor/youtubedl.py | Session._write_warc_metadata | def _write_warc_metadata(self):
'''Write the JSON metadata to WARC.
Uses pywb spec.
'''
uri = 'metadata://{}{}'.format(self._item_session.url_record.url_info.authority,
self._item_session.url_record.url_info.resource)
glob_pattern = self._path_prefix + '*.info.json'
filenames = list(glob.glob(glob_pattern))
if not filenames:
_logger.warning(__(
_('Could not find external process metadata file: {filename}'),
filename=glob_pattern
))
return
for filename in filenames:
record = WARCRecord()
record.set_common_fields('metadata', 'application/vnd.youtube-dl_formats+json')
record.fields['WARC-Target-URI'] = uri
record.block_file = open(filename, 'rb')
self._warc_recorder.set_length_and_maybe_checksums(record)
self._warc_recorder.write_record(record)
record.block_file.close() | python | def _write_warc_metadata(self):
'''Write the JSON metadata to WARC.
Uses pywb spec.
'''
uri = 'metadata://{}{}'.format(self._item_session.url_record.url_info.authority,
self._item_session.url_record.url_info.resource)
glob_pattern = self._path_prefix + '*.info.json'
filenames = list(glob.glob(glob_pattern))
if not filenames:
_logger.warning(__(
_('Could not find external process metadata file: {filename}'),
filename=glob_pattern
))
return
for filename in filenames:
record = WARCRecord()
record.set_common_fields('metadata', 'application/vnd.youtube-dl_formats+json')
record.fields['WARC-Target-URI'] = uri
record.block_file = open(filename, 'rb')
self._warc_recorder.set_length_and_maybe_checksums(record)
self._warc_recorder.write_record(record)
record.block_file.close() | [
"def",
"_write_warc_metadata",
"(",
"self",
")",
":",
"uri",
"=",
"'metadata://{}{}'",
".",
"format",
"(",
"self",
".",
"_item_session",
".",
"url_record",
".",
"url_info",
".",
"authority",
",",
"self",
".",
"_item_session",
".",
"url_record",
".",
"url_info"... | Write the JSON metadata to WARC.
Uses pywb spec. | [
"Write",
"the",
"JSON",
"metadata",
"to",
"WARC",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/youtubedl.py#L144-L171 | train | 201,404 |
ArchiveTeam/wpull | wpull/application/tasks/warc.py | WARCVisitsTask.process | def process(self, session: AppSession):
'''Populate the visits from the CDX into the URL table.'''
if not session.args.warc_dedup:
return
iterable = wpull.warc.format.read_cdx(
session.args.warc_dedup,
encoding=session.args.local_encoding or 'utf-8'
)
missing_url_msg = _('The URL ("a") is missing from the CDX file.')
missing_id_msg = _('The record ID ("u") is missing from the CDX file.')
missing_checksum_msg = \
_('The SHA1 checksum ("k") is missing from the CDX file.')
counter = 0
def visits():
nonlocal counter
checked_fields = False
for record in iterable:
if not checked_fields:
if 'a' not in record:
raise ValueError(missing_url_msg)
if 'u' not in record:
raise ValueError(missing_id_msg)
if 'k' not in record:
raise ValueError(missing_checksum_msg)
checked_fields = True
yield record['a'], record['u'], record['k']
counter += 1
url_table = session.factory['URLTable']
url_table.add_visits(visits())
_logger.info(__(
gettext.ngettext(
'Loaded {num} record from CDX file.',
'Loaded {num} records from CDX file.',
counter
),
num=counter
)) | python | def process(self, session: AppSession):
'''Populate the visits from the CDX into the URL table.'''
if not session.args.warc_dedup:
return
iterable = wpull.warc.format.read_cdx(
session.args.warc_dedup,
encoding=session.args.local_encoding or 'utf-8'
)
missing_url_msg = _('The URL ("a") is missing from the CDX file.')
missing_id_msg = _('The record ID ("u") is missing from the CDX file.')
missing_checksum_msg = \
_('The SHA1 checksum ("k") is missing from the CDX file.')
counter = 0
def visits():
nonlocal counter
checked_fields = False
for record in iterable:
if not checked_fields:
if 'a' not in record:
raise ValueError(missing_url_msg)
if 'u' not in record:
raise ValueError(missing_id_msg)
if 'k' not in record:
raise ValueError(missing_checksum_msg)
checked_fields = True
yield record['a'], record['u'], record['k']
counter += 1
url_table = session.factory['URLTable']
url_table.add_visits(visits())
_logger.info(__(
gettext.ngettext(
'Loaded {num} record from CDX file.',
'Loaded {num} records from CDX file.',
counter
),
num=counter
)) | [
"def",
"process",
"(",
"self",
",",
"session",
":",
"AppSession",
")",
":",
"if",
"not",
"session",
".",
"args",
".",
"warc_dedup",
":",
"return",
"iterable",
"=",
"wpull",
".",
"warc",
".",
"format",
".",
"read_cdx",
"(",
"session",
".",
"args",
".",
... | Populate the visits from the CDX into the URL table. | [
"Populate",
"the",
"visits",
"from",
"the",
"CDX",
"into",
"the",
"URL",
"table",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/warc.py#L90-L135 | train | 201,405 |
ArchiveTeam/wpull | wpull/document/htmlparse/lxml_.py | to_lxml_encoding | def to_lxml_encoding(encoding):
'''Check if lxml supports the specified encoding.
Returns:
str, None
'''
# XXX: Workaround lxml not liking utf-16-le
try:
lxml.html.HTMLParser(encoding=encoding)
except LookupError:
encoding = encoding.replace('-', '')
else:
return encoding
try:
lxml.html.HTMLParser(encoding=encoding)
except LookupError:
encoding = encoding.replace('_', '')
else:
return encoding
try:
lxml.html.HTMLParser(encoding=encoding)
except LookupError:
pass
else:
return encoding | python | def to_lxml_encoding(encoding):
'''Check if lxml supports the specified encoding.
Returns:
str, None
'''
# XXX: Workaround lxml not liking utf-16-le
try:
lxml.html.HTMLParser(encoding=encoding)
except LookupError:
encoding = encoding.replace('-', '')
else:
return encoding
try:
lxml.html.HTMLParser(encoding=encoding)
except LookupError:
encoding = encoding.replace('_', '')
else:
return encoding
try:
lxml.html.HTMLParser(encoding=encoding)
except LookupError:
pass
else:
return encoding | [
"def",
"to_lxml_encoding",
"(",
"encoding",
")",
":",
"# XXX: Workaround lxml not liking utf-16-le",
"try",
":",
"lxml",
".",
"html",
".",
"HTMLParser",
"(",
"encoding",
"=",
"encoding",
")",
"except",
"LookupError",
":",
"encoding",
"=",
"encoding",
".",
"replace... | Check if lxml supports the specified encoding.
Returns:
str, None | [
"Check",
"if",
"lxml",
"supports",
"the",
"specified",
"encoding",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/htmlparse/lxml_.py#L229-L254 | train | 201,406 |
ArchiveTeam/wpull | wpull/document/htmlparse/lxml_.py | HTMLParser.parse_lxml | def parse_lxml(self, file, encoding=None, target_class=HTMLParserTarget,
parser_type='html'):
'''Return an iterator of elements found in the document.
Args:
file: A file object containing the document.
encoding (str): The encoding of the document.
target_class: A class to be used for target parsing.
parser_type (str): The type of parser to use. Accepted values:
``html``, ``xhtml``, ``xml``.
Returns:
iterator: Each item is an element from
:mod:`.document.htmlparse.element`
'''
if encoding:
lxml_encoding = to_lxml_encoding(encoding) or 'latin1'
else:
lxml_encoding = encoding
elements = []
callback_func = elements.append
target = target_class(callback_func)
if parser_type == 'html':
parser = lxml.html.HTMLParser(
encoding=lxml_encoding, target=target
)
elif parser_type == 'xhtml':
parser = lxml.html.XHTMLParser(
encoding=lxml_encoding, target=target, recover=True
)
else:
parser = lxml.etree.XMLParser(
encoding=lxml_encoding, target=target, recover=True
)
if parser_type == 'html':
# XXX: Force libxml2 to do full read in case of early "</html>"
# See https://github.com/chfoo/wpull/issues/104
# See https://bugzilla.gnome.org/show_bug.cgi?id=727935
for dummy in range(3):
parser.feed('<html>'.encode(encoding))
while True:
data = file.read(self.BUFFER_SIZE)
if not data:
break
parser.feed(data)
for element in elements:
yield element
del elements[:]
parser.close()
for element in elements:
yield element | python | def parse_lxml(self, file, encoding=None, target_class=HTMLParserTarget,
parser_type='html'):
'''Return an iterator of elements found in the document.
Args:
file: A file object containing the document.
encoding (str): The encoding of the document.
target_class: A class to be used for target parsing.
parser_type (str): The type of parser to use. Accepted values:
``html``, ``xhtml``, ``xml``.
Returns:
iterator: Each item is an element from
:mod:`.document.htmlparse.element`
'''
if encoding:
lxml_encoding = to_lxml_encoding(encoding) or 'latin1'
else:
lxml_encoding = encoding
elements = []
callback_func = elements.append
target = target_class(callback_func)
if parser_type == 'html':
parser = lxml.html.HTMLParser(
encoding=lxml_encoding, target=target
)
elif parser_type == 'xhtml':
parser = lxml.html.XHTMLParser(
encoding=lxml_encoding, target=target, recover=True
)
else:
parser = lxml.etree.XMLParser(
encoding=lxml_encoding, target=target, recover=True
)
if parser_type == 'html':
# XXX: Force libxml2 to do full read in case of early "</html>"
# See https://github.com/chfoo/wpull/issues/104
# See https://bugzilla.gnome.org/show_bug.cgi?id=727935
for dummy in range(3):
parser.feed('<html>'.encode(encoding))
while True:
data = file.read(self.BUFFER_SIZE)
if not data:
break
parser.feed(data)
for element in elements:
yield element
del elements[:]
parser.close()
for element in elements:
yield element | [
"def",
"parse_lxml",
"(",
"self",
",",
"file",
",",
"encoding",
"=",
"None",
",",
"target_class",
"=",
"HTMLParserTarget",
",",
"parser_type",
"=",
"'html'",
")",
":",
"if",
"encoding",
":",
"lxml_encoding",
"=",
"to_lxml_encoding",
"(",
"encoding",
")",
"or... | Return an iterator of elements found in the document.
Args:
file: A file object containing the document.
encoding (str): The encoding of the document.
target_class: A class to be used for target parsing.
parser_type (str): The type of parser to use. Accepted values:
``html``, ``xhtml``, ``xml``.
Returns:
iterator: Each item is an element from
:mod:`.document.htmlparse.element` | [
"Return",
"an",
"iterator",
"of",
"elements",
"found",
"in",
"the",
"document",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/htmlparse/lxml_.py#L124-L186 | train | 201,407 |
ArchiveTeam/wpull | wpull/document/htmlparse/lxml_.py | HTMLParser.parse_doctype | def parse_doctype(cls, file, encoding=None):
'''Get the doctype from the document.
Returns:
str, None
'''
if encoding:
lxml_encoding = to_lxml_encoding(encoding) or 'latin1'
else:
lxml_encoding = encoding
try:
parser = lxml.etree.XMLParser(encoding=lxml_encoding, recover=True)
tree = lxml.etree.parse(
io.BytesIO(wpull.util.peek_file(file)), parser=parser
)
if tree.getroot() is not None:
return tree.docinfo.doctype
except lxml.etree.LxmlError:
pass | python | def parse_doctype(cls, file, encoding=None):
'''Get the doctype from the document.
Returns:
str, None
'''
if encoding:
lxml_encoding = to_lxml_encoding(encoding) or 'latin1'
else:
lxml_encoding = encoding
try:
parser = lxml.etree.XMLParser(encoding=lxml_encoding, recover=True)
tree = lxml.etree.parse(
io.BytesIO(wpull.util.peek_file(file)), parser=parser
)
if tree.getroot() is not None:
return tree.docinfo.doctype
except lxml.etree.LxmlError:
pass | [
"def",
"parse_doctype",
"(",
"cls",
",",
"file",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"encoding",
":",
"lxml_encoding",
"=",
"to_lxml_encoding",
"(",
"encoding",
")",
"or",
"'latin1'",
"else",
":",
"lxml_encoding",
"=",
"encoding",
"try",
":",
"pa... | Get the doctype from the document.
Returns:
str, None | [
"Get",
"the",
"doctype",
"from",
"the",
"document",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/htmlparse/lxml_.py#L189-L208 | train | 201,408 |
ArchiveTeam/wpull | wpull/document/htmlparse/lxml_.py | HTMLParser.detect_parser_type | def detect_parser_type(cls, file, encoding=None):
'''Get the suitable parser type for the document.
Returns:
str
'''
is_xml = XMLDetector.is_file(file)
doctype = cls.parse_doctype(file, encoding=encoding) or ''
if not doctype and is_xml:
return 'xml'
if 'XHTML' in doctype:
return 'xhtml'
return 'html' | python | def detect_parser_type(cls, file, encoding=None):
'''Get the suitable parser type for the document.
Returns:
str
'''
is_xml = XMLDetector.is_file(file)
doctype = cls.parse_doctype(file, encoding=encoding) or ''
if not doctype and is_xml:
return 'xml'
if 'XHTML' in doctype:
return 'xhtml'
return 'html' | [
"def",
"detect_parser_type",
"(",
"cls",
",",
"file",
",",
"encoding",
"=",
"None",
")",
":",
"is_xml",
"=",
"XMLDetector",
".",
"is_file",
"(",
"file",
")",
"doctype",
"=",
"cls",
".",
"parse_doctype",
"(",
"file",
",",
"encoding",
"=",
"encoding",
")",... | Get the suitable parser type for the document.
Returns:
str | [
"Get",
"the",
"suitable",
"parser",
"type",
"for",
"the",
"document",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/htmlparse/lxml_.py#L211-L226 | train | 201,409 |
ArchiveTeam/wpull | wpull/body.py | new_temp_file | def new_temp_file(directory=None, hint=''):
'''Return a new temporary file.'''
return tempfile.NamedTemporaryFile(
prefix='tmp-wpull-{0}-'.format(hint), suffix='.tmp', dir=directory) | python | def new_temp_file(directory=None, hint=''):
'''Return a new temporary file.'''
return tempfile.NamedTemporaryFile(
prefix='tmp-wpull-{0}-'.format(hint), suffix='.tmp', dir=directory) | [
"def",
"new_temp_file",
"(",
"directory",
"=",
"None",
",",
"hint",
"=",
"''",
")",
":",
"return",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"'tmp-wpull-{0}-'",
".",
"format",
"(",
"hint",
")",
",",
"suffix",
"=",
"'.tmp'",
",",
"dir",
"... | Return a new temporary file. | [
"Return",
"a",
"new",
"temporary",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/body.py#L93-L96 | train | 201,410 |
ArchiveTeam/wpull | wpull/body.py | Body.content | def content(self):
'''Return the content of the file.
If this function is invoked, the contents of the entire file is read
and cached.
Returns:
``bytes``: The entire content of the file.
'''
if not self._content_data:
if is_seekable(self.file):
with wpull.util.reset_file_offset(self.file):
self._content_data = self.file.read()
else:
self._content_data = self.file.read()
return self._content_data | python | def content(self):
'''Return the content of the file.
If this function is invoked, the contents of the entire file is read
and cached.
Returns:
``bytes``: The entire content of the file.
'''
if not self._content_data:
if is_seekable(self.file):
with wpull.util.reset_file_offset(self.file):
self._content_data = self.file.read()
else:
self._content_data = self.file.read()
return self._content_data | [
"def",
"content",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_content_data",
":",
"if",
"is_seekable",
"(",
"self",
".",
"file",
")",
":",
"with",
"wpull",
".",
"util",
".",
"reset_file_offset",
"(",
"self",
".",
"file",
")",
":",
"self",
".",... | Return the content of the file.
If this function is invoked, the contents of the entire file is read
and cached.
Returns:
``bytes``: The entire content of the file. | [
"Return",
"the",
"content",
"of",
"the",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/body.py#L32-L48 | train | 201,411 |
ArchiveTeam/wpull | wpull/body.py | Body.size | def size(self):
'''Return the size of the file.'''
try:
return os.fstat(self.file.fileno()).st_size
except io.UnsupportedOperation:
pass
if is_seekable(self.file):
with wpull.util.reset_file_offset(self.file):
self.file.seek(0, os.SEEK_END)
return self.file.tell()
raise OSError('Unsupported operation.') | python | def size(self):
'''Return the size of the file.'''
try:
return os.fstat(self.file.fileno()).st_size
except io.UnsupportedOperation:
pass
if is_seekable(self.file):
with wpull.util.reset_file_offset(self.file):
self.file.seek(0, os.SEEK_END)
return self.file.tell()
raise OSError('Unsupported operation.') | [
"def",
"size",
"(",
"self",
")",
":",
"try",
":",
"return",
"os",
".",
"fstat",
"(",
"self",
".",
"file",
".",
"fileno",
"(",
")",
")",
".",
"st_size",
"except",
"io",
".",
"UnsupportedOperation",
":",
"pass",
"if",
"is_seekable",
"(",
"self",
".",
... | Return the size of the file. | [
"Return",
"the",
"size",
"of",
"the",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/body.py#L50-L62 | train | 201,412 |
ArchiveTeam/wpull | wpull/database/sqltable.py | SQLiteURLTable._apply_pragmas_callback | def _apply_pragmas_callback(cls, connection, record):
'''Set SQLite pragmas.
Write-ahead logging, synchronous=NORMAL is used.
'''
_logger.debug('Setting pragmas.')
connection.execute('PRAGMA journal_mode=WAL')
connection.execute('PRAGMA synchronous=NORMAL') | python | def _apply_pragmas_callback(cls, connection, record):
'''Set SQLite pragmas.
Write-ahead logging, synchronous=NORMAL is used.
'''
_logger.debug('Setting pragmas.')
connection.execute('PRAGMA journal_mode=WAL')
connection.execute('PRAGMA synchronous=NORMAL') | [
"def",
"_apply_pragmas_callback",
"(",
"cls",
",",
"connection",
",",
"record",
")",
":",
"_logger",
".",
"debug",
"(",
"'Setting pragmas.'",
")",
"connection",
".",
"execute",
"(",
"'PRAGMA journal_mode=WAL'",
")",
"connection",
".",
"execute",
"(",
"'PRAGMA sync... | Set SQLite pragmas.
Write-ahead logging, synchronous=NORMAL is used. | [
"Set",
"SQLite",
"pragmas",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/database/sqltable.py#L285-L292 | train | 201,413 |
ArchiveTeam/wpull | wpull/robotstxt.py | RobotsTxtPool.has_parser | def has_parser(self, url_info: URLInfo):
'''Return whether a parser has been created for the URL.'''
key = self.url_info_key(url_info)
return key in self._parsers | python | def has_parser(self, url_info: URLInfo):
'''Return whether a parser has been created for the URL.'''
key = self.url_info_key(url_info)
return key in self._parsers | [
"def",
"has_parser",
"(",
"self",
",",
"url_info",
":",
"URLInfo",
")",
":",
"key",
"=",
"self",
".",
"url_info_key",
"(",
"url_info",
")",
"return",
"key",
"in",
"self",
".",
"_parsers"
] | Return whether a parser has been created for the URL. | [
"Return",
"whether",
"a",
"parser",
"has",
"been",
"created",
"for",
"the",
"URL",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/robotstxt.py#L18-L21 | train | 201,414 |
ArchiveTeam/wpull | wpull/robotstxt.py | RobotsTxtPool.can_fetch | def can_fetch(self, url_info: URLInfo, user_agent: str):
'''Return whether the URL can be fetched.'''
key = self.url_info_key(url_info)
parser = self._parsers[key]
return parser.is_allowed(user_agent, url_info.url) | python | def can_fetch(self, url_info: URLInfo, user_agent: str):
'''Return whether the URL can be fetched.'''
key = self.url_info_key(url_info)
parser = self._parsers[key]
return parser.is_allowed(user_agent, url_info.url) | [
"def",
"can_fetch",
"(",
"self",
",",
"url_info",
":",
"URLInfo",
",",
"user_agent",
":",
"str",
")",
":",
"key",
"=",
"self",
".",
"url_info_key",
"(",
"url_info",
")",
"parser",
"=",
"self",
".",
"_parsers",
"[",
"key",
"]",
"return",
"parser",
".",
... | Return whether the URL can be fetched. | [
"Return",
"whether",
"the",
"URL",
"can",
"be",
"fetched",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/robotstxt.py#L23-L28 | train | 201,415 |
ArchiveTeam/wpull | wpull/robotstxt.py | RobotsTxtPool.load_robots_txt | def load_robots_txt(self, url_info: URLInfo, text: str):
'''Load the robot.txt file.'''
key = self.url_info_key(url_info)
parser = robotexclusionrulesparser.RobotExclusionRulesParser()
parser.parse(text)
self._parsers[key] = parser | python | def load_robots_txt(self, url_info: URLInfo, text: str):
'''Load the robot.txt file.'''
key = self.url_info_key(url_info)
parser = robotexclusionrulesparser.RobotExclusionRulesParser()
parser.parse(text)
self._parsers[key] = parser | [
"def",
"load_robots_txt",
"(",
"self",
",",
"url_info",
":",
"URLInfo",
",",
"text",
":",
"str",
")",
":",
"key",
"=",
"self",
".",
"url_info_key",
"(",
"url_info",
")",
"parser",
"=",
"robotexclusionrulesparser",
".",
"RobotExclusionRulesParser",
"(",
")",
... | Load the robot.txt file. | [
"Load",
"the",
"robot",
".",
"txt",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/robotstxt.py#L30-L36 | train | 201,416 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ParserSetupTask._build_demux_document_scraper | def _build_demux_document_scraper(cls, session: AppSession):
'''Create demux document scraper.'''
session.factory.new(
'DemuxDocumentScraper', cls._build_document_scrapers(session)) | python | def _build_demux_document_scraper(cls, session: AppSession):
'''Create demux document scraper.'''
session.factory.new(
'DemuxDocumentScraper', cls._build_document_scrapers(session)) | [
"def",
"_build_demux_document_scraper",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"session",
".",
"factory",
".",
"new",
"(",
"'DemuxDocumentScraper'",
",",
"cls",
".",
"_build_document_scrapers",
"(",
"session",
")",
")"
] | Create demux document scraper. | [
"Create",
"demux",
"document",
"scraper",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L45-L48 | train | 201,417 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ParserSetupTask._build_document_scrapers | def _build_document_scrapers(cls, session: AppSession):
'''Create the document scrapers.
Returns:
A list of document scrapers
'''
html_parser = session.factory['HTMLParser']
element_walker = session.factory.new('ElementWalker')
scrapers = [
session.factory.new(
'HTMLScraper',
html_parser,
element_walker,
followed_tags=session.args.follow_tags,
ignored_tags=session.args.ignore_tags,
only_relative=session.args.relative,
robots=session.args.robots,
encoding_override=session.args.remote_encoding,
),
]
if 'css' in session.args.link_extractors:
css_scraper = session.factory.new(
'CSSScraper',
encoding_override=session.args.remote_encoding,
)
scrapers.append(css_scraper)
element_walker.css_scraper = css_scraper
if 'javascript' in session.args.link_extractors:
javascript_scraper = session.factory.new(
'JavaScriptScraper',
encoding_override=session.args.remote_encoding,
)
scrapers.append(javascript_scraper)
element_walker.javascript_scraper = javascript_scraper
if session.args.sitemaps:
scrapers.append(session.factory.new(
'SitemapScraper', html_parser,
encoding_override=session.args.remote_encoding,
))
return scrapers | python | def _build_document_scrapers(cls, session: AppSession):
'''Create the document scrapers.
Returns:
A list of document scrapers
'''
html_parser = session.factory['HTMLParser']
element_walker = session.factory.new('ElementWalker')
scrapers = [
session.factory.new(
'HTMLScraper',
html_parser,
element_walker,
followed_tags=session.args.follow_tags,
ignored_tags=session.args.ignore_tags,
only_relative=session.args.relative,
robots=session.args.robots,
encoding_override=session.args.remote_encoding,
),
]
if 'css' in session.args.link_extractors:
css_scraper = session.factory.new(
'CSSScraper',
encoding_override=session.args.remote_encoding,
)
scrapers.append(css_scraper)
element_walker.css_scraper = css_scraper
if 'javascript' in session.args.link_extractors:
javascript_scraper = session.factory.new(
'JavaScriptScraper',
encoding_override=session.args.remote_encoding,
)
scrapers.append(javascript_scraper)
element_walker.javascript_scraper = javascript_scraper
if session.args.sitemaps:
scrapers.append(session.factory.new(
'SitemapScraper', html_parser,
encoding_override=session.args.remote_encoding,
))
return scrapers | [
"def",
"_build_document_scrapers",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"html_parser",
"=",
"session",
".",
"factory",
"[",
"'HTMLParser'",
"]",
"element_walker",
"=",
"session",
".",
"factory",
".",
"new",
"(",
"'ElementWalker'",
")",
"scr... | Create the document scrapers.
Returns:
A list of document scrapers | [
"Create",
"the",
"document",
"scrapers",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L51-L95 | train | 201,418 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ClientSetupTask._build_request_factory | def _build_request_factory(cls, session: AppSession):
'''Create the request factory.
A request factory is any callable object that returns a
:class:`.http.Request`. The callable must accept the same
arguments to Request.
Returns:
A callable object
'''
def request_factory(*args, **kwargs):
request = session.factory.class_map['Request'](*args, **kwargs)
user_agent = session.args.user_agent or session.default_user_agent
request.fields['User-Agent'] = user_agent
if session.args.referer:
request.fields['Referer'] = session.args.referer
for header_string in session.args.header:
request.fields.parse(header_string)
if session.args.http_compression:
request.fields['Accept-Encoding'] = 'gzip, deflate'
if session.args.no_cache:
request.fields['Cache-Control'] = 'no-cache, must-revalidate'
request.fields['Pragma'] = 'no-cache'
return request
return request_factory | python | def _build_request_factory(cls, session: AppSession):
'''Create the request factory.
A request factory is any callable object that returns a
:class:`.http.Request`. The callable must accept the same
arguments to Request.
Returns:
A callable object
'''
def request_factory(*args, **kwargs):
request = session.factory.class_map['Request'](*args, **kwargs)
user_agent = session.args.user_agent or session.default_user_agent
request.fields['User-Agent'] = user_agent
if session.args.referer:
request.fields['Referer'] = session.args.referer
for header_string in session.args.header:
request.fields.parse(header_string)
if session.args.http_compression:
request.fields['Accept-Encoding'] = 'gzip, deflate'
if session.args.no_cache:
request.fields['Cache-Control'] = 'no-cache, must-revalidate'
request.fields['Pragma'] = 'no-cache'
return request
return request_factory | [
"def",
"_build_request_factory",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"def",
"request_factory",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"session",
".",
"factory",
".",
"class_map",
"[",
"'Request'",
"]",
"... | Create the request factory.
A request factory is any callable object that returns a
:class:`.http.Request`. The callable must accept the same
arguments to Request.
Returns:
A callable object | [
"Create",
"the",
"request",
"factory",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L105-L137 | train | 201,419 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ClientSetupTask._build_http_client | def _build_http_client(cls, session: AppSession):
'''Create the HTTP client.
Returns:
Client: An instance of :class:`.http.Client`.
'''
# TODO:
# recorder = self._build_recorder()
stream_factory = functools.partial(
HTTPStream,
ignore_length=session.args.ignore_length,
keep_alive=session.args.http_keep_alive)
return session.factory.new(
'HTTPClient',
connection_pool=session.factory['ConnectionPool'],
stream_factory=stream_factory
) | python | def _build_http_client(cls, session: AppSession):
'''Create the HTTP client.
Returns:
Client: An instance of :class:`.http.Client`.
'''
# TODO:
# recorder = self._build_recorder()
stream_factory = functools.partial(
HTTPStream,
ignore_length=session.args.ignore_length,
keep_alive=session.args.http_keep_alive)
return session.factory.new(
'HTTPClient',
connection_pool=session.factory['ConnectionPool'],
stream_factory=stream_factory
) | [
"def",
"_build_http_client",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"# TODO:",
"# recorder = self._build_recorder()",
"stream_factory",
"=",
"functools",
".",
"partial",
"(",
"HTTPStream",
",",
"ignore_length",
"=",
"session",
".",
"args",
".",
"... | Create the HTTP client.
Returns:
Client: An instance of :class:`.http.Client`. | [
"Create",
"the",
"HTTP",
"client",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L140-L158 | train | 201,420 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ClientSetupTask._build_web_client | def _build_web_client(cls, session: AppSession):
'''Build Web Client.'''
cookie_jar = cls._build_cookie_jar(session)
http_client = cls._build_http_client(session)
redirect_factory = functools.partial(
session.factory.class_map['RedirectTracker'],
max_redirects=session.args.max_redirect
)
return session.factory.new(
'WebClient',
http_client,
redirect_tracker_factory=redirect_factory,
cookie_jar=cookie_jar,
request_factory=cls._build_request_factory(session),
) | python | def _build_web_client(cls, session: AppSession):
'''Build Web Client.'''
cookie_jar = cls._build_cookie_jar(session)
http_client = cls._build_http_client(session)
redirect_factory = functools.partial(
session.factory.class_map['RedirectTracker'],
max_redirects=session.args.max_redirect
)
return session.factory.new(
'WebClient',
http_client,
redirect_tracker_factory=redirect_factory,
cookie_jar=cookie_jar,
request_factory=cls._build_request_factory(session),
) | [
"def",
"_build_web_client",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"cookie_jar",
"=",
"cls",
".",
"_build_cookie_jar",
"(",
"session",
")",
"http_client",
"=",
"cls",
".",
"_build_http_client",
"(",
"session",
")",
"redirect_factory",
"=",
"f... | Build Web Client. | [
"Build",
"Web",
"Client",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L161-L177 | train | 201,421 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ClientSetupTask._build_cookie_jar | def _build_cookie_jar(cls, session: AppSession):
'''Build the cookie jar'''
if not session.args.cookies:
return
if session.args.load_cookies or session.args.save_cookies:
session.factory.set('CookieJar', BetterMozillaCookieJar)
cookie_jar = session.factory.new('CookieJar')
if session.args.load_cookies:
cookie_jar.load(session.args.load_cookies, ignore_discard=True)
else:
cookie_jar = session.factory.new('CookieJar')
policy = session.factory.new('CookiePolicy', cookie_jar=cookie_jar)
cookie_jar.set_policy(policy)
_logger.debug(__('Loaded cookies: {0}', list(cookie_jar)))
cookie_jar_wrapper = session.factory.new(
'CookieJarWrapper',
cookie_jar,
save_filename=session.args.save_cookies,
keep_session_cookies=session.args.keep_session_cookies,
)
return cookie_jar_wrapper | python | def _build_cookie_jar(cls, session: AppSession):
'''Build the cookie jar'''
if not session.args.cookies:
return
if session.args.load_cookies or session.args.save_cookies:
session.factory.set('CookieJar', BetterMozillaCookieJar)
cookie_jar = session.factory.new('CookieJar')
if session.args.load_cookies:
cookie_jar.load(session.args.load_cookies, ignore_discard=True)
else:
cookie_jar = session.factory.new('CookieJar')
policy = session.factory.new('CookiePolicy', cookie_jar=cookie_jar)
cookie_jar.set_policy(policy)
_logger.debug(__('Loaded cookies: {0}', list(cookie_jar)))
cookie_jar_wrapper = session.factory.new(
'CookieJarWrapper',
cookie_jar,
save_filename=session.args.save_cookies,
keep_session_cookies=session.args.keep_session_cookies,
)
return cookie_jar_wrapper | [
"def",
"_build_cookie_jar",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"if",
"not",
"session",
".",
"args",
".",
"cookies",
":",
"return",
"if",
"session",
".",
"args",
".",
"load_cookies",
"or",
"session",
".",
"args",
".",
"save_cookies",
... | Build the cookie jar | [
"Build",
"the",
"cookie",
"jar"
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L180-L209 | train | 201,422 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ClientSetupTask._build_ftp_client | def _build_ftp_client(cls, session: AppSession):
'''Build FTP client.'''
return session.factory.new(
'FTPClient',
connection_pool=session.factory['ConnectionPool'],
# TODO: recorder
# recorder=session.factory['DemuxRecorder'],
) | python | def _build_ftp_client(cls, session: AppSession):
'''Build FTP client.'''
return session.factory.new(
'FTPClient',
connection_pool=session.factory['ConnectionPool'],
# TODO: recorder
# recorder=session.factory['DemuxRecorder'],
) | [
"def",
"_build_ftp_client",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"return",
"session",
".",
"factory",
".",
"new",
"(",
"'FTPClient'",
",",
"connection_pool",
"=",
"session",
".",
"factory",
"[",
"'ConnectionPool'",
"]",
",",
"# TODO: record... | Build FTP client. | [
"Build",
"FTP",
"client",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L212-L219 | train | 201,423 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ProxyServerSetupTask.process | def process(self, session: AppSession):
'''Build MITM proxy server.'''
args = session.args
if not (args.phantomjs or args.youtube_dl or args.proxy_server):
return
proxy_server = session.factory.new(
'HTTPProxyServer',
session.factory['HTTPClient'],
)
cookie_jar = session.factory.get('CookieJarWrapper')
proxy_coprocessor = session.factory.new(
'ProxyCoprocessor',
session
)
proxy_socket = tornado.netutil.bind_sockets(
session.args.proxy_server_port,
address=session.args.proxy_server_address
)[0]
proxy_port = proxy_socket.getsockname()[1]
proxy_async_server = yield from asyncio.start_server(proxy_server, sock=proxy_socket)
session.async_servers.append(proxy_async_server)
session.proxy_server_port = proxy_port | python | def process(self, session: AppSession):
'''Build MITM proxy server.'''
args = session.args
if not (args.phantomjs or args.youtube_dl or args.proxy_server):
return
proxy_server = session.factory.new(
'HTTPProxyServer',
session.factory['HTTPClient'],
)
cookie_jar = session.factory.get('CookieJarWrapper')
proxy_coprocessor = session.factory.new(
'ProxyCoprocessor',
session
)
proxy_socket = tornado.netutil.bind_sockets(
session.args.proxy_server_port,
address=session.args.proxy_server_address
)[0]
proxy_port = proxy_socket.getsockname()[1]
proxy_async_server = yield from asyncio.start_server(proxy_server, sock=proxy_socket)
session.async_servers.append(proxy_async_server)
session.proxy_server_port = proxy_port | [
"def",
"process",
"(",
"self",
",",
"session",
":",
"AppSession",
")",
":",
"args",
"=",
"session",
".",
"args",
"if",
"not",
"(",
"args",
".",
"phantomjs",
"or",
"args",
".",
"youtube_dl",
"or",
"args",
".",
"proxy_server",
")",
":",
"return",
"proxy_... | Build MITM proxy server. | [
"Build",
"MITM",
"proxy",
"server",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L224-L250 | train | 201,424 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ProcessorSetupTask._build_processor | def _build_processor(cls, session: AppSession):
'''Create the Processor
Returns:
Processor: An instance of :class:`.processor.BaseProcessor`.
'''
web_processor = cls._build_web_processor(session)
ftp_processor = cls._build_ftp_processor(session)
delegate_processor = session.factory.new('Processor')
delegate_processor.register('http', web_processor)
delegate_processor.register('https', web_processor)
delegate_processor.register('ftp', ftp_processor) | python | def _build_processor(cls, session: AppSession):
'''Create the Processor
Returns:
Processor: An instance of :class:`.processor.BaseProcessor`.
'''
web_processor = cls._build_web_processor(session)
ftp_processor = cls._build_ftp_processor(session)
delegate_processor = session.factory.new('Processor')
delegate_processor.register('http', web_processor)
delegate_processor.register('https', web_processor)
delegate_processor.register('ftp', ftp_processor) | [
"def",
"_build_processor",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"web_processor",
"=",
"cls",
".",
"_build_web_processor",
"(",
"session",
")",
"ftp_processor",
"=",
"cls",
".",
"_build_ftp_processor",
"(",
"session",
")",
"delegate_processor",
... | Create the Processor
Returns:
Processor: An instance of :class:`.processor.BaseProcessor`. | [
"Create",
"the",
"Processor"
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L259-L271 | train | 201,425 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ProcessorSetupTask._build_web_processor | def _build_web_processor(cls, session: AppSession):
'''Build WebProcessor.'''
args = session.args
url_filter = session.factory['DemuxURLFilter']
document_scraper = session.factory['DemuxDocumentScraper']
file_writer = session.factory['FileWriter']
post_data = cls._get_post_data(session.args)
web_client = session.factory['WebClient']
robots_txt_checker = cls._build_robots_txt_checker(session)
http_username = args.user or args.http_user
http_password = args.password or args.http_password
ftp_username = args.user or args.ftp_user
ftp_password = args.password or args.ftp_password
fetch_rule = session.factory.new(
'FetchRule',
url_filter=url_filter, robots_txt_checker=robots_txt_checker,
http_login=(http_username, http_password),
ftp_login=(ftp_username, ftp_password),
duration_timeout=args.session_timeout,
)
waiter = session.factory.new(
'Waiter',
wait=args.wait,
random_wait=args.random_wait,
max_wait=args.waitretry)
result_rule = session.factory.new(
'ResultRule',
ssl_verification=args.check_certificate,
retry_connrefused=args.retry_connrefused,
retry_dns_error=args.retry_dns_error,
waiter=waiter,
statistics=session.factory['Statistics'],
)
processing_rule = session.factory.new(
'ProcessingRule',
fetch_rule,
document_scraper=document_scraper,
sitemaps=session.args.sitemaps,
url_rewriter=session.factory.get('URLRewriter'),
)
web_processor_fetch_params = session.factory.new(
'WebProcessorFetchParams',
post_data=post_data,
strong_redirects=args.strong_redirects,
content_on_error=args.content_on_error,
)
processor = session.factory.new(
'WebProcessor',
web_client,
web_processor_fetch_params,
)
return processor | python | def _build_web_processor(cls, session: AppSession):
'''Build WebProcessor.'''
args = session.args
url_filter = session.factory['DemuxURLFilter']
document_scraper = session.factory['DemuxDocumentScraper']
file_writer = session.factory['FileWriter']
post_data = cls._get_post_data(session.args)
web_client = session.factory['WebClient']
robots_txt_checker = cls._build_robots_txt_checker(session)
http_username = args.user or args.http_user
http_password = args.password or args.http_password
ftp_username = args.user or args.ftp_user
ftp_password = args.password or args.ftp_password
fetch_rule = session.factory.new(
'FetchRule',
url_filter=url_filter, robots_txt_checker=robots_txt_checker,
http_login=(http_username, http_password),
ftp_login=(ftp_username, ftp_password),
duration_timeout=args.session_timeout,
)
waiter = session.factory.new(
'Waiter',
wait=args.wait,
random_wait=args.random_wait,
max_wait=args.waitretry)
result_rule = session.factory.new(
'ResultRule',
ssl_verification=args.check_certificate,
retry_connrefused=args.retry_connrefused,
retry_dns_error=args.retry_dns_error,
waiter=waiter,
statistics=session.factory['Statistics'],
)
processing_rule = session.factory.new(
'ProcessingRule',
fetch_rule,
document_scraper=document_scraper,
sitemaps=session.args.sitemaps,
url_rewriter=session.factory.get('URLRewriter'),
)
web_processor_fetch_params = session.factory.new(
'WebProcessorFetchParams',
post_data=post_data,
strong_redirects=args.strong_redirects,
content_on_error=args.content_on_error,
)
processor = session.factory.new(
'WebProcessor',
web_client,
web_processor_fetch_params,
)
return processor | [
"def",
"_build_web_processor",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"args",
"=",
"session",
".",
"args",
"url_filter",
"=",
"session",
".",
"factory",
"[",
"'DemuxURLFilter'",
"]",
"document_scraper",
"=",
"session",
".",
"factory",
"[",
... | Build WebProcessor. | [
"Build",
"WebProcessor",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L274-L334 | train | 201,426 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ProcessorSetupTask._build_ftp_processor | def _build_ftp_processor(cls, session: AppSession):
'''Build FTPProcessor.'''
ftp_client = session.factory['FTPClient']
fetch_params = session.factory.new(
'FTPProcessorFetchParams',
remove_listing=session.args.remove_listing,
retr_symlinks=session.args.retr_symlinks,
preserve_permissions=session.args.preserve_permissions,
glob=session.args.glob,
)
return session.factory.new(
'FTPProcessor',
ftp_client,
fetch_params,
) | python | def _build_ftp_processor(cls, session: AppSession):
'''Build FTPProcessor.'''
ftp_client = session.factory['FTPClient']
fetch_params = session.factory.new(
'FTPProcessorFetchParams',
remove_listing=session.args.remove_listing,
retr_symlinks=session.args.retr_symlinks,
preserve_permissions=session.args.preserve_permissions,
glob=session.args.glob,
)
return session.factory.new(
'FTPProcessor',
ftp_client,
fetch_params,
) | [
"def",
"_build_ftp_processor",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"ftp_client",
"=",
"session",
".",
"factory",
"[",
"'FTPClient'",
"]",
"fetch_params",
"=",
"session",
".",
"factory",
".",
"new",
"(",
"'FTPProcessorFetchParams'",
",",
"r... | Build FTPProcessor. | [
"Build",
"FTPProcessor",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L337-L353 | train | 201,427 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ProcessorSetupTask._get_post_data | def _get_post_data(cls, args):
'''Return the post data.'''
if args.post_data:
return args.post_data
elif args.post_file:
return args.post_file.read() | python | def _get_post_data(cls, args):
'''Return the post data.'''
if args.post_data:
return args.post_data
elif args.post_file:
return args.post_file.read() | [
"def",
"_get_post_data",
"(",
"cls",
",",
"args",
")",
":",
"if",
"args",
".",
"post_data",
":",
"return",
"args",
".",
"post_data",
"elif",
"args",
".",
"post_file",
":",
"return",
"args",
".",
"post_file",
".",
"read",
"(",
")"
] | Return the post data. | [
"Return",
"the",
"post",
"data",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L356-L361 | train | 201,428 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | ProcessorSetupTask._build_robots_txt_checker | def _build_robots_txt_checker(cls, session: AppSession):
'''Build robots.txt checker.'''
if session.args.robots:
robots_txt_pool = session.factory.new('RobotsTxtPool')
robots_txt_checker = session.factory.new(
'RobotsTxtChecker',
web_client=session.factory['WebClient'],
robots_txt_pool=robots_txt_pool
)
return robots_txt_checker | python | def _build_robots_txt_checker(cls, session: AppSession):
'''Build robots.txt checker.'''
if session.args.robots:
robots_txt_pool = session.factory.new('RobotsTxtPool')
robots_txt_checker = session.factory.new(
'RobotsTxtChecker',
web_client=session.factory['WebClient'],
robots_txt_pool=robots_txt_pool
)
return robots_txt_checker | [
"def",
"_build_robots_txt_checker",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"if",
"session",
".",
"args",
".",
"robots",
":",
"robots_txt_pool",
"=",
"session",
".",
"factory",
".",
"new",
"(",
"'RobotsTxtPool'",
")",
"robots_txt_checker",
"="... | Build robots.txt checker. | [
"Build",
"robots",
".",
"txt",
"checker",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L364-L374 | train | 201,429 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | CoprocessorSetupTask._build_phantomjs_coprocessor | def _build_phantomjs_coprocessor(cls, session: AppSession, proxy_port: int):
'''Build proxy server and PhantomJS client. controller, coprocessor.'''
page_settings = {}
default_headers = NameValueRecord()
for header_string in session.args.header:
default_headers.parse(header_string)
# Since we can only pass a one-to-one mapping to PhantomJS,
# we put these last since NameValueRecord.items() will use only the
# first value added for each key.
default_headers.add('Accept-Language', '*')
if not session.args.http_compression:
default_headers.add('Accept-Encoding', 'identity')
default_headers = dict(default_headers.items())
if session.args.read_timeout:
page_settings['resourceTimeout'] = session.args.read_timeout * 1000
page_settings['userAgent'] = session.args.user_agent \
or session.default_user_agent
# Test early for executable
wpull.driver.phantomjs.get_version(session.args.phantomjs_exe)
phantomjs_params = PhantomJSParams(
wait_time=session.args.phantomjs_wait,
num_scrolls=session.args.phantomjs_scroll,
smart_scroll=session.args.phantomjs_smart_scroll,
snapshot=session.args.phantomjs_snapshot,
custom_headers=default_headers,
page_settings=page_settings,
load_time=session.args.phantomjs_max_time,
)
extra_args = [
'--proxy',
'{}:{}'.format(session.args.proxy_server_address, proxy_port),
'--ignore-ssl-errors=true'
]
phantomjs_driver_factory = functools.partial(
session.factory.class_map['PhantomJSDriver'],
exe_path=session.args.phantomjs_exe,
extra_args=extra_args,
)
phantomjs_coprocessor = session.factory.new(
'PhantomJSCoprocessor',
phantomjs_driver_factory,
session.factory['ProcessingRule'],
phantomjs_params,
root_path=session.args.directory_prefix,
warc_recorder=session.factory.get('WARCRecorder'),
)
return phantomjs_coprocessor | python | def _build_phantomjs_coprocessor(cls, session: AppSession, proxy_port: int):
'''Build proxy server and PhantomJS client. controller, coprocessor.'''
page_settings = {}
default_headers = NameValueRecord()
for header_string in session.args.header:
default_headers.parse(header_string)
# Since we can only pass a one-to-one mapping to PhantomJS,
# we put these last since NameValueRecord.items() will use only the
# first value added for each key.
default_headers.add('Accept-Language', '*')
if not session.args.http_compression:
default_headers.add('Accept-Encoding', 'identity')
default_headers = dict(default_headers.items())
if session.args.read_timeout:
page_settings['resourceTimeout'] = session.args.read_timeout * 1000
page_settings['userAgent'] = session.args.user_agent \
or session.default_user_agent
# Test early for executable
wpull.driver.phantomjs.get_version(session.args.phantomjs_exe)
phantomjs_params = PhantomJSParams(
wait_time=session.args.phantomjs_wait,
num_scrolls=session.args.phantomjs_scroll,
smart_scroll=session.args.phantomjs_smart_scroll,
snapshot=session.args.phantomjs_snapshot,
custom_headers=default_headers,
page_settings=page_settings,
load_time=session.args.phantomjs_max_time,
)
extra_args = [
'--proxy',
'{}:{}'.format(session.args.proxy_server_address, proxy_port),
'--ignore-ssl-errors=true'
]
phantomjs_driver_factory = functools.partial(
session.factory.class_map['PhantomJSDriver'],
exe_path=session.args.phantomjs_exe,
extra_args=extra_args,
)
phantomjs_coprocessor = session.factory.new(
'PhantomJSCoprocessor',
phantomjs_driver_factory,
session.factory['ProcessingRule'],
phantomjs_params,
root_path=session.args.directory_prefix,
warc_recorder=session.factory.get('WARCRecorder'),
)
return phantomjs_coprocessor | [
"def",
"_build_phantomjs_coprocessor",
"(",
"cls",
",",
"session",
":",
"AppSession",
",",
"proxy_port",
":",
"int",
")",
":",
"page_settings",
"=",
"{",
"}",
"default_headers",
"=",
"NameValueRecord",
"(",
")",
"for",
"header_string",
"in",
"session",
".",
"a... | Build proxy server and PhantomJS client. controller, coprocessor. | [
"Build",
"proxy",
"server",
"and",
"PhantomJS",
"client",
".",
"controller",
"coprocessor",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L406-L464 | train | 201,430 |
ArchiveTeam/wpull | wpull/application/tasks/download.py | CoprocessorSetupTask._build_youtube_dl_coprocessor | def _build_youtube_dl_coprocessor(cls, session: AppSession, proxy_port: int):
'''Build youtube-dl coprocessor.'''
# Test early for executable
wpull.processor.coprocessor.youtubedl.get_version(session.args.youtube_dl_exe)
coprocessor = session.factory.new(
'YoutubeDlCoprocessor',
session.args.youtube_dl_exe,
(session.args.proxy_server_address, proxy_port),
root_path=session.args.directory_prefix,
user_agent=session.args.user_agent or session.default_user_agent,
warc_recorder=session.factory.get('WARCRecorder'),
inet_family=session.args.inet_family,
# Proxy will always present a invalid MITM cert
#check_certificate=session.args.check_certificate
check_certificate=False
)
return coprocessor | python | def _build_youtube_dl_coprocessor(cls, session: AppSession, proxy_port: int):
'''Build youtube-dl coprocessor.'''
# Test early for executable
wpull.processor.coprocessor.youtubedl.get_version(session.args.youtube_dl_exe)
coprocessor = session.factory.new(
'YoutubeDlCoprocessor',
session.args.youtube_dl_exe,
(session.args.proxy_server_address, proxy_port),
root_path=session.args.directory_prefix,
user_agent=session.args.user_agent or session.default_user_agent,
warc_recorder=session.factory.get('WARCRecorder'),
inet_family=session.args.inet_family,
# Proxy will always present a invalid MITM cert
#check_certificate=session.args.check_certificate
check_certificate=False
)
return coprocessor | [
"def",
"_build_youtube_dl_coprocessor",
"(",
"cls",
",",
"session",
":",
"AppSession",
",",
"proxy_port",
":",
"int",
")",
":",
"# Test early for executable",
"wpull",
".",
"processor",
".",
"coprocessor",
".",
"youtubedl",
".",
"get_version",
"(",
"session",
".",... | Build youtube-dl coprocessor. | [
"Build",
"youtube",
"-",
"dl",
"coprocessor",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L467-L486 | train | 201,431 |
ArchiveTeam/wpull | wpull/application/builder.py | Builder.build | def build(self) -> Application:
'''Put the application together.
'''
pipelines = self._build_pipelines()
self._factory.new('Application', pipelines)
return self._factory['Application'] | python | def build(self) -> Application:
'''Put the application together.
'''
pipelines = self._build_pipelines()
self._factory.new('Application', pipelines)
return self._factory['Application'] | [
"def",
"build",
"(",
"self",
")",
"->",
"Application",
":",
"pipelines",
"=",
"self",
".",
"_build_pipelines",
"(",
")",
"self",
".",
"_factory",
".",
"new",
"(",
"'Application'",
",",
"pipelines",
")",
"return",
"self",
".",
"_factory",
"[",
"'Application... | Put the application together. | [
"Put",
"the",
"application",
"together",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/builder.py#L147-L154 | train | 201,432 |
ArchiveTeam/wpull | wpull/document/base.py | BaseDocumentDetector.is_supported | def is_supported(cls, file=None, request=None, response=None,
url_info=None):
'''Given the hints, return whether the document is supported.
Args:
file: A file object containing the document.
request (:class:`.http.request.Request`): An HTTP request.
response (:class:`.http.request.Response`): An HTTP response.
url_info (:class:`.url.URLInfo`): A URLInfo.
Returns:
bool: If True, the reader should be able to read it.
'''
tests = (
(response, cls.is_response),
(file, cls.is_file),
(request, cls.is_request),
(url_info, cls.is_url)
)
for instance, method in tests:
if instance:
try:
result = method(instance)
except NotImplementedError:
pass
else:
if result:
return True
elif result is VeryFalse:
return VeryFalse | python | def is_supported(cls, file=None, request=None, response=None,
url_info=None):
'''Given the hints, return whether the document is supported.
Args:
file: A file object containing the document.
request (:class:`.http.request.Request`): An HTTP request.
response (:class:`.http.request.Response`): An HTTP response.
url_info (:class:`.url.URLInfo`): A URLInfo.
Returns:
bool: If True, the reader should be able to read it.
'''
tests = (
(response, cls.is_response),
(file, cls.is_file),
(request, cls.is_request),
(url_info, cls.is_url)
)
for instance, method in tests:
if instance:
try:
result = method(instance)
except NotImplementedError:
pass
else:
if result:
return True
elif result is VeryFalse:
return VeryFalse | [
"def",
"is_supported",
"(",
"cls",
",",
"file",
"=",
"None",
",",
"request",
"=",
"None",
",",
"response",
"=",
"None",
",",
"url_info",
"=",
"None",
")",
":",
"tests",
"=",
"(",
"(",
"response",
",",
"cls",
".",
"is_response",
")",
",",
"(",
"file... | Given the hints, return whether the document is supported.
Args:
file: A file object containing the document.
request (:class:`.http.request.Request`): An HTTP request.
response (:class:`.http.request.Response`): An HTTP response.
url_info (:class:`.url.URLInfo`): A URLInfo.
Returns:
bool: If True, the reader should be able to read it. | [
"Given",
"the",
"hints",
"return",
"whether",
"the",
"document",
"is",
"supported",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/base.py#L18-L48 | train | 201,433 |
ArchiveTeam/wpull | wpull/application/tasks/stats.py | StatsStopTask._print_stats | def _print_stats(cls, stats: Statistics, human_format_speed: bool=True):
'''Log the final statistics to the user.'''
time_length = datetime.timedelta(
seconds=int(stats.stop_time - stats.start_time)
)
file_size = wpull.string.format_size(stats.size)
if stats.bandwidth_meter.num_samples:
speed = stats.bandwidth_meter.speed()
if human_format_speed:
speed_size_str = wpull.string.format_size(speed)
else:
speed_size_str = '{:.1f} b'.format(speed * 8)
else:
speed_size_str = _('-- B')
_logger.info(_('FINISHED.'))
_logger.info(__(
_(
'Duration: {preformatted_timedelta}. '
'Speed: {preformatted_speed_size}/s.'
),
preformatted_timedelta=time_length,
preformatted_speed_size=speed_size_str,
))
_logger.info(__(
gettext.ngettext(
'Downloaded: {num_files} file, {preformatted_file_size}.',
'Downloaded: {num_files} files, {preformatted_file_size}.',
stats.files
),
num_files=stats.files,
preformatted_file_size=file_size
))
if stats.is_quota_exceeded:
_logger.info(_('Download quota exceeded.')) | python | def _print_stats(cls, stats: Statistics, human_format_speed: bool=True):
'''Log the final statistics to the user.'''
time_length = datetime.timedelta(
seconds=int(stats.stop_time - stats.start_time)
)
file_size = wpull.string.format_size(stats.size)
if stats.bandwidth_meter.num_samples:
speed = stats.bandwidth_meter.speed()
if human_format_speed:
speed_size_str = wpull.string.format_size(speed)
else:
speed_size_str = '{:.1f} b'.format(speed * 8)
else:
speed_size_str = _('-- B')
_logger.info(_('FINISHED.'))
_logger.info(__(
_(
'Duration: {preformatted_timedelta}. '
'Speed: {preformatted_speed_size}/s.'
),
preformatted_timedelta=time_length,
preformatted_speed_size=speed_size_str,
))
_logger.info(__(
gettext.ngettext(
'Downloaded: {num_files} file, {preformatted_file_size}.',
'Downloaded: {num_files} files, {preformatted_file_size}.',
stats.files
),
num_files=stats.files,
preformatted_file_size=file_size
))
if stats.is_quota_exceeded:
_logger.info(_('Download quota exceeded.')) | [
"def",
"_print_stats",
"(",
"cls",
",",
"stats",
":",
"Statistics",
",",
"human_format_speed",
":",
"bool",
"=",
"True",
")",
":",
"time_length",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"int",
"(",
"stats",
".",
"stop_time",
"-",
"stats",
... | Log the final statistics to the user. | [
"Log",
"the",
"final",
"statistics",
"to",
"the",
"user",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/stats.py#L45-L82 | train | 201,434 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | is_no_body | def is_no_body(request, response, no_content_codes=DEFAULT_NO_CONTENT_CODES):
'''Return whether a content body is not expected.'''
if 'Content-Length' not in response.fields \
and 'Transfer-Encoding' not in response.fields \
and (
response.status_code in no_content_codes
or request.method.upper() == 'HEAD'
):
return True
else:
return False | python | def is_no_body(request, response, no_content_codes=DEFAULT_NO_CONTENT_CODES):
'''Return whether a content body is not expected.'''
if 'Content-Length' not in response.fields \
and 'Transfer-Encoding' not in response.fields \
and (
response.status_code in no_content_codes
or request.method.upper() == 'HEAD'
):
return True
else:
return False | [
"def",
"is_no_body",
"(",
"request",
",",
"response",
",",
"no_content_codes",
"=",
"DEFAULT_NO_CONTENT_CODES",
")",
":",
"if",
"'Content-Length'",
"not",
"in",
"response",
".",
"fields",
"and",
"'Transfer-Encoding'",
"not",
"in",
"response",
".",
"fields",
"and",... | Return whether a content body is not expected. | [
"Return",
"whether",
"a",
"content",
"body",
"is",
"not",
"expected",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L441-L451 | train | 201,435 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream.write_request | def write_request(self, request, full_url=False):
'''Send the request's HTTP status line and header fields.
This class will automatically connect the connection if the
connection is closed.
Coroutine.
'''
_logger.debug('Sending headers.')
if hasattr(request, 'prepare_for_send'):
request.prepare_for_send(full_url=full_url)
if self._ignore_length:
request.fields['Connection'] = 'close'
data = request.to_bytes()
self._data_event_dispatcher.notify_write(data)
# XXX: Connection lost is raised too early on Python 3.2, 3.3 so
# don't flush but check for connection closed on reads
yield from self._connection.write(data, drain=False) | python | def write_request(self, request, full_url=False):
'''Send the request's HTTP status line and header fields.
This class will automatically connect the connection if the
connection is closed.
Coroutine.
'''
_logger.debug('Sending headers.')
if hasattr(request, 'prepare_for_send'):
request.prepare_for_send(full_url=full_url)
if self._ignore_length:
request.fields['Connection'] = 'close'
data = request.to_bytes()
self._data_event_dispatcher.notify_write(data)
# XXX: Connection lost is raised too early on Python 3.2, 3.3 so
# don't flush but check for connection closed on reads
yield from self._connection.write(data, drain=False) | [
"def",
"write_request",
"(",
"self",
",",
"request",
",",
"full_url",
"=",
"False",
")",
":",
"_logger",
".",
"debug",
"(",
"'Sending headers.'",
")",
"if",
"hasattr",
"(",
"request",
",",
"'prepare_for_send'",
")",
":",
"request",
".",
"prepare_for_send",
"... | Send the request's HTTP status line and header fields.
This class will automatically connect the connection if the
connection is closed.
Coroutine. | [
"Send",
"the",
"request",
"s",
"HTTP",
"status",
"line",
"and",
"header",
"fields",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L65-L87 | train | 201,436 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream.write_body | def write_body(self, file, length=None):
'''Send the request's content body.
Coroutine.
'''
_logger.debug('Sending body.')
file_is_async = (asyncio.iscoroutine(file.read) or
asyncio.iscoroutinefunction(file.read))
_logger.debug(__('Body is async: {0}', file_is_async))
if length is not None:
bytes_left = length
while True:
if length is not None:
if bytes_left <= 0:
break
read_size = min(bytes_left, self._read_size)
else:
read_size = self._read_size
if file_is_async:
data = yield from file.read(read_size)
else:
data = file.read(read_size)
if not data:
break
self._data_event_dispatcher.notify_write(data)
if bytes_left <= self._read_size:
# XXX: Connection lost is raised too early on Python 3.2, 3.3
# so don't flush on the last chunk but check for connection
# closed on reads
drain = False
else:
drain = True
yield from self._connection.write(data, drain=drain)
if length is not None:
bytes_left -= len(data) | python | def write_body(self, file, length=None):
'''Send the request's content body.
Coroutine.
'''
_logger.debug('Sending body.')
file_is_async = (asyncio.iscoroutine(file.read) or
asyncio.iscoroutinefunction(file.read))
_logger.debug(__('Body is async: {0}', file_is_async))
if length is not None:
bytes_left = length
while True:
if length is not None:
if bytes_left <= 0:
break
read_size = min(bytes_left, self._read_size)
else:
read_size = self._read_size
if file_is_async:
data = yield from file.read(read_size)
else:
data = file.read(read_size)
if not data:
break
self._data_event_dispatcher.notify_write(data)
if bytes_left <= self._read_size:
# XXX: Connection lost is raised too early on Python 3.2, 3.3
# so don't flush on the last chunk but check for connection
# closed on reads
drain = False
else:
drain = True
yield from self._connection.write(data, drain=drain)
if length is not None:
bytes_left -= len(data) | [
"def",
"write_body",
"(",
"self",
",",
"file",
",",
"length",
"=",
"None",
")",
":",
"_logger",
".",
"debug",
"(",
"'Sending body.'",
")",
"file_is_async",
"=",
"(",
"asyncio",
".",
"iscoroutine",
"(",
"file",
".",
"read",
")",
"or",
"asyncio",
".",
"i... | Send the request's content body.
Coroutine. | [
"Send",
"the",
"request",
"s",
"content",
"body",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L91-L135 | train | 201,437 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream.read_response | def read_response(self, response=None):
'''Read the response's HTTP status line and header fields.
Coroutine.
'''
_logger.debug('Reading header.')
if response is None:
response = Response()
header_lines = []
bytes_read = 0
while True:
try:
data = yield from self._connection.readline()
except ValueError as error:
raise ProtocolError(
'Invalid header: {0}'.format(error)) from error
self._data_event_dispatcher.notify_read(data)
if not data.endswith(b'\n'):
raise NetworkError('Connection closed.')
elif data in (b'\r\n', b'\n'):
break
header_lines.append(data)
assert data.endswith(b'\n')
bytes_read += len(data)
if bytes_read > 32768:
raise ProtocolError('Header too big.')
if not header_lines:
raise ProtocolError('No header received.')
response.parse(b''.join(header_lines))
return response | python | def read_response(self, response=None):
'''Read the response's HTTP status line and header fields.
Coroutine.
'''
_logger.debug('Reading header.')
if response is None:
response = Response()
header_lines = []
bytes_read = 0
while True:
try:
data = yield from self._connection.readline()
except ValueError as error:
raise ProtocolError(
'Invalid header: {0}'.format(error)) from error
self._data_event_dispatcher.notify_read(data)
if not data.endswith(b'\n'):
raise NetworkError('Connection closed.')
elif data in (b'\r\n', b'\n'):
break
header_lines.append(data)
assert data.endswith(b'\n')
bytes_read += len(data)
if bytes_read > 32768:
raise ProtocolError('Header too big.')
if not header_lines:
raise ProtocolError('No header received.')
response.parse(b''.join(header_lines))
return response | [
"def",
"read_response",
"(",
"self",
",",
"response",
"=",
"None",
")",
":",
"_logger",
".",
"debug",
"(",
"'Reading header.'",
")",
"if",
"response",
"is",
"None",
":",
"response",
"=",
"Response",
"(",
")",
"header_lines",
"=",
"[",
"]",
"bytes_read",
... | Read the response's HTTP status line and header fields.
Coroutine. | [
"Read",
"the",
"response",
"s",
"HTTP",
"status",
"line",
"and",
"header",
"fields",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L139-L179 | train | 201,438 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream.read_body | def read_body(self, request, response, file=None, raw=False):
'''Read the response's content body.
Coroutine.
'''
if is_no_body(request, response):
return
if not raw:
self._setup_decompressor(response)
read_strategy = self.get_read_strategy(response)
if self._ignore_length and read_strategy == 'length':
read_strategy = 'close'
if read_strategy == 'chunked':
yield from self._read_body_by_chunk(response, file, raw=raw)
elif read_strategy == 'length':
yield from self._read_body_by_length(response, file)
else:
yield from self._read_body_until_close(response, file)
should_close = wpull.protocol.http.util.should_close(
request.version, response.fields.get('Connection'))
if not self._keep_alive or should_close:
_logger.debug('Not keep-alive. Closing connection.')
self.close() | python | def read_body(self, request, response, file=None, raw=False):
'''Read the response's content body.
Coroutine.
'''
if is_no_body(request, response):
return
if not raw:
self._setup_decompressor(response)
read_strategy = self.get_read_strategy(response)
if self._ignore_length and read_strategy == 'length':
read_strategy = 'close'
if read_strategy == 'chunked':
yield from self._read_body_by_chunk(response, file, raw=raw)
elif read_strategy == 'length':
yield from self._read_body_by_length(response, file)
else:
yield from self._read_body_until_close(response, file)
should_close = wpull.protocol.http.util.should_close(
request.version, response.fields.get('Connection'))
if not self._keep_alive or should_close:
_logger.debug('Not keep-alive. Closing connection.')
self.close() | [
"def",
"read_body",
"(",
"self",
",",
"request",
",",
"response",
",",
"file",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"if",
"is_no_body",
"(",
"request",
",",
"response",
")",
":",
"return",
"if",
"not",
"raw",
":",
"self",
".",
"_setup_dec... | Read the response's content body.
Coroutine. | [
"Read",
"the",
"response",
"s",
"content",
"body",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L183-L211 | train | 201,439 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream._read_body_until_close | def _read_body_until_close(self, response, file):
'''Read the response until the connection closes.
Coroutine.
'''
_logger.debug('Reading body until close.')
file_is_async = hasattr(file, 'drain')
while True:
data = yield from self._connection.read(self._read_size)
if not data:
break
self._data_event_dispatcher.notify_read(data)
content_data = self._decompress_data(data)
if file:
file.write(content_data)
if file_is_async:
yield from file.drain()
content_data = self._flush_decompressor()
if file:
file.write(content_data)
if file_is_async:
yield from file.drain() | python | def _read_body_until_close(self, response, file):
'''Read the response until the connection closes.
Coroutine.
'''
_logger.debug('Reading body until close.')
file_is_async = hasattr(file, 'drain')
while True:
data = yield from self._connection.read(self._read_size)
if not data:
break
self._data_event_dispatcher.notify_read(data)
content_data = self._decompress_data(data)
if file:
file.write(content_data)
if file_is_async:
yield from file.drain()
content_data = self._flush_decompressor()
if file:
file.write(content_data)
if file_is_async:
yield from file.drain() | [
"def",
"_read_body_until_close",
"(",
"self",
",",
"response",
",",
"file",
")",
":",
"_logger",
".",
"debug",
"(",
"'Reading body until close.'",
")",
"file_is_async",
"=",
"hasattr",
"(",
"file",
",",
"'drain'",
")",
"while",
"True",
":",
"data",
"=",
"yie... | Read the response until the connection closes.
Coroutine. | [
"Read",
"the",
"response",
"until",
"the",
"connection",
"closes",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L214-L245 | train | 201,440 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream._read_body_by_length | def _read_body_by_length(self, response, file):
'''Read the connection specified by a length.
Coroutine.
'''
_logger.debug('Reading body by length.')
file_is_async = hasattr(file, 'drain')
try:
body_size = int(response.fields['Content-Length'])
if body_size < 0:
raise ValueError('Content length cannot be negative.')
except ValueError as error:
_logger.warning(__(
_('Invalid content length: {error}'), error=error
))
yield from self._read_body_until_close(response, file)
return
bytes_left = body_size
while bytes_left > 0:
data = yield from self._connection.read(self._read_size)
if not data:
break
bytes_left -= len(data)
if bytes_left < 0:
data = data[:bytes_left]
_logger.warning(_('Content overrun.'))
self.close()
self._data_event_dispatcher.notify_read(data)
content_data = self._decompress_data(data)
if file:
file.write(content_data)
if file_is_async:
yield from file.drain()
if bytes_left > 0:
raise NetworkError('Connection closed.')
content_data = self._flush_decompressor()
if file and content_data:
file.write(content_data)
if file_is_async:
yield from file.drain() | python | def _read_body_by_length(self, response, file):
'''Read the connection specified by a length.
Coroutine.
'''
_logger.debug('Reading body by length.')
file_is_async = hasattr(file, 'drain')
try:
body_size = int(response.fields['Content-Length'])
if body_size < 0:
raise ValueError('Content length cannot be negative.')
except ValueError as error:
_logger.warning(__(
_('Invalid content length: {error}'), error=error
))
yield from self._read_body_until_close(response, file)
return
bytes_left = body_size
while bytes_left > 0:
data = yield from self._connection.read(self._read_size)
if not data:
break
bytes_left -= len(data)
if bytes_left < 0:
data = data[:bytes_left]
_logger.warning(_('Content overrun.'))
self.close()
self._data_event_dispatcher.notify_read(data)
content_data = self._decompress_data(data)
if file:
file.write(content_data)
if file_is_async:
yield from file.drain()
if bytes_left > 0:
raise NetworkError('Connection closed.')
content_data = self._flush_decompressor()
if file and content_data:
file.write(content_data)
if file_is_async:
yield from file.drain() | [
"def",
"_read_body_by_length",
"(",
"self",
",",
"response",
",",
"file",
")",
":",
"_logger",
".",
"debug",
"(",
"'Reading body by length.'",
")",
"file_is_async",
"=",
"hasattr",
"(",
"file",
",",
"'drain'",
")",
"try",
":",
"body_size",
"=",
"int",
"(",
... | Read the connection specified by a length.
Coroutine. | [
"Read",
"the",
"connection",
"specified",
"by",
"a",
"length",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L248-L306 | train | 201,441 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream._read_body_by_chunk | def _read_body_by_chunk(self, response, file, raw=False):
'''Read the connection using chunked transfer encoding.
Coroutine.
'''
reader = ChunkedTransferReader(self._connection)
file_is_async = hasattr(file, 'drain')
while True:
chunk_size, data = yield from reader.read_chunk_header()
self._data_event_dispatcher.notify_read(data)
if raw:
file.write(data)
if not chunk_size:
break
while True:
content, data = yield from reader.read_chunk_body()
self._data_event_dispatcher.notify_read(data)
if not content:
if raw:
file.write(data)
break
content = self._decompress_data(content)
if file:
file.write(content)
if file_is_async:
yield from file.drain()
content = self._flush_decompressor()
if file:
file.write(content)
if file_is_async:
yield from file.drain()
trailer_data = yield from reader.read_trailer()
self._data_event_dispatcher.notify_read(trailer_data)
if file and raw:
file.write(trailer_data)
if file_is_async:
yield from file.drain()
response.fields.parse(trailer_data) | python | def _read_body_by_chunk(self, response, file, raw=False):
'''Read the connection using chunked transfer encoding.
Coroutine.
'''
reader = ChunkedTransferReader(self._connection)
file_is_async = hasattr(file, 'drain')
while True:
chunk_size, data = yield from reader.read_chunk_header()
self._data_event_dispatcher.notify_read(data)
if raw:
file.write(data)
if not chunk_size:
break
while True:
content, data = yield from reader.read_chunk_body()
self._data_event_dispatcher.notify_read(data)
if not content:
if raw:
file.write(data)
break
content = self._decompress_data(content)
if file:
file.write(content)
if file_is_async:
yield from file.drain()
content = self._flush_decompressor()
if file:
file.write(content)
if file_is_async:
yield from file.drain()
trailer_data = yield from reader.read_trailer()
self._data_event_dispatcher.notify_read(trailer_data)
if file and raw:
file.write(trailer_data)
if file_is_async:
yield from file.drain()
response.fields.parse(trailer_data) | [
"def",
"_read_body_by_chunk",
"(",
"self",
",",
"response",
",",
"file",
",",
"raw",
"=",
"False",
")",
":",
"reader",
"=",
"ChunkedTransferReader",
"(",
"self",
".",
"_connection",
")",
"file_is_async",
"=",
"hasattr",
"(",
"file",
",",
"'drain'",
")",
"w... | Read the connection using chunked transfer encoding.
Coroutine. | [
"Read",
"the",
"connection",
"using",
"chunked",
"transfer",
"encoding",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L309-L365 | train | 201,442 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream.get_read_strategy | def get_read_strategy(cls, response):
'''Return the appropriate algorithm of reading response.
Returns:
str: ``chunked``, ``length``, ``close``.
'''
chunked_match = re.match(
r'chunked($|;)',
response.fields.get('Transfer-Encoding', '')
)
if chunked_match:
return 'chunked'
elif 'Content-Length' in response.fields:
return 'length'
else:
return 'close' | python | def get_read_strategy(cls, response):
'''Return the appropriate algorithm of reading response.
Returns:
str: ``chunked``, ``length``, ``close``.
'''
chunked_match = re.match(
r'chunked($|;)',
response.fields.get('Transfer-Encoding', '')
)
if chunked_match:
return 'chunked'
elif 'Content-Length' in response.fields:
return 'length'
else:
return 'close' | [
"def",
"get_read_strategy",
"(",
"cls",
",",
"response",
")",
":",
"chunked_match",
"=",
"re",
".",
"match",
"(",
"r'chunked($|;)'",
",",
"response",
".",
"fields",
".",
"get",
"(",
"'Transfer-Encoding'",
",",
"''",
")",
")",
"if",
"chunked_match",
":",
"r... | Return the appropriate algorithm of reading response.
Returns:
str: ``chunked``, ``length``, ``close``. | [
"Return",
"the",
"appropriate",
"algorithm",
"of",
"reading",
"response",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L368-L384 | train | 201,443 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream._setup_decompressor | def _setup_decompressor(self, response):
'''Set up the content encoding decompressor.'''
encoding = response.fields.get('Content-Encoding', '').lower()
if encoding == 'gzip':
self._decompressor = wpull.decompression.GzipDecompressor()
elif encoding == 'deflate':
self._decompressor = wpull.decompression.DeflateDecompressor()
else:
self._decompressor = None | python | def _setup_decompressor(self, response):
'''Set up the content encoding decompressor.'''
encoding = response.fields.get('Content-Encoding', '').lower()
if encoding == 'gzip':
self._decompressor = wpull.decompression.GzipDecompressor()
elif encoding == 'deflate':
self._decompressor = wpull.decompression.DeflateDecompressor()
else:
self._decompressor = None | [
"def",
"_setup_decompressor",
"(",
"self",
",",
"response",
")",
":",
"encoding",
"=",
"response",
".",
"fields",
".",
"get",
"(",
"'Content-Encoding'",
",",
"''",
")",
".",
"lower",
"(",
")",
"if",
"encoding",
"==",
"'gzip'",
":",
"self",
".",
"_decompr... | Set up the content encoding decompressor. | [
"Set",
"up",
"the",
"content",
"encoding",
"decompressor",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L386-L395 | train | 201,444 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream._decompress_data | def _decompress_data(self, data):
'''Decompress the given data and return the uncompressed data.'''
if self._decompressor:
try:
return self._decompressor.decompress(data)
except zlib.error as error:
raise ProtocolError(
'zlib error: {0}.'.format(error)
) from error
else:
return data | python | def _decompress_data(self, data):
'''Decompress the given data and return the uncompressed data.'''
if self._decompressor:
try:
return self._decompressor.decompress(data)
except zlib.error as error:
raise ProtocolError(
'zlib error: {0}.'.format(error)
) from error
else:
return data | [
"def",
"_decompress_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"_decompressor",
":",
"try",
":",
"return",
"self",
".",
"_decompressor",
".",
"decompress",
"(",
"data",
")",
"except",
"zlib",
".",
"error",
"as",
"error",
":",
"raise",
... | Decompress the given data and return the uncompressed data. | [
"Decompress",
"the",
"given",
"data",
"and",
"return",
"the",
"uncompressed",
"data",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L397-L407 | train | 201,445 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | Stream._flush_decompressor | def _flush_decompressor(self):
'''Return any data left in the decompressor.'''
if self._decompressor:
try:
return self._decompressor.flush()
except zlib.error as error:
raise ProtocolError(
'zlib flush error: {0}.'.format(error)
) from error
else:
return b'' | python | def _flush_decompressor(self):
'''Return any data left in the decompressor.'''
if self._decompressor:
try:
return self._decompressor.flush()
except zlib.error as error:
raise ProtocolError(
'zlib flush error: {0}.'.format(error)
) from error
else:
return b'' | [
"def",
"_flush_decompressor",
"(",
"self",
")",
":",
"if",
"self",
".",
"_decompressor",
":",
"try",
":",
"return",
"self",
".",
"_decompressor",
".",
"flush",
"(",
")",
"except",
"zlib",
".",
"error",
"as",
"error",
":",
"raise",
"ProtocolError",
"(",
"... | Return any data left in the decompressor. | [
"Return",
"any",
"data",
"left",
"in",
"the",
"decompressor",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L409-L419 | train | 201,446 |
ArchiveTeam/wpull | wpull/decompression.py | gzip_uncompress | def gzip_uncompress(data, truncated=False):
'''Uncompress gzip data.
Args:
data (bytes): The gzip data.
truncated (bool): If True, the decompressor is not flushed.
This is a convenience function.
Returns:
bytes: The inflated data.
Raises:
zlib.error
'''
decompressor = SimpleGzipDecompressor()
inflated_data = decompressor.decompress(data)
if not truncated:
inflated_data += decompressor.flush()
return inflated_data | python | def gzip_uncompress(data, truncated=False):
'''Uncompress gzip data.
Args:
data (bytes): The gzip data.
truncated (bool): If True, the decompressor is not flushed.
This is a convenience function.
Returns:
bytes: The inflated data.
Raises:
zlib.error
'''
decompressor = SimpleGzipDecompressor()
inflated_data = decompressor.decompress(data)
if not truncated:
inflated_data += decompressor.flush()
return inflated_data | [
"def",
"gzip_uncompress",
"(",
"data",
",",
"truncated",
"=",
"False",
")",
":",
"decompressor",
"=",
"SimpleGzipDecompressor",
"(",
")",
"inflated_data",
"=",
"decompressor",
".",
"decompress",
"(",
"data",
")",
"if",
"not",
"truncated",
":",
"inflated_data",
... | Uncompress gzip data.
Args:
data (bytes): The gzip data.
truncated (bool): If True, the decompressor is not flushed.
This is a convenience function.
Returns:
bytes: The inflated data.
Raises:
zlib.error | [
"Uncompress",
"gzip",
"data",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/decompression.py#L102-L123 | train | 201,447 |
ArchiveTeam/wpull | wpull/pipeline/session.py | ItemSession.set_status | def set_status(self, status: Status, increment_try_count: bool=True,
filename: str=None):
'''Mark the item with the given status.
Args:
status: a value from :class:`Status`.
increment_try_count: if True, increment the ``try_count``
value
'''
url = self.url_record.url
assert not self._try_count_incremented, (url, status)
if increment_try_count:
self._try_count_incremented = True
_logger.debug(__('Marking URL {0} status {1}.', url, status))
url_result = URLResult()
url_result.filename = filename
self.app_session.factory['URLTable'].check_in(
url,
status,
increment_try_count=increment_try_count,
url_result=url_result,
)
self._processed = True | python | def set_status(self, status: Status, increment_try_count: bool=True,
filename: str=None):
'''Mark the item with the given status.
Args:
status: a value from :class:`Status`.
increment_try_count: if True, increment the ``try_count``
value
'''
url = self.url_record.url
assert not self._try_count_incremented, (url, status)
if increment_try_count:
self._try_count_incremented = True
_logger.debug(__('Marking URL {0} status {1}.', url, status))
url_result = URLResult()
url_result.filename = filename
self.app_session.factory['URLTable'].check_in(
url,
status,
increment_try_count=increment_try_count,
url_result=url_result,
)
self._processed = True | [
"def",
"set_status",
"(",
"self",
",",
"status",
":",
"Status",
",",
"increment_try_count",
":",
"bool",
"=",
"True",
",",
"filename",
":",
"str",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"url_record",
".",
"url",
"assert",
"not",
"self",
".",
... | Mark the item with the given status.
Args:
status: a value from :class:`Status`.
increment_try_count: if True, increment the ``try_count``
value | [
"Mark",
"the",
"item",
"with",
"the",
"given",
"status",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/session.py#L65-L92 | train | 201,448 |
ArchiveTeam/wpull | wpull/pipeline/session.py | ItemSession.add_child_url | def add_child_url(self, url: str, inline: bool=False,
link_type: Optional[LinkType]=None,
post_data: Optional[str]=None,
level: Optional[int]=None,
replace: bool=False):
'''Add links scraped from the document with automatic values.
Args:
url: A full URL. (It can't be a relative path.)
inline: Whether the URL is an embedded object.
link_type: Expected link type.
post_data: URL encoded form data. The request will be made using
POST. (Don't use this to upload files.)
level: The child depth of this URL.
replace: Whether to replace the existing entry in the database
table so it will be redownloaded again.
This function provides values automatically for:
* ``inline``
* ``level``
* ``parent``: The referrering page.
* ``root``
See also :meth:`add_url`.
'''
url_properties = URLProperties()
url_properties.level = self.url_record.level + 1 if level is None else level
url_properties.inline_level = (self.url_record.inline_level or 0) + 1 if inline else None
url_properties.parent_url = self.url_record.url
url_properties.root_url = self.url_record.root_url or self.url_record.url
url_properties.link_type = link_type
url_data = URLData()
url_data.post_data = post_data
if replace:
self.app_session.factory['URLTable'].remove_many([url])
self.add_url(url, url_properties, url_data) | python | def add_child_url(self, url: str, inline: bool=False,
link_type: Optional[LinkType]=None,
post_data: Optional[str]=None,
level: Optional[int]=None,
replace: bool=False):
'''Add links scraped from the document with automatic values.
Args:
url: A full URL. (It can't be a relative path.)
inline: Whether the URL is an embedded object.
link_type: Expected link type.
post_data: URL encoded form data. The request will be made using
POST. (Don't use this to upload files.)
level: The child depth of this URL.
replace: Whether to replace the existing entry in the database
table so it will be redownloaded again.
This function provides values automatically for:
* ``inline``
* ``level``
* ``parent``: The referrering page.
* ``root``
See also :meth:`add_url`.
'''
url_properties = URLProperties()
url_properties.level = self.url_record.level + 1 if level is None else level
url_properties.inline_level = (self.url_record.inline_level or 0) + 1 if inline else None
url_properties.parent_url = self.url_record.url
url_properties.root_url = self.url_record.root_url or self.url_record.url
url_properties.link_type = link_type
url_data = URLData()
url_data.post_data = post_data
if replace:
self.app_session.factory['URLTable'].remove_many([url])
self.add_url(url, url_properties, url_data) | [
"def",
"add_child_url",
"(",
"self",
",",
"url",
":",
"str",
",",
"inline",
":",
"bool",
"=",
"False",
",",
"link_type",
":",
"Optional",
"[",
"LinkType",
"]",
"=",
"None",
",",
"post_data",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"level"... | Add links scraped from the document with automatic values.
Args:
url: A full URL. (It can't be a relative path.)
inline: Whether the URL is an embedded object.
link_type: Expected link type.
post_data: URL encoded form data. The request will be made using
POST. (Don't use this to upload files.)
level: The child depth of this URL.
replace: Whether to replace the existing entry in the database
table so it will be redownloaded again.
This function provides values automatically for:
* ``inline``
* ``level``
* ``parent``: The referrering page.
* ``root``
See also :meth:`add_url`. | [
"Add",
"links",
"scraped",
"from",
"the",
"document",
"with",
"automatic",
"values",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/session.py#L110-L148 | train | 201,449 |
ArchiveTeam/wpull | wpull/pipeline/session.py | ItemSession.child_url_record | def child_url_record(self, url: str, inline: bool=False,
link_type: Optional[LinkType]=None,
post_data: Optional[str]=None,
level: Optional[int]=None):
'''Return a child URLRecord.
This function is useful for testing filters before adding to table.
'''
url_record = URLRecord()
url_record.url = url
url_record.status = Status.todo
url_record.try_count = 0
url_record.level = self.url_record.level + 1 if level is None else level
url_record.root_url = self.url_record.root_url or self.url_record.url
url_record.parent_url = self.url_record.url
url_record.inline_level = (self.url_record.inline_level or 0) + 1 if inline else 0
url_record.link_type = link_type
url_record.post_data = post_data
return url_record | python | def child_url_record(self, url: str, inline: bool=False,
link_type: Optional[LinkType]=None,
post_data: Optional[str]=None,
level: Optional[int]=None):
'''Return a child URLRecord.
This function is useful for testing filters before adding to table.
'''
url_record = URLRecord()
url_record.url = url
url_record.status = Status.todo
url_record.try_count = 0
url_record.level = self.url_record.level + 1 if level is None else level
url_record.root_url = self.url_record.root_url or self.url_record.url
url_record.parent_url = self.url_record.url
url_record.inline_level = (self.url_record.inline_level or 0) + 1 if inline else 0
url_record.link_type = link_type
url_record.post_data = post_data
return url_record | [
"def",
"child_url_record",
"(",
"self",
",",
"url",
":",
"str",
",",
"inline",
":",
"bool",
"=",
"False",
",",
"link_type",
":",
"Optional",
"[",
"LinkType",
"]",
"=",
"None",
",",
"post_data",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"lev... | Return a child URLRecord.
This function is useful for testing filters before adding to table. | [
"Return",
"a",
"child",
"URLRecord",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/session.py#L150-L169 | train | 201,450 |
ArchiveTeam/wpull | wpull/document/util.py | get_heading_encoding | def get_heading_encoding(response):
'''Return the document encoding from a HTTP header.
Args:
response (Response): An instance of :class:`.http.Response`.
Returns:
``str``, ``None``: The codec name.
'''
encoding = wpull.protocol.http.util.parse_charset(
response.fields.get('content-type', ''))
if encoding:
return wpull.string.normalize_codec_name(encoding)
else:
return None | python | def get_heading_encoding(response):
'''Return the document encoding from a HTTP header.
Args:
response (Response): An instance of :class:`.http.Response`.
Returns:
``str``, ``None``: The codec name.
'''
encoding = wpull.protocol.http.util.parse_charset(
response.fields.get('content-type', ''))
if encoding:
return wpull.string.normalize_codec_name(encoding)
else:
return None | [
"def",
"get_heading_encoding",
"(",
"response",
")",
":",
"encoding",
"=",
"wpull",
".",
"protocol",
".",
"http",
".",
"util",
".",
"parse_charset",
"(",
"response",
".",
"fields",
".",
"get",
"(",
"'content-type'",
",",
"''",
")",
")",
"if",
"encoding",
... | Return the document encoding from a HTTP header.
Args:
response (Response): An instance of :class:`.http.Response`.
Returns:
``str``, ``None``: The codec name. | [
"Return",
"the",
"document",
"encoding",
"from",
"a",
"HTTP",
"header",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/util.py#L14-L29 | train | 201,451 |
ArchiveTeam/wpull | wpull/document/util.py | detect_response_encoding | def detect_response_encoding(response, is_html=False, peek=131072):
'''Return the likely encoding of the response document.
Args:
response (Response): An instance of :class:`.http.Response`.
is_html (bool): See :func:`.util.detect_encoding`.
peek (int): The maximum number of bytes of the document to be analyzed.
Returns:
``str``, ``None``: The codec name.
'''
encoding = get_heading_encoding(response)
encoding = wpull.string.detect_encoding(
wpull.util.peek_file(response.body, peek), encoding=encoding, is_html=is_html
)
_logger.debug(__('Got encoding: {0}', encoding))
return encoding | python | def detect_response_encoding(response, is_html=False, peek=131072):
'''Return the likely encoding of the response document.
Args:
response (Response): An instance of :class:`.http.Response`.
is_html (bool): See :func:`.util.detect_encoding`.
peek (int): The maximum number of bytes of the document to be analyzed.
Returns:
``str``, ``None``: The codec name.
'''
encoding = get_heading_encoding(response)
encoding = wpull.string.detect_encoding(
wpull.util.peek_file(response.body, peek), encoding=encoding, is_html=is_html
)
_logger.debug(__('Got encoding: {0}', encoding))
return encoding | [
"def",
"detect_response_encoding",
"(",
"response",
",",
"is_html",
"=",
"False",
",",
"peek",
"=",
"131072",
")",
":",
"encoding",
"=",
"get_heading_encoding",
"(",
"response",
")",
"encoding",
"=",
"wpull",
".",
"string",
".",
"detect_encoding",
"(",
"wpull"... | Return the likely encoding of the response document.
Args:
response (Response): An instance of :class:`.http.Response`.
is_html (bool): See :func:`.util.detect_encoding`.
peek (int): The maximum number of bytes of the document to be analyzed.
Returns:
``str``, ``None``: The codec name. | [
"Return",
"the",
"likely",
"encoding",
"of",
"the",
"response",
"document",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/util.py#L32-L51 | train | 201,452 |
ArchiveTeam/wpull | wpull/database/base.py | BaseURLTable.contains | def contains(self, url: str):
'''Return whether the URL is in the table.'''
try:
self.get_one(url)
except NotFound:
return False
else:
return True | python | def contains(self, url: str):
'''Return whether the URL is in the table.'''
try:
self.get_one(url)
except NotFound:
return False
else:
return True | [
"def",
"contains",
"(",
"self",
",",
"url",
":",
"str",
")",
":",
"try",
":",
"self",
".",
"get_one",
"(",
"url",
")",
"except",
"NotFound",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | Return whether the URL is in the table. | [
"Return",
"whether",
"the",
"URL",
"is",
"in",
"the",
"table",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/database/base.py#L44-L52 | train | 201,453 |
ArchiveTeam/wpull | wpull/database/base.py | BaseURLTable.add_one | def add_one(self, url: str,
url_properties: Optional[URLProperties]=None,
url_data: Optional[URLData]=None):
'''Add a single URL to the table.
Args:
url: The URL to be added
url_properties: Additional values to be saved
url_data: Additional data to be saved
'''
self.add_many([AddURLInfo(url, url_properties, url_data)]) | python | def add_one(self, url: str,
url_properties: Optional[URLProperties]=None,
url_data: Optional[URLData]=None):
'''Add a single URL to the table.
Args:
url: The URL to be added
url_properties: Additional values to be saved
url_data: Additional data to be saved
'''
self.add_many([AddURLInfo(url, url_properties, url_data)]) | [
"def",
"add_one",
"(",
"self",
",",
"url",
":",
"str",
",",
"url_properties",
":",
"Optional",
"[",
"URLProperties",
"]",
"=",
"None",
",",
"url_data",
":",
"Optional",
"[",
"URLData",
"]",
"=",
"None",
")",
":",
"self",
".",
"add_many",
"(",
"[",
"A... | Add a single URL to the table.
Args:
url: The URL to be added
url_properties: Additional values to be saved
url_data: Additional data to be saved | [
"Add",
"a",
"single",
"URL",
"to",
"the",
"table",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/database/base.py#L69-L79 | train | 201,454 |
ArchiveTeam/wpull | wpull/regexstream.py | RegexStream.stream | def stream(self):
'''Iterate the file stream.
Returns:
iterator: Each item is a tuple:
1. None, regex match
2. str
'''
chunk_a = None
chunk_b = None
chunk_a_index = 0
chunk_b_index = 0
search_start_index = 0
while True:
chunk_a = chunk_b
chunk_a_index = chunk_b_index
chunk_b = self._file.read(self._read_size)
if chunk_a is None:
continue
chunk_b_index = chunk_a_index + len(chunk_a)
if not chunk_a:
break
current_chunk = chunk_a + chunk_b[:self._overlap_size]
offset_end = len(chunk_a) + self._overlap_size
while True:
offset_start = search_start_index - chunk_a_index
match = self._pattern.search(
current_chunk, offset_start, offset_end)
if not match:
unmatched_part = chunk_a[offset_start:]
if unmatched_part:
yield (None, unmatched_part)
search_start_index += len(unmatched_part)
break
start_index, end_index = match.span(match.lastindex)
unmatched_part = current_chunk[offset_start:start_index]
if unmatched_part:
yield (None, unmatched_part)
yield (match, match.group(match.lastindex))
search_start_index += len(unmatched_part) + \
len(match.group(match.lastindex)) | python | def stream(self):
'''Iterate the file stream.
Returns:
iterator: Each item is a tuple:
1. None, regex match
2. str
'''
chunk_a = None
chunk_b = None
chunk_a_index = 0
chunk_b_index = 0
search_start_index = 0
while True:
chunk_a = chunk_b
chunk_a_index = chunk_b_index
chunk_b = self._file.read(self._read_size)
if chunk_a is None:
continue
chunk_b_index = chunk_a_index + len(chunk_a)
if not chunk_a:
break
current_chunk = chunk_a + chunk_b[:self._overlap_size]
offset_end = len(chunk_a) + self._overlap_size
while True:
offset_start = search_start_index - chunk_a_index
match = self._pattern.search(
current_chunk, offset_start, offset_end)
if not match:
unmatched_part = chunk_a[offset_start:]
if unmatched_part:
yield (None, unmatched_part)
search_start_index += len(unmatched_part)
break
start_index, end_index = match.span(match.lastindex)
unmatched_part = current_chunk[offset_start:start_index]
if unmatched_part:
yield (None, unmatched_part)
yield (match, match.group(match.lastindex))
search_start_index += len(unmatched_part) + \
len(match.group(match.lastindex)) | [
"def",
"stream",
"(",
"self",
")",
":",
"chunk_a",
"=",
"None",
"chunk_b",
"=",
"None",
"chunk_a_index",
"=",
"0",
"chunk_b_index",
"=",
"0",
"search_start_index",
"=",
"0",
"while",
"True",
":",
"chunk_a",
"=",
"chunk_b",
"chunk_a_index",
"=",
"chunk_b_inde... | Iterate the file stream.
Returns:
iterator: Each item is a tuple:
1. None, regex match
2. str | [
"Iterate",
"the",
"file",
"stream",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/regexstream.py#L21-L77 | train | 201,455 |
ArchiveTeam/wpull | wpull/observer.py | Observer.notify | def notify(self, *args, **kwargs):
'''Call all the callback handlers with given arguments.'''
for handler in tuple(self.handlers):
handler(*args, **kwargs) | python | def notify(self, *args, **kwargs):
'''Call all the callback handlers with given arguments.'''
for handler in tuple(self.handlers):
handler(*args, **kwargs) | [
"def",
"notify",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"handler",
"in",
"tuple",
"(",
"self",
".",
"handlers",
")",
":",
"handler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Call all the callback handlers with given arguments. | [
"Call",
"all",
"the",
"callback",
"handlers",
"with",
"given",
"arguments",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/observer.py#L27-L30 | train | 201,456 |
ArchiveTeam/wpull | wpull/application/factory.py | Factory.new | def new(self, name, *args, **kwargs):
'''Create an instance.
Args:
name (str): The name of the class
args: The arguments to pass to the class.
kwargs: The keyword arguments to pass to the class.
Returns:
instance
'''
if name in self._instance_map:
raise ValueError('Instance {0} is already initialized'
.format(name))
instance = self._class_map[name](*args, **kwargs)
self._instance_map[name] = instance
return instance | python | def new(self, name, *args, **kwargs):
'''Create an instance.
Args:
name (str): The name of the class
args: The arguments to pass to the class.
kwargs: The keyword arguments to pass to the class.
Returns:
instance
'''
if name in self._instance_map:
raise ValueError('Instance {0} is already initialized'
.format(name))
instance = self._class_map[name](*args, **kwargs)
self._instance_map[name] = instance
return instance | [
"def",
"new",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"in",
"self",
".",
"_instance_map",
":",
"raise",
"ValueError",
"(",
"'Instance {0} is already initialized'",
".",
"format",
"(",
"name",
")",
")",... | Create an instance.
Args:
name (str): The name of the class
args: The arguments to pass to the class.
kwargs: The keyword arguments to pass to the class.
Returns:
instance | [
"Create",
"an",
"instance",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/factory.py#L45-L62 | train | 201,457 |
ArchiveTeam/wpull | wpull/application/factory.py | Factory.is_all_initialized | def is_all_initialized(self):
'''Return whether all the instances have been initialized.
Returns:
bool
'''
return frozenset(self._class_map.keys()) == \
frozenset(self._instance_map.keys()) | python | def is_all_initialized(self):
'''Return whether all the instances have been initialized.
Returns:
bool
'''
return frozenset(self._class_map.keys()) == \
frozenset(self._instance_map.keys()) | [
"def",
"is_all_initialized",
"(",
"self",
")",
":",
"return",
"frozenset",
"(",
"self",
".",
"_class_map",
".",
"keys",
"(",
")",
")",
"==",
"frozenset",
"(",
"self",
".",
"_instance_map",
".",
"keys",
"(",
")",
")"
] | Return whether all the instances have been initialized.
Returns:
bool | [
"Return",
"whether",
"all",
"the",
"instances",
"have",
"been",
"initialized",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/factory.py#L64-L71 | train | 201,458 |
ArchiveTeam/wpull | wpull/namevalue.py | normalize_name | def normalize_name(name, overrides=None):
'''Normalize the key name to title case.
For example, ``normalize_name('content-id')`` will become ``Content-Id``
Args:
name (str): The name to normalize.
overrides (set, sequence): A set or sequence containing keys that
should be cased to themselves. For example, passing
``set('WARC-Type')`` will normalize any key named "warc-type" to
``WARC-Type`` instead of the default ``Warc-Type``.
Returns:
str
'''
normalized_name = name.title()
if overrides:
override_map = dict([(name.title(), name) for name in overrides])
return override_map.get(normalized_name, normalized_name)
else:
return normalized_name | python | def normalize_name(name, overrides=None):
'''Normalize the key name to title case.
For example, ``normalize_name('content-id')`` will become ``Content-Id``
Args:
name (str): The name to normalize.
overrides (set, sequence): A set or sequence containing keys that
should be cased to themselves. For example, passing
``set('WARC-Type')`` will normalize any key named "warc-type" to
``WARC-Type`` instead of the default ``Warc-Type``.
Returns:
str
'''
normalized_name = name.title()
if overrides:
override_map = dict([(name.title(), name) for name in overrides])
return override_map.get(normalized_name, normalized_name)
else:
return normalized_name | [
"def",
"normalize_name",
"(",
"name",
",",
"overrides",
"=",
"None",
")",
":",
"normalized_name",
"=",
"name",
".",
"title",
"(",
")",
"if",
"overrides",
":",
"override_map",
"=",
"dict",
"(",
"[",
"(",
"name",
".",
"title",
"(",
")",
",",
"name",
")... | Normalize the key name to title case.
For example, ``normalize_name('content-id')`` will become ``Content-Id``
Args:
name (str): The name to normalize.
overrides (set, sequence): A set or sequence containing keys that
should be cased to themselves. For example, passing
``set('WARC-Type')`` will normalize any key named "warc-type" to
``WARC-Type`` instead of the default ``Warc-Type``.
Returns:
str | [
"Normalize",
"the",
"key",
"name",
"to",
"title",
"case",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/namevalue.py#L131-L154 | train | 201,459 |
ArchiveTeam/wpull | wpull/namevalue.py | guess_line_ending | def guess_line_ending(string):
'''Return the most likely line delimiter from the string.'''
assert isinstance(string, str), 'Expect str. Got {}'.format(type(string))
crlf_count = string.count('\r\n')
lf_count = string.count('\n')
if crlf_count >= lf_count:
return '\r\n'
else:
return '\n' | python | def guess_line_ending(string):
'''Return the most likely line delimiter from the string.'''
assert isinstance(string, str), 'Expect str. Got {}'.format(type(string))
crlf_count = string.count('\r\n')
lf_count = string.count('\n')
if crlf_count >= lf_count:
return '\r\n'
else:
return '\n' | [
"def",
"guess_line_ending",
"(",
"string",
")",
":",
"assert",
"isinstance",
"(",
"string",
",",
"str",
")",
",",
"'Expect str. Got {}'",
".",
"format",
"(",
"type",
"(",
"string",
")",
")",
"crlf_count",
"=",
"string",
".",
"count",
"(",
"'\\r\\n'",
")",
... | Return the most likely line delimiter from the string. | [
"Return",
"the",
"most",
"likely",
"line",
"delimiter",
"from",
"the",
"string",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/namevalue.py#L157-L166 | train | 201,460 |
ArchiveTeam/wpull | wpull/namevalue.py | unfold_lines | def unfold_lines(string):
'''Join lines that are wrapped.
Any line that starts with a space or tab is joined to the previous
line.
'''
assert isinstance(string, str), 'Expect str. Got {}'.format(type(string))
lines = string.splitlines()
line_buffer = io.StringIO()
for line_number in range(len(lines)):
line = lines[line_number]
if line and line[0:1] in (' ', '\t'):
line_buffer.write(' ')
elif line_number != 0:
line_buffer.write('\r\n')
line_buffer.write(line.strip())
line_buffer.write('\r\n')
return line_buffer.getvalue() | python | def unfold_lines(string):
'''Join lines that are wrapped.
Any line that starts with a space or tab is joined to the previous
line.
'''
assert isinstance(string, str), 'Expect str. Got {}'.format(type(string))
lines = string.splitlines()
line_buffer = io.StringIO()
for line_number in range(len(lines)):
line = lines[line_number]
if line and line[0:1] in (' ', '\t'):
line_buffer.write(' ')
elif line_number != 0:
line_buffer.write('\r\n')
line_buffer.write(line.strip())
line_buffer.write('\r\n')
return line_buffer.getvalue() | [
"def",
"unfold_lines",
"(",
"string",
")",
":",
"assert",
"isinstance",
"(",
"string",
",",
"str",
")",
",",
"'Expect str. Got {}'",
".",
"format",
"(",
"type",
"(",
"string",
")",
")",
"lines",
"=",
"string",
".",
"splitlines",
"(",
")",
"line_buffer",
... | Join lines that are wrapped.
Any line that starts with a space or tab is joined to the previous
line. | [
"Join",
"lines",
"that",
"are",
"wrapped",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/namevalue.py#L169-L189 | train | 201,461 |
ArchiveTeam/wpull | wpull/namevalue.py | NameValueRecord.parse | def parse(self, string, strict=True):
'''Parse the string or bytes.
Args:
strict (bool): If True, errors will not be ignored
Raises:
:class:`ValueError` if the record is malformed.
'''
if isinstance(string, bytes):
errors = 'strict' if strict else 'replace'
string = string.decode(self.encoding, errors=errors)
if not self.raw:
self.raw = string
else:
self.raw += string
lines = unfold_lines(string).splitlines()
for line in lines:
if line:
if ':' not in line:
if strict:
raise ValueError('Field missing colon.')
else:
continue
name, value = line.split(':', 1)
name = name.strip()
value = value.strip()
self.add(name, value) | python | def parse(self, string, strict=True):
'''Parse the string or bytes.
Args:
strict (bool): If True, errors will not be ignored
Raises:
:class:`ValueError` if the record is malformed.
'''
if isinstance(string, bytes):
errors = 'strict' if strict else 'replace'
string = string.decode(self.encoding, errors=errors)
if not self.raw:
self.raw = string
else:
self.raw += string
lines = unfold_lines(string).splitlines()
for line in lines:
if line:
if ':' not in line:
if strict:
raise ValueError('Field missing colon.')
else:
continue
name, value = line.split(':', 1)
name = name.strip()
value = value.strip()
self.add(name, value) | [
"def",
"parse",
"(",
"self",
",",
"string",
",",
"strict",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"bytes",
")",
":",
"errors",
"=",
"'strict'",
"if",
"strict",
"else",
"'replace'",
"string",
"=",
"string",
".",
"decode",
"(",
... | Parse the string or bytes.
Args:
strict (bool): If True, errors will not be ignored
Raises:
:class:`ValueError` if the record is malformed. | [
"Parse",
"the",
"string",
"or",
"bytes",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/namevalue.py#L29-L59 | train | 201,462 |
ArchiveTeam/wpull | wpull/namevalue.py | NameValueRecord.add | def add(self, name, value):
'''Append the name-value pair to the record.'''
normalized_name = normalize_name(name, self._normalize_overrides)
self._map[normalized_name].append(value) | python | def add(self, name, value):
'''Append the name-value pair to the record.'''
normalized_name = normalize_name(name, self._normalize_overrides)
self._map[normalized_name].append(value) | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"normalized_name",
"=",
"normalize_name",
"(",
"name",
",",
"self",
".",
"_normalize_overrides",
")",
"self",
".",
"_map",
"[",
"normalized_name",
"]",
".",
"append",
"(",
"value",
")"
] | Append the name-value pair to the record. | [
"Append",
"the",
"name",
"-",
"value",
"pair",
"to",
"the",
"record",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/namevalue.py#L83-L86 | train | 201,463 |
ArchiveTeam/wpull | wpull/namevalue.py | NameValueRecord.get_list | def get_list(self, name):
'''Return all the values for given name.'''
normalized_name = normalize_name(name, self._normalize_overrides)
return self._map[normalized_name] | python | def get_list(self, name):
'''Return all the values for given name.'''
normalized_name = normalize_name(name, self._normalize_overrides)
return self._map[normalized_name] | [
"def",
"get_list",
"(",
"self",
",",
"name",
")",
":",
"normalized_name",
"=",
"normalize_name",
"(",
"name",
",",
"self",
".",
"_normalize_overrides",
")",
"return",
"self",
".",
"_map",
"[",
"normalized_name",
"]"
] | Return all the values for given name. | [
"Return",
"all",
"the",
"values",
"for",
"given",
"name",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/namevalue.py#L88-L91 | train | 201,464 |
ArchiveTeam/wpull | wpull/namevalue.py | NameValueRecord.get_all | def get_all(self):
'''Return an iterator of name-value pairs.'''
for name, values in self._map.items():
for value in values:
yield (name, value) | python | def get_all(self):
'''Return an iterator of name-value pairs.'''
for name, values in self._map.items():
for value in values:
yield (name, value) | [
"def",
"get_all",
"(",
"self",
")",
":",
"for",
"name",
",",
"values",
"in",
"self",
".",
"_map",
".",
"items",
"(",
")",
":",
"for",
"value",
"in",
"values",
":",
"yield",
"(",
"name",
",",
"value",
")"
] | Return an iterator of name-value pairs. | [
"Return",
"an",
"iterator",
"of",
"name",
"-",
"value",
"pairs",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/namevalue.py#L93-L97 | train | 201,465 |
ArchiveTeam/wpull | wpull/namevalue.py | NameValueRecord.to_str | def to_str(self):
'''Convert to string.'''
pairs = []
for name, value in self.get_all():
if value and self._wrap_width:
pairs.append('{0}:{1}'.format(
name,
'\r\n'.join(textwrap.wrap(
value, width=self._wrap_width,
drop_whitespace=False, initial_indent=' ',
subsequent_indent=' '
))
))
elif value:
pairs.append('{0}: {1}'.format(name, value))
else:
pairs.append('{0}:'.format(name))
pairs.append('')
return '\r\n'.join(pairs) | python | def to_str(self):
'''Convert to string.'''
pairs = []
for name, value in self.get_all():
if value and self._wrap_width:
pairs.append('{0}:{1}'.format(
name,
'\r\n'.join(textwrap.wrap(
value, width=self._wrap_width,
drop_whitespace=False, initial_indent=' ',
subsequent_indent=' '
))
))
elif value:
pairs.append('{0}: {1}'.format(name, value))
else:
pairs.append('{0}:'.format(name))
pairs.append('')
return '\r\n'.join(pairs) | [
"def",
"to_str",
"(",
"self",
")",
":",
"pairs",
"=",
"[",
"]",
"for",
"name",
",",
"value",
"in",
"self",
".",
"get_all",
"(",
")",
":",
"if",
"value",
"and",
"self",
".",
"_wrap_width",
":",
"pairs",
".",
"append",
"(",
"'{0}:{1}'",
".",
"format"... | Convert to string. | [
"Convert",
"to",
"string",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/namevalue.py#L102-L121 | train | 201,466 |
ArchiveTeam/wpull | wpull/namevalue.py | NameValueRecord.to_bytes | def to_bytes(self, errors='strict'):
'''Convert to bytes.'''
return str(self).encode(self.encoding, errors=errors) | python | def to_bytes(self, errors='strict'):
'''Convert to bytes.'''
return str(self).encode(self.encoding, errors=errors) | [
"def",
"to_bytes",
"(",
"self",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"str",
"(",
"self",
")",
".",
"encode",
"(",
"self",
".",
"encoding",
",",
"errors",
"=",
"errors",
")"
] | Convert to bytes. | [
"Convert",
"to",
"bytes",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/namevalue.py#L126-L128 | train | 201,467 |
ArchiveTeam/wpull | wpull/protocol/abstract/client.py | BaseSession.recycle | def recycle(self):
'''Clean up and return connections back to the pool.
Connections should be kept alive if supported.
'''
for connection in self._connections:
self._connection_pool.no_wait_release(connection)
self._connections.clear() | python | def recycle(self):
'''Clean up and return connections back to the pool.
Connections should be kept alive if supported.
'''
for connection in self._connections:
self._connection_pool.no_wait_release(connection)
self._connections.clear() | [
"def",
"recycle",
"(",
"self",
")",
":",
"for",
"connection",
"in",
"self",
".",
"_connections",
":",
"self",
".",
"_connection_pool",
".",
"no_wait_release",
"(",
"connection",
")",
"self",
".",
"_connections",
".",
"clear",
"(",
")"
] | Clean up and return connections back to the pool.
Connections should be kept alive if supported. | [
"Clean",
"up",
"and",
"return",
"connections",
"back",
"to",
"the",
"pool",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/abstract/client.py#L61-L70 | train | 201,468 |
ArchiveTeam/wpull | wpull/protocol/abstract/client.py | BaseClient.session | def session(self) -> SessionT:
'''Return a new session.'''
session = self._session_class()(
connection_pool=self._connection_pool,
)
self.event_dispatcher.notify(self.ClientEvent.new_session, session)
return session | python | def session(self) -> SessionT:
'''Return a new session.'''
session = self._session_class()(
connection_pool=self._connection_pool,
)
self.event_dispatcher.notify(self.ClientEvent.new_session, session)
return session | [
"def",
"session",
"(",
"self",
")",
"->",
"SessionT",
":",
"session",
"=",
"self",
".",
"_session_class",
"(",
")",
"(",
"connection_pool",
"=",
"self",
".",
"_connection_pool",
",",
")",
"self",
".",
"event_dispatcher",
".",
"notify",
"(",
"self",
".",
... | Return a new session. | [
"Return",
"a",
"new",
"session",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/abstract/client.py#L127-L133 | train | 201,469 |
ArchiveTeam/wpull | wpull/cookie.py | DeFactoCookiePolicy.count_cookies | def count_cookies(self, domain):
'''Return the number of cookies for the given domain.'''
cookies = self.cookie_jar._cookies
if domain in cookies:
return sum(
[len(cookie) for cookie in cookies[domain].values()]
)
else:
return 0 | python | def count_cookies(self, domain):
'''Return the number of cookies for the given domain.'''
cookies = self.cookie_jar._cookies
if domain in cookies:
return sum(
[len(cookie) for cookie in cookies[domain].values()]
)
else:
return 0 | [
"def",
"count_cookies",
"(",
"self",
",",
"domain",
")",
":",
"cookies",
"=",
"self",
".",
"cookie_jar",
".",
"_cookies",
"if",
"domain",
"in",
"cookies",
":",
"return",
"sum",
"(",
"[",
"len",
"(",
"cookie",
")",
"for",
"cookie",
"in",
"cookies",
"[",... | Return the number of cookies for the given domain. | [
"Return",
"the",
"number",
"of",
"cookies",
"for",
"the",
"given",
"domain",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/cookie.py#L58-L67 | train | 201,470 |
ArchiveTeam/wpull | wpull/cookie.py | DeFactoCookiePolicy.cookie_length | def cookie_length(self, domain):
'''Return approximate length of all cookie key-values for a domain.'''
cookies = self.cookie_jar._cookies
if domain not in cookies:
return 0
length = 0
for path in cookies[domain]:
for name in cookies[domain][path]:
cookie = cookies[domain][path][name]
length += len(path) + len(name) + len(cookie.value or '')
return length | python | def cookie_length(self, domain):
'''Return approximate length of all cookie key-values for a domain.'''
cookies = self.cookie_jar._cookies
if domain not in cookies:
return 0
length = 0
for path in cookies[domain]:
for name in cookies[domain][path]:
cookie = cookies[domain][path][name]
length += len(path) + len(name) + len(cookie.value or '')
return length | [
"def",
"cookie_length",
"(",
"self",
",",
"domain",
")",
":",
"cookies",
"=",
"self",
".",
"cookie_jar",
".",
"_cookies",
"if",
"domain",
"not",
"in",
"cookies",
":",
"return",
"0",
"length",
"=",
"0",
"for",
"path",
"in",
"cookies",
"[",
"domain",
"]"... | Return approximate length of all cookie key-values for a domain. | [
"Return",
"approximate",
"length",
"of",
"all",
"cookie",
"key",
"-",
"values",
"for",
"a",
"domain",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/cookie.py#L69-L83 | train | 201,471 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/listing.py | guess_listing_type | def guess_listing_type(lines, threshold=100):
'''Guess the style of directory listing.
Returns:
str: ``unix``, ``msdos``, ``nlst``, ``unknown``.
'''
scores = {
'unix': 0,
'msdos': 0,
'nlst': 0,
}
for line in lines:
if not line:
continue
if re.search(r'---|r--|rw-|rwx', line):
scores['unix'] += 1
if '<DIR>' in line or re.search(r'^.{0,4}\d\d', line):
scores['msdos'] += 1
words = line.split(' ', 1)
if len(words) == 1:
scores['nlst'] += 1
if max(scores.values()) > threshold:
break
top = max(scores.items(), key=lambda item: item[1])
if top[1]:
return top[0]
else:
return 'unknown' | python | def guess_listing_type(lines, threshold=100):
'''Guess the style of directory listing.
Returns:
str: ``unix``, ``msdos``, ``nlst``, ``unknown``.
'''
scores = {
'unix': 0,
'msdos': 0,
'nlst': 0,
}
for line in lines:
if not line:
continue
if re.search(r'---|r--|rw-|rwx', line):
scores['unix'] += 1
if '<DIR>' in line or re.search(r'^.{0,4}\d\d', line):
scores['msdos'] += 1
words = line.split(' ', 1)
if len(words) == 1:
scores['nlst'] += 1
if max(scores.values()) > threshold:
break
top = max(scores.items(), key=lambda item: item[1])
if top[1]:
return top[0]
else:
return 'unknown' | [
"def",
"guess_listing_type",
"(",
"lines",
",",
"threshold",
"=",
"100",
")",
":",
"scores",
"=",
"{",
"'unix'",
":",
"0",
",",
"'msdos'",
":",
"0",
",",
"'nlst'",
":",
"0",
",",
"}",
"for",
"line",
"in",
"lines",
":",
"if",
"not",
"line",
":",
"... | Guess the style of directory listing.
Returns:
str: ``unix``, ``msdos``, ``nlst``, ``unknown``. | [
"Guess",
"the",
"style",
"of",
"directory",
"listing",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/listing.py#L165-L199 | train | 201,472 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/listing.py | parse_unix_perm | def parse_unix_perm(text):
'''Parse a Unix permission string and return integer value.'''
# Based on ftp-ls.c symperms
if len(text) != 9:
return 0
perms = 0
for triad_index in range(3):
string_index = triad_index * 3
perms <<= 3
if text[string_index] == 'r':
perms |= 1 << 2
if text[string_index + 1] == 'w':
perms |= 1 << 1
if text[string_index + 2] in 'xs':
perms |= 1
return perms | python | def parse_unix_perm(text):
'''Parse a Unix permission string and return integer value.'''
# Based on ftp-ls.c symperms
if len(text) != 9:
return 0
perms = 0
for triad_index in range(3):
string_index = triad_index * 3
perms <<= 3
if text[string_index] == 'r':
perms |= 1 << 2
if text[string_index + 1] == 'w':
perms |= 1 << 1
if text[string_index + 2] in 'xs':
perms |= 1
return perms | [
"def",
"parse_unix_perm",
"(",
"text",
")",
":",
"# Based on ftp-ls.c symperms",
"if",
"len",
"(",
"text",
")",
"!=",
"9",
":",
"return",
"0",
"perms",
"=",
"0",
"for",
"triad_index",
"in",
"range",
"(",
"3",
")",
":",
"string_index",
"=",
"triad_index",
... | Parse a Unix permission string and return integer value. | [
"Parse",
"a",
"Unix",
"permission",
"string",
"and",
"return",
"integer",
"value",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/listing.py#L211-L232 | train | 201,473 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/listing.py | LineParser.parse | def parse(self, lines):
'''Parse the lines.'''
if self.type == 'msdos':
return self.parse_msdos(lines)
elif self.type == 'unix':
return self.parse_unix(lines)
elif self.type == 'nlst':
return self.parse_nlst(lines)
else:
raise UnknownListingError('Unsupported listing type.') | python | def parse(self, lines):
'''Parse the lines.'''
if self.type == 'msdos':
return self.parse_msdos(lines)
elif self.type == 'unix':
return self.parse_unix(lines)
elif self.type == 'nlst':
return self.parse_nlst(lines)
else:
raise UnknownListingError('Unsupported listing type.') | [
"def",
"parse",
"(",
"self",
",",
"lines",
")",
":",
"if",
"self",
".",
"type",
"==",
"'msdos'",
":",
"return",
"self",
".",
"parse_msdos",
"(",
"lines",
")",
"elif",
"self",
".",
"type",
"==",
"'unix'",
":",
"return",
"self",
".",
"parse_unix",
"(",... | Parse the lines. | [
"Parse",
"the",
"lines",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/listing.py#L57-L66 | train | 201,474 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/listing.py | LineParser.parse_datetime | def parse_datetime(self, text):
'''Parse datetime from line of text.'''
return parse_datetime(text, date_format=self.date_format,
is_day_period=self.is_day_period) | python | def parse_datetime(self, text):
'''Parse datetime from line of text.'''
return parse_datetime(text, date_format=self.date_format,
is_day_period=self.is_day_period) | [
"def",
"parse_datetime",
"(",
"self",
",",
"text",
")",
":",
"return",
"parse_datetime",
"(",
"text",
",",
"date_format",
"=",
"self",
".",
"date_format",
",",
"is_day_period",
"=",
"self",
".",
"is_day_period",
")"
] | Parse datetime from line of text. | [
"Parse",
"datetime",
"from",
"line",
"of",
"text",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/listing.py#L68-L71 | train | 201,475 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/listing.py | LineParser.parse_msdos | def parse_msdos(self, lines):
'''Parse lines from a MS-DOS format.'''
for line in lines:
fields = line.split(None, 4)
date_str = fields[0]
time_str = fields[1]
datetime_str = '{} {}'.format(date_str, time_str)
file_datetime = self.parse_datetime(datetime_str)[0]
if fields[2] == '<DIR>':
file_size = None
file_type = 'dir'
else:
file_size = parse_int(fields[2])
file_type = 'file'
filename = fields[3]
yield FileEntry(filename, file_type, file_size, file_datetime) | python | def parse_msdos(self, lines):
'''Parse lines from a MS-DOS format.'''
for line in lines:
fields = line.split(None, 4)
date_str = fields[0]
time_str = fields[1]
datetime_str = '{} {}'.format(date_str, time_str)
file_datetime = self.parse_datetime(datetime_str)[0]
if fields[2] == '<DIR>':
file_size = None
file_type = 'dir'
else:
file_size = parse_int(fields[2])
file_type = 'file'
filename = fields[3]
yield FileEntry(filename, file_type, file_size, file_datetime) | [
"def",
"parse_msdos",
"(",
"self",
",",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
":",
"fields",
"=",
"line",
".",
"split",
"(",
"None",
",",
"4",
")",
"date_str",
"=",
"fields",
"[",
"0",
"]",
"time_str",
"=",
"fields",
"[",
"1",
"]",
"da... | Parse lines from a MS-DOS format. | [
"Parse",
"lines",
"from",
"a",
"MS",
"-",
"DOS",
"format",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/listing.py#L78-L99 | train | 201,476 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/listing.py | LineParser.parse_unix | def parse_unix(self, lines):
'''Parse listings from a Unix ls command format.'''
# This method uses some Filezilla parsing algorithms
for line in lines:
original_line = line
fields = line.split(' ')
after_perm_index = 0
# Search for the permissions field by checking the file type
for field in fields:
after_perm_index += len(field)
if not field:
continue
# If the filesystem goes corrupt, it may show ? instead
# but I don't really care in that situation.
if field[0] in 'bcdlps-':
if field[0] == 'd':
file_type = 'dir'
elif field[0] == '-':
file_type = 'file'
elif field[0] == 'l':
file_type = 'symlink'
else:
file_type = 'other'
perms = parse_unix_perm(field[1:])
break
else:
raise ListingError('Failed to parse file type.')
line = line[after_perm_index:]
# We look for the position of the date and use the integer
# before it as the file size.
# We look for the position of the time and use the text
# after it as the filename
while line:
try:
datetime_obj, start_index, end_index = self.parse_datetime(line)
except ValueError:
line = line[4:]
else:
break
else:
raise ListingError(
'Could parse a date from {}'.format(repr(original_line)))
file_size = int(line[:start_index].rstrip().rpartition(' ')[-1])
filename = line[end_index:].strip()
if file_type == 'symlink':
filename, sep, symlink_dest = filename.partition(' -> ')
else:
symlink_dest = None
yield FileEntry(filename, file_type, file_size, datetime_obj,
symlink_dest, perm=perms) | python | def parse_unix(self, lines):
'''Parse listings from a Unix ls command format.'''
# This method uses some Filezilla parsing algorithms
for line in lines:
original_line = line
fields = line.split(' ')
after_perm_index = 0
# Search for the permissions field by checking the file type
for field in fields:
after_perm_index += len(field)
if not field:
continue
# If the filesystem goes corrupt, it may show ? instead
# but I don't really care in that situation.
if field[0] in 'bcdlps-':
if field[0] == 'd':
file_type = 'dir'
elif field[0] == '-':
file_type = 'file'
elif field[0] == 'l':
file_type = 'symlink'
else:
file_type = 'other'
perms = parse_unix_perm(field[1:])
break
else:
raise ListingError('Failed to parse file type.')
line = line[after_perm_index:]
# We look for the position of the date and use the integer
# before it as the file size.
# We look for the position of the time and use the text
# after it as the filename
while line:
try:
datetime_obj, start_index, end_index = self.parse_datetime(line)
except ValueError:
line = line[4:]
else:
break
else:
raise ListingError(
'Could parse a date from {}'.format(repr(original_line)))
file_size = int(line[:start_index].rstrip().rpartition(' ')[-1])
filename = line[end_index:].strip()
if file_type == 'symlink':
filename, sep, symlink_dest = filename.partition(' -> ')
else:
symlink_dest = None
yield FileEntry(filename, file_type, file_size, datetime_obj,
symlink_dest, perm=perms) | [
"def",
"parse_unix",
"(",
"self",
",",
"lines",
")",
":",
"# This method uses some Filezilla parsing algorithms",
"for",
"line",
"in",
"lines",
":",
"original_line",
"=",
"line",
"fields",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"after_perm_index",
"=",
"0",... | Parse listings from a Unix ls command format. | [
"Parse",
"listings",
"from",
"a",
"Unix",
"ls",
"command",
"format",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/listing.py#L101-L162 | train | 201,477 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/listing.py | ListingParser.parse_input | def parse_input(self):
'''Parse the listings.
Returns:
iter: A iterable of :class:`.ftp.ls.listing.FileEntry`
'''
if self._text:
lines = iter(self._text.splitlines())
elif self._file:
lines = self._file
else:
lines = ()
sample_lines = []
for line in lines:
if len(sample_lines) > 100:
break
sample_lines.append(line)
lines = itertools.chain(sample_lines, lines)
self.guess_type(sample_lines)
datetime_format = wpull.protocol.ftp.ls.date.guess_datetime_format(
sample_lines)
self.set_datetime_format(datetime_format)
return self.parse(lines) | python | def parse_input(self):
'''Parse the listings.
Returns:
iter: A iterable of :class:`.ftp.ls.listing.FileEntry`
'''
if self._text:
lines = iter(self._text.splitlines())
elif self._file:
lines = self._file
else:
lines = ()
sample_lines = []
for line in lines:
if len(sample_lines) > 100:
break
sample_lines.append(line)
lines = itertools.chain(sample_lines, lines)
self.guess_type(sample_lines)
datetime_format = wpull.protocol.ftp.ls.date.guess_datetime_format(
sample_lines)
self.set_datetime_format(datetime_format)
return self.parse(lines) | [
"def",
"parse_input",
"(",
"self",
")",
":",
"if",
"self",
".",
"_text",
":",
"lines",
"=",
"iter",
"(",
"self",
".",
"_text",
".",
"splitlines",
"(",
")",
")",
"elif",
"self",
".",
"_file",
":",
"lines",
"=",
"self",
".",
"_file",
"else",
":",
"... | Parse the listings.
Returns:
iter: A iterable of :class:`.ftp.ls.listing.FileEntry` | [
"Parse",
"the",
"listings",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/listing.py#L248-L279 | train | 201,478 |
ArchiveTeam/wpull | wpull/writer.py | BaseFileWriterSession.open_file | def open_file(cls, filename: str, response: BaseResponse, mode='wb+'):
'''Open a file object on to the Response Body.
Args:
filename: The path where the file is to be saved
response: Response
mode: The file mode
This function will create the directories if not exist.
'''
_logger.debug('Saving file to {0}, mode={1}.',
filename, mode)
dir_path = os.path.dirname(filename)
if dir_path and not os.path.exists(dir_path):
os.makedirs(dir_path)
response.body = Body(open(filename, mode)) | python | def open_file(cls, filename: str, response: BaseResponse, mode='wb+'):
'''Open a file object on to the Response Body.
Args:
filename: The path where the file is to be saved
response: Response
mode: The file mode
This function will create the directories if not exist.
'''
_logger.debug('Saving file to {0}, mode={1}.',
filename, mode)
dir_path = os.path.dirname(filename)
if dir_path and not os.path.exists(dir_path):
os.makedirs(dir_path)
response.body = Body(open(filename, mode)) | [
"def",
"open_file",
"(",
"cls",
",",
"filename",
":",
"str",
",",
"response",
":",
"BaseResponse",
",",
"mode",
"=",
"'wb+'",
")",
":",
"_logger",
".",
"debug",
"(",
"'Saving file to {0}, mode={1}.'",
",",
"filename",
",",
"mode",
")",
"dir_path",
"=",
"os... | Open a file object on to the Response Body.
Args:
filename: The path where the file is to be saved
response: Response
mode: The file mode
This function will create the directories if not exist. | [
"Open",
"a",
"file",
"object",
"on",
"to",
"the",
"Response",
"Body",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L106-L123 | train | 201,479 |
ArchiveTeam/wpull | wpull/writer.py | BaseFileWriterSession.set_timestamp | def set_timestamp(cls, filename: str, response: HTTPResponse):
'''Set the Last-Modified timestamp onto the given file.
Args:
filename: The path of the file
response: Response
'''
last_modified = response.fields.get('Last-Modified')
if not last_modified:
return
try:
last_modified = email.utils.parsedate(last_modified)
except ValueError:
_logger.exception('Failed to parse date.')
return
last_modified = time.mktime(last_modified)
os.utime(filename, (time.time(), last_modified)) | python | def set_timestamp(cls, filename: str, response: HTTPResponse):
'''Set the Last-Modified timestamp onto the given file.
Args:
filename: The path of the file
response: Response
'''
last_modified = response.fields.get('Last-Modified')
if not last_modified:
return
try:
last_modified = email.utils.parsedate(last_modified)
except ValueError:
_logger.exception('Failed to parse date.')
return
last_modified = time.mktime(last_modified)
os.utime(filename, (time.time(), last_modified)) | [
"def",
"set_timestamp",
"(",
"cls",
",",
"filename",
":",
"str",
",",
"response",
":",
"HTTPResponse",
")",
":",
"last_modified",
"=",
"response",
".",
"fields",
".",
"get",
"(",
"'Last-Modified'",
")",
"if",
"not",
"last_modified",
":",
"return",
"try",
"... | Set the Last-Modified timestamp onto the given file.
Args:
filename: The path of the file
response: Response | [
"Set",
"the",
"Last",
"-",
"Modified",
"timestamp",
"onto",
"the",
"given",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L126-L146 | train | 201,480 |
ArchiveTeam/wpull | wpull/writer.py | BaseFileWriterSession.save_headers | def save_headers(cls, filename: str, response: HTTPResponse):
'''Prepend the HTTP response header to the file.
Args:
filename: The path of the file
response: Response
'''
new_filename = filename + '-new'
with open('wb') as new_file:
new_file.write(response.header())
with wpull.util.reset_file_offset(response.body):
response.body.seek(0)
shutil.copyfileobj(response.body, new_file)
os.remove(filename)
os.rename(new_filename, filename) | python | def save_headers(cls, filename: str, response: HTTPResponse):
'''Prepend the HTTP response header to the file.
Args:
filename: The path of the file
response: Response
'''
new_filename = filename + '-new'
with open('wb') as new_file:
new_file.write(response.header())
with wpull.util.reset_file_offset(response.body):
response.body.seek(0)
shutil.copyfileobj(response.body, new_file)
os.remove(filename)
os.rename(new_filename, filename) | [
"def",
"save_headers",
"(",
"cls",
",",
"filename",
":",
"str",
",",
"response",
":",
"HTTPResponse",
")",
":",
"new_filename",
"=",
"filename",
"+",
"'-new'",
"with",
"open",
"(",
"'wb'",
")",
"as",
"new_file",
":",
"new_file",
".",
"write",
"(",
"respo... | Prepend the HTTP response header to the file.
Args:
filename: The path of the file
response: Response | [
"Prepend",
"the",
"HTTP",
"response",
"header",
"to",
"the",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L149-L166 | train | 201,481 |
ArchiveTeam/wpull | wpull/writer.py | BaseFileWriterSession._compute_filename | def _compute_filename(self, request: BaseRequest):
'''Get the appropriate filename from the request.'''
path = self._path_namer.get_filename(request.url_info)
if os.path.isdir(path):
path += '.f'
else:
dir_name, name = os.path.split(path)
path = os.path.join(anti_clobber_dir_path(dir_name), name)
return path | python | def _compute_filename(self, request: BaseRequest):
'''Get the appropriate filename from the request.'''
path = self._path_namer.get_filename(request.url_info)
if os.path.isdir(path):
path += '.f'
else:
dir_name, name = os.path.split(path)
path = os.path.join(anti_clobber_dir_path(dir_name), name)
return path | [
"def",
"_compute_filename",
"(",
"self",
",",
"request",
":",
"BaseRequest",
")",
":",
"path",
"=",
"self",
".",
"_path_namer",
".",
"get_filename",
"(",
"request",
".",
"url_info",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"pa... | Get the appropriate filename from the request. | [
"Get",
"the",
"appropriate",
"filename",
"from",
"the",
"request",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L177-L187 | train | 201,482 |
ArchiveTeam/wpull | wpull/writer.py | BaseFileWriterSession._process_file_continue_request | def _process_file_continue_request(self, request: BaseRequest):
'''Modify the request to resume downloading file.'''
if os.path.exists(self._filename):
size = os.path.getsize(self._filename)
request.set_continue(size)
self._file_continue_requested = True
_logger.debug('Continue file from {0}.', size)
else:
_logger.debug('No file to continue.') | python | def _process_file_continue_request(self, request: BaseRequest):
'''Modify the request to resume downloading file.'''
if os.path.exists(self._filename):
size = os.path.getsize(self._filename)
request.set_continue(size)
self._file_continue_requested = True
_logger.debug('Continue file from {0}.', size)
else:
_logger.debug('No file to continue.') | [
"def",
"_process_file_continue_request",
"(",
"self",
",",
"request",
":",
"BaseRequest",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_filename",
")",
":",
"size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"self",
".",
"_fil... | Modify the request to resume downloading file. | [
"Modify",
"the",
"request",
"to",
"resume",
"downloading",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L189-L198 | train | 201,483 |
ArchiveTeam/wpull | wpull/writer.py | BaseFileWriterSession._process_file_continue_response | def _process_file_continue_response(self, response: HTTPResponse):
'''Process a partial content response.'''
code = response.status_code
if code == http.client.PARTIAL_CONTENT:
self.open_file(self._filename, response, mode='ab+')
else:
self._raise_cannot_continue_error() | python | def _process_file_continue_response(self, response: HTTPResponse):
'''Process a partial content response.'''
code = response.status_code
if code == http.client.PARTIAL_CONTENT:
self.open_file(self._filename, response, mode='ab+')
else:
self._raise_cannot_continue_error() | [
"def",
"_process_file_continue_response",
"(",
"self",
",",
"response",
":",
"HTTPResponse",
")",
":",
"code",
"=",
"response",
".",
"status_code",
"if",
"code",
"==",
"http",
".",
"client",
".",
"PARTIAL_CONTENT",
":",
"self",
".",
"open_file",
"(",
"self",
... | Process a partial content response. | [
"Process",
"a",
"partial",
"content",
"response",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L228-L235 | train | 201,484 |
ArchiveTeam/wpull | wpull/writer.py | BaseFileWriterSession._process_file_continue_ftp_response | def _process_file_continue_ftp_response(self, response: FTPResponse):
'''Process a restarted content response.'''
if response.request.restart_value and response.restart_value:
self.open_file(self._filename, response, mode='ab+')
else:
self._raise_cannot_continue_error() | python | def _process_file_continue_ftp_response(self, response: FTPResponse):
'''Process a restarted content response.'''
if response.request.restart_value and response.restart_value:
self.open_file(self._filename, response, mode='ab+')
else:
self._raise_cannot_continue_error() | [
"def",
"_process_file_continue_ftp_response",
"(",
"self",
",",
"response",
":",
"FTPResponse",
")",
":",
"if",
"response",
".",
"request",
".",
"restart_value",
"and",
"response",
".",
"restart_value",
":",
"self",
".",
"open_file",
"(",
"self",
".",
"_filename... | Process a restarted content response. | [
"Process",
"a",
"restarted",
"content",
"response",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L237-L242 | train | 201,485 |
ArchiveTeam/wpull | wpull/writer.py | BaseFileWriterSession._rename_with_content_disposition | def _rename_with_content_disposition(self, response: HTTPResponse):
'''Rename using the Content-Disposition header.'''
if not self._filename:
return
if response.request.url_info.scheme not in ('http', 'https'):
return
header_value = response.fields.get('Content-Disposition')
if not header_value:
return
filename = parse_content_disposition(header_value)
if filename:
dir_path = os.path.dirname(self._filename)
new_filename = self._path_namer.safe_filename(filename)
self._filename = os.path.join(dir_path, new_filename) | python | def _rename_with_content_disposition(self, response: HTTPResponse):
'''Rename using the Content-Disposition header.'''
if not self._filename:
return
if response.request.url_info.scheme not in ('http', 'https'):
return
header_value = response.fields.get('Content-Disposition')
if not header_value:
return
filename = parse_content_disposition(header_value)
if filename:
dir_path = os.path.dirname(self._filename)
new_filename = self._path_namer.safe_filename(filename)
self._filename = os.path.join(dir_path, new_filename) | [
"def",
"_rename_with_content_disposition",
"(",
"self",
",",
"response",
":",
"HTTPResponse",
")",
":",
"if",
"not",
"self",
".",
"_filename",
":",
"return",
"if",
"response",
".",
"request",
".",
"url_info",
".",
"scheme",
"not",
"in",
"(",
"'http'",
",",
... | Rename using the Content-Disposition header. | [
"Rename",
"using",
"the",
"Content",
"-",
"Disposition",
"header",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L270-L288 | train | 201,486 |
ArchiveTeam/wpull | wpull/writer.py | BaseFileWriter.session | def session(self) -> BaseFileWriterSession:
'''Return the File Writer Session.'''
return self.session_class(
self._path_namer,
self._file_continuing,
self._headers_included,
self._local_timestamping,
self._adjust_extension,
self._content_disposition,
self._trust_server_names,
) | python | def session(self) -> BaseFileWriterSession:
'''Return the File Writer Session.'''
return self.session_class(
self._path_namer,
self._file_continuing,
self._headers_included,
self._local_timestamping,
self._adjust_extension,
self._content_disposition,
self._trust_server_names,
) | [
"def",
"session",
"(",
"self",
")",
"->",
"BaseFileWriterSession",
":",
"return",
"self",
".",
"session_class",
"(",
"self",
".",
"_path_namer",
",",
"self",
".",
"_file_continuing",
",",
"self",
".",
"_headers_included",
",",
"self",
".",
"_local_timestamping",... | Return the File Writer Session. | [
"Return",
"the",
"File",
"Writer",
"Session",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L359-L369 | train | 201,487 |
ArchiveTeam/wpull | wpull/protocol/http/util.py | parse_charset | def parse_charset(header_string):
'''Parse a "Content-Type" string for the document encoding.
Returns:
str, None
'''
match = re.search(
r'''charset[ ]?=[ ]?["']?([a-z0-9_-]+)''',
header_string,
re.IGNORECASE
)
if match:
return match.group(1) | python | def parse_charset(header_string):
'''Parse a "Content-Type" string for the document encoding.
Returns:
str, None
'''
match = re.search(
r'''charset[ ]?=[ ]?["']?([a-z0-9_-]+)''',
header_string,
re.IGNORECASE
)
if match:
return match.group(1) | [
"def",
"parse_charset",
"(",
"header_string",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'''charset[ ]?=[ ]?[\"']?([a-z0-9_-]+)'''",
",",
"header_string",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"1"... | Parse a "Content-Type" string for the document encoding.
Returns:
str, None | [
"Parse",
"a",
"Content",
"-",
"Type",
"string",
"for",
"the",
"document",
"encoding",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/util.py#L6-L19 | train | 201,488 |
ArchiveTeam/wpull | wpull/protocol/http/util.py | should_close | def should_close(http_version, connection_field):
'''Return whether the connection should be closed.
Args:
http_version (str): The HTTP version string like ``HTTP/1.0``.
connection_field (str): The value for the ``Connection`` header.
'''
connection_field = (connection_field or '').lower()
if http_version == 'HTTP/1.0':
return connection_field.replace('-', '') != 'keepalive'
else:
return connection_field == 'close' | python | def should_close(http_version, connection_field):
'''Return whether the connection should be closed.
Args:
http_version (str): The HTTP version string like ``HTTP/1.0``.
connection_field (str): The value for the ``Connection`` header.
'''
connection_field = (connection_field or '').lower()
if http_version == 'HTTP/1.0':
return connection_field.replace('-', '') != 'keepalive'
else:
return connection_field == 'close' | [
"def",
"should_close",
"(",
"http_version",
",",
"connection_field",
")",
":",
"connection_field",
"=",
"(",
"connection_field",
"or",
"''",
")",
".",
"lower",
"(",
")",
"if",
"http_version",
"==",
"'HTTP/1.0'",
":",
"return",
"connection_field",
".",
"replace",... | Return whether the connection should be closed.
Args:
http_version (str): The HTTP version string like ``HTTP/1.0``.
connection_field (str): The value for the ``Connection`` header. | [
"Return",
"whether",
"the",
"connection",
"should",
"be",
"closed",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/util.py#L22-L34 | train | 201,489 |
ArchiveTeam/wpull | wpull/util.py | seek_file_end | def seek_file_end(file):
'''Seek to the end of the file.'''
try:
file.seek(0, 2)
except ValueError:
# gzip files don't support seek from end
while True:
data = file.read(4096)
if not data:
break | python | def seek_file_end(file):
'''Seek to the end of the file.'''
try:
file.seek(0, 2)
except ValueError:
# gzip files don't support seek from end
while True:
data = file.read(4096)
if not data:
break | [
"def",
"seek_file_end",
"(",
"file",
")",
":",
"try",
":",
"file",
".",
"seek",
"(",
"0",
",",
"2",
")",
"except",
"ValueError",
":",
"# gzip files don't support seek from end",
"while",
"True",
":",
"data",
"=",
"file",
".",
"read",
"(",
"4096",
")",
"i... | Seek to the end of the file. | [
"Seek",
"to",
"the",
"end",
"of",
"the",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L64-L73 | train | 201,490 |
ArchiveTeam/wpull | wpull/util.py | parse_iso8601_str | def parse_iso8601_str(string):
'''Parse a fixed ISO8601 datetime string.
.. Note:: This function only parses dates in the format
``%Y-%m-%dT%H:%M:%SZ``. You must use a library like ``dateutils``
to properly parse dates and times.
Returns:
float: A UNIX timestamp.
'''
datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%SZ")
return int(calendar.timegm(datetime_obj.utctimetuple())) | python | def parse_iso8601_str(string):
'''Parse a fixed ISO8601 datetime string.
.. Note:: This function only parses dates in the format
``%Y-%m-%dT%H:%M:%SZ``. You must use a library like ``dateutils``
to properly parse dates and times.
Returns:
float: A UNIX timestamp.
'''
datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%SZ")
return int(calendar.timegm(datetime_obj.utctimetuple())) | [
"def",
"parse_iso8601_str",
"(",
"string",
")",
":",
"datetime_obj",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"string",
",",
"\"%Y-%m-%dT%H:%M:%SZ\"",
")",
"return",
"int",
"(",
"calendar",
".",
"timegm",
"(",
"datetime_obj",
".",
"utctimetuple",
... | Parse a fixed ISO8601 datetime string.
.. Note:: This function only parses dates in the format
``%Y-%m-%dT%H:%M:%SZ``. You must use a library like ``dateutils``
to properly parse dates and times.
Returns:
float: A UNIX timestamp. | [
"Parse",
"a",
"fixed",
"ISO8601",
"datetime",
"string",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L81-L92 | train | 201,491 |
ArchiveTeam/wpull | wpull/util.py | python_version | def python_version():
'''Return the Python version as a string.'''
major, minor, patch = sys.version_info[0:3]
return '{0}.{1}.{2}'.format(major, minor, patch) | python | def python_version():
'''Return the Python version as a string.'''
major, minor, patch = sys.version_info[0:3]
return '{0}.{1}.{2}'.format(major, minor, patch) | [
"def",
"python_version",
"(",
")",
":",
"major",
",",
"minor",
",",
"patch",
"=",
"sys",
".",
"version_info",
"[",
"0",
":",
"3",
"]",
"return",
"'{0}.{1}.{2}'",
".",
"format",
"(",
"major",
",",
"minor",
",",
"patch",
")"
] | Return the Python version as a string. | [
"Return",
"the",
"Python",
"version",
"as",
"a",
"string",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L95-L98 | train | 201,492 |
ArchiveTeam/wpull | wpull/util.py | filter_pem | def filter_pem(data):
'''Processes the bytes for PEM certificates.
Returns:
``set`` containing each certificate
'''
assert isinstance(data, bytes), 'Expect bytes. Got {}.'.format(type(data))
certs = set()
new_list = []
in_pem_block = False
for line in re.split(br'[\r\n]+', data):
if line == b'-----BEGIN CERTIFICATE-----':
assert not in_pem_block
in_pem_block = True
elif line == b'-----END CERTIFICATE-----':
assert in_pem_block
in_pem_block = False
content = b''.join(new_list)
content = rewrap_bytes(content)
certs.add(b'-----BEGIN CERTIFICATE-----\n' +
content +
b'\n-----END CERTIFICATE-----\n')
new_list = []
elif in_pem_block:
new_list.append(line)
return certs | python | def filter_pem(data):
'''Processes the bytes for PEM certificates.
Returns:
``set`` containing each certificate
'''
assert isinstance(data, bytes), 'Expect bytes. Got {}.'.format(type(data))
certs = set()
new_list = []
in_pem_block = False
for line in re.split(br'[\r\n]+', data):
if line == b'-----BEGIN CERTIFICATE-----':
assert not in_pem_block
in_pem_block = True
elif line == b'-----END CERTIFICATE-----':
assert in_pem_block
in_pem_block = False
content = b''.join(new_list)
content = rewrap_bytes(content)
certs.add(b'-----BEGIN CERTIFICATE-----\n' +
content +
b'\n-----END CERTIFICATE-----\n')
new_list = []
elif in_pem_block:
new_list.append(line)
return certs | [
"def",
"filter_pem",
"(",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
",",
"'Expect bytes. Got {}.'",
".",
"format",
"(",
"type",
"(",
"data",
")",
")",
"certs",
"=",
"set",
"(",
")",
"new_list",
"=",
"[",
"]",
"in_pem_blo... | Processes the bytes for PEM certificates.
Returns:
``set`` containing each certificate | [
"Processes",
"the",
"bytes",
"for",
"PEM",
"certificates",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L101-L131 | train | 201,493 |
ArchiveTeam/wpull | wpull/util.py | rewrap_bytes | def rewrap_bytes(data):
'''Rewrap characters to 70 character width.
Intended to rewrap base64 content.
'''
return b'\n'.join(
data[index:index+70] for index in range(0, len(data), 70)
) | python | def rewrap_bytes(data):
'''Rewrap characters to 70 character width.
Intended to rewrap base64 content.
'''
return b'\n'.join(
data[index:index+70] for index in range(0, len(data), 70)
) | [
"def",
"rewrap_bytes",
"(",
"data",
")",
":",
"return",
"b'\\n'",
".",
"join",
"(",
"data",
"[",
"index",
":",
"index",
"+",
"70",
"]",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"70",
")",
")"
] | Rewrap characters to 70 character width.
Intended to rewrap base64 content. | [
"Rewrap",
"characters",
"to",
"70",
"character",
"width",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L134-L141 | train | 201,494 |
ArchiveTeam/wpull | wpull/util.py | get_package_data | def get_package_data(filename, mode='rb'):
'''Return the contents of a real file or a zip file.'''
if os.path.exists(filename):
with open(filename, mode=mode) as in_file:
return in_file.read()
else:
parts = os.path.normpath(filename).split(os.sep)
for part, index in zip(parts, range(len(parts))):
if part.endswith('.zip'):
zip_path = os.sep.join(parts[:index + 1])
member_path = os.sep.join(parts[index + 1:])
break
if platform.system() == 'Windows':
member_path = member_path.replace('\\', '/')
with zipfile.ZipFile(zip_path) as zip_file:
return zip_file.read(member_path) | python | def get_package_data(filename, mode='rb'):
'''Return the contents of a real file or a zip file.'''
if os.path.exists(filename):
with open(filename, mode=mode) as in_file:
return in_file.read()
else:
parts = os.path.normpath(filename).split(os.sep)
for part, index in zip(parts, range(len(parts))):
if part.endswith('.zip'):
zip_path = os.sep.join(parts[:index + 1])
member_path = os.sep.join(parts[index + 1:])
break
if platform.system() == 'Windows':
member_path = member_path.replace('\\', '/')
with zipfile.ZipFile(zip_path) as zip_file:
return zip_file.read(member_path) | [
"def",
"get_package_data",
"(",
"filename",
",",
"mode",
"=",
"'rb'",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"mode",
"=",
"mode",
")",
"as",
"in_file",
":",
"return",
"in_fil... | Return the contents of a real file or a zip file. | [
"Return",
"the",
"contents",
"of",
"a",
"real",
"file",
"or",
"a",
"zip",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L150-L168 | train | 201,495 |
ArchiveTeam/wpull | wpull/util.py | get_package_filename | def get_package_filename(filename, package_dir=None):
'''Return the filename of the data file.'''
if getattr(sys, 'frozen', False):
package_dir = os.path.join(
sys._MEIPASS,
os.path.basename(os.path.dirname(__file__))
)
elif not package_dir:
package_dir = os.path.dirname(__file__)
return os.path.join(package_dir, filename) | python | def get_package_filename(filename, package_dir=None):
'''Return the filename of the data file.'''
if getattr(sys, 'frozen', False):
package_dir = os.path.join(
sys._MEIPASS,
os.path.basename(os.path.dirname(__file__))
)
elif not package_dir:
package_dir = os.path.dirname(__file__)
return os.path.join(package_dir, filename) | [
"def",
"get_package_filename",
"(",
"filename",
",",
"package_dir",
"=",
"None",
")",
":",
"if",
"getattr",
"(",
"sys",
",",
"'frozen'",
",",
"False",
")",
":",
"package_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sys",
".",
"_MEIPASS",
",",
"os",... | Return the filename of the data file. | [
"Return",
"the",
"filename",
"of",
"the",
"data",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L171-L181 | train | 201,496 |
ArchiveTeam/wpull | wpull/util.py | get_exception_message | def get_exception_message(instance):
'''Try to get the exception message or the class name.'''
args = getattr(instance, 'args', None)
if args:
return str(instance)
try:
return type(instance).__name__
except AttributeError:
return str(instance) | python | def get_exception_message(instance):
'''Try to get the exception message or the class name.'''
args = getattr(instance, 'args', None)
if args:
return str(instance)
try:
return type(instance).__name__
except AttributeError:
return str(instance) | [
"def",
"get_exception_message",
"(",
"instance",
")",
":",
"args",
"=",
"getattr",
"(",
"instance",
",",
"'args'",
",",
"None",
")",
"if",
"args",
":",
"return",
"str",
"(",
"instance",
")",
"try",
":",
"return",
"type",
"(",
"instance",
")",
".",
"__n... | Try to get the exception message or the class name. | [
"Try",
"to",
"get",
"the",
"exception",
"message",
"or",
"the",
"class",
"name",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L205-L215 | train | 201,497 |
ArchiveTeam/wpull | wpull/util.py | PickleStream.dump | def dump(self, obj):
'''Pickle an object.'''
pickle.dump(obj, self._file, protocol=self._protocol) | python | def dump(self, obj):
'''Pickle an object.'''
pickle.dump(obj, self._file, protocol=self._protocol) | [
"def",
"dump",
"(",
"self",
",",
"obj",
")",
":",
"pickle",
".",
"dump",
"(",
"obj",
",",
"self",
".",
"_file",
",",
"protocol",
"=",
"self",
".",
"_protocol",
")"
] | Pickle an object. | [
"Pickle",
"an",
"object",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L229-L231 | train | 201,498 |
ArchiveTeam/wpull | wpull/thirdparty/dammit.py | EntitySubstitution.quoted_attribute_value | def quoted_attribute_value(self, value):
"""Make a value into a quoted XML attribute, possibly escaping it.
Most strings will be quoted using double quotes.
Bob's Bar -> "Bob's Bar"
If a string contains double quotes, it will be quoted using
single quotes.
Welcome to "my bar" -> 'Welcome to "my bar"'
If a string contains both single and double quotes, the
double quotes will be escaped, and the string will be quoted
using double quotes.
Welcome to "Bob's Bar" -> "Welcome to "Bob's bar"
"""
quote_with = '"'
if '"' in value:
if "'" in value:
# The string contains both single and double
# quotes. Turn the double quotes into
# entities. We quote the double quotes rather than
# the single quotes because the entity name is
# """ whether this is HTML or XML. If we
# quoted the single quotes, we'd have to decide
# between ' and &squot;.
replace_with = """
value = value.replace('"', replace_with)
else:
# There are double quotes but no single quotes.
# We can use single quotes to quote the attribute.
quote_with = "'"
return quote_with + value + quote_with | python | def quoted_attribute_value(self, value):
"""Make a value into a quoted XML attribute, possibly escaping it.
Most strings will be quoted using double quotes.
Bob's Bar -> "Bob's Bar"
If a string contains double quotes, it will be quoted using
single quotes.
Welcome to "my bar" -> 'Welcome to "my bar"'
If a string contains both single and double quotes, the
double quotes will be escaped, and the string will be quoted
using double quotes.
Welcome to "Bob's Bar" -> "Welcome to "Bob's bar"
"""
quote_with = '"'
if '"' in value:
if "'" in value:
# The string contains both single and double
# quotes. Turn the double quotes into
# entities. We quote the double quotes rather than
# the single quotes because the entity name is
# """ whether this is HTML or XML. If we
# quoted the single quotes, we'd have to decide
# between ' and &squot;.
replace_with = """
value = value.replace('"', replace_with)
else:
# There are double quotes but no single quotes.
# We can use single quotes to quote the attribute.
quote_with = "'"
return quote_with + value + quote_with | [
"def",
"quoted_attribute_value",
"(",
"self",
",",
"value",
")",
":",
"quote_with",
"=",
"'\"'",
"if",
"'\"'",
"in",
"value",
":",
"if",
"\"'\"",
"in",
"value",
":",
"# The string contains both single and double",
"# quotes. Turn the double quotes into",
"# entities. W... | Make a value into a quoted XML attribute, possibly escaping it.
Most strings will be quoted using double quotes.
Bob's Bar -> "Bob's Bar"
If a string contains double quotes, it will be quoted using
single quotes.
Welcome to "my bar" -> 'Welcome to "my bar"'
If a string contains both single and double quotes, the
double quotes will be escaped, and the string will be quoted
using double quotes.
Welcome to "Bob's Bar" -> "Welcome to "Bob's bar" | [
"Make",
"a",
"value",
"into",
"a",
"quoted",
"XML",
"attribute",
"possibly",
"escaping",
"it",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/thirdparty/dammit.py#L102-L136 | train | 201,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.