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/stats.py | Statistics.increment_error | def increment_error(self, error: Exception):
'''Increment the error counter preferring base exceptions.'''
_logger.debug('Increment error %s', error)
for error_class in ERROR_PRIORITIES:
if isinstance(error, error_class):
self.errors[error_class] += 1
return
self.errors[type(error)] += 1 | python | def increment_error(self, error: Exception):
'''Increment the error counter preferring base exceptions.'''
_logger.debug('Increment error %s', error)
for error_class in ERROR_PRIORITIES:
if isinstance(error, error_class):
self.errors[error_class] += 1
return
self.errors[type(error)] += 1 | [
"def",
"increment_error",
"(",
"self",
",",
"error",
":",
"Exception",
")",
":",
"_logger",
".",
"debug",
"(",
"'Increment error %s'",
",",
"error",
")",
"for",
"error_class",
"in",
"ERROR_PRIORITIES",
":",
"if",
"isinstance",
"(",
"error",
",",
"error_class",... | Increment the error counter preferring base exceptions. | [
"Increment",
"the",
"error",
"counter",
"preferring",
"base",
"exceptions",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/stats.py#L76-L85 | train | 201,300 |
ArchiveTeam/wpull | wpull/collections.py | LinkedListNode.link_head | def link_head(self, node):
'''Add a node to the head. '''
assert not node.tail
old_head = self.head
if old_head:
assert old_head.tail == self
old_head.tail = node
node.head = old_head
node.tail = self
self.head = node | python | def link_head(self, node):
'''Add a node to the head. '''
assert not node.tail
old_head = self.head
if old_head:
assert old_head.tail == self
old_head.tail = node
node.head = old_head
node.tail = self
self.head = node | [
"def",
"link_head",
"(",
"self",
",",
"node",
")",
":",
"assert",
"not",
"node",
".",
"tail",
"old_head",
"=",
"self",
".",
"head",
"if",
"old_head",
":",
"assert",
"old_head",
".",
"tail",
"==",
"self",
"old_head",
".",
"tail",
"=",
"node",
"node",
... | Add a node to the head. | [
"Add",
"a",
"node",
"to",
"the",
"head",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/collections.py#L71-L82 | train | 201,301 |
ArchiveTeam/wpull | wpull/collections.py | LinkedListNode.link_tail | def link_tail(self, node):
'''Add a node to the tail.'''
assert not node.head
old_tail = self.tail
if old_tail:
assert old_tail.head == self
old_tail.head = node
node.tail = old_tail
node.head = self
self.tail = node | python | def link_tail(self, node):
'''Add a node to the tail.'''
assert not node.head
old_tail = self.tail
if old_tail:
assert old_tail.head == self
old_tail.head = node
node.tail = old_tail
node.head = self
self.tail = node | [
"def",
"link_tail",
"(",
"self",
",",
"node",
")",
":",
"assert",
"not",
"node",
".",
"head",
"old_tail",
"=",
"self",
".",
"tail",
"if",
"old_tail",
":",
"assert",
"old_tail",
".",
"head",
"==",
"self",
"old_tail",
".",
"head",
"=",
"node",
"node",
... | Add a node to the tail. | [
"Add",
"a",
"node",
"to",
"the",
"tail",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/collections.py#L84-L95 | train | 201,302 |
ArchiveTeam/wpull | wpull/collections.py | LinkedListNode.unlink | def unlink(self):
'''Remove this node and link any head or tail.'''
old_head = self.head
old_tail = self.tail
self.head = None
self.tail = None
if old_head:
old_head.tail = old_tail
if old_tail:
old_tail.head = old_head | python | def unlink(self):
'''Remove this node and link any head or tail.'''
old_head = self.head
old_tail = self.tail
self.head = None
self.tail = None
if old_head:
old_head.tail = old_tail
if old_tail:
old_tail.head = old_head | [
"def",
"unlink",
"(",
"self",
")",
":",
"old_head",
"=",
"self",
".",
"head",
"old_tail",
"=",
"self",
".",
"tail",
"self",
".",
"head",
"=",
"None",
"self",
".",
"tail",
"=",
"None",
"if",
"old_head",
":",
"old_head",
".",
"tail",
"=",
"old_tail",
... | Remove this node and link any head or tail. | [
"Remove",
"this",
"node",
"and",
"link",
"any",
"head",
"or",
"tail",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/collections.py#L97-L109 | train | 201,303 |
ArchiveTeam/wpull | wpull/protocol/http/request.py | Request.prepare_for_send | def prepare_for_send(self, full_url=False):
'''Modify the request to be suitable for HTTP server.
Args:
full_url (bool): Use full URL as the URI. By default, only
the path of the URL is given to the server.
'''
assert self.url
assert self.method
assert self.version
url_info = self.url_info
if 'Host' not in self.fields:
self.fields['Host'] = url_info.hostname_with_port
if not full_url:
if url_info.query:
self.resource_path = '{0}?{1}'.format(url_info.path, url_info.query)
else:
self.resource_path = url_info.path
else:
self.resource_path = url_info.url | python | def prepare_for_send(self, full_url=False):
'''Modify the request to be suitable for HTTP server.
Args:
full_url (bool): Use full URL as the URI. By default, only
the path of the URL is given to the server.
'''
assert self.url
assert self.method
assert self.version
url_info = self.url_info
if 'Host' not in self.fields:
self.fields['Host'] = url_info.hostname_with_port
if not full_url:
if url_info.query:
self.resource_path = '{0}?{1}'.format(url_info.path, url_info.query)
else:
self.resource_path = url_info.path
else:
self.resource_path = url_info.url | [
"def",
"prepare_for_send",
"(",
"self",
",",
"full_url",
"=",
"False",
")",
":",
"assert",
"self",
".",
"url",
"assert",
"self",
".",
"method",
"assert",
"self",
".",
"version",
"url_info",
"=",
"self",
".",
"url_info",
"if",
"'Host'",
"not",
"in",
"self... | Modify the request to be suitable for HTTP server.
Args:
full_url (bool): Use full URL as the URI. By default, only
the path of the URL is given to the server. | [
"Modify",
"the",
"request",
"to",
"be",
"suitable",
"for",
"HTTP",
"server",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/request.py#L125-L147 | train | 201,304 |
ArchiveTeam/wpull | wpull/document/css.py | CSSReader.is_response | def is_response(cls, response):
'''Return whether the document is likely to be CSS.'''
if 'css' in response.fields.get('content-type', '').lower():
return True
if response.body:
# Stylesheet mistakenly served as HTML
if 'html' in response.fields.get('content-type', '').lower():
return cls.is_file(response.body) | python | def is_response(cls, response):
'''Return whether the document is likely to be CSS.'''
if 'css' in response.fields.get('content-type', '').lower():
return True
if response.body:
# Stylesheet mistakenly served as HTML
if 'html' in response.fields.get('content-type', '').lower():
return cls.is_file(response.body) | [
"def",
"is_response",
"(",
"cls",
",",
"response",
")",
":",
"if",
"'css'",
"in",
"response",
".",
"fields",
".",
"get",
"(",
"'content-type'",
",",
"''",
")",
".",
"lower",
"(",
")",
":",
"return",
"True",
"if",
"response",
".",
"body",
":",
"# Styl... | Return whether the document is likely to be CSS. | [
"Return",
"whether",
"the",
"document",
"is",
"likely",
"to",
"be",
"CSS",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/css.py#L33-L41 | train | 201,305 |
ArchiveTeam/wpull | wpull/document/css.py | CSSReader.is_file | def is_file(cls, file):
'''Return whether the file is likely CSS.'''
peeked_data = wpull.string.printable_bytes(
wpull.util.peek_file(file)).lower()
if b'<html' in peeked_data:
return VeryFalse
if re.search(br'@import |color:|background[a-z-]*:|font[a-z-]*:',
peeked_data):
return True | python | def is_file(cls, file):
'''Return whether the file is likely CSS.'''
peeked_data = wpull.string.printable_bytes(
wpull.util.peek_file(file)).lower()
if b'<html' in peeked_data:
return VeryFalse
if re.search(br'@import |color:|background[a-z-]*:|font[a-z-]*:',
peeked_data):
return True | [
"def",
"is_file",
"(",
"cls",
",",
"file",
")",
":",
"peeked_data",
"=",
"wpull",
".",
"string",
".",
"printable_bytes",
"(",
"wpull",
".",
"util",
".",
"peek_file",
"(",
"file",
")",
")",
".",
"lower",
"(",
")",
"if",
"b'<html'",
"in",
"peeked_data",
... | Return whether the file is likely CSS. | [
"Return",
"whether",
"the",
"file",
"is",
"likely",
"CSS",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/css.py#L44-L54 | train | 201,306 |
ArchiveTeam/wpull | wpull/protocol/http/web.py | WebSession.start | def start(self):
'''Begin fetching the next request.'''
self._current_session = session = self._http_client.session()
request = self.next_request()
assert request
if request.url_info.password or \
request.url_info.hostname_with_port in self._hostnames_with_auth:
self._add_basic_auth_header(request)
response = yield from session.start(request)
self._process_response(response)
return response | python | def start(self):
'''Begin fetching the next request.'''
self._current_session = session = self._http_client.session()
request = self.next_request()
assert request
if request.url_info.password or \
request.url_info.hostname_with_port in self._hostnames_with_auth:
self._add_basic_auth_header(request)
response = yield from session.start(request)
self._process_response(response)
return response | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_current_session",
"=",
"session",
"=",
"self",
".",
"_http_client",
".",
"session",
"(",
")",
"request",
"=",
"self",
".",
"next_request",
"(",
")",
"assert",
"request",
"if",
"request",
".",
"url_inf... | Begin fetching the next request. | [
"Begin",
"fetching",
"the",
"next",
"request",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L96-L111 | train | 201,307 |
ArchiveTeam/wpull | wpull/protocol/http/web.py | WebSession.download | def download(self, file: Optional[IO[bytes]]=None,
duration_timeout: Optional[float]=None):
'''Download content.
Args:
file: An optional file object for the document contents.
duration_timeout: Maximum time in seconds of which the
entire file must be read.
Returns:
Response: An instance of :class:`.http.request.Response`.
See :meth:`WebClient.session` for proper usage of this function.
Coroutine.
'''
yield from \
self._current_session.download(file, duration_timeout=duration_timeout) | python | def download(self, file: Optional[IO[bytes]]=None,
duration_timeout: Optional[float]=None):
'''Download content.
Args:
file: An optional file object for the document contents.
duration_timeout: Maximum time in seconds of which the
entire file must be read.
Returns:
Response: An instance of :class:`.http.request.Response`.
See :meth:`WebClient.session` for proper usage of this function.
Coroutine.
'''
yield from \
self._current_session.download(file, duration_timeout=duration_timeout) | [
"def",
"download",
"(",
"self",
",",
"file",
":",
"Optional",
"[",
"IO",
"[",
"bytes",
"]",
"]",
"=",
"None",
",",
"duration_timeout",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
")",
":",
"yield",
"from",
"self",
".",
"_current_session",
".",
"... | Download content.
Args:
file: An optional file object for the document contents.
duration_timeout: Maximum time in seconds of which the
entire file must be read.
Returns:
Response: An instance of :class:`.http.request.Response`.
See :meth:`WebClient.session` for proper usage of this function.
Coroutine. | [
"Download",
"content",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L114-L131 | train | 201,308 |
ArchiveTeam/wpull | wpull/protocol/http/web.py | WebSession._process_response | def _process_response(self, response: Response):
'''Handle the response and update the internal state.'''
_logger.debug('Handling response')
self._redirect_tracker.load(response)
if self._redirect_tracker.is_redirect():
self._process_redirect()
self._loop_type = LoopType.redirect
elif response.status_code == http.client.UNAUTHORIZED and self._next_request.password:
self._process_authentication(response)
else:
self._next_request = None
self._loop_type = LoopType.normal
if self._cookie_jar:
self._extract_cookies(response)
if self._next_request:
self._add_cookies(self._next_request) | python | def _process_response(self, response: Response):
'''Handle the response and update the internal state.'''
_logger.debug('Handling response')
self._redirect_tracker.load(response)
if self._redirect_tracker.is_redirect():
self._process_redirect()
self._loop_type = LoopType.redirect
elif response.status_code == http.client.UNAUTHORIZED and self._next_request.password:
self._process_authentication(response)
else:
self._next_request = None
self._loop_type = LoopType.normal
if self._cookie_jar:
self._extract_cookies(response)
if self._next_request:
self._add_cookies(self._next_request) | [
"def",
"_process_response",
"(",
"self",
",",
"response",
":",
"Response",
")",
":",
"_logger",
".",
"debug",
"(",
"'Handling response'",
")",
"self",
".",
"_redirect_tracker",
".",
"load",
"(",
"response",
")",
"if",
"self",
".",
"_redirect_tracker",
".",
"... | Handle the response and update the internal state. | [
"Handle",
"the",
"response",
"and",
"update",
"the",
"internal",
"state",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L133-L152 | train | 201,309 |
ArchiveTeam/wpull | wpull/protocol/http/web.py | WebSession._process_redirect | def _process_redirect(self):
'''Update the Redirect Tracker.'''
_logger.debug('Handling redirect.')
if self._redirect_tracker.exceeded():
raise ProtocolError('Too many redirects.')
try:
url = self._redirect_tracker.next_location()
if not url:
raise ProtocolError('Redirect location missing.')
if self._redirect_tracker.is_repeat():
_logger.debug('Got redirect is repeat.')
request = self._original_request.copy()
request.url = url
else:
request = self._request_factory(url)
request.prepare_for_send()
except ValueError as error:
raise ProtocolError('Invalid redirect location.') from error
self._next_request = request
_logger.debug('Updated next redirect request to {0}.'.format(request)) | python | def _process_redirect(self):
'''Update the Redirect Tracker.'''
_logger.debug('Handling redirect.')
if self._redirect_tracker.exceeded():
raise ProtocolError('Too many redirects.')
try:
url = self._redirect_tracker.next_location()
if not url:
raise ProtocolError('Redirect location missing.')
if self._redirect_tracker.is_repeat():
_logger.debug('Got redirect is repeat.')
request = self._original_request.copy()
request.url = url
else:
request = self._request_factory(url)
request.prepare_for_send()
except ValueError as error:
raise ProtocolError('Invalid redirect location.') from error
self._next_request = request
_logger.debug('Updated next redirect request to {0}.'.format(request)) | [
"def",
"_process_redirect",
"(",
"self",
")",
":",
"_logger",
".",
"debug",
"(",
"'Handling redirect.'",
")",
"if",
"self",
".",
"_redirect_tracker",
".",
"exceeded",
"(",
")",
":",
"raise",
"ProtocolError",
"(",
"'Too many redirects.'",
")",
"try",
":",
"url"... | Update the Redirect Tracker. | [
"Update",
"the",
"Redirect",
"Tracker",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L154-L181 | train | 201,310 |
ArchiveTeam/wpull | wpull/protocol/http/web.py | WebSession._get_cookie_referrer_host | def _get_cookie_referrer_host(self):
'''Return the referrer hostname.'''
referer = self._original_request.fields.get('Referer')
if referer:
return URLInfo.parse(referer).hostname
else:
return None | python | def _get_cookie_referrer_host(self):
'''Return the referrer hostname.'''
referer = self._original_request.fields.get('Referer')
if referer:
return URLInfo.parse(referer).hostname
else:
return None | [
"def",
"_get_cookie_referrer_host",
"(",
"self",
")",
":",
"referer",
"=",
"self",
".",
"_original_request",
".",
"fields",
".",
"get",
"(",
"'Referer'",
")",
"if",
"referer",
":",
"return",
"URLInfo",
".",
"parse",
"(",
"referer",
")",
".",
"hostname",
"e... | Return the referrer hostname. | [
"Return",
"the",
"referrer",
"hostname",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L183-L190 | train | 201,311 |
ArchiveTeam/wpull | wpull/protocol/http/web.py | WebSession._add_cookies | def _add_cookies(self, request: Request):
'''Add the cookie headers to the Request.'''
self._cookie_jar.add_cookie_header(
request, self._get_cookie_referrer_host()
) | python | def _add_cookies(self, request: Request):
'''Add the cookie headers to the Request.'''
self._cookie_jar.add_cookie_header(
request, self._get_cookie_referrer_host()
) | [
"def",
"_add_cookies",
"(",
"self",
",",
"request",
":",
"Request",
")",
":",
"self",
".",
"_cookie_jar",
".",
"add_cookie_header",
"(",
"request",
",",
"self",
".",
"_get_cookie_referrer_host",
"(",
")",
")"
] | Add the cookie headers to the Request. | [
"Add",
"the",
"cookie",
"headers",
"to",
"the",
"Request",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L192-L196 | train | 201,312 |
ArchiveTeam/wpull | wpull/protocol/http/web.py | WebSession._extract_cookies | def _extract_cookies(self, response: Response):
'''Load the cookie headers from the Response.'''
self._cookie_jar.extract_cookies(
response, response.request, self._get_cookie_referrer_host()
) | python | def _extract_cookies(self, response: Response):
'''Load the cookie headers from the Response.'''
self._cookie_jar.extract_cookies(
response, response.request, self._get_cookie_referrer_host()
) | [
"def",
"_extract_cookies",
"(",
"self",
",",
"response",
":",
"Response",
")",
":",
"self",
".",
"_cookie_jar",
".",
"extract_cookies",
"(",
"response",
",",
"response",
".",
"request",
",",
"self",
".",
"_get_cookie_referrer_host",
"(",
")",
")"
] | Load the cookie headers from the Response. | [
"Load",
"the",
"cookie",
"headers",
"from",
"the",
"Response",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L198-L202 | train | 201,313 |
ArchiveTeam/wpull | wpull/protocol/http/web.py | WebClient.session | def session(self, request: Request) -> WebSession:
'''Return a fetch session.
Args:
request: The request to be fetched.
Example usage::
client = WebClient()
session = client.session(Request('http://www.example.com'))
with session:
while not session.done():
request = session.next_request()
print(request)
response = yield from session.start()
print(response)
if session.done():
with open('myfile.html') as file:
yield from session.download(file)
else:
yield from session.download()
Returns:
WebSession
'''
return WebSession(
request,
http_client=self._http_client,
redirect_tracker=self._redirect_tracker_factory(),
request_factory=self._request_factory,
cookie_jar=self._cookie_jar,
) | python | def session(self, request: Request) -> WebSession:
'''Return a fetch session.
Args:
request: The request to be fetched.
Example usage::
client = WebClient()
session = client.session(Request('http://www.example.com'))
with session:
while not session.done():
request = session.next_request()
print(request)
response = yield from session.start()
print(response)
if session.done():
with open('myfile.html') as file:
yield from session.download(file)
else:
yield from session.download()
Returns:
WebSession
'''
return WebSession(
request,
http_client=self._http_client,
redirect_tracker=self._redirect_tracker_factory(),
request_factory=self._request_factory,
cookie_jar=self._cookie_jar,
) | [
"def",
"session",
"(",
"self",
",",
"request",
":",
"Request",
")",
"->",
"WebSession",
":",
"return",
"WebSession",
"(",
"request",
",",
"http_client",
"=",
"self",
".",
"_http_client",
",",
"redirect_tracker",
"=",
"self",
".",
"_redirect_tracker_factory",
"... | Return a fetch session.
Args:
request: The request to be fetched.
Example usage::
client = WebClient()
session = client.session(Request('http://www.example.com'))
with session:
while not session.done():
request = session.next_request()
print(request)
response = yield from session.start()
print(response)
if session.done():
with open('myfile.html') as file:
yield from session.download(file)
else:
yield from session.download()
Returns:
WebSession | [
"Return",
"a",
"fetch",
"session",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L271-L305 | train | 201,314 |
ArchiveTeam/wpull | wpull/processor/ftp.py | to_dir_path_url | def to_dir_path_url(url_info: URLInfo) -> str:
'''Return URL string with the path replaced with directory only.'''
dir_name = posixpath.dirname(url_info.path)
if not dir_name.endswith('/'):
url_template = 'ftp://{}{}/'
else:
url_template = 'ftp://{}{}'
return url_template.format(url_info.hostname_with_port, dir_name) | python | def to_dir_path_url(url_info: URLInfo) -> str:
'''Return URL string with the path replaced with directory only.'''
dir_name = posixpath.dirname(url_info.path)
if not dir_name.endswith('/'):
url_template = 'ftp://{}{}/'
else:
url_template = 'ftp://{}{}'
return url_template.format(url_info.hostname_with_port, dir_name) | [
"def",
"to_dir_path_url",
"(",
"url_info",
":",
"URLInfo",
")",
"->",
"str",
":",
"dir_name",
"=",
"posixpath",
".",
"dirname",
"(",
"url_info",
".",
"path",
")",
"if",
"not",
"dir_name",
".",
"endswith",
"(",
"'/'",
")",
":",
"url_template",
"=",
"'ftp:... | Return URL string with the path replaced with directory only. | [
"Return",
"URL",
"string",
"with",
"the",
"path",
"replaced",
"with",
"directory",
"only",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/ftp.py#L435-L444 | train | 201,315 |
ArchiveTeam/wpull | wpull/processor/ftp.py | FTPProcessorSession._prepare_request_file_vs_dir | def _prepare_request_file_vs_dir(self, request: Request) -> bool:
'''Check if file, modify request, and return whether is a file.
Coroutine.
'''
if self._item_session.url_record.link_type:
is_file = self._item_session.url_record.link_type == LinkType.file
elif request.url_info.path.endswith('/'):
is_file = False
else:
is_file = 'unknown'
if is_file == 'unknown':
files = yield from self._fetch_parent_path(request)
if not files:
return True
filename = posixpath.basename(request.file_path)
for file_entry in files:
if file_entry.name == filename:
_logger.debug('Found entry in parent. Type {}',
file_entry.type)
is_file = file_entry.type != 'dir'
break
else:
_logger.debug('Did not find entry. Assume file.')
return True
if not is_file:
request.url = append_slash_to_path_url(request.url_info)
_logger.debug('Request URL changed to {}. Path={}.',
request.url, request.file_path)
return is_file | python | def _prepare_request_file_vs_dir(self, request: Request) -> bool:
'''Check if file, modify request, and return whether is a file.
Coroutine.
'''
if self._item_session.url_record.link_type:
is_file = self._item_session.url_record.link_type == LinkType.file
elif request.url_info.path.endswith('/'):
is_file = False
else:
is_file = 'unknown'
if is_file == 'unknown':
files = yield from self._fetch_parent_path(request)
if not files:
return True
filename = posixpath.basename(request.file_path)
for file_entry in files:
if file_entry.name == filename:
_logger.debug('Found entry in parent. Type {}',
file_entry.type)
is_file = file_entry.type != 'dir'
break
else:
_logger.debug('Did not find entry. Assume file.')
return True
if not is_file:
request.url = append_slash_to_path_url(request.url_info)
_logger.debug('Request URL changed to {}. Path={}.',
request.url, request.file_path)
return is_file | [
"def",
"_prepare_request_file_vs_dir",
"(",
"self",
",",
"request",
":",
"Request",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_item_session",
".",
"url_record",
".",
"link_type",
":",
"is_file",
"=",
"self",
".",
"_item_session",
".",
"url_record",
".",
"l... | Check if file, modify request, and return whether is a file.
Coroutine. | [
"Check",
"if",
"file",
"modify",
"request",
"and",
"return",
"whether",
"is",
"a",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/ftp.py#L170-L205 | train | 201,316 |
ArchiveTeam/wpull | wpull/processor/ftp.py | FTPProcessorSession._fetch_parent_path | def _fetch_parent_path(self, request: Request, use_cache: bool=True):
'''Fetch parent directory and return list FileEntry.
Coroutine.
'''
directory_url = to_dir_path_url(request.url_info)
if use_cache:
if directory_url in self._processor.listing_cache:
return self._processor.listing_cache[directory_url]
directory_request = copy.deepcopy(request)
directory_request.url = directory_url
_logger.debug('Check if URL {} is file with {}.', request.url,
directory_url)
with self._processor.ftp_client.session() as session:
try:
yield from session.start_listing(directory_request)
except FTPServerError:
_logger.debug('Got an error. Assume is file.')
if use_cache:
self._processor.listing_cache[directory_url] = None
return
temp_file = tempfile.NamedTemporaryFile(
dir=self._item_session.app_session.root_path,
prefix='tmp-wpull-list'
)
with temp_file as file:
directory_response = yield from session.download_listing(
file, duration_timeout=self._fetch_rule.duration_timeout)
if use_cache:
self._processor.listing_cache[directory_url] = \
directory_response.files
return directory_response.files | python | def _fetch_parent_path(self, request: Request, use_cache: bool=True):
'''Fetch parent directory and return list FileEntry.
Coroutine.
'''
directory_url = to_dir_path_url(request.url_info)
if use_cache:
if directory_url in self._processor.listing_cache:
return self._processor.listing_cache[directory_url]
directory_request = copy.deepcopy(request)
directory_request.url = directory_url
_logger.debug('Check if URL {} is file with {}.', request.url,
directory_url)
with self._processor.ftp_client.session() as session:
try:
yield from session.start_listing(directory_request)
except FTPServerError:
_logger.debug('Got an error. Assume is file.')
if use_cache:
self._processor.listing_cache[directory_url] = None
return
temp_file = tempfile.NamedTemporaryFile(
dir=self._item_session.app_session.root_path,
prefix='tmp-wpull-list'
)
with temp_file as file:
directory_response = yield from session.download_listing(
file, duration_timeout=self._fetch_rule.duration_timeout)
if use_cache:
self._processor.listing_cache[directory_url] = \
directory_response.files
return directory_response.files | [
"def",
"_fetch_parent_path",
"(",
"self",
",",
"request",
":",
"Request",
",",
"use_cache",
":",
"bool",
"=",
"True",
")",
":",
"directory_url",
"=",
"to_dir_path_url",
"(",
"request",
".",
"url_info",
")",
"if",
"use_cache",
":",
"if",
"directory_url",
"in"... | Fetch parent directory and return list FileEntry.
Coroutine. | [
"Fetch",
"parent",
"directory",
"and",
"return",
"list",
"FileEntry",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/ftp.py#L208-L249 | train | 201,317 |
ArchiveTeam/wpull | wpull/processor/ftp.py | FTPProcessorSession._add_listing_links | def _add_listing_links(self, response: ListingResponse):
'''Add links from file listing response.'''
base_url = response.request.url_info.url
if self._glob_pattern:
level = self._item_session.url_record.level
else:
level = None
for file_entry in response.files:
if self._glob_pattern and \
not fnmatch.fnmatchcase(file_entry.name, self._glob_pattern):
continue
if file_entry.type == 'dir':
linked_url = urljoin_safe(base_url, file_entry.name + '/')
elif file_entry.type in ('file', 'symlink', None):
if not self._processor.fetch_params.retr_symlinks and \
file_entry.type == 'symlink':
self._make_symlink(file_entry.name, file_entry.dest)
linked_url = None
else:
linked_url = urljoin_safe(base_url, file_entry.name)
else:
linked_url = None
if linked_url:
linked_url_info = parse_url_or_log(linked_url)
if linked_url_info:
verdict = self._fetch_rule.check_ftp_request(self._item_session)[0]
if verdict:
if linked_url_info.path.endswith('/'):
self._item_session.add_child_url(linked_url_info.url, link_type=LinkType.directory)
else:
self._item_session.add_child_url(linked_url_info.url, link_type=LinkType.file, level=level) | python | def _add_listing_links(self, response: ListingResponse):
'''Add links from file listing response.'''
base_url = response.request.url_info.url
if self._glob_pattern:
level = self._item_session.url_record.level
else:
level = None
for file_entry in response.files:
if self._glob_pattern and \
not fnmatch.fnmatchcase(file_entry.name, self._glob_pattern):
continue
if file_entry.type == 'dir':
linked_url = urljoin_safe(base_url, file_entry.name + '/')
elif file_entry.type in ('file', 'symlink', None):
if not self._processor.fetch_params.retr_symlinks and \
file_entry.type == 'symlink':
self._make_symlink(file_entry.name, file_entry.dest)
linked_url = None
else:
linked_url = urljoin_safe(base_url, file_entry.name)
else:
linked_url = None
if linked_url:
linked_url_info = parse_url_or_log(linked_url)
if linked_url_info:
verdict = self._fetch_rule.check_ftp_request(self._item_session)[0]
if verdict:
if linked_url_info.path.endswith('/'):
self._item_session.add_child_url(linked_url_info.url, link_type=LinkType.directory)
else:
self._item_session.add_child_url(linked_url_info.url, link_type=LinkType.file, level=level) | [
"def",
"_add_listing_links",
"(",
"self",
",",
"response",
":",
"ListingResponse",
")",
":",
"base_url",
"=",
"response",
".",
"request",
".",
"url_info",
".",
"url",
"if",
"self",
".",
"_glob_pattern",
":",
"level",
"=",
"self",
".",
"_item_session",
".",
... | Add links from file listing response. | [
"Add",
"links",
"from",
"file",
"listing",
"response",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/ftp.py#L328-L364 | train | 201,318 |
ArchiveTeam/wpull | wpull/processor/ftp.py | FTPProcessorSession._make_symlink | def _make_symlink(self, link_name: str, link_target: str):
'''Make a symlink on the system.'''
path = self._file_writer_session.extra_resource_path('dummy')
if path:
dir_path = os.path.dirname(path)
symlink_path = os.path.join(dir_path, link_name)
_logger.debug('symlink {} -> {}', symlink_path, link_target)
os.symlink(link_target, symlink_path)
_logger.info(
_('Created symbolic link {symlink_path} to target {symlink_target}.'),
symlink_path=symlink_path,
symlink_target=link_target
) | python | def _make_symlink(self, link_name: str, link_target: str):
'''Make a symlink on the system.'''
path = self._file_writer_session.extra_resource_path('dummy')
if path:
dir_path = os.path.dirname(path)
symlink_path = os.path.join(dir_path, link_name)
_logger.debug('symlink {} -> {}', symlink_path, link_target)
os.symlink(link_target, symlink_path)
_logger.info(
_('Created symbolic link {symlink_path} to target {symlink_target}.'),
symlink_path=symlink_path,
symlink_target=link_target
) | [
"def",
"_make_symlink",
"(",
"self",
",",
"link_name",
":",
"str",
",",
"link_target",
":",
"str",
")",
":",
"path",
"=",
"self",
".",
"_file_writer_session",
".",
"extra_resource_path",
"(",
"'dummy'",
")",
"if",
"path",
":",
"dir_path",
"=",
"os",
".",
... | Make a symlink on the system. | [
"Make",
"a",
"symlink",
"on",
"the",
"system",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/ftp.py#L395-L411 | train | 201,319 |
ArchiveTeam/wpull | wpull/processor/ftp.py | FTPProcessorSession._apply_unix_permissions | def _apply_unix_permissions(self, request: Request, response: Response):
'''Fetch and apply Unix permissions.
Coroutine.
'''
files = yield from self._fetch_parent_path(request)
if not files:
return
filename = posixpath.basename(request.file_path)
for file_entry in files:
if file_entry.name == filename and file_entry.perm:
_logger.debug(
'Set chmod {} o{:o}.',
response.body.name, file_entry.perm
)
os.chmod(response.body.name, file_entry.perm) | python | def _apply_unix_permissions(self, request: Request, response: Response):
'''Fetch and apply Unix permissions.
Coroutine.
'''
files = yield from self._fetch_parent_path(request)
if not files:
return
filename = posixpath.basename(request.file_path)
for file_entry in files:
if file_entry.name == filename and file_entry.perm:
_logger.debug(
'Set chmod {} o{:o}.',
response.body.name, file_entry.perm
)
os.chmod(response.body.name, file_entry.perm) | [
"def",
"_apply_unix_permissions",
"(",
"self",
",",
"request",
":",
"Request",
",",
"response",
":",
"Response",
")",
":",
"files",
"=",
"yield",
"from",
"self",
".",
"_fetch_parent_path",
"(",
"request",
")",
"if",
"not",
"files",
":",
"return",
"filename",... | Fetch and apply Unix permissions.
Coroutine. | [
"Fetch",
"and",
"apply",
"Unix",
"permissions",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/ftp.py#L414-L432 | train | 201,320 |
ArchiveTeam/wpull | wpull/application/tasks/rule.py | URLFiltersSetupTask._build_url_rewriter | def _build_url_rewriter(cls, session: AppSession):
'''Build URL rewriter if needed.'''
if session.args.escaped_fragment or session.args.strip_session_id:
return session.factory.new(
'URLRewriter',
hash_fragment=session.args.escaped_fragment,
session_id=session.args.strip_session_id
) | python | def _build_url_rewriter(cls, session: AppSession):
'''Build URL rewriter if needed.'''
if session.args.escaped_fragment or session.args.strip_session_id:
return session.factory.new(
'URLRewriter',
hash_fragment=session.args.escaped_fragment,
session_id=session.args.strip_session_id
) | [
"def",
"_build_url_rewriter",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"if",
"session",
".",
"args",
".",
"escaped_fragment",
"or",
"session",
".",
"args",
".",
"strip_session_id",
":",
"return",
"session",
".",
"factory",
".",
"new",
"(",
... | Build URL rewriter if needed. | [
"Build",
"URL",
"rewriter",
"if",
"needed",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/rule.py#L24-L31 | train | 201,321 |
ArchiveTeam/wpull | wpull/application/tasks/rule.py | URLFiltersSetupTask._build_url_filters | def _build_url_filters(cls, session: AppSession):
'''Create the URL filter instances.
Returns:
A list of URL filter instances
'''
args = session.args
filters = [
HTTPSOnlyFilter() if args.https_only else SchemeFilter(),
RecursiveFilter(
enabled=args.recursive, page_requisites=args.page_requisites
),
FollowFTPFilter(follow=args.follow_ftp),
]
if args.no_parent:
filters.append(ParentFilter())
if args.domains or args.exclude_domains:
filters.append(
BackwardDomainFilter(args.domains, args.exclude_domains)
)
if args.hostnames or args.exclude_hostnames:
filters.append(
HostnameFilter(args.hostnames, args.exclude_hostnames)
)
if args.tries:
filters.append(TriesFilter(args.tries))
if args.level and args.recursive or args.page_requisites_level:
filters.append(
LevelFilter(args.level,
inline_max_depth=args.page_requisites_level)
)
if args.accept_regex or args.reject_regex:
filters.append(RegexFilter(args.accept_regex, args.reject_regex))
if args.include_directories or args.exclude_directories:
filters.append(
DirectoryFilter(
args.include_directories, args.exclude_directories
)
)
if args.accept or args.reject:
filters.append(BackwardFilenameFilter(args.accept, args.reject))
return filters | python | def _build_url_filters(cls, session: AppSession):
'''Create the URL filter instances.
Returns:
A list of URL filter instances
'''
args = session.args
filters = [
HTTPSOnlyFilter() if args.https_only else SchemeFilter(),
RecursiveFilter(
enabled=args.recursive, page_requisites=args.page_requisites
),
FollowFTPFilter(follow=args.follow_ftp),
]
if args.no_parent:
filters.append(ParentFilter())
if args.domains or args.exclude_domains:
filters.append(
BackwardDomainFilter(args.domains, args.exclude_domains)
)
if args.hostnames or args.exclude_hostnames:
filters.append(
HostnameFilter(args.hostnames, args.exclude_hostnames)
)
if args.tries:
filters.append(TriesFilter(args.tries))
if args.level and args.recursive or args.page_requisites_level:
filters.append(
LevelFilter(args.level,
inline_max_depth=args.page_requisites_level)
)
if args.accept_regex or args.reject_regex:
filters.append(RegexFilter(args.accept_regex, args.reject_regex))
if args.include_directories or args.exclude_directories:
filters.append(
DirectoryFilter(
args.include_directories, args.exclude_directories
)
)
if args.accept or args.reject:
filters.append(BackwardFilenameFilter(args.accept, args.reject))
return filters | [
"def",
"_build_url_filters",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"args",
"=",
"session",
".",
"args",
"filters",
"=",
"[",
"HTTPSOnlyFilter",
"(",
")",
"if",
"args",
".",
"https_only",
"else",
"SchemeFilter",
"(",
")",
",",
"RecursiveF... | Create the URL filter instances.
Returns:
A list of URL filter instances | [
"Create",
"the",
"URL",
"filter",
"instances",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/rule.py#L34-L85 | train | 201,322 |
ArchiveTeam/wpull | wpull/application/tasks/conversion.py | LinkConversionSetupTask._build_document_converter | def _build_document_converter(cls, session: AppSession):
'''Build the Document Converter.'''
if not session.args.convert_links:
return
converter = session.factory.new(
'BatchDocumentConverter',
session.factory['HTMLParser'],
session.factory['ElementWalker'],
session.factory['URLTable'],
backup=session.args.backup_converted
)
return converter | python | def _build_document_converter(cls, session: AppSession):
'''Build the Document Converter.'''
if not session.args.convert_links:
return
converter = session.factory.new(
'BatchDocumentConverter',
session.factory['HTMLParser'],
session.factory['ElementWalker'],
session.factory['URLTable'],
backup=session.args.backup_converted
)
return converter | [
"def",
"_build_document_converter",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"if",
"not",
"session",
".",
"args",
".",
"convert_links",
":",
"return",
"converter",
"=",
"session",
".",
"factory",
".",
"new",
"(",
"'BatchDocumentConverter'",
","... | Build the Document Converter. | [
"Build",
"the",
"Document",
"Converter",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/conversion.py#L16-L30 | train | 201,323 |
ArchiveTeam/wpull | wpull/application/tasks/log.py | LoggingSetupTask._setup_logging | def _setup_logging(cls, args):
'''Set up the root logger if needed.
The root logger is set the appropriate level so the file and WARC logs
work correctly.
'''
assert (
logging.CRITICAL >
logging.ERROR >
logging.WARNING >
logging.INFO >
logging.DEBUG >
logging.NOTSET
)
assert (
LOG_VERY_QUIET >
LOG_QUIET >
LOG_NO_VERBOSE >
LOG_VERBOSE >
LOG_DEBUG
)
assert args.verbosity
root_logger = logging.getLogger()
current_level = root_logger.getEffectiveLevel()
min_level = LOG_VERY_QUIET
if args.verbosity == LOG_QUIET:
min_level = logging.ERROR
if args.verbosity in (LOG_NO_VERBOSE, LOG_VERBOSE) \
or args.warc_file \
or args.output_file or args.append_output:
min_level = logging.INFO
if args.verbosity == LOG_DEBUG:
min_level = logging.DEBUG
if current_level > min_level:
root_logger.setLevel(min_level)
root_logger.debug(
'Wpull needs the root logger level set to {0}.'
.format(min_level)
)
if current_level <= logging.INFO:
logging.captureWarnings(True) | python | def _setup_logging(cls, args):
'''Set up the root logger if needed.
The root logger is set the appropriate level so the file and WARC logs
work correctly.
'''
assert (
logging.CRITICAL >
logging.ERROR >
logging.WARNING >
logging.INFO >
logging.DEBUG >
logging.NOTSET
)
assert (
LOG_VERY_QUIET >
LOG_QUIET >
LOG_NO_VERBOSE >
LOG_VERBOSE >
LOG_DEBUG
)
assert args.verbosity
root_logger = logging.getLogger()
current_level = root_logger.getEffectiveLevel()
min_level = LOG_VERY_QUIET
if args.verbosity == LOG_QUIET:
min_level = logging.ERROR
if args.verbosity in (LOG_NO_VERBOSE, LOG_VERBOSE) \
or args.warc_file \
or args.output_file or args.append_output:
min_level = logging.INFO
if args.verbosity == LOG_DEBUG:
min_level = logging.DEBUG
if current_level > min_level:
root_logger.setLevel(min_level)
root_logger.debug(
'Wpull needs the root logger level set to {0}.'
.format(min_level)
)
if current_level <= logging.INFO:
logging.captureWarnings(True) | [
"def",
"_setup_logging",
"(",
"cls",
",",
"args",
")",
":",
"assert",
"(",
"logging",
".",
"CRITICAL",
">",
"logging",
".",
"ERROR",
">",
"logging",
".",
"WARNING",
">",
"logging",
".",
"INFO",
">",
"logging",
".",
"DEBUG",
">",
"logging",
".",
"NOTSET... | Set up the root logger if needed.
The root logger is set the appropriate level so the file and WARC logs
work correctly. | [
"Set",
"up",
"the",
"root",
"logger",
"if",
"needed",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/log.py#L18-L64 | train | 201,324 |
ArchiveTeam/wpull | wpull/application/tasks/log.py | LoggingSetupTask._setup_console_logger | def _setup_console_logger(cls, session: AppSession, args, stderr):
'''Set up the console logger.
A handler and with a formatter is added to the root logger.
'''
stream = new_encoded_stream(args, stderr)
logger = logging.getLogger()
session.console_log_handler = handler = logging.StreamHandler(stream)
formatter = logging.Formatter('%(levelname)s %(message)s')
log_filter = logging.Filter('wpull')
handler.setFormatter(formatter)
handler.setLevel(args.verbosity or logging.INFO)
handler.addFilter(log_filter)
logger.addHandler(handler) | python | def _setup_console_logger(cls, session: AppSession, args, stderr):
'''Set up the console logger.
A handler and with a formatter is added to the root logger.
'''
stream = new_encoded_stream(args, stderr)
logger = logging.getLogger()
session.console_log_handler = handler = logging.StreamHandler(stream)
formatter = logging.Formatter('%(levelname)s %(message)s')
log_filter = logging.Filter('wpull')
handler.setFormatter(formatter)
handler.setLevel(args.verbosity or logging.INFO)
handler.addFilter(log_filter)
logger.addHandler(handler) | [
"def",
"_setup_console_logger",
"(",
"cls",
",",
"session",
":",
"AppSession",
",",
"args",
",",
"stderr",
")",
":",
"stream",
"=",
"new_encoded_stream",
"(",
"args",
",",
"stderr",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"session",
".",... | Set up the console logger.
A handler and with a formatter is added to the root logger. | [
"Set",
"up",
"the",
"console",
"logger",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/log.py#L67-L83 | train | 201,325 |
ArchiveTeam/wpull | wpull/application/tasks/log.py | LoggingSetupTask._setup_file_logger | def _setup_file_logger(cls, session: AppSession, args):
'''Set up the file message logger.
A file log handler and with a formatter is added to the root logger.
'''
if not (args.output_file or args.append_output):
return
logger = logging.getLogger()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if args.output_file:
filename = args.output_file
mode = 'w'
else:
filename = args.append_output
mode = 'a'
session.file_log_handler = handler = logging.FileHandler(
filename, mode, encoding='utf-8')
handler.setFormatter(formatter)
logger.addHandler(handler)
if args.verbosity == logging.DEBUG:
handler.setLevel(logging.DEBUG)
else:
handler.setLevel(logging.INFO) | python | def _setup_file_logger(cls, session: AppSession, args):
'''Set up the file message logger.
A file log handler and with a formatter is added to the root logger.
'''
if not (args.output_file or args.append_output):
return
logger = logging.getLogger()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if args.output_file:
filename = args.output_file
mode = 'w'
else:
filename = args.append_output
mode = 'a'
session.file_log_handler = handler = logging.FileHandler(
filename, mode, encoding='utf-8')
handler.setFormatter(formatter)
logger.addHandler(handler)
if args.verbosity == logging.DEBUG:
handler.setLevel(logging.DEBUG)
else:
handler.setLevel(logging.INFO) | [
"def",
"_setup_file_logger",
"(",
"cls",
",",
"session",
":",
"AppSession",
",",
"args",
")",
":",
"if",
"not",
"(",
"args",
".",
"output_file",
"or",
"args",
".",
"append_output",
")",
":",
"return",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",... | Set up the file message logger.
A file log handler and with a formatter is added to the root logger. | [
"Set",
"up",
"the",
"file",
"message",
"logger",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/log.py#L86-L114 | train | 201,326 |
ArchiveTeam/wpull | wpull/processor/coprocessor/phantomjs.py | PhantomJSCoprocessor._run_driver | def _run_driver(self, item_session: ItemSession, request, response):
'''Start PhantomJS processing.'''
_logger.debug('Started PhantomJS processing.')
session = PhantomJSCoprocessorSession(
self._phantomjs_driver_factory, self._root_path,
self._processing_rule, self._file_writer_session,
request, response,
item_session, self._phantomjs_params, self._warc_recorder
)
with contextlib.closing(session):
yield from session.run()
_logger.debug('Ended PhantomJS processing.') | python | def _run_driver(self, item_session: ItemSession, request, response):
'''Start PhantomJS processing.'''
_logger.debug('Started PhantomJS processing.')
session = PhantomJSCoprocessorSession(
self._phantomjs_driver_factory, self._root_path,
self._processing_rule, self._file_writer_session,
request, response,
item_session, self._phantomjs_params, self._warc_recorder
)
with contextlib.closing(session):
yield from session.run()
_logger.debug('Ended PhantomJS processing.') | [
"def",
"_run_driver",
"(",
"self",
",",
"item_session",
":",
"ItemSession",
",",
"request",
",",
"response",
")",
":",
"_logger",
".",
"debug",
"(",
"'Started PhantomJS processing.'",
")",
"session",
"=",
"PhantomJSCoprocessorSession",
"(",
"self",
".",
"_phantomj... | Start PhantomJS processing. | [
"Start",
"PhantomJS",
"processing",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/phantomjs.py#L125-L139 | train | 201,327 |
ArchiveTeam/wpull | wpull/processor/coprocessor/phantomjs.py | PhantomJSCoprocessorSession._add_warc_action_log | def _add_warc_action_log(self, path, url):
'''Add the action log to the WARC file.'''
_logger.debug('Adding action log record.')
actions = []
with open(path, 'r', encoding='utf-8', errors='replace') as file:
for line in file:
actions.append(json.loads(line))
log_data = json.dumps(
{'actions': actions},
indent=4,
).encode('utf-8')
self._action_warc_record = record = WARCRecord()
record.set_common_fields('metadata', 'application/json')
record.fields['WARC-Target-URI'] = 'urn:X-wpull:snapshot?url={0}' \
.format(wpull.url.percent_encode_query_value(url))
record.block_file = io.BytesIO(log_data)
self._warc_recorder.set_length_and_maybe_checksums(record)
self._warc_recorder.write_record(record) | python | def _add_warc_action_log(self, path, url):
'''Add the action log to the WARC file.'''
_logger.debug('Adding action log record.')
actions = []
with open(path, 'r', encoding='utf-8', errors='replace') as file:
for line in file:
actions.append(json.loads(line))
log_data = json.dumps(
{'actions': actions},
indent=4,
).encode('utf-8')
self._action_warc_record = record = WARCRecord()
record.set_common_fields('metadata', 'application/json')
record.fields['WARC-Target-URI'] = 'urn:X-wpull:snapshot?url={0}' \
.format(wpull.url.percent_encode_query_value(url))
record.block_file = io.BytesIO(log_data)
self._warc_recorder.set_length_and_maybe_checksums(record)
self._warc_recorder.write_record(record) | [
"def",
"_add_warc_action_log",
"(",
"self",
",",
"path",
",",
"url",
")",
":",
"_logger",
".",
"debug",
"(",
"'Adding action log record.'",
")",
"actions",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
",",
"err... | Add the action log to the WARC file. | [
"Add",
"the",
"action",
"log",
"to",
"the",
"WARC",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/phantomjs.py#L247-L268 | train | 201,328 |
ArchiveTeam/wpull | wpull/processor/coprocessor/phantomjs.py | PhantomJSCoprocessorSession._add_warc_snapshot | def _add_warc_snapshot(self, filename, url):
'''Add the snaphot to the WARC file.'''
_logger.debug('Adding snapshot record.')
extension = os.path.splitext(filename)[1]
content_type = {
'.pdf': 'application/pdf',
'.html': 'text/html',
'.png': 'image/png',
'.gif': 'image/gif'
}[extension]
record = WARCRecord()
record.set_common_fields('resource', content_type)
record.fields['WARC-Target-URI'] = 'urn:X-wpull:snapshot?url={0}' \
.format(wpull.url.percent_encode_query_value(url))
if self._action_warc_record:
record.fields['WARC-Concurrent-To'] = \
self._action_warc_record.fields[WARCRecord.WARC_RECORD_ID]
with open(filename, 'rb') as in_file:
record.block_file = in_file
self._warc_recorder.set_length_and_maybe_checksums(record)
self._warc_recorder.write_record(record) | python | def _add_warc_snapshot(self, filename, url):
'''Add the snaphot to the WARC file.'''
_logger.debug('Adding snapshot record.')
extension = os.path.splitext(filename)[1]
content_type = {
'.pdf': 'application/pdf',
'.html': 'text/html',
'.png': 'image/png',
'.gif': 'image/gif'
}[extension]
record = WARCRecord()
record.set_common_fields('resource', content_type)
record.fields['WARC-Target-URI'] = 'urn:X-wpull:snapshot?url={0}' \
.format(wpull.url.percent_encode_query_value(url))
if self._action_warc_record:
record.fields['WARC-Concurrent-To'] = \
self._action_warc_record.fields[WARCRecord.WARC_RECORD_ID]
with open(filename, 'rb') as in_file:
record.block_file = in_file
self._warc_recorder.set_length_and_maybe_checksums(record)
self._warc_recorder.write_record(record) | [
"def",
"_add_warc_snapshot",
"(",
"self",
",",
"filename",
",",
"url",
")",
":",
"_logger",
".",
"debug",
"(",
"'Adding snapshot record.'",
")",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"content_type",
"=",... | Add the snaphot to the WARC file. | [
"Add",
"the",
"snaphot",
"to",
"the",
"WARC",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/phantomjs.py#L270-L295 | train | 201,329 |
ArchiveTeam/wpull | wpull/processor/coprocessor/phantomjs.py | PhantomJSCoprocessorSession._scrape_document | def _scrape_document(self):
'''Extract links from the DOM.'''
mock_response = self._new_mock_response(
self._response, self._get_temp_path('phantom', '.html')
)
self._item_session.request = self._request
self._item_session.response = mock_response
self._processing_rule.scrape_document(item_session)
if mock_response.body:
mock_response.body.close() | python | def _scrape_document(self):
'''Extract links from the DOM.'''
mock_response = self._new_mock_response(
self._response, self._get_temp_path('phantom', '.html')
)
self._item_session.request = self._request
self._item_session.response = mock_response
self._processing_rule.scrape_document(item_session)
if mock_response.body:
mock_response.body.close() | [
"def",
"_scrape_document",
"(",
"self",
")",
":",
"mock_response",
"=",
"self",
".",
"_new_mock_response",
"(",
"self",
".",
"_response",
",",
"self",
".",
"_get_temp_path",
"(",
"'phantom'",
",",
"'.html'",
")",
")",
"self",
".",
"_item_session",
".",
"requ... | Extract links from the DOM. | [
"Extract",
"links",
"from",
"the",
"DOM",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/phantomjs.py#L297-L309 | train | 201,330 |
ArchiveTeam/wpull | wpull/processor/coprocessor/phantomjs.py | PhantomJSCoprocessorSession._new_mock_response | def _new_mock_response(self, response, file_path):
'''Return a new mock Response with the content.'''
mock_response = copy.copy(response)
mock_response.body = Body(open(file_path, 'rb'))
mock_response.fields = NameValueRecord()
for name, value in response.fields.get_all():
mock_response.fields.add(name, value)
mock_response.fields['Content-Type'] = 'text/html; charset="utf-8"'
return mock_response | python | def _new_mock_response(self, response, file_path):
'''Return a new mock Response with the content.'''
mock_response = copy.copy(response)
mock_response.body = Body(open(file_path, 'rb'))
mock_response.fields = NameValueRecord()
for name, value in response.fields.get_all():
mock_response.fields.add(name, value)
mock_response.fields['Content-Type'] = 'text/html; charset="utf-8"'
return mock_response | [
"def",
"_new_mock_response",
"(",
"self",
",",
"response",
",",
"file_path",
")",
":",
"mock_response",
"=",
"copy",
".",
"copy",
"(",
"response",
")",
"mock_response",
".",
"body",
"=",
"Body",
"(",
"open",
"(",
"file_path",
",",
"'rb'",
")",
")",
"mock... | Return a new mock Response with the content. | [
"Return",
"a",
"new",
"mock",
"Response",
"with",
"the",
"content",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/phantomjs.py#L311-L323 | train | 201,331 |
ArchiveTeam/wpull | wpull/application/tasks/sslcontext.py | SSLContextTask._build_ssl_context | def _build_ssl_context(cls, session: AppSession) -> ssl.SSLContext:
'''Create the SSL options.
The options must be accepted by the `ssl` module.
'''
args = session.args
# Logic is based on tornado.netutil.ssl_options_to_context
ssl_context = ssl.SSLContext(args.secure_protocol)
if args.check_certificate:
ssl_context.verify_mode = ssl.CERT_REQUIRED
cls._load_ca_certs(session)
ssl_context.load_verify_locations(session.ca_certs_filename)
else:
ssl_context.verify_mode = ssl.CERT_NONE
if args.strong_crypto:
ssl_context.options |= ssl.OP_NO_SSLv2
ssl_context.options |= ssl.OP_NO_SSLv3 # POODLE
if hasattr(ssl, 'OP_NO_COMPRESSION'):
ssl_context.options |= ssl.OP_NO_COMPRESSION # CRIME
else:
_logger.warning(_('Unable to disable TLS compression.'))
if args.certificate:
ssl_context.load_cert_chain(args.certificate, args.private_key)
if args.edg_file:
ssl.RAND_egd(args.edg_file)
if args.random_file:
with open(args.random_file, 'rb') as in_file:
# Use 16KB because Wget
ssl.RAND_add(in_file.read(15360), 0.0)
return ssl_context | python | def _build_ssl_context(cls, session: AppSession) -> ssl.SSLContext:
'''Create the SSL options.
The options must be accepted by the `ssl` module.
'''
args = session.args
# Logic is based on tornado.netutil.ssl_options_to_context
ssl_context = ssl.SSLContext(args.secure_protocol)
if args.check_certificate:
ssl_context.verify_mode = ssl.CERT_REQUIRED
cls._load_ca_certs(session)
ssl_context.load_verify_locations(session.ca_certs_filename)
else:
ssl_context.verify_mode = ssl.CERT_NONE
if args.strong_crypto:
ssl_context.options |= ssl.OP_NO_SSLv2
ssl_context.options |= ssl.OP_NO_SSLv3 # POODLE
if hasattr(ssl, 'OP_NO_COMPRESSION'):
ssl_context.options |= ssl.OP_NO_COMPRESSION # CRIME
else:
_logger.warning(_('Unable to disable TLS compression.'))
if args.certificate:
ssl_context.load_cert_chain(args.certificate, args.private_key)
if args.edg_file:
ssl.RAND_egd(args.edg_file)
if args.random_file:
with open(args.random_file, 'rb') as in_file:
# Use 16KB because Wget
ssl.RAND_add(in_file.read(15360), 0.0)
return ssl_context | [
"def",
"_build_ssl_context",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
"->",
"ssl",
".",
"SSLContext",
":",
"args",
"=",
"session",
".",
"args",
"# Logic is based on tornado.netutil.ssl_options_to_context",
"ssl_context",
"=",
"ssl",
".",
"SSLContext",
"("... | Create the SSL options.
The options must be accepted by the `ssl` module. | [
"Create",
"the",
"SSL",
"options",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/sslcontext.py#L25-L62 | train | 201,332 |
ArchiveTeam/wpull | wpull/application/tasks/sslcontext.py | SSLContextTask._load_ca_certs | def _load_ca_certs(cls, session: AppSession, clean: bool=True):
'''Load the Certificate Authority certificates.
'''
args = session.args
if session.ca_certs_filename:
return session.ca_certs_filename
certs = set()
if args.use_internal_ca_certs:
pem_filename = os.path.join(
os.path.dirname(__file__), '..', '..', 'cert', 'ca-bundle.pem'
)
certs.update(cls._read_pem_file(pem_filename, from_package=True))
if args.ca_directory:
if os.path.isdir(args.ca_directory):
for filename in os.listdir(args.ca_directory):
if os.path.isfile(filename):
certs.update(cls._read_pem_file(filename))
else:
_logger.warning(__(
_('Certificate directory {path} does not exist.'),
path=args.ca_directory
))
if args.ca_certificate:
if os.path.isfile(args.ca_certificate):
certs.update(cls._read_pem_file(args.ca_certificate))
else:
_logger.warning(__(
_('Certificate file {path} does not exist.'),
path=args.ca_certificate
))
session.ca_certs_filename = certs_filename = tempfile.mkstemp(
suffix='.pem', prefix='tmp-wpull-')[1]
def clean_certs_file():
os.remove(certs_filename)
if clean:
atexit.register(clean_certs_file)
with open(certs_filename, 'w+b') as certs_file:
for cert in certs:
certs_file.write(cert)
_logger.debug('CA certs loaded.') | python | def _load_ca_certs(cls, session: AppSession, clean: bool=True):
'''Load the Certificate Authority certificates.
'''
args = session.args
if session.ca_certs_filename:
return session.ca_certs_filename
certs = set()
if args.use_internal_ca_certs:
pem_filename = os.path.join(
os.path.dirname(__file__), '..', '..', 'cert', 'ca-bundle.pem'
)
certs.update(cls._read_pem_file(pem_filename, from_package=True))
if args.ca_directory:
if os.path.isdir(args.ca_directory):
for filename in os.listdir(args.ca_directory):
if os.path.isfile(filename):
certs.update(cls._read_pem_file(filename))
else:
_logger.warning(__(
_('Certificate directory {path} does not exist.'),
path=args.ca_directory
))
if args.ca_certificate:
if os.path.isfile(args.ca_certificate):
certs.update(cls._read_pem_file(args.ca_certificate))
else:
_logger.warning(__(
_('Certificate file {path} does not exist.'),
path=args.ca_certificate
))
session.ca_certs_filename = certs_filename = tempfile.mkstemp(
suffix='.pem', prefix='tmp-wpull-')[1]
def clean_certs_file():
os.remove(certs_filename)
if clean:
atexit.register(clean_certs_file)
with open(certs_filename, 'w+b') as certs_file:
for cert in certs:
certs_file.write(cert)
_logger.debug('CA certs loaded.') | [
"def",
"_load_ca_certs",
"(",
"cls",
",",
"session",
":",
"AppSession",
",",
"clean",
":",
"bool",
"=",
"True",
")",
":",
"args",
"=",
"session",
".",
"args",
"if",
"session",
".",
"ca_certs_filename",
":",
"return",
"session",
".",
"ca_certs_filename",
"c... | Load the Certificate Authority certificates. | [
"Load",
"the",
"Certificate",
"Authority",
"certificates",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/sslcontext.py#L65-L114 | train | 201,333 |
ArchiveTeam/wpull | wpull/application/tasks/sslcontext.py | SSLContextTask._read_pem_file | def _read_pem_file(cls, filename, from_package=False):
'''Read the PEM file.
Returns:
iterable: An iterable of certificates. The certificate data
is :class:`byte`.
'''
_logger.debug('Reading PEM {0}.'.format(filename))
if from_package:
return wpull.util.filter_pem(wpull.util.get_package_data(filename))
with open(filename, 'rb') as in_file:
return wpull.util.filter_pem(in_file.read()) | python | def _read_pem_file(cls, filename, from_package=False):
'''Read the PEM file.
Returns:
iterable: An iterable of certificates. The certificate data
is :class:`byte`.
'''
_logger.debug('Reading PEM {0}.'.format(filename))
if from_package:
return wpull.util.filter_pem(wpull.util.get_package_data(filename))
with open(filename, 'rb') as in_file:
return wpull.util.filter_pem(in_file.read()) | [
"def",
"_read_pem_file",
"(",
"cls",
",",
"filename",
",",
"from_package",
"=",
"False",
")",
":",
"_logger",
".",
"debug",
"(",
"'Reading PEM {0}.'",
".",
"format",
"(",
"filename",
")",
")",
"if",
"from_package",
":",
"return",
"wpull",
".",
"util",
".",... | Read the PEM file.
Returns:
iterable: An iterable of certificates. The certificate data
is :class:`byte`. | [
"Read",
"the",
"PEM",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/sslcontext.py#L117-L130 | train | 201,334 |
ArchiveTeam/wpull | wpull/protocol/http/client.py | Session.start | def start(self, request: Request) -> Response:
'''Begin a HTTP request
Args:
request: Request information.
Returns:
A response populated with the HTTP headers.
Once the headers are received, call :meth:`download`.
Coroutine.
'''
if self._session_state != SessionState.ready:
raise RuntimeError('Session already started')
assert not self._request
self._request = request
_logger.debug(__('Client fetch request {0}.', request))
connection = yield from self._acquire_request_connection(request)
full_url = connection.proxied and not connection.tunneled
self._stream = stream = self._stream_factory(connection)
yield from self._stream.reconnect()
request.address = connection.address
self.event_dispatcher.notify(self.Event.begin_request, request)
write_callback = functools.partial(self.event_dispatcher.notify, self.Event.request_data)
stream.data_event_dispatcher.add_write_listener(write_callback)
yield from stream.write_request(request, full_url=full_url)
if request.body:
assert 'Content-Length' in request.fields
length = int(request.fields['Content-Length'])
yield from stream.write_body(request.body, length=length)
stream.data_event_dispatcher.remove_write_listener(write_callback)
self.event_dispatcher.notify(self.Event.end_request, request)
read_callback = functools.partial(self.event_dispatcher.notify, self.Event.response_data)
stream.data_event_dispatcher.add_read_listener(read_callback)
self._response = response = yield from stream.read_response()
response.request = request
self.event_dispatcher.notify(self.Event.begin_response, response)
self._session_state = SessionState.request_sent
return response | python | def start(self, request: Request) -> Response:
'''Begin a HTTP request
Args:
request: Request information.
Returns:
A response populated with the HTTP headers.
Once the headers are received, call :meth:`download`.
Coroutine.
'''
if self._session_state != SessionState.ready:
raise RuntimeError('Session already started')
assert not self._request
self._request = request
_logger.debug(__('Client fetch request {0}.', request))
connection = yield from self._acquire_request_connection(request)
full_url = connection.proxied and not connection.tunneled
self._stream = stream = self._stream_factory(connection)
yield from self._stream.reconnect()
request.address = connection.address
self.event_dispatcher.notify(self.Event.begin_request, request)
write_callback = functools.partial(self.event_dispatcher.notify, self.Event.request_data)
stream.data_event_dispatcher.add_write_listener(write_callback)
yield from stream.write_request(request, full_url=full_url)
if request.body:
assert 'Content-Length' in request.fields
length = int(request.fields['Content-Length'])
yield from stream.write_body(request.body, length=length)
stream.data_event_dispatcher.remove_write_listener(write_callback)
self.event_dispatcher.notify(self.Event.end_request, request)
read_callback = functools.partial(self.event_dispatcher.notify, self.Event.response_data)
stream.data_event_dispatcher.add_read_listener(read_callback)
self._response = response = yield from stream.read_response()
response.request = request
self.event_dispatcher.notify(self.Event.begin_response, response)
self._session_state = SessionState.request_sent
return response | [
"def",
"start",
"(",
"self",
",",
"request",
":",
"Request",
")",
"->",
"Response",
":",
"if",
"self",
".",
"_session_state",
"!=",
"SessionState",
".",
"ready",
":",
"raise",
"RuntimeError",
"(",
"'Session already started'",
")",
"assert",
"not",
"self",
".... | Begin a HTTP request
Args:
request: Request information.
Returns:
A response populated with the HTTP headers.
Once the headers are received, call :meth:`download`.
Coroutine. | [
"Begin",
"a",
"HTTP",
"request"
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/client.py#L62-L115 | train | 201,335 |
ArchiveTeam/wpull | wpull/string.py | to_bytes | def to_bytes(instance, encoding='utf-8', error='strict'):
'''Convert an instance recursively to bytes.'''
if isinstance(instance, bytes):
return instance
elif hasattr(instance, 'encode'):
return instance.encode(encoding, error)
elif isinstance(instance, list):
return list([to_bytes(item, encoding, error) for item in instance])
elif isinstance(instance, tuple):
return tuple([to_bytes(item, encoding, error) for item in instance])
elif isinstance(instance, dict):
return dict(
[(to_bytes(key, encoding, error), to_bytes(value, encoding, error))
for key, value in instance.items()])
else:
return instance | python | def to_bytes(instance, encoding='utf-8', error='strict'):
'''Convert an instance recursively to bytes.'''
if isinstance(instance, bytes):
return instance
elif hasattr(instance, 'encode'):
return instance.encode(encoding, error)
elif isinstance(instance, list):
return list([to_bytes(item, encoding, error) for item in instance])
elif isinstance(instance, tuple):
return tuple([to_bytes(item, encoding, error) for item in instance])
elif isinstance(instance, dict):
return dict(
[(to_bytes(key, encoding, error), to_bytes(value, encoding, error))
for key, value in instance.items()])
else:
return instance | [
"def",
"to_bytes",
"(",
"instance",
",",
"encoding",
"=",
"'utf-8'",
",",
"error",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"instance",
",",
"bytes",
")",
":",
"return",
"instance",
"elif",
"hasattr",
"(",
"instance",
",",
"'encode'",
")",
":"... | Convert an instance recursively to bytes. | [
"Convert",
"an",
"instance",
"recursively",
"to",
"bytes",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/string.py#L9-L24 | train | 201,336 |
ArchiveTeam/wpull | wpull/string.py | to_str | def to_str(instance, encoding='utf-8'):
'''Convert an instance recursively to string.'''
if isinstance(instance, str):
return instance
elif hasattr(instance, 'decode'):
return instance.decode(encoding)
elif isinstance(instance, list):
return list([to_str(item, encoding) for item in instance])
elif isinstance(instance, tuple):
return tuple([to_str(item, encoding) for item in instance])
elif isinstance(instance, dict):
return dict(
[(to_str(key, encoding), to_str(value, encoding))
for key, value in instance.items()])
else:
return instance | python | def to_str(instance, encoding='utf-8'):
'''Convert an instance recursively to string.'''
if isinstance(instance, str):
return instance
elif hasattr(instance, 'decode'):
return instance.decode(encoding)
elif isinstance(instance, list):
return list([to_str(item, encoding) for item in instance])
elif isinstance(instance, tuple):
return tuple([to_str(item, encoding) for item in instance])
elif isinstance(instance, dict):
return dict(
[(to_str(key, encoding), to_str(value, encoding))
for key, value in instance.items()])
else:
return instance | [
"def",
"to_str",
"(",
"instance",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"instance",
",",
"str",
")",
":",
"return",
"instance",
"elif",
"hasattr",
"(",
"instance",
",",
"'decode'",
")",
":",
"return",
"instance",
".",
"decod... | Convert an instance recursively to string. | [
"Convert",
"an",
"instance",
"recursively",
"to",
"string",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/string.py#L27-L42 | train | 201,337 |
ArchiveTeam/wpull | wpull/string.py | detect_encoding | def detect_encoding(data, encoding=None, fallback='latin1', is_html=False):
'''Detect the character encoding of the data.
Returns:
str: The name of the codec
Raises:
ValueError: The codec could not be detected. This error can only
occur if fallback is not a "lossless" codec.
'''
if encoding:
encoding = normalize_codec_name(encoding)
bs4_detector = EncodingDetector(
data,
override_encodings=(encoding,) if encoding else (),
is_html=is_html
)
candidates = itertools.chain(bs4_detector.encodings, (fallback,))
for candidate in candidates:
if not candidate:
continue
candidate = normalize_codec_name(candidate)
if not candidate:
continue
if candidate == 'ascii' and fallback != 'ascii':
# it's never ascii :)
# Falling back on UTF-8/CP-1252/Latin-1 reduces chance of
# failure
continue
if try_decoding(data, candidate):
return candidate
raise ValueError('Unable to detect encoding.') | python | def detect_encoding(data, encoding=None, fallback='latin1', is_html=False):
'''Detect the character encoding of the data.
Returns:
str: The name of the codec
Raises:
ValueError: The codec could not be detected. This error can only
occur if fallback is not a "lossless" codec.
'''
if encoding:
encoding = normalize_codec_name(encoding)
bs4_detector = EncodingDetector(
data,
override_encodings=(encoding,) if encoding else (),
is_html=is_html
)
candidates = itertools.chain(bs4_detector.encodings, (fallback,))
for candidate in candidates:
if not candidate:
continue
candidate = normalize_codec_name(candidate)
if not candidate:
continue
if candidate == 'ascii' and fallback != 'ascii':
# it's never ascii :)
# Falling back on UTF-8/CP-1252/Latin-1 reduces chance of
# failure
continue
if try_decoding(data, candidate):
return candidate
raise ValueError('Unable to detect encoding.') | [
"def",
"detect_encoding",
"(",
"data",
",",
"encoding",
"=",
"None",
",",
"fallback",
"=",
"'latin1'",
",",
"is_html",
"=",
"False",
")",
":",
"if",
"encoding",
":",
"encoding",
"=",
"normalize_codec_name",
"(",
"encoding",
")",
"bs4_detector",
"=",
"Encodin... | Detect the character encoding of the data.
Returns:
str: The name of the codec
Raises:
ValueError: The codec could not be detected. This error can only
occur if fallback is not a "lossless" codec. | [
"Detect",
"the",
"character",
"encoding",
"of",
"the",
"data",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/string.py#L60-L98 | train | 201,338 |
ArchiveTeam/wpull | wpull/string.py | try_decoding | def try_decoding(data, encoding):
'''Return whether the Python codec could decode the data.'''
try:
data.decode(encoding, 'strict')
except UnicodeError:
# Data under 16 bytes is very unlikely to be truncated
if len(data) > 16:
for trim in (1, 2, 3):
trimmed_data = data[:-trim]
if trimmed_data:
try:
trimmed_data.decode(encoding, 'strict')
except UnicodeError:
continue
else:
return True
return False
else:
return True | python | def try_decoding(data, encoding):
'''Return whether the Python codec could decode the data.'''
try:
data.decode(encoding, 'strict')
except UnicodeError:
# Data under 16 bytes is very unlikely to be truncated
if len(data) > 16:
for trim in (1, 2, 3):
trimmed_data = data[:-trim]
if trimmed_data:
try:
trimmed_data.decode(encoding, 'strict')
except UnicodeError:
continue
else:
return True
return False
else:
return True | [
"def",
"try_decoding",
"(",
"data",
",",
"encoding",
")",
":",
"try",
":",
"data",
".",
"decode",
"(",
"encoding",
",",
"'strict'",
")",
"except",
"UnicodeError",
":",
"# Data under 16 bytes is very unlikely to be truncated",
"if",
"len",
"(",
"data",
")",
">",
... | Return whether the Python codec could decode the data. | [
"Return",
"whether",
"the",
"Python",
"codec",
"could",
"decode",
"the",
"data",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/string.py#L101-L119 | train | 201,339 |
ArchiveTeam/wpull | wpull/string.py | format_size | def format_size(num, format_str='{num:.1f} {unit}'):
'''Format the file size into a human readable text.
http://stackoverflow.com/a/1094933/1524507
'''
for unit in ('B', 'KiB', 'MiB', 'GiB'):
if -1024 < num < 1024:
return format_str.format(num=num, unit=unit)
num /= 1024.0
return format_str.format(num=num, unit='TiB') | python | def format_size(num, format_str='{num:.1f} {unit}'):
'''Format the file size into a human readable text.
http://stackoverflow.com/a/1094933/1524507
'''
for unit in ('B', 'KiB', 'MiB', 'GiB'):
if -1024 < num < 1024:
return format_str.format(num=num, unit=unit)
num /= 1024.0
return format_str.format(num=num, unit='TiB') | [
"def",
"format_size",
"(",
"num",
",",
"format_str",
"=",
"'{num:.1f} {unit}'",
")",
":",
"for",
"unit",
"in",
"(",
"'B'",
",",
"'KiB'",
",",
"'MiB'",
",",
"'GiB'",
")",
":",
"if",
"-",
"1024",
"<",
"num",
"<",
"1024",
":",
"return",
"format_str",
".... | Format the file size into a human readable text.
http://stackoverflow.com/a/1094933/1524507 | [
"Format",
"the",
"file",
"size",
"into",
"a",
"human",
"readable",
"text",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/string.py#L122-L133 | train | 201,340 |
ArchiveTeam/wpull | wpull/string.py | printable_str | def printable_str(text, keep_newlines=False):
'''Escape any control or non-ASCII characters from string.
This function is intended for use with strings from an untrusted
source such as writing to a console or writing to logs. It is
designed to prevent things like ANSI escape sequences from
showing.
Use :func:`repr` or :func:`ascii` instead for things such as
Exception messages.
'''
if isinstance(text, str):
new_text = ascii(text)[1:-1]
else:
new_text = ascii(text)
if keep_newlines:
new_text = new_text.replace('\\r', '\r').replace('\\n', '\n')
return new_text | python | def printable_str(text, keep_newlines=False):
'''Escape any control or non-ASCII characters from string.
This function is intended for use with strings from an untrusted
source such as writing to a console or writing to logs. It is
designed to prevent things like ANSI escape sequences from
showing.
Use :func:`repr` or :func:`ascii` instead for things such as
Exception messages.
'''
if isinstance(text, str):
new_text = ascii(text)[1:-1]
else:
new_text = ascii(text)
if keep_newlines:
new_text = new_text.replace('\\r', '\r').replace('\\n', '\n')
return new_text | [
"def",
"printable_str",
"(",
"text",
",",
"keep_newlines",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"new_text",
"=",
"ascii",
"(",
"text",
")",
"[",
"1",
":",
"-",
"1",
"]",
"else",
":",
"new_text",
"=",
"ascii... | Escape any control or non-ASCII characters from string.
This function is intended for use with strings from an untrusted
source such as writing to a console or writing to logs. It is
designed to prevent things like ANSI escape sequences from
showing.
Use :func:`repr` or :func:`ascii` instead for things such as
Exception messages. | [
"Escape",
"any",
"control",
"or",
"non",
"-",
"ASCII",
"characters",
"from",
"string",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/string.py#L151-L170 | train | 201,341 |
ArchiveTeam/wpull | wpull/pipeline/progress.py | BarProgress._print_status | def _print_status(self):
'''Print an entire status line including bar and stats.'''
self._clear_line()
self._print(' ')
if self.max_value:
self._print_percent()
self._print(' ')
self._print_bar()
else:
self._print_throbber()
self._print(' ')
if self.measurement == Measurement.bytes:
self._print_size_downloaded()
else:
self._print(self.current_value)
self._print(' ')
self._print_duration()
self._print(' ')
if self.measurement == Measurement.bytes:
self._print_speed()
self._flush() | python | def _print_status(self):
'''Print an entire status line including bar and stats.'''
self._clear_line()
self._print(' ')
if self.max_value:
self._print_percent()
self._print(' ')
self._print_bar()
else:
self._print_throbber()
self._print(' ')
if self.measurement == Measurement.bytes:
self._print_size_downloaded()
else:
self._print(self.current_value)
self._print(' ')
self._print_duration()
self._print(' ')
if self.measurement == Measurement.bytes:
self._print_speed()
self._flush() | [
"def",
"_print_status",
"(",
"self",
")",
":",
"self",
".",
"_clear_line",
"(",
")",
"self",
".",
"_print",
"(",
"' '",
")",
"if",
"self",
".",
"max_value",
":",
"self",
".",
"_print_percent",
"(",
")",
"self",
".",
"_print",
"(",
"' '",
")",
"self"... | Print an entire status line including bar and stats. | [
"Print",
"an",
"entire",
"status",
"line",
"including",
"bar",
"and",
"stats",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/progress.py#L217-L244 | train | 201,342 |
ArchiveTeam/wpull | wpull/pipeline/progress.py | BarProgress._print_throbber | def _print_throbber(self):
'''Print an indefinite progress bar.'''
self._print('[')
for position in range(self._bar_width):
self._print('O' if position == self._throbber_index else ' ')
self._print(']')
self._throbber_index = next(self._throbber_iter) | python | def _print_throbber(self):
'''Print an indefinite progress bar.'''
self._print('[')
for position in range(self._bar_width):
self._print('O' if position == self._throbber_index else ' ')
self._print(']')
self._throbber_index = next(self._throbber_iter) | [
"def",
"_print_throbber",
"(",
"self",
")",
":",
"self",
".",
"_print",
"(",
"'['",
")",
"for",
"position",
"in",
"range",
"(",
"self",
".",
"_bar_width",
")",
":",
"self",
".",
"_print",
"(",
"'O'",
"if",
"position",
"==",
"self",
".",
"_throbber_inde... | Print an indefinite progress bar. | [
"Print",
"an",
"indefinite",
"progress",
"bar",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/progress.py#L251-L260 | train | 201,343 |
ArchiveTeam/wpull | wpull/pipeline/progress.py | BarProgress._print_bar | def _print_bar(self):
'''Print a progress bar.'''
self._print('[')
for position in range(self._bar_width):
position_fraction = position / (self._bar_width - 1)
position_bytes = position_fraction * self.max_value
if position_bytes < (self.continue_value or 0):
self._print('+')
elif position_bytes <= (self.continue_value or 0) + self.current_value:
self._print('=')
else:
self._print(' ')
self._print(']') | python | def _print_bar(self):
'''Print a progress bar.'''
self._print('[')
for position in range(self._bar_width):
position_fraction = position / (self._bar_width - 1)
position_bytes = position_fraction * self.max_value
if position_bytes < (self.continue_value or 0):
self._print('+')
elif position_bytes <= (self.continue_value or 0) + self.current_value:
self._print('=')
else:
self._print(' ')
self._print(']') | [
"def",
"_print_bar",
"(",
"self",
")",
":",
"self",
".",
"_print",
"(",
"'['",
")",
"for",
"position",
"in",
"range",
"(",
"self",
".",
"_bar_width",
")",
":",
"position_fraction",
"=",
"position",
"/",
"(",
"self",
".",
"_bar_width",
"-",
"1",
")",
... | Print a progress bar. | [
"Print",
"a",
"progress",
"bar",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/progress.py#L262-L277 | train | 201,344 |
ArchiveTeam/wpull | wpull/pipeline/progress.py | BarProgress._print_duration | def _print_duration(self):
'''Print the elapsed download time.'''
duration = int(time.time() - self._start_time)
self._print(datetime.timedelta(seconds=duration)) | python | def _print_duration(self):
'''Print the elapsed download time.'''
duration = int(time.time() - self._start_time)
self._print(datetime.timedelta(seconds=duration)) | [
"def",
"_print_duration",
"(",
"self",
")",
":",
"duration",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_start_time",
")",
"self",
".",
"_print",
"(",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"duration",
")",
")"
] | Print the elapsed download time. | [
"Print",
"the",
"elapsed",
"download",
"time",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/progress.py#L283-L286 | train | 201,345 |
ArchiveTeam/wpull | wpull/pipeline/progress.py | BarProgress._print_speed | def _print_speed(self):
'''Print the current speed.'''
if self._bandwidth_meter.num_samples:
speed = self._bandwidth_meter.speed()
if self._human_format:
file_size_str = wpull.string.format_size(speed)
else:
file_size_str = '{:.1f} b'.format(speed * 8)
speed_str = _('{preformatted_file_size}/s').format(
preformatted_file_size=file_size_str
)
else:
speed_str = _('-- B/s')
self._print(speed_str) | python | def _print_speed(self):
'''Print the current speed.'''
if self._bandwidth_meter.num_samples:
speed = self._bandwidth_meter.speed()
if self._human_format:
file_size_str = wpull.string.format_size(speed)
else:
file_size_str = '{:.1f} b'.format(speed * 8)
speed_str = _('{preformatted_file_size}/s').format(
preformatted_file_size=file_size_str
)
else:
speed_str = _('-- B/s')
self._print(speed_str) | [
"def",
"_print_speed",
"(",
"self",
")",
":",
"if",
"self",
".",
"_bandwidth_meter",
".",
"num_samples",
":",
"speed",
"=",
"self",
".",
"_bandwidth_meter",
".",
"speed",
"(",
")",
"if",
"self",
".",
"_human_format",
":",
"file_size_str",
"=",
"wpull",
"."... | Print the current speed. | [
"Print",
"the",
"current",
"speed",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/progress.py#L288-L304 | train | 201,346 |
ArchiveTeam/wpull | wpull/pipeline/progress.py | BarProgress._print_percent | def _print_percent(self):
'''Print how much is done in percentage.'''
fraction_done = ((self.continue_value or 0 + self.current_value) /
self.max_value)
self._print('{fraction_done:.1%}'.format(fraction_done=fraction_done)) | python | def _print_percent(self):
'''Print how much is done in percentage.'''
fraction_done = ((self.continue_value or 0 + self.current_value) /
self.max_value)
self._print('{fraction_done:.1%}'.format(fraction_done=fraction_done)) | [
"def",
"_print_percent",
"(",
"self",
")",
":",
"fraction_done",
"=",
"(",
"(",
"self",
".",
"continue_value",
"or",
"0",
"+",
"self",
".",
"current_value",
")",
"/",
"self",
".",
"max_value",
")",
"self",
".",
"_print",
"(",
"'{fraction_done:.1%}'",
".",
... | Print how much is done in percentage. | [
"Print",
"how",
"much",
"is",
"done",
"in",
"percentage",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/pipeline/progress.py#L306-L311 | train | 201,347 |
ArchiveTeam/wpull | wpull/application/hook.py | HookDispatcher.register | def register(self, name: str):
'''Register hooks that can be connected.'''
if name in self._callbacks:
raise ValueError('Hook already registered')
self._callbacks[name] = None
if self._event_dispatcher is not None:
self._event_dispatcher.register(name) | python | def register(self, name: str):
'''Register hooks that can be connected.'''
if name in self._callbacks:
raise ValueError('Hook already registered')
self._callbacks[name] = None
if self._event_dispatcher is not None:
self._event_dispatcher.register(name) | [
"def",
"register",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"if",
"name",
"in",
"self",
".",
"_callbacks",
":",
"raise",
"ValueError",
"(",
"'Hook already registered'",
")",
"self",
".",
"_callbacks",
"[",
"name",
"]",
"=",
"None",
"if",
"self",
... | Register hooks that can be connected. | [
"Register",
"hooks",
"that",
"can",
"be",
"connected",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/hook.py#L47-L55 | train | 201,348 |
ArchiveTeam/wpull | wpull/application/hook.py | HookDispatcher.unregister | def unregister(self, name: str):
'''Unregister hook.'''
del self._callbacks[name]
if self._event_dispatcher is not None:
self._event_dispatcher.unregister(name) | python | def unregister(self, name: str):
'''Unregister hook.'''
del self._callbacks[name]
if self._event_dispatcher is not None:
self._event_dispatcher.unregister(name) | [
"def",
"unregister",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"del",
"self",
".",
"_callbacks",
"[",
"name",
"]",
"if",
"self",
".",
"_event_dispatcher",
"is",
"not",
"None",
":",
"self",
".",
"_event_dispatcher",
".",
"unregister",
"(",
"name",
... | Unregister hook. | [
"Unregister",
"hook",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/hook.py#L57-L62 | train | 201,349 |
ArchiveTeam/wpull | wpull/application/hook.py | HookDispatcher.connect | def connect(self, name, callback):
'''Add callback to hook.'''
if not self._callbacks[name]:
self._callbacks[name] = callback
else:
raise HookAlreadyConnectedError('Callback hook already connected.') | python | def connect(self, name, callback):
'''Add callback to hook.'''
if not self._callbacks[name]:
self._callbacks[name] = callback
else:
raise HookAlreadyConnectedError('Callback hook already connected.') | [
"def",
"connect",
"(",
"self",
",",
"name",
",",
"callback",
")",
":",
"if",
"not",
"self",
".",
"_callbacks",
"[",
"name",
"]",
":",
"self",
".",
"_callbacks",
"[",
"name",
"]",
"=",
"callback",
"else",
":",
"raise",
"HookAlreadyConnectedError",
"(",
... | Add callback to hook. | [
"Add",
"callback",
"to",
"hook",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/hook.py#L64-L69 | train | 201,350 |
ArchiveTeam/wpull | wpull/application/hook.py | HookDispatcher.call | def call(self, name: str, *args, **kwargs):
'''Invoke the callback.'''
if self._event_dispatcher is not None:
self._event_dispatcher.notify(name, *args, **kwargs)
if self._callbacks[name]:
return self._callbacks[name](*args, **kwargs)
else:
raise HookDisconnected('No callback is connected.') | python | def call(self, name: str, *args, **kwargs):
'''Invoke the callback.'''
if self._event_dispatcher is not None:
self._event_dispatcher.notify(name, *args, **kwargs)
if self._callbacks[name]:
return self._callbacks[name](*args, **kwargs)
else:
raise HookDisconnected('No callback is connected.') | [
"def",
"call",
"(",
"self",
",",
"name",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_event_dispatcher",
"is",
"not",
"None",
":",
"self",
".",
"_event_dispatcher",
".",
"notify",
"(",
"name",
",",
"*",
"arg... | Invoke the callback. | [
"Invoke",
"the",
"callback",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/hook.py#L75-L83 | train | 201,351 |
ArchiveTeam/wpull | wpull/thirdparty/robotexclusionrulesparser.py | RobotExclusionRulesParser.get_crawl_delay | def get_crawl_delay(self, user_agent):
"""Returns a float representing the crawl delay specified for this
user agent, or None if the crawl delay was unspecified or not a float.
"""
# See is_allowed() comment about the explicit unicode conversion.
if (PY_MAJOR_VERSION < 3) and (not isinstance(user_agent, unicode)):
user_agent = user_agent.decode()
for ruleset in self.__rulesets:
if ruleset.does_user_agent_match(user_agent):
return ruleset.crawl_delay
return None | python | def get_crawl_delay(self, user_agent):
"""Returns a float representing the crawl delay specified for this
user agent, or None if the crawl delay was unspecified or not a float.
"""
# See is_allowed() comment about the explicit unicode conversion.
if (PY_MAJOR_VERSION < 3) and (not isinstance(user_agent, unicode)):
user_agent = user_agent.decode()
for ruleset in self.__rulesets:
if ruleset.does_user_agent_match(user_agent):
return ruleset.crawl_delay
return None | [
"def",
"get_crawl_delay",
"(",
"self",
",",
"user_agent",
")",
":",
"# See is_allowed() comment about the explicit unicode conversion.",
"if",
"(",
"PY_MAJOR_VERSION",
"<",
"3",
")",
"and",
"(",
"not",
"isinstance",
"(",
"user_agent",
",",
"unicode",
")",
")",
":",
... | Returns a float representing the crawl delay specified for this
user agent, or None if the crawl delay was unspecified or not a float. | [
"Returns",
"a",
"float",
"representing",
"the",
"crawl",
"delay",
"specified",
"for",
"this",
"user",
"agent",
"or",
"None",
"if",
"the",
"crawl",
"delay",
"was",
"unspecified",
"or",
"not",
"a",
"float",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/thirdparty/robotexclusionrulesparser.py#L393-L405 | train | 201,352 |
ArchiveTeam/wpull | wpull/thirdparty/robotexclusionrulesparser.py | RobotExclusionRulesParser.parse | def parse(self, s):
"""Parses the passed string as a set of robots.txt rules."""
self._sitemaps = [ ]
self.__rulesets = [ ]
if (PY_MAJOR_VERSION > 2) and (isinstance(s, bytes) or isinstance(s, bytearray)) or \
(PY_MAJOR_VERSION == 2) and (not isinstance(s, unicode)):
s = s.decode("iso-8859-1")
# Normalize newlines.
s = _end_of_line_regex.sub("\n", s)
lines = s.split("\n")
previous_line_was_a_user_agent = False
current_ruleset = None
for line in lines:
line = line.strip()
if line and line[0] == '#':
# "Lines containing only a comment are discarded completely,
# and therefore do not indicate a record boundary." (MK1994)
pass
else:
# Remove comments
i = line.find("#")
if i != -1: line = line[:i]
line = line.strip()
if not line:
# An empty line indicates the end of a ruleset.
if current_ruleset and current_ruleset.is_not_empty():
self.__rulesets.append(current_ruleset)
current_ruleset = None
previous_line_was_a_user_agent = False
else:
# Each non-empty line falls into one of six categories:
# 1) User-agent: blah blah blah
# 2) Disallow: blah blah blah
# 3) Allow: blah blah blah
# 4) Crawl-delay: blah blah blah
# 5) Sitemap: blah blah blah
# 6) Everything else
# 1 - 5 are interesting and I find them with the regex
# below. Category 6 I discard as directed by the MK1994
# ("Unrecognised headers are ignored.")
# Note that 4 & 5 are specific to GYM2008 syntax, but
# respecting them here is not a problem. They're just
# additional information the the caller is free to ignore.
matches = _directive_regex.findall(line)
# Categories 1 - 5 produce two matches, #6 produces none.
if matches:
field, data = matches[0]
field = field.lower()
data = _scrub_data(data)
# Matching "useragent" is a deviation from the
# MK1994/96 which permits only "user-agent".
if field in ("useragent", "user-agent"):
if previous_line_was_a_user_agent:
# Add this UA to the current ruleset
if current_ruleset and data:
current_ruleset.add_robot_name(data)
else:
# Save the current ruleset and start a new one.
if current_ruleset and current_ruleset.is_not_empty():
self.__rulesets.append(current_ruleset)
#else:
# (is_not_empty() == False) ==> malformed
# robots.txt listed a UA line but provided
# no name or didn't provide any rules
# for a named UA.
current_ruleset = _Ruleset()
if data:
current_ruleset.add_robot_name(data)
previous_line_was_a_user_agent = True
elif field == "allow":
previous_line_was_a_user_agent = False
if current_ruleset:
current_ruleset.add_allow_rule(data)
elif field == "sitemap":
previous_line_was_a_user_agent = False
self._sitemaps.append(data)
elif field == "crawl-delay":
# Only Yahoo documents the syntax for Crawl-delay.
# ref: http://help.yahoo.com/l/us/yahoo/search/webcrawler/slurp-03.html
previous_line_was_a_user_agent = False
if current_ruleset:
try:
current_ruleset.crawl_delay = float(data)
except ValueError:
# Invalid crawl-delay -- ignore.
pass
else:
# This is a disallow line
previous_line_was_a_user_agent = False
if current_ruleset:
current_ruleset.add_disallow_rule(data)
if current_ruleset and current_ruleset.is_not_empty():
self.__rulesets.append(current_ruleset)
# Now that I have all the rulesets, I want to order them in a way
# that makes comparisons easier later. Specifically, any ruleset that
# contains the default user agent '*' should go at the end of the list
# so that I only apply the default as a last resort. According to
# MK1994/96, there should only be one ruleset that specifies * as the
# user-agent, but you know how these things go.
not_defaults = [r for r in self.__rulesets if not r.is_default()]
defaults = [r for r in self.__rulesets if r.is_default()]
self.__rulesets = not_defaults + defaults | python | def parse(self, s):
"""Parses the passed string as a set of robots.txt rules."""
self._sitemaps = [ ]
self.__rulesets = [ ]
if (PY_MAJOR_VERSION > 2) and (isinstance(s, bytes) or isinstance(s, bytearray)) or \
(PY_MAJOR_VERSION == 2) and (not isinstance(s, unicode)):
s = s.decode("iso-8859-1")
# Normalize newlines.
s = _end_of_line_regex.sub("\n", s)
lines = s.split("\n")
previous_line_was_a_user_agent = False
current_ruleset = None
for line in lines:
line = line.strip()
if line and line[0] == '#':
# "Lines containing only a comment are discarded completely,
# and therefore do not indicate a record boundary." (MK1994)
pass
else:
# Remove comments
i = line.find("#")
if i != -1: line = line[:i]
line = line.strip()
if not line:
# An empty line indicates the end of a ruleset.
if current_ruleset and current_ruleset.is_not_empty():
self.__rulesets.append(current_ruleset)
current_ruleset = None
previous_line_was_a_user_agent = False
else:
# Each non-empty line falls into one of six categories:
# 1) User-agent: blah blah blah
# 2) Disallow: blah blah blah
# 3) Allow: blah blah blah
# 4) Crawl-delay: blah blah blah
# 5) Sitemap: blah blah blah
# 6) Everything else
# 1 - 5 are interesting and I find them with the regex
# below. Category 6 I discard as directed by the MK1994
# ("Unrecognised headers are ignored.")
# Note that 4 & 5 are specific to GYM2008 syntax, but
# respecting them here is not a problem. They're just
# additional information the the caller is free to ignore.
matches = _directive_regex.findall(line)
# Categories 1 - 5 produce two matches, #6 produces none.
if matches:
field, data = matches[0]
field = field.lower()
data = _scrub_data(data)
# Matching "useragent" is a deviation from the
# MK1994/96 which permits only "user-agent".
if field in ("useragent", "user-agent"):
if previous_line_was_a_user_agent:
# Add this UA to the current ruleset
if current_ruleset and data:
current_ruleset.add_robot_name(data)
else:
# Save the current ruleset and start a new one.
if current_ruleset and current_ruleset.is_not_empty():
self.__rulesets.append(current_ruleset)
#else:
# (is_not_empty() == False) ==> malformed
# robots.txt listed a UA line but provided
# no name or didn't provide any rules
# for a named UA.
current_ruleset = _Ruleset()
if data:
current_ruleset.add_robot_name(data)
previous_line_was_a_user_agent = True
elif field == "allow":
previous_line_was_a_user_agent = False
if current_ruleset:
current_ruleset.add_allow_rule(data)
elif field == "sitemap":
previous_line_was_a_user_agent = False
self._sitemaps.append(data)
elif field == "crawl-delay":
# Only Yahoo documents the syntax for Crawl-delay.
# ref: http://help.yahoo.com/l/us/yahoo/search/webcrawler/slurp-03.html
previous_line_was_a_user_agent = False
if current_ruleset:
try:
current_ruleset.crawl_delay = float(data)
except ValueError:
# Invalid crawl-delay -- ignore.
pass
else:
# This is a disallow line
previous_line_was_a_user_agent = False
if current_ruleset:
current_ruleset.add_disallow_rule(data)
if current_ruleset and current_ruleset.is_not_empty():
self.__rulesets.append(current_ruleset)
# Now that I have all the rulesets, I want to order them in a way
# that makes comparisons easier later. Specifically, any ruleset that
# contains the default user agent '*' should go at the end of the list
# so that I only apply the default as a last resort. According to
# MK1994/96, there should only be one ruleset that specifies * as the
# user-agent, but you know how these things go.
not_defaults = [r for r in self.__rulesets if not r.is_default()]
defaults = [r for r in self.__rulesets if r.is_default()]
self.__rulesets = not_defaults + defaults | [
"def",
"parse",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"_sitemaps",
"=",
"[",
"]",
"self",
".",
"__rulesets",
"=",
"[",
"]",
"if",
"(",
"PY_MAJOR_VERSION",
">",
"2",
")",
"and",
"(",
"isinstance",
"(",
"s",
",",
"bytes",
")",
"or",
"isinst... | Parses the passed string as a set of robots.txt rules. | [
"Parses",
"the",
"passed",
"string",
"as",
"a",
"set",
"of",
"robots",
".",
"txt",
"rules",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/thirdparty/robotexclusionrulesparser.py#L543-L659 | train | 201,353 |
ArchiveTeam/wpull | wpull/protocol/abstract/stream.py | close_stream_on_error | def close_stream_on_error(func):
'''Decorator to close stream on error.'''
@asyncio.coroutine
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
with wpull.util.close_on_error(self.close):
return (yield from func(self, *args, **kwargs))
return wrapper | python | def close_stream_on_error(func):
'''Decorator to close stream on error.'''
@asyncio.coroutine
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
with wpull.util.close_on_error(self.close):
return (yield from func(self, *args, **kwargs))
return wrapper | [
"def",
"close_stream_on_error",
"(",
"func",
")",
":",
"@",
"asyncio",
".",
"coroutine",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"wpull",
".",
"util... | Decorator to close stream on error. | [
"Decorator",
"to",
"close",
"stream",
"on",
"error",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/abstract/stream.py#L11-L18 | train | 201,354 |
ArchiveTeam/wpull | wpull/path.py | url_to_filename | def url_to_filename(url, index='index.html', alt_char=False):
'''Return a filename from a URL.
Args:
url (str): The URL.
index (str): If a filename could not be derived from the URL path,
use index instead. For example, ``/images/`` will return
``index.html``.
alt_char (bool): If True, the character for the query deliminator
will be ``@`` intead of ``?``.
This function does not include the directories and does not sanitize
the filename.
Returns:
str
'''
assert isinstance(url, str), 'Expect str. Got {}.'.format(type(url))
url_split_result = urllib.parse.urlsplit(url)
filename = url_split_result.path.split('/')[-1]
if not filename:
filename = index
if url_split_result.query:
if alt_char:
query_delim = '@'
else:
query_delim = '?'
filename = '{0}{1}{2}'.format(
filename, query_delim, url_split_result.query
)
return filename | python | def url_to_filename(url, index='index.html', alt_char=False):
'''Return a filename from a URL.
Args:
url (str): The URL.
index (str): If a filename could not be derived from the URL path,
use index instead. For example, ``/images/`` will return
``index.html``.
alt_char (bool): If True, the character for the query deliminator
will be ``@`` intead of ``?``.
This function does not include the directories and does not sanitize
the filename.
Returns:
str
'''
assert isinstance(url, str), 'Expect str. Got {}.'.format(type(url))
url_split_result = urllib.parse.urlsplit(url)
filename = url_split_result.path.split('/')[-1]
if not filename:
filename = index
if url_split_result.query:
if alt_char:
query_delim = '@'
else:
query_delim = '?'
filename = '{0}{1}{2}'.format(
filename, query_delim, url_split_result.query
)
return filename | [
"def",
"url_to_filename",
"(",
"url",
",",
"index",
"=",
"'index.html'",
",",
"alt_char",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"url",
",",
"str",
")",
",",
"'Expect str. Got {}.'",
".",
"format",
"(",
"type",
"(",
"url",
")",
")",
"url_sp... | Return a filename from a URL.
Args:
url (str): The URL.
index (str): If a filename could not be derived from the URL path,
use index instead. For example, ``/images/`` will return
``index.html``.
alt_char (bool): If True, the character for the query deliminator
will be ``@`` intead of ``?``.
This function does not include the directories and does not sanitize
the filename.
Returns:
str | [
"Return",
"a",
"filename",
"from",
"a",
"URL",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/path.py#L92-L127 | train | 201,355 |
ArchiveTeam/wpull | wpull/path.py | url_to_dir_parts | def url_to_dir_parts(url, include_protocol=False, include_hostname=False,
alt_char=False):
'''Return a list of directory parts from a URL.
Args:
url (str): The URL.
include_protocol (bool): If True, the scheme from the URL will be
included.
include_hostname (bool): If True, the hostname from the URL will be
included.
alt_char (bool): If True, the character for the port deliminator
will be ``+`` intead of ``:``.
This function does not include the filename and the paths are not
sanitized.
Returns:
list
'''
assert isinstance(url, str), 'Expect str. Got {}.'.format(type(url))
url_split_result = urllib.parse.urlsplit(url)
parts = []
if include_protocol:
parts.append(url_split_result.scheme)
if include_hostname:
hostname = url_split_result.hostname
if url_split_result.port:
if alt_char:
port_delim = '+'
else:
port_delim = ':'
hostname = '{0}{1}{2}'.format(
hostname, port_delim, url_split_result.port
)
parts.append(hostname)
for path_part in url_split_result.path.split('/'):
if path_part:
parts.append(path_part)
if not url.endswith('/') and parts:
parts.pop()
return parts | python | def url_to_dir_parts(url, include_protocol=False, include_hostname=False,
alt_char=False):
'''Return a list of directory parts from a URL.
Args:
url (str): The URL.
include_protocol (bool): If True, the scheme from the URL will be
included.
include_hostname (bool): If True, the hostname from the URL will be
included.
alt_char (bool): If True, the character for the port deliminator
will be ``+`` intead of ``:``.
This function does not include the filename and the paths are not
sanitized.
Returns:
list
'''
assert isinstance(url, str), 'Expect str. Got {}.'.format(type(url))
url_split_result = urllib.parse.urlsplit(url)
parts = []
if include_protocol:
parts.append(url_split_result.scheme)
if include_hostname:
hostname = url_split_result.hostname
if url_split_result.port:
if alt_char:
port_delim = '+'
else:
port_delim = ':'
hostname = '{0}{1}{2}'.format(
hostname, port_delim, url_split_result.port
)
parts.append(hostname)
for path_part in url_split_result.path.split('/'):
if path_part:
parts.append(path_part)
if not url.endswith('/') and parts:
parts.pop()
return parts | [
"def",
"url_to_dir_parts",
"(",
"url",
",",
"include_protocol",
"=",
"False",
",",
"include_hostname",
"=",
"False",
",",
"alt_char",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"url",
",",
"str",
")",
",",
"'Expect str. Got {}.'",
".",
"format",
"(... | Return a list of directory parts from a URL.
Args:
url (str): The URL.
include_protocol (bool): If True, the scheme from the URL will be
included.
include_hostname (bool): If True, the hostname from the URL will be
included.
alt_char (bool): If True, the character for the port deliminator
will be ``+`` intead of ``:``.
This function does not include the filename and the paths are not
sanitized.
Returns:
list | [
"Return",
"a",
"list",
"of",
"directory",
"parts",
"from",
"a",
"URL",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/path.py#L130-L179 | train | 201,356 |
ArchiveTeam/wpull | wpull/path.py | safe_filename | def safe_filename(filename, os_type='unix', no_control=True, ascii_only=True,
case=None, encoding='utf8', max_length=None):
'''Return a safe filename or path part.
Args:
filename (str): The filename or path component.
os_type (str): If ``unix``, escape the slash. If ``windows``, escape
extra Windows characters.
no_control (bool): If True, escape control characters.
ascii_only (bool): If True, escape non-ASCII characters.
case (str): If ``lower``, lowercase the string. If ``upper``, uppercase
the string.
encoding (str): The character encoding.
max_length (int): The maximum length of the filename.
This function assumes that `filename` has not already been percent-encoded.
Returns:
str
'''
assert isinstance(filename, str), \
'Expect str. Got {}.'.format(type(filename))
if filename in ('.', os.curdir):
new_filename = '%2E'
elif filename in ('.', os.pardir):
new_filename = '%2E%2E'
else:
unix = os_type == 'unix'
windows = os_type == 'windows'
encoder_args = (unix, no_control, windows, ascii_only)
if encoder_args not in _encoder_cache:
_encoder_cache[encoder_args] = PercentEncoder(
unix=unix, control=no_control, windows=windows,
ascii_=ascii_only
)
encoder = _encoder_cache[encoder_args]
encoded_filename = filename.encode(encoding)
new_filename = encoder.quote(encoded_filename).decode(encoding)
if os_type == 'windows':
if new_filename[-1] in ' .':
new_filename = '{0}{1:02X}'.format(
new_filename[:-1], new_filename[-1]
)
if max_length and len(new_filename) > max_length:
hash_obj = hashlib.sha1(new_filename.encode(encoding))
new_length = max(0, max_length - 8)
new_filename = '{0}{1}'.format(
new_filename[:new_length], hash_obj.hexdigest()[:8]
)
if case == 'lower':
new_filename = new_filename.lower()
elif case == 'upper':
new_filename = new_filename.upper()
return new_filename | python | def safe_filename(filename, os_type='unix', no_control=True, ascii_only=True,
case=None, encoding='utf8', max_length=None):
'''Return a safe filename or path part.
Args:
filename (str): The filename or path component.
os_type (str): If ``unix``, escape the slash. If ``windows``, escape
extra Windows characters.
no_control (bool): If True, escape control characters.
ascii_only (bool): If True, escape non-ASCII characters.
case (str): If ``lower``, lowercase the string. If ``upper``, uppercase
the string.
encoding (str): The character encoding.
max_length (int): The maximum length of the filename.
This function assumes that `filename` has not already been percent-encoded.
Returns:
str
'''
assert isinstance(filename, str), \
'Expect str. Got {}.'.format(type(filename))
if filename in ('.', os.curdir):
new_filename = '%2E'
elif filename in ('.', os.pardir):
new_filename = '%2E%2E'
else:
unix = os_type == 'unix'
windows = os_type == 'windows'
encoder_args = (unix, no_control, windows, ascii_only)
if encoder_args not in _encoder_cache:
_encoder_cache[encoder_args] = PercentEncoder(
unix=unix, control=no_control, windows=windows,
ascii_=ascii_only
)
encoder = _encoder_cache[encoder_args]
encoded_filename = filename.encode(encoding)
new_filename = encoder.quote(encoded_filename).decode(encoding)
if os_type == 'windows':
if new_filename[-1] in ' .':
new_filename = '{0}{1:02X}'.format(
new_filename[:-1], new_filename[-1]
)
if max_length and len(new_filename) > max_length:
hash_obj = hashlib.sha1(new_filename.encode(encoding))
new_length = max(0, max_length - 8)
new_filename = '{0}{1}'.format(
new_filename[:new_length], hash_obj.hexdigest()[:8]
)
if case == 'lower':
new_filename = new_filename.lower()
elif case == 'upper':
new_filename = new_filename.upper()
return new_filename | [
"def",
"safe_filename",
"(",
"filename",
",",
"os_type",
"=",
"'unix'",
",",
"no_control",
"=",
"True",
",",
"ascii_only",
"=",
"True",
",",
"case",
"=",
"None",
",",
"encoding",
"=",
"'utf8'",
",",
"max_length",
"=",
"None",
")",
":",
"assert",
"isinsta... | Return a safe filename or path part.
Args:
filename (str): The filename or path component.
os_type (str): If ``unix``, escape the slash. If ``windows``, escape
extra Windows characters.
no_control (bool): If True, escape control characters.
ascii_only (bool): If True, escape non-ASCII characters.
case (str): If ``lower``, lowercase the string. If ``upper``, uppercase
the string.
encoding (str): The character encoding.
max_length (int): The maximum length of the filename.
This function assumes that `filename` has not already been percent-encoded.
Returns:
str | [
"Return",
"a",
"safe",
"filename",
"or",
"path",
"part",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/path.py#L221-L281 | train | 201,357 |
ArchiveTeam/wpull | wpull/path.py | anti_clobber_dir_path | def anti_clobber_dir_path(dir_path, suffix='.d'):
'''Return a directory path free of filenames.
Args:
dir_path (str): A directory path.
suffix (str): The suffix to append to the part of the path that is
a file.
Returns:
str
'''
dir_path = os.path.normpath(dir_path)
parts = dir_path.split(os.sep)
for index in range(len(parts)):
test_path = os.sep.join(parts[:index + 1])
if os.path.isfile(test_path):
parts[index] += suffix
return os.sep.join(parts)
return dir_path | python | def anti_clobber_dir_path(dir_path, suffix='.d'):
'''Return a directory path free of filenames.
Args:
dir_path (str): A directory path.
suffix (str): The suffix to append to the part of the path that is
a file.
Returns:
str
'''
dir_path = os.path.normpath(dir_path)
parts = dir_path.split(os.sep)
for index in range(len(parts)):
test_path = os.sep.join(parts[:index + 1])
if os.path.isfile(test_path):
parts[index] += suffix
return os.sep.join(parts)
return dir_path | [
"def",
"anti_clobber_dir_path",
"(",
"dir_path",
",",
"suffix",
"=",
"'.d'",
")",
":",
"dir_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"dir_path",
")",
"parts",
"=",
"dir_path",
".",
"split",
"(",
"os",
".",
"sep",
")",
"for",
"index",
"in",
... | Return a directory path free of filenames.
Args:
dir_path (str): A directory path.
suffix (str): The suffix to append to the part of the path that is
a file.
Returns:
str | [
"Return",
"a",
"directory",
"path",
"free",
"of",
"filenames",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/path.py#L284-L306 | train | 201,358 |
ArchiveTeam/wpull | wpull/path.py | parse_content_disposition | def parse_content_disposition(text):
'''Parse a Content-Disposition header value.'''
match = re.search(r'filename\s*=\s*(.+)', text, re.IGNORECASE)
if not match:
return
filename = match.group(1)
if filename[0] in '"\'':
match = re.match(r'(.)(.+)(?!\\)\1', filename)
if match:
filename = match.group(2).replace('\\"', '"')
return filename
else:
filename = filename.partition(';')[0].strip()
return filename | python | def parse_content_disposition(text):
'''Parse a Content-Disposition header value.'''
match = re.search(r'filename\s*=\s*(.+)', text, re.IGNORECASE)
if not match:
return
filename = match.group(1)
if filename[0] in '"\'':
match = re.match(r'(.)(.+)(?!\\)\1', filename)
if match:
filename = match.group(2).replace('\\"', '"')
return filename
else:
filename = filename.partition(';')[0].strip()
return filename | [
"def",
"parse_content_disposition",
"(",
"text",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'filename\\s*=\\s*(.+)'",
",",
"text",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"not",
"match",
":",
"return",
"filename",
"=",
"match",
".",
"group",
"(",... | Parse a Content-Disposition header value. | [
"Parse",
"a",
"Content",
"-",
"Disposition",
"header",
"value",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/path.py#L309-L328 | train | 201,359 |
ArchiveTeam/wpull | wpull/path.py | PathNamer.safe_filename | def safe_filename(self, part):
'''Return a safe filename or file part.'''
return safe_filename(
part,
os_type=self._os_type, no_control=self._no_control,
ascii_only=self._ascii_only, case=self._case,
max_length=self._max_filename_length,
) | python | def safe_filename(self, part):
'''Return a safe filename or file part.'''
return safe_filename(
part,
os_type=self._os_type, no_control=self._no_control,
ascii_only=self._ascii_only, case=self._case,
max_length=self._max_filename_length,
) | [
"def",
"safe_filename",
"(",
"self",
",",
"part",
")",
":",
"return",
"safe_filename",
"(",
"part",
",",
"os_type",
"=",
"self",
".",
"_os_type",
",",
"no_control",
"=",
"self",
".",
"_no_control",
",",
"ascii_only",
"=",
"self",
".",
"_ascii_only",
",",
... | Return a safe filename or file part. | [
"Return",
"a",
"safe",
"filename",
"or",
"file",
"part",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/path.py#L82-L89 | train | 201,360 |
ArchiveTeam/wpull | wpull/application/plugins/arg_warning.plugin.py | ArgWarningPlugin._warn_unsafe_options | def _warn_unsafe_options(cls, args):
'''Print warnings about any enabled hazardous options.
This function will print messages complaining about:
* ``--save-headers``
* ``--no-iri``
* ``--output-document``
* ``--ignore-fatal-errors``
'''
enabled_options = []
for option_name in cls.UNSAFE_OPTIONS:
if getattr(args, option_name):
enabled_options.append(option_name)
if enabled_options:
_logger.warning(__(
_('The following unsafe options are enabled: {list}.'),
list=enabled_options
))
_logger.warning(
_('The use of unsafe options may lead to unexpected behavior '
'or file corruption.'))
if not args.retr_symlinks:
_logger.warning(
_('The --retr-symlinks=off option is a security risk.')
) | python | def _warn_unsafe_options(cls, args):
'''Print warnings about any enabled hazardous options.
This function will print messages complaining about:
* ``--save-headers``
* ``--no-iri``
* ``--output-document``
* ``--ignore-fatal-errors``
'''
enabled_options = []
for option_name in cls.UNSAFE_OPTIONS:
if getattr(args, option_name):
enabled_options.append(option_name)
if enabled_options:
_logger.warning(__(
_('The following unsafe options are enabled: {list}.'),
list=enabled_options
))
_logger.warning(
_('The use of unsafe options may lead to unexpected behavior '
'or file corruption.'))
if not args.retr_symlinks:
_logger.warning(
_('The --retr-symlinks=off option is a security risk.')
) | [
"def",
"_warn_unsafe_options",
"(",
"cls",
",",
"args",
")",
":",
"enabled_options",
"=",
"[",
"]",
"for",
"option_name",
"in",
"cls",
".",
"UNSAFE_OPTIONS",
":",
"if",
"getattr",
"(",
"args",
",",
"option_name",
")",
":",
"enabled_options",
".",
"append",
... | Print warnings about any enabled hazardous options.
This function will print messages complaining about:
* ``--save-headers``
* ``--no-iri``
* ``--output-document``
* ``--ignore-fatal-errors`` | [
"Print",
"warnings",
"about",
"any",
"enabled",
"hazardous",
"options",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/plugins/arg_warning.plugin.py#L21-L49 | train | 201,361 |
ArchiveTeam/wpull | wpull/application/plugins/arg_warning.plugin.py | ArgWarningPlugin._warn_silly_options | def _warn_silly_options(cls, args):
'''Print warnings about any options that may be silly.'''
if 'page-requisites' in args.span_hosts_allow \
and not args.page_requisites:
_logger.warning(
_('Spanning hosts is allowed for page requisites, '
'but the page requisites option is not on.')
)
if 'linked-pages' in args.span_hosts_allow \
and not args.recursive:
_logger.warning(
_('Spanning hosts is allowed for linked pages, '
'but the recursive option is not on.')
)
if args.warc_file and \
(args.http_proxy or args.https_proxy):
_logger.warning(_('WARC specifications do not handle proxies.'))
if (args.password or args.ftp_password or
args.http_password or args.proxy_password) and \
args.warc_file:
_logger.warning(
_('Your password is recorded in the WARC file.')) | python | def _warn_silly_options(cls, args):
'''Print warnings about any options that may be silly.'''
if 'page-requisites' in args.span_hosts_allow \
and not args.page_requisites:
_logger.warning(
_('Spanning hosts is allowed for page requisites, '
'but the page requisites option is not on.')
)
if 'linked-pages' in args.span_hosts_allow \
and not args.recursive:
_logger.warning(
_('Spanning hosts is allowed for linked pages, '
'but the recursive option is not on.')
)
if args.warc_file and \
(args.http_proxy or args.https_proxy):
_logger.warning(_('WARC specifications do not handle proxies.'))
if (args.password or args.ftp_password or
args.http_password or args.proxy_password) and \
args.warc_file:
_logger.warning(
_('Your password is recorded in the WARC file.')) | [
"def",
"_warn_silly_options",
"(",
"cls",
",",
"args",
")",
":",
"if",
"'page-requisites'",
"in",
"args",
".",
"span_hosts_allow",
"and",
"not",
"args",
".",
"page_requisites",
":",
"_logger",
".",
"warning",
"(",
"_",
"(",
"'Spanning hosts is allowed for page req... | Print warnings about any options that may be silly. | [
"Print",
"warnings",
"about",
"any",
"options",
"that",
"may",
"be",
"silly",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/plugins/arg_warning.plugin.py#L52-L76 | train | 201,362 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/date.py | parse_month | def parse_month(text: str) -> int:
'''Parse month string into integer.'''
text = text.lower()
try:
return MONTH_MAP[text]
except KeyError:
pass
try:
return MONTH_MAP[text[:3]]
except KeyError:
pass
raise ValueError('Month {} not found.'.format(repr(text))) | python | def parse_month(text: str) -> int:
'''Parse month string into integer.'''
text = text.lower()
try:
return MONTH_MAP[text]
except KeyError:
pass
try:
return MONTH_MAP[text[:3]]
except KeyError:
pass
raise ValueError('Month {} not found.'.format(repr(text))) | [
"def",
"parse_month",
"(",
"text",
":",
"str",
")",
"->",
"int",
":",
"text",
"=",
"text",
".",
"lower",
"(",
")",
"try",
":",
"return",
"MONTH_MAP",
"[",
"text",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"MONTH_MAP",
"[",
"text",... | Parse month string into integer. | [
"Parse",
"month",
"string",
"into",
"integer",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/date.py#L313-L326 | train | 201,363 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/date.py | y2k | def y2k(year: int) -> int:
'''Convert two digit year to four digit year.'''
assert 0 <= year <= 99, 'Not a two digit year {}'.format(year)
return year + 1000 if year >= 69 else year + 2000 | python | def y2k(year: int) -> int:
'''Convert two digit year to four digit year.'''
assert 0 <= year <= 99, 'Not a two digit year {}'.format(year)
return year + 1000 if year >= 69 else year + 2000 | [
"def",
"y2k",
"(",
"year",
":",
"int",
")",
"->",
"int",
":",
"assert",
"0",
"<=",
"year",
"<=",
"99",
",",
"'Not a two digit year {}'",
".",
"format",
"(",
"year",
")",
"return",
"year",
"+",
"1000",
"if",
"year",
">=",
"69",
"else",
"year",
"+",
... | Convert two digit year to four digit year. | [
"Convert",
"two",
"digit",
"year",
"to",
"four",
"digit",
"year",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/date.py#L329-L332 | train | 201,364 |
ArchiveTeam/wpull | wpull/protocol/ftp/ls/date.py | parse_cldr_json | def parse_cldr_json(directory, language_codes=DEFAULT_LANGUAGE_CODES,
massage=True):
'''Parse CLDR JSON datasets to for date time things.'''
am_strings = set()
pm_strings = set()
month_to_int = {}
for lang in language_codes:
path = os.path.join(directory, 'main', lang, 'ca-gregorian.json')
with open(path) as in_file:
doc = json.load(in_file)
months_dict = doc['main'][lang]['dates']['calendars']['gregorian']['months']['format']['abbreviated']
day_periods_dict = doc['main'][lang]['dates']['calendars']['gregorian']['dayPeriods']['format']['abbreviated']
for month, month_str in months_dict.items():
if massage:
month_str = unicodedata.normalize('NFKD', month_str).lower().strip('.')
month_to_int[month_str] = int(month)
am_str = day_periods_dict['am']
pm_str = day_periods_dict['pm']
if massage:
am_str = unicodedata.normalize('NFKD', am_str).lower().strip('.')
pm_str = unicodedata.normalize('NFKD', pm_str).lower().strip('.')
am_strings.add(am_str)
pm_strings.add(pm_str)
print(pprint.pformat(am_strings))
print(pprint.pformat(pm_strings))
print(pprint.pformat(month_to_int)) | python | def parse_cldr_json(directory, language_codes=DEFAULT_LANGUAGE_CODES,
massage=True):
'''Parse CLDR JSON datasets to for date time things.'''
am_strings = set()
pm_strings = set()
month_to_int = {}
for lang in language_codes:
path = os.path.join(directory, 'main', lang, 'ca-gregorian.json')
with open(path) as in_file:
doc = json.load(in_file)
months_dict = doc['main'][lang]['dates']['calendars']['gregorian']['months']['format']['abbreviated']
day_periods_dict = doc['main'][lang]['dates']['calendars']['gregorian']['dayPeriods']['format']['abbreviated']
for month, month_str in months_dict.items():
if massage:
month_str = unicodedata.normalize('NFKD', month_str).lower().strip('.')
month_to_int[month_str] = int(month)
am_str = day_periods_dict['am']
pm_str = day_periods_dict['pm']
if massage:
am_str = unicodedata.normalize('NFKD', am_str).lower().strip('.')
pm_str = unicodedata.normalize('NFKD', pm_str).lower().strip('.')
am_strings.add(am_str)
pm_strings.add(pm_str)
print(pprint.pformat(am_strings))
print(pprint.pformat(pm_strings))
print(pprint.pformat(month_to_int)) | [
"def",
"parse_cldr_json",
"(",
"directory",
",",
"language_codes",
"=",
"DEFAULT_LANGUAGE_CODES",
",",
"massage",
"=",
"True",
")",
":",
"am_strings",
"=",
"set",
"(",
")",
"pm_strings",
"=",
"set",
"(",
")",
"month_to_int",
"=",
"{",
"}",
"for",
"lang",
"... | Parse CLDR JSON datasets to for date time things. | [
"Parse",
"CLDR",
"JSON",
"datasets",
"to",
"for",
"date",
"time",
"things",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/date.py#L342-L377 | train | 201,365 |
ArchiveTeam/wpull | wpull/proxy/client.py | HTTPProxyConnectionPool.acquire_proxy | def acquire_proxy(self, host, port, use_ssl=False, host_key=None,
tunnel=True):
'''Check out a connection.
This function is the same as acquire but with extra arguments
concerning proxies.
Coroutine.
'''
if self._host_filter and not self._host_filter.test(host):
connection = yield from \
super().acquire(host, port, use_ssl, host_key)
return connection
host_key = host_key or (host, port, use_ssl)
proxy_host, proxy_port = self._proxy_address
connection = yield from super().acquire(
proxy_host, proxy_port, self._proxy_ssl, host_key=host_key
)
connection.proxied = True
_logger.debug('Request for proxy connection.')
if connection.closed():
_logger.debug('Connecting to proxy.')
yield from connection.connect()
if tunnel:
yield from self._establish_tunnel(connection, (host, port))
if use_ssl:
ssl_connection = yield from connection.start_tls(self._ssl_context)
ssl_connection.proxied = True
ssl_connection.tunneled = True
self._connection_map[ssl_connection] = connection
connection.wrapped_connection = ssl_connection
return ssl_connection
if connection.wrapped_connection:
ssl_connection = connection.wrapped_connection
self._connection_map[ssl_connection] = connection
return ssl_connection
else:
return connection | python | def acquire_proxy(self, host, port, use_ssl=False, host_key=None,
tunnel=True):
'''Check out a connection.
This function is the same as acquire but with extra arguments
concerning proxies.
Coroutine.
'''
if self._host_filter and not self._host_filter.test(host):
connection = yield from \
super().acquire(host, port, use_ssl, host_key)
return connection
host_key = host_key or (host, port, use_ssl)
proxy_host, proxy_port = self._proxy_address
connection = yield from super().acquire(
proxy_host, proxy_port, self._proxy_ssl, host_key=host_key
)
connection.proxied = True
_logger.debug('Request for proxy connection.')
if connection.closed():
_logger.debug('Connecting to proxy.')
yield from connection.connect()
if tunnel:
yield from self._establish_tunnel(connection, (host, port))
if use_ssl:
ssl_connection = yield from connection.start_tls(self._ssl_context)
ssl_connection.proxied = True
ssl_connection.tunneled = True
self._connection_map[ssl_connection] = connection
connection.wrapped_connection = ssl_connection
return ssl_connection
if connection.wrapped_connection:
ssl_connection = connection.wrapped_connection
self._connection_map[ssl_connection] = connection
return ssl_connection
else:
return connection | [
"def",
"acquire_proxy",
"(",
"self",
",",
"host",
",",
"port",
",",
"use_ssl",
"=",
"False",
",",
"host_key",
"=",
"None",
",",
"tunnel",
"=",
"True",
")",
":",
"if",
"self",
".",
"_host_filter",
"and",
"not",
"self",
".",
"_host_filter",
".",
"test",
... | Check out a connection.
This function is the same as acquire but with extra arguments
concerning proxies.
Coroutine. | [
"Check",
"out",
"a",
"connection",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/proxy/client.py#L58-L105 | train | 201,366 |
ArchiveTeam/wpull | wpull/proxy/client.py | HTTPProxyConnectionPool._establish_tunnel | def _establish_tunnel(self, connection, address):
'''Establish a TCP tunnel.
Coroutine.
'''
host = '[{}]'.format(address[0]) if ':' in address[0] else address[0]
port = address[1]
request = RawRequest('CONNECT', '{0}:{1}'.format(host, port))
self.add_auth_header(request)
stream = Stream(connection, keep_alive=True)
_logger.debug('Sending Connect.')
yield from stream.write_request(request)
_logger.debug('Read proxy response.')
response = yield from stream.read_response()
if response.status_code != 200:
debug_file = io.BytesIO()
_logger.debug('Read proxy response body.')
yield from stream.read_body(request, response, file=debug_file)
debug_file.seek(0)
_logger.debug(ascii(debug_file.read()))
if response.status_code == 200:
connection.tunneled = True
else:
raise NetworkError(
'Proxy does not support CONNECT: {} {}'
.format(response.status_code,
wpull.string.printable_str(response.reason))
) | python | def _establish_tunnel(self, connection, address):
'''Establish a TCP tunnel.
Coroutine.
'''
host = '[{}]'.format(address[0]) if ':' in address[0] else address[0]
port = address[1]
request = RawRequest('CONNECT', '{0}:{1}'.format(host, port))
self.add_auth_header(request)
stream = Stream(connection, keep_alive=True)
_logger.debug('Sending Connect.')
yield from stream.write_request(request)
_logger.debug('Read proxy response.')
response = yield from stream.read_response()
if response.status_code != 200:
debug_file = io.BytesIO()
_logger.debug('Read proxy response body.')
yield from stream.read_body(request, response, file=debug_file)
debug_file.seek(0)
_logger.debug(ascii(debug_file.read()))
if response.status_code == 200:
connection.tunneled = True
else:
raise NetworkError(
'Proxy does not support CONNECT: {} {}'
.format(response.status_code,
wpull.string.printable_str(response.reason))
) | [
"def",
"_establish_tunnel",
"(",
"self",
",",
"connection",
",",
"address",
")",
":",
"host",
"=",
"'[{}]'",
".",
"format",
"(",
"address",
"[",
"0",
"]",
")",
"if",
"':'",
"in",
"address",
"[",
"0",
"]",
"else",
"address",
"[",
"0",
"]",
"port",
"... | Establish a TCP tunnel.
Coroutine. | [
"Establish",
"a",
"TCP",
"tunnel",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/proxy/client.py#L117-L151 | train | 201,367 |
ArchiveTeam/wpull | wpull/document/html.py | HTMLReader.is_file | def is_file(cls, file):
'''Return whether the file is likely to be HTML.'''
peeked_data = wpull.string.printable_bytes(
wpull.util.peek_file(file)).lower()
if b'<!doctype html' in peeked_data \
or b'<head' in peeked_data \
or b'<title' in peeked_data \
or b'<html' in peeked_data \
or b'<script' in peeked_data \
or b'<table' in peeked_data \
or b'<a href' in peeked_data:
return True | python | def is_file(cls, file):
'''Return whether the file is likely to be HTML.'''
peeked_data = wpull.string.printable_bytes(
wpull.util.peek_file(file)).lower()
if b'<!doctype html' in peeked_data \
or b'<head' in peeked_data \
or b'<title' in peeked_data \
or b'<html' in peeked_data \
or b'<script' in peeked_data \
or b'<table' in peeked_data \
or b'<a href' in peeked_data:
return True | [
"def",
"is_file",
"(",
"cls",
",",
"file",
")",
":",
"peeked_data",
"=",
"wpull",
".",
"string",
".",
"printable_bytes",
"(",
"wpull",
".",
"util",
".",
"peek_file",
"(",
"file",
")",
")",
".",
"lower",
"(",
")",
"if",
"b'<!doctype html'",
"in",
"peeke... | Return whether the file is likely to be HTML. | [
"Return",
"whether",
"the",
"file",
"is",
"likely",
"to",
"be",
"HTML",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/html.py#L214-L226 | train | 201,368 |
ArchiveTeam/wpull | wpull/cookiewrapper.py | convert_http_request | def convert_http_request(request, referrer_host=None):
'''Convert a HTTP request.
Args:
request: An instance of :class:`.http.request.Request`.
referrer_host (str): The referrering hostname or IP address.
Returns:
Request: An instance of :class:`urllib.request.Request`
'''
new_request = urllib.request.Request(
request.url_info.url,
origin_req_host=referrer_host,
)
for name, value in request.fields.get_all():
new_request.add_header(name, value)
return new_request | python | def convert_http_request(request, referrer_host=None):
'''Convert a HTTP request.
Args:
request: An instance of :class:`.http.request.Request`.
referrer_host (str): The referrering hostname or IP address.
Returns:
Request: An instance of :class:`urllib.request.Request`
'''
new_request = urllib.request.Request(
request.url_info.url,
origin_req_host=referrer_host,
)
for name, value in request.fields.get_all():
new_request.add_header(name, value)
return new_request | [
"def",
"convert_http_request",
"(",
"request",
",",
"referrer_host",
"=",
"None",
")",
":",
"new_request",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"request",
".",
"url_info",
".",
"url",
",",
"origin_req_host",
"=",
"referrer_host",
",",
")",
"fo... | Convert a HTTP request.
Args:
request: An instance of :class:`.http.request.Request`.
referrer_host (str): The referrering hostname or IP address.
Returns:
Request: An instance of :class:`urllib.request.Request` | [
"Convert",
"a",
"HTTP",
"request",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/cookiewrapper.py#L13-L31 | train | 201,369 |
ArchiveTeam/wpull | wpull/cookiewrapper.py | CookieJarWrapper.add_cookie_header | def add_cookie_header(self, request, referrer_host=None):
'''Wrapped ``add_cookie_header``.
Args:
request: An instance of :class:`.http.request.Request`.
referrer_host (str): An hostname or IP address of the referrer
URL.
'''
new_request = convert_http_request(request, referrer_host)
self._cookie_jar.add_cookie_header(new_request)
request.fields.clear()
for name, value in new_request.header_items():
request.fields.add(name, value) | python | def add_cookie_header(self, request, referrer_host=None):
'''Wrapped ``add_cookie_header``.
Args:
request: An instance of :class:`.http.request.Request`.
referrer_host (str): An hostname or IP address of the referrer
URL.
'''
new_request = convert_http_request(request, referrer_host)
self._cookie_jar.add_cookie_header(new_request)
request.fields.clear()
for name, value in new_request.header_items():
request.fields.add(name, value) | [
"def",
"add_cookie_header",
"(",
"self",
",",
"request",
",",
"referrer_host",
"=",
"None",
")",
":",
"new_request",
"=",
"convert_http_request",
"(",
"request",
",",
"referrer_host",
")",
"self",
".",
"_cookie_jar",
".",
"add_cookie_header",
"(",
"new_request",
... | Wrapped ``add_cookie_header``.
Args:
request: An instance of :class:`.http.request.Request`.
referrer_host (str): An hostname or IP address of the referrer
URL. | [
"Wrapped",
"add_cookie_header",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/cookiewrapper.py#L71-L85 | train | 201,370 |
ArchiveTeam/wpull | wpull/cookiewrapper.py | CookieJarWrapper.extract_cookies | def extract_cookies(self, response, request, referrer_host=None):
'''Wrapped ``extract_cookies``.
Args:
response: An instance of :class:`.http.request.Response`.
request: An instance of :class:`.http.request.Request`.
referrer_host (str): An hostname or IP address of the referrer
URL.
'''
new_response = HTTPResponseInfoWrapper(response)
new_request = convert_http_request(request, referrer_host)
self._cookie_jar.extract_cookies(new_response, new_request) | python | def extract_cookies(self, response, request, referrer_host=None):
'''Wrapped ``extract_cookies``.
Args:
response: An instance of :class:`.http.request.Response`.
request: An instance of :class:`.http.request.Request`.
referrer_host (str): An hostname or IP address of the referrer
URL.
'''
new_response = HTTPResponseInfoWrapper(response)
new_request = convert_http_request(request, referrer_host)
self._cookie_jar.extract_cookies(new_response, new_request) | [
"def",
"extract_cookies",
"(",
"self",
",",
"response",
",",
"request",
",",
"referrer_host",
"=",
"None",
")",
":",
"new_response",
"=",
"HTTPResponseInfoWrapper",
"(",
"response",
")",
"new_request",
"=",
"convert_http_request",
"(",
"request",
",",
"referrer_ho... | Wrapped ``extract_cookies``.
Args:
response: An instance of :class:`.http.request.Response`.
request: An instance of :class:`.http.request.Request`.
referrer_host (str): An hostname or IP address of the referrer
URL. | [
"Wrapped",
"extract_cookies",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/cookiewrapper.py#L87-L99 | train | 201,371 |
ArchiveTeam/wpull | wpull/cookiewrapper.py | CookieJarWrapper.close | def close(self):
'''Save the cookie jar if needed.'''
if self._save_filename:
self._cookie_jar.save(
self._save_filename,
ignore_discard=self._keep_session_cookies
) | python | def close(self):
'''Save the cookie jar if needed.'''
if self._save_filename:
self._cookie_jar.save(
self._save_filename,
ignore_discard=self._keep_session_cookies
) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_save_filename",
":",
"self",
".",
"_cookie_jar",
".",
"save",
"(",
"self",
".",
"_save_filename",
",",
"ignore_discard",
"=",
"self",
".",
"_keep_session_cookies",
")"
] | Save the cookie jar if needed. | [
"Save",
"the",
"cookie",
"jar",
"if",
"needed",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/cookiewrapper.py#L106-L112 | train | 201,372 |
ArchiveTeam/wpull | wpull/driver/process.py | Process.start | def start(self, use_atexit=True):
'''Start the executable.
Args:
use_atexit (bool): If True, the process will automatically be
terminated at exit.
'''
assert not self._process
_logger.debug('Starting process %s', self._proc_args)
process_future = asyncio.create_subprocess_exec(
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
*self._proc_args
)
self._process = yield from process_future
self._stderr_reader = asyncio.async(self._read_stderr())
self._stdout_reader = asyncio.async(self._read_stdout())
if use_atexit:
atexit.register(self.close) | python | def start(self, use_atexit=True):
'''Start the executable.
Args:
use_atexit (bool): If True, the process will automatically be
terminated at exit.
'''
assert not self._process
_logger.debug('Starting process %s', self._proc_args)
process_future = asyncio.create_subprocess_exec(
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
*self._proc_args
)
self._process = yield from process_future
self._stderr_reader = asyncio.async(self._read_stderr())
self._stdout_reader = asyncio.async(self._read_stdout())
if use_atexit:
atexit.register(self.close) | [
"def",
"start",
"(",
"self",
",",
"use_atexit",
"=",
"True",
")",
":",
"assert",
"not",
"self",
".",
"_process",
"_logger",
".",
"debug",
"(",
"'Starting process %s'",
",",
"self",
".",
"_proc_args",
")",
"process_future",
"=",
"asyncio",
".",
"create_subpro... | Start the executable.
Args:
use_atexit (bool): If True, the process will automatically be
terminated at exit. | [
"Start",
"the",
"executable",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/driver/process.py#L37-L60 | train | 201,373 |
ArchiveTeam/wpull | wpull/driver/process.py | Process.close | def close(self):
'''Terminate or kill the subprocess.
This function is blocking.
'''
if not self._process:
return
if self._process.returncode is not None:
return
_logger.debug('Terminate process.')
try:
self._process.terminate()
except OSError as error:
if error.errno != errno.ESRCH:
raise
for dummy in range(10):
if self._process.returncode is not None:
return
time.sleep(0.05)
_logger.debug('Failed to terminate. Killing.')
try:
self._process.kill()
except OSError as error:
if error.errno != errno.ESRCH:
raise | python | def close(self):
'''Terminate or kill the subprocess.
This function is blocking.
'''
if not self._process:
return
if self._process.returncode is not None:
return
_logger.debug('Terminate process.')
try:
self._process.terminate()
except OSError as error:
if error.errno != errno.ESRCH:
raise
for dummy in range(10):
if self._process.returncode is not None:
return
time.sleep(0.05)
_logger.debug('Failed to terminate. Killing.')
try:
self._process.kill()
except OSError as error:
if error.errno != errno.ESRCH:
raise | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_process",
":",
"return",
"if",
"self",
".",
"_process",
".",
"returncode",
"is",
"not",
"None",
":",
"return",
"_logger",
".",
"debug",
"(",
"'Terminate process.'",
")",
"try",
":",
"se... | Terminate or kill the subprocess.
This function is blocking. | [
"Terminate",
"or",
"kill",
"the",
"subprocess",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/driver/process.py#L62-L93 | train | 201,374 |
ArchiveTeam/wpull | wpull/driver/process.py | Process._read_stdout | def _read_stdout(self):
'''Continuously read the stdout for messages.'''
try:
while self._process.returncode is None:
line = yield from self._process.stdout.readline()
_logger.debug('Read stdout line %s', repr(line))
if not line:
break
if self._stdout_callback:
yield from self._stdout_callback(line)
except Exception:
_logger.exception('Unhandled read stdout exception.')
raise | python | def _read_stdout(self):
'''Continuously read the stdout for messages.'''
try:
while self._process.returncode is None:
line = yield from self._process.stdout.readline()
_logger.debug('Read stdout line %s', repr(line))
if not line:
break
if self._stdout_callback:
yield from self._stdout_callback(line)
except Exception:
_logger.exception('Unhandled read stdout exception.')
raise | [
"def",
"_read_stdout",
"(",
"self",
")",
":",
"try",
":",
"while",
"self",
".",
"_process",
".",
"returncode",
"is",
"None",
":",
"line",
"=",
"yield",
"from",
"self",
".",
"_process",
".",
"stdout",
".",
"readline",
"(",
")",
"_logger",
".",
"debug",
... | Continuously read the stdout for messages. | [
"Continuously",
"read",
"the",
"stdout",
"for",
"messages",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/driver/process.py#L96-L112 | train | 201,375 |
ArchiveTeam/wpull | wpull/driver/process.py | Process._read_stderr | def _read_stderr(self):
'''Continuously read stderr for error messages.'''
try:
while self._process.returncode is None:
line = yield from self._process.stderr.readline()
if not line:
break
if self._stderr_callback:
yield from self._stderr_callback(line)
except Exception:
_logger.exception('Unhandled read stderr exception.')
raise | python | def _read_stderr(self):
'''Continuously read stderr for error messages.'''
try:
while self._process.returncode is None:
line = yield from self._process.stderr.readline()
if not line:
break
if self._stderr_callback:
yield from self._stderr_callback(line)
except Exception:
_logger.exception('Unhandled read stderr exception.')
raise | [
"def",
"_read_stderr",
"(",
"self",
")",
":",
"try",
":",
"while",
"self",
".",
"_process",
".",
"returncode",
"is",
"None",
":",
"line",
"=",
"yield",
"from",
"self",
".",
"_process",
".",
"stderr",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":... | Continuously read stderr for error messages. | [
"Continuously",
"read",
"stderr",
"for",
"error",
"messages",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/driver/process.py#L115-L129 | train | 201,376 |
ArchiveTeam/wpull | wpull/protocol/ftp/stream.py | DataStream.read_file | def read_file(self, file: Union[IO, asyncio.StreamWriter]=None):
'''Read from connection to file.
Args:
file: A file object or a writer stream.
'''
if file:
file_is_async = hasattr(file, 'drain')
while True:
data = yield from self._connection.read(4096)
if not data:
break
if file:
file.write(data)
if file_is_async:
yield from file.drain()
self._data_event_dispatcher.notify_read(data) | python | def read_file(self, file: Union[IO, asyncio.StreamWriter]=None):
'''Read from connection to file.
Args:
file: A file object or a writer stream.
'''
if file:
file_is_async = hasattr(file, 'drain')
while True:
data = yield from self._connection.read(4096)
if not data:
break
if file:
file.write(data)
if file_is_async:
yield from file.drain()
self._data_event_dispatcher.notify_read(data) | [
"def",
"read_file",
"(",
"self",
",",
"file",
":",
"Union",
"[",
"IO",
",",
"asyncio",
".",
"StreamWriter",
"]",
"=",
"None",
")",
":",
"if",
"file",
":",
"file_is_async",
"=",
"hasattr",
"(",
"file",
",",
"'drain'",
")",
"while",
"True",
":",
"data"... | Read from connection to file.
Args:
file: A file object or a writer stream. | [
"Read",
"from",
"connection",
"to",
"file",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/stream.py#L43-L64 | train | 201,377 |
ArchiveTeam/wpull | wpull/protocol/ftp/stream.py | ControlStream.reconnect | def reconnect(self):
'''Connected the stream if needed.
Coroutine.
'''
if self._connection.closed():
self._connection.reset()
yield from self._connection.connect() | python | def reconnect(self):
'''Connected the stream if needed.
Coroutine.
'''
if self._connection.closed():
self._connection.reset()
yield from self._connection.connect() | [
"def",
"reconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
".",
"closed",
"(",
")",
":",
"self",
".",
"_connection",
".",
"reset",
"(",
")",
"yield",
"from",
"self",
".",
"_connection",
".",
"connect",
"(",
")"
] | Connected the stream if needed.
Coroutine. | [
"Connected",
"the",
"stream",
"if",
"needed",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/stream.py#L92-L100 | train | 201,378 |
ArchiveTeam/wpull | wpull/protocol/ftp/stream.py | ControlStream.write_command | def write_command(self, command: Command):
'''Write a command to the stream.
Args:
command: The command.
Coroutine.
'''
_logger.debug('Write command.')
data = command.to_bytes()
yield from self._connection.write(data)
self._data_event_dispatcher.notify_write(data) | python | def write_command(self, command: Command):
'''Write a command to the stream.
Args:
command: The command.
Coroutine.
'''
_logger.debug('Write command.')
data = command.to_bytes()
yield from self._connection.write(data)
self._data_event_dispatcher.notify_write(data) | [
"def",
"write_command",
"(",
"self",
",",
"command",
":",
"Command",
")",
":",
"_logger",
".",
"debug",
"(",
"'Write command.'",
")",
"data",
"=",
"command",
".",
"to_bytes",
"(",
")",
"yield",
"from",
"self",
".",
"_connection",
".",
"write",
"(",
"data... | Write a command to the stream.
Args:
command: The command.
Coroutine. | [
"Write",
"a",
"command",
"to",
"the",
"stream",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/stream.py#L104-L115 | train | 201,379 |
ArchiveTeam/wpull | wpull/protocol/ftp/stream.py | ControlStream.read_reply | def read_reply(self) -> Reply:
'''Read a reply from the stream.
Returns:
.ftp.request.Reply: The reply
Coroutine.
'''
_logger.debug('Read reply')
reply = Reply()
while True:
line = yield from self._connection.readline()
if line[-1:] != b'\n':
raise NetworkError('Connection closed.')
self._data_event_dispatcher.notify_read(line)
reply.parse(line)
if reply.code is not None:
break
return reply | python | def read_reply(self) -> Reply:
'''Read a reply from the stream.
Returns:
.ftp.request.Reply: The reply
Coroutine.
'''
_logger.debug('Read reply')
reply = Reply()
while True:
line = yield from self._connection.readline()
if line[-1:] != b'\n':
raise NetworkError('Connection closed.')
self._data_event_dispatcher.notify_read(line)
reply.parse(line)
if reply.code is not None:
break
return reply | [
"def",
"read_reply",
"(",
"self",
")",
"->",
"Reply",
":",
"_logger",
".",
"debug",
"(",
"'Read reply'",
")",
"reply",
"=",
"Reply",
"(",
")",
"while",
"True",
":",
"line",
"=",
"yield",
"from",
"self",
".",
"_connection",
".",
"readline",
"(",
")",
... | Read a reply from the stream.
Returns:
.ftp.request.Reply: The reply
Coroutine. | [
"Read",
"a",
"reply",
"from",
"the",
"stream",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/stream.py#L119-L142 | train | 201,380 |
ArchiveTeam/wpull | wpull/protocol/http/robots.py | RobotsTxtChecker.can_fetch_pool | def can_fetch_pool(self, request: Request):
'''Return whether the request can be fetched based on the pool.'''
url_info = request.url_info
user_agent = request.fields.get('User-agent', '')
if self._robots_txt_pool.has_parser(url_info):
return self._robots_txt_pool.can_fetch(url_info, user_agent)
else:
raise NotInPoolError() | python | def can_fetch_pool(self, request: Request):
'''Return whether the request can be fetched based on the pool.'''
url_info = request.url_info
user_agent = request.fields.get('User-agent', '')
if self._robots_txt_pool.has_parser(url_info):
return self._robots_txt_pool.can_fetch(url_info, user_agent)
else:
raise NotInPoolError() | [
"def",
"can_fetch_pool",
"(",
"self",
",",
"request",
":",
"Request",
")",
":",
"url_info",
"=",
"request",
".",
"url_info",
"user_agent",
"=",
"request",
".",
"fields",
".",
"get",
"(",
"'User-agent'",
",",
"''",
")",
"if",
"self",
".",
"_robots_txt_pool"... | Return whether the request can be fetched based on the pool. | [
"Return",
"whether",
"the",
"request",
"can",
"be",
"fetched",
"based",
"on",
"the",
"pool",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/robots.py#L50-L58 | train | 201,381 |
ArchiveTeam/wpull | wpull/protocol/http/robots.py | RobotsTxtChecker.fetch_robots_txt | def fetch_robots_txt(self, request: Request, file=None):
'''Fetch the robots.txt file for the request.
Coroutine.
'''
url_info = request.url_info
url = URLInfo.parse('{0}://{1}/robots.txt'.format(
url_info.scheme, url_info.hostname_with_port)).url
if not file:
file = wpull.body.new_temp_file(os.getcwd(), hint='robots')
with contextlib.closing(file):
request = Request(url)
session = self._web_client.session(request)
while not session.done():
wpull.util.truncate_file(file.name)
try:
response = yield from session.start()
yield from session.download(file=file)
except ProtocolError:
self._accept_as_blank(url_info)
return
status_code = response.status_code
if 500 <= status_code <= 599:
raise ServerError('Server returned error for robots.txt.')
if status_code == 200:
self._read_content(response, url_info)
else:
self._accept_as_blank(url_info) | python | def fetch_robots_txt(self, request: Request, file=None):
'''Fetch the robots.txt file for the request.
Coroutine.
'''
url_info = request.url_info
url = URLInfo.parse('{0}://{1}/robots.txt'.format(
url_info.scheme, url_info.hostname_with_port)).url
if not file:
file = wpull.body.new_temp_file(os.getcwd(), hint='robots')
with contextlib.closing(file):
request = Request(url)
session = self._web_client.session(request)
while not session.done():
wpull.util.truncate_file(file.name)
try:
response = yield from session.start()
yield from session.download(file=file)
except ProtocolError:
self._accept_as_blank(url_info)
return
status_code = response.status_code
if 500 <= status_code <= 599:
raise ServerError('Server returned error for robots.txt.')
if status_code == 200:
self._read_content(response, url_info)
else:
self._accept_as_blank(url_info) | [
"def",
"fetch_robots_txt",
"(",
"self",
",",
"request",
":",
"Request",
",",
"file",
"=",
"None",
")",
":",
"url_info",
"=",
"request",
".",
"url_info",
"url",
"=",
"URLInfo",
".",
"parse",
"(",
"'{0}://{1}/robots.txt'",
".",
"format",
"(",
"url_info",
"."... | Fetch the robots.txt file for the request.
Coroutine. | [
"Fetch",
"the",
"robots",
".",
"txt",
"file",
"for",
"the",
"request",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/robots.py#L61-L96 | train | 201,382 |
ArchiveTeam/wpull | wpull/protocol/http/robots.py | RobotsTxtChecker.can_fetch | def can_fetch(self, request: Request, file=None) -> bool:
'''Return whether the request can fetched.
Args:
request: Request.
file: A file object to where the robots.txt contents are written.
Coroutine.
'''
try:
return self.can_fetch_pool(request)
except NotInPoolError:
pass
yield from self.fetch_robots_txt(request, file=file)
return self.can_fetch_pool(request) | python | def can_fetch(self, request: Request, file=None) -> bool:
'''Return whether the request can fetched.
Args:
request: Request.
file: A file object to where the robots.txt contents are written.
Coroutine.
'''
try:
return self.can_fetch_pool(request)
except NotInPoolError:
pass
yield from self.fetch_robots_txt(request, file=file)
return self.can_fetch_pool(request) | [
"def",
"can_fetch",
"(",
"self",
",",
"request",
":",
"Request",
",",
"file",
"=",
"None",
")",
"->",
"bool",
":",
"try",
":",
"return",
"self",
".",
"can_fetch_pool",
"(",
"request",
")",
"except",
"NotInPoolError",
":",
"pass",
"yield",
"from",
"self",... | Return whether the request can fetched.
Args:
request: Request.
file: A file object to where the robots.txt contents are written.
Coroutine. | [
"Return",
"whether",
"the",
"request",
"can",
"fetched",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/robots.py#L99-L115 | train | 201,383 |
ArchiveTeam/wpull | wpull/protocol/http/robots.py | RobotsTxtChecker._read_content | def _read_content(self, response: Response, original_url_info: URLInfo):
'''Read response and parse the contents into the pool.'''
data = response.body.read(4096)
url_info = original_url_info
try:
self._robots_txt_pool.load_robots_txt(url_info, data)
except ValueError:
_logger.warning(__(
_('Failed to parse {url} for robots exclusion rules. '
'Ignoring.'), url_info.url))
self._accept_as_blank(url_info)
else:
_logger.debug(__('Got a good robots.txt for {0}.',
url_info.url)) | python | def _read_content(self, response: Response, original_url_info: URLInfo):
'''Read response and parse the contents into the pool.'''
data = response.body.read(4096)
url_info = original_url_info
try:
self._robots_txt_pool.load_robots_txt(url_info, data)
except ValueError:
_logger.warning(__(
_('Failed to parse {url} for robots exclusion rules. '
'Ignoring.'), url_info.url))
self._accept_as_blank(url_info)
else:
_logger.debug(__('Got a good robots.txt for {0}.',
url_info.url)) | [
"def",
"_read_content",
"(",
"self",
",",
"response",
":",
"Response",
",",
"original_url_info",
":",
"URLInfo",
")",
":",
"data",
"=",
"response",
".",
"body",
".",
"read",
"(",
"4096",
")",
"url_info",
"=",
"original_url_info",
"try",
":",
"self",
".",
... | Read response and parse the contents into the pool. | [
"Read",
"response",
"and",
"parse",
"the",
"contents",
"into",
"the",
"pool",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/robots.py#L117-L131 | train | 201,384 |
ArchiveTeam/wpull | wpull/protocol/http/robots.py | RobotsTxtChecker._accept_as_blank | def _accept_as_blank(self, url_info: URLInfo):
'''Mark the URL as OK in the pool.'''
_logger.debug(__('Got empty robots.txt for {0}.', url_info.url))
self._robots_txt_pool.load_robots_txt(url_info, '') | python | def _accept_as_blank(self, url_info: URLInfo):
'''Mark the URL as OK in the pool.'''
_logger.debug(__('Got empty robots.txt for {0}.', url_info.url))
self._robots_txt_pool.load_robots_txt(url_info, '') | [
"def",
"_accept_as_blank",
"(",
"self",
",",
"url_info",
":",
"URLInfo",
")",
":",
"_logger",
".",
"debug",
"(",
"__",
"(",
"'Got empty robots.txt for {0}.'",
",",
"url_info",
".",
"url",
")",
")",
"self",
".",
"_robots_txt_pool",
".",
"load_robots_txt",
"(",
... | Mark the URL as OK in the pool. | [
"Mark",
"the",
"URL",
"as",
"OK",
"in",
"the",
"pool",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/robots.py#L133-L136 | train | 201,385 |
ArchiveTeam/wpull | wpull/network/dns.py | DNSInfo.to_text_format | def to_text_format(self):
'''Format as detached DNS information as text.'''
return '\n'.join(itertools.chain(
(self.fetch_date.strftime('%Y%m%d%H%M%S'), ),
(rr.to_text() for rr in self.resource_records),
(),
)) | python | def to_text_format(self):
'''Format as detached DNS information as text.'''
return '\n'.join(itertools.chain(
(self.fetch_date.strftime('%Y%m%d%H%M%S'), ),
(rr.to_text() for rr in self.resource_records),
(),
)) | [
"def",
"to_text_format",
"(",
"self",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"itertools",
".",
"chain",
"(",
"(",
"self",
".",
"fetch_date",
".",
"strftime",
"(",
"'%Y%m%d%H%M%S'",
")",
",",
")",
",",
"(",
"rr",
".",
"to_text",
"(",
")",
"for... | Format as detached DNS information as text. | [
"Format",
"as",
"detached",
"DNS",
"information",
"as",
"text",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L51-L57 | train | 201,386 |
ArchiveTeam/wpull | wpull/network/dns.py | ResolveResult.first_ipv4 | def first_ipv4(self) -> Optional[AddressInfo]:
'''The first IPv4 address.'''
for info in self._address_infos:
if info.family == socket.AF_INET:
return info | python | def first_ipv4(self) -> Optional[AddressInfo]:
'''The first IPv4 address.'''
for info in self._address_infos:
if info.family == socket.AF_INET:
return info | [
"def",
"first_ipv4",
"(",
"self",
")",
"->",
"Optional",
"[",
"AddressInfo",
"]",
":",
"for",
"info",
"in",
"self",
".",
"_address_infos",
":",
"if",
"info",
".",
"family",
"==",
"socket",
".",
"AF_INET",
":",
"return",
"info"
] | The first IPv4 address. | [
"The",
"first",
"IPv4",
"address",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L78-L82 | train | 201,387 |
ArchiveTeam/wpull | wpull/network/dns.py | ResolveResult.first_ipv6 | def first_ipv6(self) -> Optional[AddressInfo]:
'''The first IPV6 address.'''
for info in self._address_infos:
if info.family == socket.AF_INET6:
return info | python | def first_ipv6(self) -> Optional[AddressInfo]:
'''The first IPV6 address.'''
for info in self._address_infos:
if info.family == socket.AF_INET6:
return info | [
"def",
"first_ipv6",
"(",
"self",
")",
"->",
"Optional",
"[",
"AddressInfo",
"]",
":",
"for",
"info",
"in",
"self",
".",
"_address_infos",
":",
"if",
"info",
".",
"family",
"==",
"socket",
".",
"AF_INET6",
":",
"return",
"info"
] | The first IPV6 address. | [
"The",
"first",
"IPV6",
"address",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L85-L89 | train | 201,388 |
ArchiveTeam/wpull | wpull/network/dns.py | ResolveResult.rotate | def rotate(self):
'''Move the first address to the last position.'''
item = self._address_infos.pop(0)
self._address_infos.append(item) | python | def rotate(self):
'''Move the first address to the last position.'''
item = self._address_infos.pop(0)
self._address_infos.append(item) | [
"def",
"rotate",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"_address_infos",
".",
"pop",
"(",
"0",
")",
"self",
".",
"_address_infos",
".",
"append",
"(",
"item",
")"
] | Move the first address to the last position. | [
"Move",
"the",
"first",
"address",
"to",
"the",
"last",
"position",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L95-L98 | train | 201,389 |
ArchiveTeam/wpull | wpull/network/dns.py | Resolver._query_dns | def _query_dns(self, host: str, family: int=socket.AF_INET) \
-> dns.resolver.Answer:
'''Query DNS using Python.
Coroutine.
'''
record_type = {socket.AF_INET: 'A', socket.AF_INET6: 'AAAA'}[family]
event_loop = asyncio.get_event_loop()
query = functools.partial(
self._dns_resolver.query, host, record_type,
source=self._bind_address)
try:
answer = yield from event_loop.run_in_executor(None, query)
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer) as error:
# dnspython doesn't raise an instance with a message, so use the
# class name instead.
raise DNSNotFound(
'DNS resolution failed: {error}'
.format(error=wpull.util.get_exception_message(error))
) from error
except dns.exception.DNSException as error:
raise NetworkError(
'DNS resolution error: {error}'
.format(error=wpull.util.get_exception_message(error))
) from error
else:
return answer | python | def _query_dns(self, host: str, family: int=socket.AF_INET) \
-> dns.resolver.Answer:
'''Query DNS using Python.
Coroutine.
'''
record_type = {socket.AF_INET: 'A', socket.AF_INET6: 'AAAA'}[family]
event_loop = asyncio.get_event_loop()
query = functools.partial(
self._dns_resolver.query, host, record_type,
source=self._bind_address)
try:
answer = yield from event_loop.run_in_executor(None, query)
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer) as error:
# dnspython doesn't raise an instance with a message, so use the
# class name instead.
raise DNSNotFound(
'DNS resolution failed: {error}'
.format(error=wpull.util.get_exception_message(error))
) from error
except dns.exception.DNSException as error:
raise NetworkError(
'DNS resolution error: {error}'
.format(error=wpull.util.get_exception_message(error))
) from error
else:
return answer | [
"def",
"_query_dns",
"(",
"self",
",",
"host",
":",
"str",
",",
"family",
":",
"int",
"=",
"socket",
".",
"AF_INET",
")",
"->",
"dns",
".",
"resolver",
".",
"Answer",
":",
"record_type",
"=",
"{",
"socket",
".",
"AF_INET",
":",
"'A'",
",",
"socket",
... | Query DNS using Python.
Coroutine. | [
"Query",
"DNS",
"using",
"Python",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L241-L269 | train | 201,390 |
ArchiveTeam/wpull | wpull/network/dns.py | Resolver._getaddrinfo | def _getaddrinfo(self, host: str, family: int=socket.AF_UNSPEC) \
-> List[tuple]:
'''Query DNS using system resolver.
Coroutine.
'''
event_loop = asyncio.get_event_loop()
query = event_loop.getaddrinfo(host, 0, family=family,
proto=socket.IPPROTO_TCP)
if self._timeout:
query = asyncio.wait_for(query, self._timeout)
try:
results = yield from query
except socket.error as error:
if error.errno in (
socket.EAI_FAIL,
socket.EAI_NODATA,
socket.EAI_NONAME):
raise DNSNotFound(
'DNS resolution failed: {error}'.format(error=error)
) from error
else:
raise NetworkError(
'DNS resolution error: {error}'.format(error=error)
) from error
except asyncio.TimeoutError as error:
raise NetworkError('DNS resolve timed out.') from error
else:
return results | python | def _getaddrinfo(self, host: str, family: int=socket.AF_UNSPEC) \
-> List[tuple]:
'''Query DNS using system resolver.
Coroutine.
'''
event_loop = asyncio.get_event_loop()
query = event_loop.getaddrinfo(host, 0, family=family,
proto=socket.IPPROTO_TCP)
if self._timeout:
query = asyncio.wait_for(query, self._timeout)
try:
results = yield from query
except socket.error as error:
if error.errno in (
socket.EAI_FAIL,
socket.EAI_NODATA,
socket.EAI_NONAME):
raise DNSNotFound(
'DNS resolution failed: {error}'.format(error=error)
) from error
else:
raise NetworkError(
'DNS resolution error: {error}'.format(error=error)
) from error
except asyncio.TimeoutError as error:
raise NetworkError('DNS resolve timed out.') from error
else:
return results | [
"def",
"_getaddrinfo",
"(",
"self",
",",
"host",
":",
"str",
",",
"family",
":",
"int",
"=",
"socket",
".",
"AF_UNSPEC",
")",
"->",
"List",
"[",
"tuple",
"]",
":",
"event_loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"query",
"=",
"event_loop... | Query DNS using system resolver.
Coroutine. | [
"Query",
"DNS",
"using",
"system",
"resolver",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L272-L302 | train | 201,391 |
ArchiveTeam/wpull | wpull/network/dns.py | Resolver._convert_dns_answer | def _convert_dns_answer(cls, answer: dns.resolver.Answer) \
-> Iterable[AddressInfo]:
'''Convert the DNS answer to address info.'''
assert answer.rdtype in (dns.rdatatype.A, dns.rdatatype.AAAA)
if answer.rdtype == dns.rdatatype.A:
family = socket.AF_INET
else:
family = socket.AF_INET6
for record in answer:
ip_address = record.to_text()
if family == socket.AF_INET6:
flow_info, control_id = cls._get_ipv6_info(ip_address)
else:
flow_info = control_id = None
yield AddressInfo(ip_address, family, flow_info, control_id) | python | def _convert_dns_answer(cls, answer: dns.resolver.Answer) \
-> Iterable[AddressInfo]:
'''Convert the DNS answer to address info.'''
assert answer.rdtype in (dns.rdatatype.A, dns.rdatatype.AAAA)
if answer.rdtype == dns.rdatatype.A:
family = socket.AF_INET
else:
family = socket.AF_INET6
for record in answer:
ip_address = record.to_text()
if family == socket.AF_INET6:
flow_info, control_id = cls._get_ipv6_info(ip_address)
else:
flow_info = control_id = None
yield AddressInfo(ip_address, family, flow_info, control_id) | [
"def",
"_convert_dns_answer",
"(",
"cls",
",",
"answer",
":",
"dns",
".",
"resolver",
".",
"Answer",
")",
"->",
"Iterable",
"[",
"AddressInfo",
"]",
":",
"assert",
"answer",
".",
"rdtype",
"in",
"(",
"dns",
".",
"rdatatype",
".",
"A",
",",
"dns",
".",
... | Convert the DNS answer to address info. | [
"Convert",
"the",
"DNS",
"answer",
"to",
"address",
"info",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L305-L323 | train | 201,392 |
ArchiveTeam/wpull | wpull/network/dns.py | Resolver._convert_addrinfo | def _convert_addrinfo(cls, results: List[tuple]) -> Iterable[AddressInfo]:
'''Convert the result list to address info.'''
for result in results:
family = result[0]
address = result[4]
ip_address = address[0]
if family == socket.AF_INET6:
flow_info = address[2]
control_id = address[3]
else:
flow_info = None
control_id = None
yield AddressInfo(ip_address, family, flow_info, control_id) | python | def _convert_addrinfo(cls, results: List[tuple]) -> Iterable[AddressInfo]:
'''Convert the result list to address info.'''
for result in results:
family = result[0]
address = result[4]
ip_address = address[0]
if family == socket.AF_INET6:
flow_info = address[2]
control_id = address[3]
else:
flow_info = None
control_id = None
yield AddressInfo(ip_address, family, flow_info, control_id) | [
"def",
"_convert_addrinfo",
"(",
"cls",
",",
"results",
":",
"List",
"[",
"tuple",
"]",
")",
"->",
"Iterable",
"[",
"AddressInfo",
"]",
":",
"for",
"result",
"in",
"results",
":",
"family",
"=",
"result",
"[",
"0",
"]",
"address",
"=",
"result",
"[",
... | Convert the result list to address info. | [
"Convert",
"the",
"result",
"list",
"to",
"address",
"info",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L326-L340 | train | 201,393 |
ArchiveTeam/wpull | wpull/network/dns.py | Resolver._get_ipv6_info | def _get_ipv6_info(cls, ip_address: str) -> tuple:
'''Extract the flow info and control id.'''
results = socket.getaddrinfo(
ip_address, 0, proto=socket.IPPROTO_TCP,
flags=socket.AI_NUMERICHOST)
flow_info = results[0][4][2]
control_id = results[0][4][3]
return flow_info, control_id | python | def _get_ipv6_info(cls, ip_address: str) -> tuple:
'''Extract the flow info and control id.'''
results = socket.getaddrinfo(
ip_address, 0, proto=socket.IPPROTO_TCP,
flags=socket.AI_NUMERICHOST)
flow_info = results[0][4][2]
control_id = results[0][4][3]
return flow_info, control_id | [
"def",
"_get_ipv6_info",
"(",
"cls",
",",
"ip_address",
":",
"str",
")",
"->",
"tuple",
":",
"results",
"=",
"socket",
".",
"getaddrinfo",
"(",
"ip_address",
",",
"0",
",",
"proto",
"=",
"socket",
".",
"IPPROTO_TCP",
",",
"flags",
"=",
"socket",
".",
"... | Extract the flow info and control id. | [
"Extract",
"the",
"flow",
"info",
"and",
"control",
"id",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/dns.py#L343-L352 | train | 201,394 |
ArchiveTeam/wpull | wpull/protocol/ftp/command.py | Commander.raise_if_not_match | def raise_if_not_match(cls, action: str,
expected_code: Union[int, Sequence[int]],
reply: Reply):
'''Raise FTPServerError if not expected reply code.
Args:
action: Label to use in the exception message.
expected_code: Expected 3 digit code.
reply: Reply from the server.
'''
if isinstance(expected_code, int):
expected_codes = (expected_code,)
else:
expected_codes = expected_code
if reply.code not in expected_codes:
raise FTPServerError(
'Failed action {action}: {reply_code} {reply_text}'
.format(action=action, reply_code=reply.code,
reply_text=ascii(reply.text)
),
reply.code
) | python | def raise_if_not_match(cls, action: str,
expected_code: Union[int, Sequence[int]],
reply: Reply):
'''Raise FTPServerError if not expected reply code.
Args:
action: Label to use in the exception message.
expected_code: Expected 3 digit code.
reply: Reply from the server.
'''
if isinstance(expected_code, int):
expected_codes = (expected_code,)
else:
expected_codes = expected_code
if reply.code not in expected_codes:
raise FTPServerError(
'Failed action {action}: {reply_code} {reply_text}'
.format(action=action, reply_code=reply.code,
reply_text=ascii(reply.text)
),
reply.code
) | [
"def",
"raise_if_not_match",
"(",
"cls",
",",
"action",
":",
"str",
",",
"expected_code",
":",
"Union",
"[",
"int",
",",
"Sequence",
"[",
"int",
"]",
"]",
",",
"reply",
":",
"Reply",
")",
":",
"if",
"isinstance",
"(",
"expected_code",
",",
"int",
")",
... | Raise FTPServerError if not expected reply code.
Args:
action: Label to use in the exception message.
expected_code: Expected 3 digit code.
reply: Reply from the server. | [
"Raise",
"FTPServerError",
"if",
"not",
"expected",
"reply",
"code",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/command.py#L32-L54 | train | 201,395 |
ArchiveTeam/wpull | wpull/protocol/ftp/command.py | Commander.read_welcome_message | def read_welcome_message(self):
'''Read the welcome message.
Coroutine.
'''
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'Server ready', ReplyCodes.service_ready_for_new_user, reply) | python | def read_welcome_message(self):
'''Read the welcome message.
Coroutine.
'''
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'Server ready', ReplyCodes.service_ready_for_new_user, reply) | [
"def",
"read_welcome_message",
"(",
"self",
")",
":",
"reply",
"=",
"yield",
"from",
"self",
".",
"_control_stream",
".",
"read_reply",
"(",
")",
"self",
".",
"raise_if_not_match",
"(",
"'Server ready'",
",",
"ReplyCodes",
".",
"service_ready_for_new_user",
",",
... | Read the welcome message.
Coroutine. | [
"Read",
"the",
"welcome",
"message",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/command.py#L57-L65 | train | 201,396 |
ArchiveTeam/wpull | wpull/protocol/ftp/command.py | Commander.passive_mode | def passive_mode(self) -> Tuple[str, int]:
'''Enable passive mode.
Returns:
The address (IP address, port) of the passive port.
Coroutine.
'''
yield from self._control_stream.write_command(Command('PASV'))
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'Passive mode', ReplyCodes.entering_passive_mode, reply)
try:
return wpull.protocol.ftp.util.parse_address(reply.text)
except ValueError as error:
raise ProtocolError(str(error)) from error | python | def passive_mode(self) -> Tuple[str, int]:
'''Enable passive mode.
Returns:
The address (IP address, port) of the passive port.
Coroutine.
'''
yield from self._control_stream.write_command(Command('PASV'))
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'Passive mode', ReplyCodes.entering_passive_mode, reply)
try:
return wpull.protocol.ftp.util.parse_address(reply.text)
except ValueError as error:
raise ProtocolError(str(error)) from error | [
"def",
"passive_mode",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"int",
"]",
":",
"yield",
"from",
"self",
".",
"_control_stream",
".",
"write_command",
"(",
"Command",
"(",
"'PASV'",
")",
")",
"reply",
"=",
"yield",
"from",
"self",
".",
"_cont... | Enable passive mode.
Returns:
The address (IP address, port) of the passive port.
Coroutine. | [
"Enable",
"passive",
"mode",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/command.py#L91-L109 | train | 201,397 |
ArchiveTeam/wpull | wpull/protocol/ftp/command.py | Commander.setup_data_stream | def setup_data_stream(
self,
connection_factory: Callable[[tuple], Connection],
data_stream_factory: Callable[[Connection], DataStream]=DataStream) -> \
DataStream:
'''Create and setup a data stream.
This function will set up passive and binary mode and handle
connecting to the data connection.
Args:
connection_factory: A coroutine callback that returns a connection
data_stream_factory: A callback that returns a data stream
Coroutine.
Returns:
DataStream
'''
yield from self._control_stream.write_command(Command('TYPE', 'I'))
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match('Binary mode', ReplyCodes.command_okay, reply)
address = yield from self.passive_mode()
connection = yield from connection_factory(address)
# TODO: unit test for following line for connections that have
# the same port over time but within pool cleaning intervals
connection.reset()
yield from connection.connect()
data_stream = data_stream_factory(connection)
return data_stream | python | def setup_data_stream(
self,
connection_factory: Callable[[tuple], Connection],
data_stream_factory: Callable[[Connection], DataStream]=DataStream) -> \
DataStream:
'''Create and setup a data stream.
This function will set up passive and binary mode and handle
connecting to the data connection.
Args:
connection_factory: A coroutine callback that returns a connection
data_stream_factory: A callback that returns a data stream
Coroutine.
Returns:
DataStream
'''
yield from self._control_stream.write_command(Command('TYPE', 'I'))
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match('Binary mode', ReplyCodes.command_okay, reply)
address = yield from self.passive_mode()
connection = yield from connection_factory(address)
# TODO: unit test for following line for connections that have
# the same port over time but within pool cleaning intervals
connection.reset()
yield from connection.connect()
data_stream = data_stream_factory(connection)
return data_stream | [
"def",
"setup_data_stream",
"(",
"self",
",",
"connection_factory",
":",
"Callable",
"[",
"[",
"tuple",
"]",
",",
"Connection",
"]",
",",
"data_stream_factory",
":",
"Callable",
"[",
"[",
"Connection",
"]",
",",
"DataStream",
"]",
"=",
"DataStream",
")",
"->... | Create and setup a data stream.
This function will set up passive and binary mode and handle
connecting to the data connection.
Args:
connection_factory: A coroutine callback that returns a connection
data_stream_factory: A callback that returns a data stream
Coroutine.
Returns:
DataStream | [
"Create",
"and",
"setup",
"a",
"data",
"stream",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/command.py#L112-L148 | train | 201,398 |
ArchiveTeam/wpull | wpull/protocol/ftp/command.py | Commander.begin_stream | def begin_stream(self, command: Command) -> Reply:
'''Start sending content on the data stream.
Args:
command: A command that tells the server to send data over the
data connection.
Coroutine.
Returns:
The begin reply.
'''
yield from self._control_stream.write_command(command)
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'Begin stream',
(
ReplyCodes.file_status_okay_about_to_open_data_connection,
ReplyCodes.data_connection_already_open_transfer_starting,
),
reply
)
return reply | python | def begin_stream(self, command: Command) -> Reply:
'''Start sending content on the data stream.
Args:
command: A command that tells the server to send data over the
data connection.
Coroutine.
Returns:
The begin reply.
'''
yield from self._control_stream.write_command(command)
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'Begin stream',
(
ReplyCodes.file_status_okay_about_to_open_data_connection,
ReplyCodes.data_connection_already_open_transfer_starting,
),
reply
)
return reply | [
"def",
"begin_stream",
"(",
"self",
",",
"command",
":",
"Command",
")",
"->",
"Reply",
":",
"yield",
"from",
"self",
".",
"_control_stream",
".",
"write_command",
"(",
"command",
")",
"reply",
"=",
"yield",
"from",
"self",
".",
"_control_stream",
".",
"re... | Start sending content on the data stream.
Args:
command: A command that tells the server to send data over the
data connection.
Coroutine.
Returns:
The begin reply. | [
"Start",
"sending",
"content",
"on",
"the",
"data",
"stream",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/command.py#L151-L175 | train | 201,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.