docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Cache a refresh token, ignoring any failure.
Args:
refresh_token (str): Refresh token to cache. | def set(self, refresh_token):
logger.info('Saving refresh_token to %s', repr(self._filename))
try:
with open(self._filename, 'w') as f:
f.write(refresh_token)
except IOError as e:
logger.warning('Failed to save refresh_token: %s', e) | 360,547 |
Create a new channel.
Args:
session (http_utils.Session): Request session.
max_retries (int): Number of retries for long-polling request.
retry_backoff_base (int): The base term for the long-polling
exponential backoff. | def __init__(self, session, max_retries, retry_backoff_base):
# Event fired when channel connects with arguments ():
self.on_connect = event.Event('Channel.on_connect')
# Event fired when channel reconnects with arguments ():
self.on_reconnect = event.Event('Channel.on_reconnec... | 360,552 |
Construct :class:`ChatMessageSegment` list parsed from a string.
Args:
text (str): Text to parse. May contain line breaks, URLs and
formatting markup (simplified Markdown and HTML) to be
converted into equivalent segments.
Returns:
List of :class... | def from_str(text):
segment_list = chat_message_parser.parse(text)
return [ChatMessageSegment(segment.text, **segment.params)
for segment in segment_list] | 360,560 |
Construct :class:`ChatMessageSegment` from ``Segment`` message.
Args:
segment: ``Segment`` message to parse.
Returns:
:class:`ChatMessageSegment` object. | def deserialize(segment):
link_target = segment.link_data.link_target
return ChatMessageSegment(
segment.text, segment_type=segment.type,
is_bold=segment.formatting.bold,
is_italic=segment.formatting.italic,
is_strikethrough=segment.formatting.str... | 360,561 |
Return whether the a path is a subpath of another.
Args:
base_path: The base path
test_path: The path which we are testing
trailing_slash: If True, the trailing slash is treated with importance.
For example, ``/images/`` is a directory while ``/images`` is a
file.
... | def is_subdir(base_path, test_path, trailing_slash=False, wildcards=False):
if trailing_slash:
base_path = base_path.rsplit('/', 1)[0] + '/'
test_path = test_path.rsplit('/', 1)[0] + '/'
else:
if not base_path.endswith('/'):
base_path += '/'
if not test_path.end... | 360,621 |
Flatten an absolute URL path by removing the dot segments.
:func:`urllib.parse.urljoin` has some support for removing dot segments,
but it is conservative and only removes them as needed.
Arguments:
path (str): The URL path.
flatten_slashes (bool): If True, consecutive slashes are removed.... | def flatten_path(path, flatten_slashes=False):
# Based on posixpath.normpath
# Fast path
if not path or path == '/':
return '/'
# Take off leading slash
if path[0] == '/':
path = path[1:]
parts = path.split('/')
new_parts = collections.deque()
for part in parts:
... | 360,626 |
Start a file or directory listing download.
Args:
request: Request.
Returns:
A Response populated with the initial data connection reply.
Once the response is received, call :meth:`download`.
Coroutine. | def start(self, request: Request) -> Response:
if self._session_state != SessionState.ready:
raise RuntimeError('Session not ready')
response = Response()
yield from self._prepare_fetch(request, response)
response.file_transfer_size = yield from self._fetch_size(r... | 360,651 |
Fetch a file listing.
Args:
request: Request.
Returns:
A listing response populated with the initial data connection
reply.
Once the response is received, call :meth:`download_listing`.
Coroutine. | def start_listing(self, request: Request) -> ListingResponse:
if self._session_state != SessionState.ready:
raise RuntimeError('Session not ready')
response = ListingResponse()
yield from self._prepare_fetch(request, response)
yield from self._open_data_stream()
... | 360,652 |
Read the response content into file.
Args:
file: A file object or asyncio stream.
rewind: Seek the given file back to its original offset after
reading is finished.
duration_timeout: Maximum time in seconds of which the
entire file must be rea... | def download(self, file: Optional[IO]=None, rewind: bool=True,
duration_timeout: Optional[float]=None) -> Response:
if self._session_state != SessionState.file_request_sent:
raise RuntimeError('File request not sent')
if rewind and file and hasattr(file, 'seek'):
... | 360,655 |
Read file listings.
Args:
file: A file object or asyncio stream.
duration_timeout: Maximum time in seconds of which the
entire file must be read.
Returns:
A Response populated the file listings
Be sure to call :meth:`start_file_listing` firs... | def download_listing(self, file: Optional[IO],
duration_timeout: Optional[float]=None) -> \
ListingResponse:
if self._session_state != SessionState.directory_request_sent:
raise RuntimeError('File request not sent')
self._session_state = Session... | 360,656 |
Return the reply code as a tuple.
Args:
code: The reply code.
Returns:
Each item in the tuple is the digit. | def reply_code_tuple(code: int) -> Tuple[int, int, int]:
return code // 100, code // 10 % 10, code % 10 | 360,713 |
Parse machine listing.
Args:
text: The listing.
convert: Convert sizes and dates.
strict: Method of handling errors. ``True`` will raise
``ValueError``. ``False`` will ignore rows with errors.
Returns:
list: A list of dict of the facts defined in RFC 3659.
T... | def parse_machine_listing(text: str, convert: bool=True, strict: bool=True) -> \
List[dict]:
# TODO: this function should be moved into the 'ls' package
listing = []
for line in text.splitlines(False):
facts = line.split(';')
row = {}
filename = None
for fact i... | 360,714 |
Iterate CDX file.
Args:
file (str): A file object.
encoding (str): The encoding of the file.
Returns:
iterator: Each item is a dict that maps from field key to value. | def read_cdx(file, encoding='utf8'):
with codecs.getreader(encoding)(file) as stream:
header_line = stream.readline()
separator = header_line[0]
field_keys = header_line.strip().split(separator)
if field_keys.pop(0) != 'CDX':
raise ValueError('CDX header not found.'... | 360,745 |
Clean closed connections.
Args:
force: Clean connected and idle connections too.
Coroutine. | def clean(self, force: bool=False):
with (yield from self._lock):
for connection in tuple(self.ready):
if force or connection.closed():
connection.close()
self.ready.remove(connection) | 360,757 |
Unregister a connection.
Args:
connection: Connection instance returned from :meth:`acquire`.
reuse: If True, the connection is made available for reuse.
Coroutine. | def release(self, connection: Connection, reuse: bool=True):
yield from self._condition.acquire()
self.busy.remove(connection)
if reuse:
self.ready.add(connection)
self._condition.notify()
self._condition.release() | 360,760 |
Return an available connection.
Args:
host: A hostname or IP address.
port: Port number.
use_ssl: Whether to return a SSL connection.
host_key: If provided, it overrides the key used for per-host
connection pooling. This is useful for proxies for ... | def acquire(self, host: str, port: int, use_ssl: bool=False,
host_key: Optional[Any]=None) \
-> Union[Connection, SSLConnection]:
assert isinstance(port, int), 'Expect int. Got {}'.format(type(port))
assert not self._closed
yield from self._process_no_wait_r... | 360,762 |
Clean all closed connections.
Args:
force: Clean connected and idle connections too.
Coroutine. | def clean(self, force: bool=False):
assert not self._closed
with (yield from self._host_pools_lock):
for key, pool in tuple(self._host_pools.items()):
yield from pool.clean(force=force)
if not self._host_pool_waiters[key] and pool.empty():
... | 360,766 |
Increment the number of files downloaded.
Args:
size: The size of the file | def increment(self, size: int):
assert size >= 0, size
self.files += 1
self.size += size
self.bandwidth_meter.feed(size) | 360,816 |
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. | 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.fields:
self.fields['Host'] = url_info.hostname_with_port
if not full_url:
if url_info.que... | 360,841 |
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:`W... | def download(self, file: Optional[IO[bytes]]=None,
duration_timeout: Optional[float]=None):
yield from \
self._current_session.download(file, duration_timeout=duration_timeout) | 360,856 |
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. | def start(self, request: Request) -> Response:
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 = ... | 360,914 |
Read the response content into file.
Args:
file: A file object or asyncio stream.
raw: Whether chunked transfer encoding should be included.
rewind: Seek the given file back to its original offset after
reading is finished.
duration_timeout: Maxim... | def download(
self,
file: Union[IO[bytes], asyncio.StreamWriter, None]=None,
raw: bool=False, rewind: bool=True,
duration_timeout: Optional[float]=None):
if self._session_state != SessionState.request_sent:
raise RuntimeError('Request not sent... | 360,915 |
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
... | def url_to_filename(url, index='index.html', alt_char=False):
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... | 361,001 |
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 | 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 range(len(parts)):
test_path = os.sep.join(parts[:index + 1])
if os.path.isfile(test_path):
parts[index] += suffix
return os.sep... | 361,004 |
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` | def convert_http_request(request, referrer_host=None):
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 | 361,060 |
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. | 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)
request.fields.clear()
for name, value in new_request.header_items():
request.fields.add(name, value... | 361,063 |
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. | def extract_cookies(self, response, request, referrer_host=None):
new_response = HTTPResponseInfoWrapper(response)
new_request = convert_http_request(request, referrer_host)
self._cookie_jar.extract_cookies(new_response, new_request) | 361,064 |
Start the executable.
Args:
use_atexit (bool): If True, the process will automatically be
terminated at exit. | def start(self, use_atexit=True):
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,
*sel... | 361,067 |
Read from connection to file.
Args:
file: A file object or a writer stream. | def read_file(self, file: Union[IO, asyncio.StreamWriter]=None):
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(da... | 361,076 |
Write a command to the stream.
Args:
command: The command.
Coroutine. | def write_command(self, command: Command):
_logger.debug('Write command.')
data = command.to_bytes()
yield from self._connection.write(data)
self._data_event_dispatcher.notify_write(data) | 361,078 |
Return whether the request can fetched.
Args:
request: Request.
file: A file object to where the robots.txt contents are written.
Coroutine. | def can_fetch(self, request: Request, file=None) -> bool:
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) | 361,083 |
Resolve hostname.
Args:
host: Hostname.
Returns:
Resolved IP addresses.
Raises:
DNSNotFound if the hostname could not be resolved or
NetworkError if there was an error connecting to DNS servers.
Coroutine. | def resolve(self, host: str) -> ResolveResult:
_logger.debug(__('Lookup address {0}.', host))
try:
host = self.hook_dispatcher.call(PluginFunctions.resolve_dns, host
) or host
except HookDisconnected:
pass
c... | 361,092 |
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. | def raise_if_not_match(cls, action: str,
expected_code: Union[int, Sequence[int]],
reply: Reply):
if isinstance(expected_code, int):
expected_codes = (expected_code,)
else:
expected_codes = expected_code
if r... | 361,098 |
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
C... | def setup_data_stream(
self,
connection_factory: Callable[[tuple], Connection],
data_stream_factory: Callable[[Connection], DataStream]=DataStream) -> \
DataStream:
yield from self._control_stream.write_command(Command('TYPE', 'I'))
reply = yield ... | 361,102 |
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. | def begin_stream(self, command: Command) -> 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_da... | 361,103 |
Read from the data stream.
Args:
file: A destination file object or a stream writer.
data_stream: The stream of which to read from.
Coroutine.
Returns:
Reply: The final reply. | def read_stream(self, file: IO, data_stream: DataStream) -> Reply:
yield from data_stream.read_file(file=file)
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
'End stream',
ReplyCodes.closing_data_connection,
reply
... | 361,104 |
Return an iterator of elements found in the document.
Args:
file: A file object containing the document.
encoding (str): The encoding of the document.
target_class: A class to be used for target parsing.
parser_type (str): The type of parser to use. Accepted valu... | def parse_lxml(self, file, encoding=None, target_class=HTMLParserTarget,
parser_type='html'):
if encoding:
lxml_encoding = to_lxml_encoding(encoding) or 'latin1'
else:
lxml_encoding = encoding
elements = []
callback_func = elements.ap... | 361,121 |
Given the hints, return whether the document is supported.
Args:
file: A file object containing the document.
request (:class:`.http.request.Request`): An HTTP request.
response (:class:`.http.request.Response`): An HTTP response.
url_info (:class:`.url.URLInfo`)... | def is_supported(cls, file=None, request=None, response=None,
url_info=None):
tests = (
(response, cls.is_response),
(file, cls.is_file),
(request, cls.is_request),
(url_info, cls.is_url)
)
for instance, method in tes... | 361,179 |
Uncompress gzip data.
Args:
data (bytes): The gzip data.
truncated (bool): If True, the decompressor is not flushed.
This is a convenience function.
Returns:
bytes: The inflated data.
Raises:
zlib.error | def gzip_uncompress(data, truncated=False):
decompressor = SimpleGzipDecompressor()
inflated_data = decompressor.decompress(data)
if not truncated:
inflated_data += decompressor.flush()
return inflated_data | 361,197 |
Mark the item with the given status.
Args:
status: a value from :class:`Status`.
increment_try_count: if True, increment the ``try_count``
value | def set_status(self, status: Status, increment_try_count: bool=True,
filename: str=None):
url = self.url_record.url
assert not self._try_count_incremented, (url, status)
if increment_try_count:
self._try_count_incremented = True
_logger.debug(__(... | 361,205 |
Return the document encoding from a HTTP header.
Args:
response (Response): An instance of :class:`.http.Response`.
Returns:
``str``, ``None``: The codec name. | def get_heading_encoding(response):
encoding = wpull.protocol.http.util.parse_charset(
response.fields.get('content-type', ''))
if encoding:
return wpull.string.normalize_codec_name(encoding)
else:
return None | 361,212 |
Return the likely encoding of the response document.
Args:
response (Response): An instance of :class:`.http.Response`.
is_html (bool): See :func:`.util.detect_encoding`.
peek (int): The maximum number of bytes of the document to be analyzed.
Returns:
``str``, ``None``: The cod... | def detect_response_encoding(response, is_html=False, peek=131072):
encoding = get_heading_encoding(response)
encoding = wpull.string.detect_encoding(
wpull.util.peek_file(response.body, peek), encoding=encoding, is_html=is_html
)
_logger.debug(__('Got encoding: {0}', encoding))
retu... | 361,213 |
Add a single URL to the table.
Args:
url: The URL to be added
url_properties: Additional values to be saved
url_data: Additional data to be saved | def add_one(self, url: str,
url_properties: Optional[URLProperties]=None,
url_data: Optional[URLData]=None):
self.add_many([AddURLInfo(url, url_properties, url_data)]) | 361,217 |
Update record for processed URL.
Args:
url: The URL.
new_status: Update the item status to `new_status`.
increment_try_count: Whether to increment the try counter
for the URL.
url_result: Additional values. | def check_in(self, url: str, new_status: Status,
increment_try_count: bool=True,
url_result: Optional[URLResult]=None):
| 361,218 |
Create an instance.
Args:
name (str): The name of the class
args: The arguments to pass to the class.
kwargs: The keyword arguments to pass to the class.
Returns:
instance | def new(self, name, *args, **kwargs):
if name in self._instance_map:
raise ValueError('Instance {0} is already initialized'
.format(name))
instance = self._class_map[name](*args, **kwargs)
self._instance_map[name] = instance
return insta... | 361,227 |
Normalize the key name to title case.
For example, ``normalize_name('content-id')`` will become ``Content-Id``
Args:
name (str): The name to normalize.
overrides (set, sequence): A set or sequence containing keys that
should be cased to themselves. For example, passing
... | def normalize_name(name, overrides=None):
normalized_name = name.title()
if overrides:
override_map = dict([(name.title(), name) for name in overrides])
return override_map.get(normalized_name, normalized_name)
else:
return normalized_name | 361,229 |
Parse the string or bytes.
Args:
strict (bool): If True, errors will not be ignored
Raises:
:class:`ValueError` if the record is malformed. | def parse(self, string, strict=True):
if isinstance(string, bytes):
errors = 'strict' if strict else 'replace'
string = string.decode(self.encoding, errors=errors)
if not self.raw:
self.raw = string
else:
self.raw += string
lines... | 361,233 |
Open a file object on to the Response Body.
Args:
filename: The path where the file is to be saved
response: Response
mode: The file mode
This function will create the directories if not exist. | def open_file(cls, filename: str, response: BaseResponse, mode='wb+'):
_logger.debug('Saving file to {0}, mode={1}.',
filename, mode)
dir_path = os.path.dirname(filename)
if dir_path and not os.path.exists(dir_path):
os.makedirs(dir_path)
resp... | 361,272 |
Set the Last-Modified timestamp onto the given file.
Args:
filename: The path of the file
response: Response | def set_timestamp(cls, filename: str, response: HTTPResponse):
last_modified = response.fields.get('Last-Modified')
if not last_modified:
return
try:
last_modified = email.utils.parsedate(last_modified)
except ValueError:
_logger.exception('... | 361,273 |
Prepend the HTTP response header to the file.
Args:
filename: The path of the file
response: Response | def save_headers(cls, filename: str, response: HTTPResponse):
new_filename = filename + '-new'
with open('wb') as new_file:
new_file.write(response.header())
with wpull.util.reset_file_offset(response.body):
response.body.seek(0)
shutil.... | 361,274 |
Return whether the connection should be closed.
Args:
http_version (str): The HTTP version string like ``HTTP/1.0``.
connection_field (str): The value for the ``Connection`` header. | def should_close(http_version, connection_field):
connection_field = (connection_field or '').lower()
if http_version == 'HTTP/1.0':
return connection_field.replace('-', '') != 'keepalive'
else:
return connection_field == 'close' | 361,298 |
Return the file text and processed absolute links.
Args:
file: A file object containing the document.
encoding (str): The encoding of the document.
base_url (str): The URL at which the document is located.
Returns:
iterator: Each item is a tuple:
... | def iter_processed_text(self, file, encoding=None, base_url=None):
for text, is_link in self.iter_text(file, encoding):
if is_link and base_url:
new_link = urljoin_safe(base_url, text, allow_fragments=False)
if new_link:
yield (new_link, ... | 361,354 |
Update the bandwidth meter.
Args:
data_len (int): The number of bytes transfered since the last
call to :func:`feed`.
feed_time (float): Current time. | def feed(self, data_len, feed_time=None):
self._bytes_transferred += data_len
self._collected_bytes_transferred += data_len
time_now = feed_time or time.time()
time_diff = time_now - self._last_feed_time
if time_diff < self._sample_min_time:
return
... | 361,361 |
Load the response and increment the counter.
Args:
response (:class:`.http.request.Response`): The response from
a previous request. | def load(self, response):
self._response = response
if self.next_location(raw=True):
self._num_redirects += 1 | 361,372 |
Returns the next location.
Args:
raw (bool): If True, the original string contained in the Location
field will be returned. Otherwise, the URL will be
normalized to a complete URL.
Returns:
str, None: If str, the location. Otherwise, no next loca... | def next_location(self, raw=False):
if self._response:
location = self._response.fields.get('location')
if not location or raw:
return location
return wpull.url.urljoin(self._response.request.url_info.url,
locati... | 361,373 |
Return an iterator of links found in the document.
Args:
file: A file object containing the document.
encoding (str): The encoding of the document.
Returns:
iterable: str | def read_links(self, file, encoding=None):
return [item[0] for item in self.iter_text(file, encoding) if item[1]] | 361,450 |
Set the exit code based on the error type.
Args:
error (:class:`Exception`): An exception instance. | def _update_exit_code_from_error(self, error):
for error_type, exit_code in self.ERROR_CODE_MAP.items():
if isinstance(error, error_type):
self.update_exit_code(exit_code)
break
else:
self.update_exit_code(ExitStatus.generic_error) | 361,457 |
Set the exit code if it is serious than before.
Args:
code: The exit code. | def update_exit_code(self, code: int):
if code:
if self._exit_code:
self._exit_code = min(self._exit_code, code)
else:
self._exit_code = code | 361,458 |
Consult by fetching robots.txt as needed.
Args:
request: The request to be made
to get the file.
Returns:
True if can fetch
Coroutine | def consult_robots_txt(self, request: HTTPRequest) -> bool:
if not self._robots_txt_checker:
return True
result = yield from self._robots_txt_checker.can_fetch(request)
return result | 361,461 |
Consult the URL filter.
Args:
url_record: The URL record.
is_redirect: Whether the request is a redirect and it is
desired that it spans hosts.
Returns
tuple:
1. bool: The verdict
2. str: A short reason string: nofilters, fil... | def consult_filters(self, url_info: URLInfo, url_record: URLRecord, is_redirect: bool=False) \
-> Tuple[bool, str, dict]:
if not self._url_filter:
return True, 'nofilters', None
test_info = self._url_filter.test_info(url_info, url_record)
verdict = test_info['v... | 361,462 |
Return the wait time between requests.
Args:
seconds: The original time in seconds.
item_session:
error:
Returns:
The time in seconds. | def plugin_wait_time(seconds: float, item_session: ItemSession, error: Optional[Exception]=None) -> float:
return seconds | 361,476 |
Upload local images to Mapillary
Args:
import_path: Directory path to where the images are stored.
verbose: Print extra warnings and errors.
skip_subfolders: Skip images stored in subdirectories.
Returns:
Images are uploaded to Mapillary and flagged locally as uploaded. | def upload(import_path, verbose=False, skip_subfolders=False, number_threads=None, max_attempts=None, video_import_path=None, dry_run=False,api_version=1.0):
# sanity check if video file is passed
if video_import_path and (not os.path.isdir(video_import_path) and not os.path.isfile(video_import_path)):
... | 361,634 |
The memcached "append" command.
Args:
key: str, see class docs for details.
value: str, see class docs for details.
expire: optional int, number of seconds until the item is expired
from the cache, or zero for no expiry (the default).
noreply: optional ... | def append(self, key, value, expire=0, noreply=None):
if noreply is None:
noreply = self.default_noreply
return self._store_cmd(b'append', {key: value}, expire, noreply)[key] | 361,900 |
The memcached "prepend" command.
Args:
key: str, see class docs for details.
value: str, see class docs for details.
expire: optional int, number of seconds until the item is expired
from the cache, or zero for no expiry (the default).
noreply: optional... | def prepend(self, key, value, expire=0, noreply=None):
if noreply is None:
noreply = self.default_noreply
return self._store_cmd(b'prepend', {key: value}, expire, noreply)[key] | 361,901 |
The memcached "get" command, but only for one key, as a convenience.
Args:
key: str, see class docs for details.
default: value that will be returned if the key was not found.
Returns:
The value for the key, or default if the key wasn't found. | def get(self, key, default=None):
return self._fetch_cmd(b'get', [key], False).get(key, default) | 361,903 |
The memcached "gets" command for one key, as a convenience.
Args:
key: str, see class docs for details.
default: value that will be returned if the key was not found.
cas_default: same behaviour as default argument.
Returns:
A tuple of (value, cas)
or ... | def gets(self, key, default=None, cas_default=None):
defaults = (default, cas_default)
return self._fetch_cmd(b'gets', [key], True).get(key, defaults) | 361,904 |
The memcached "delete" command.
Args:
key: str, see class docs for details.
noreply: optional bool, True to not wait for the reply (defaults to
self.default_noreply).
Returns:
If noreply is True, always returns True. Otherwise returns True if
... | def delete(self, key, noreply=None):
if noreply is None:
noreply = self.default_noreply
cmd = b'delete ' + self.check_key(key)
if noreply:
cmd += b' noreply'
cmd += b'\r\n'
results = self._misc_cmd([cmd], b'delete', noreply)
if noreply:
... | 361,905 |
The memcached "incr" command.
Args:
key: str, see class docs for details.
value: int, the amount by which to increment the value.
noreply: optional bool, False to wait for the reply (the default).
Returns:
If noreply is True, always returns None. Otherwise retur... | def incr(self, key, value, noreply=False):
key = self.check_key(key)
cmd = b'incr ' + key + b' ' + six.text_type(value).encode('ascii')
if noreply:
cmd += b' noreply'
cmd += b'\r\n'
results = self._misc_cmd([cmd], b'incr', noreply)
if noreply:
... | 361,907 |
The memcached "decr" command.
Args:
key: str, see class docs for details.
value: int, the amount by which to increment the value.
noreply: optional bool, False to wait for the reply (the default).
Returns:
If noreply is True, always returns None. Otherwise retur... | def decr(self, key, value, noreply=False):
key = self.check_key(key)
cmd = b'decr ' + key + b' ' + six.text_type(value).encode('ascii')
if noreply:
cmd += b' noreply'
cmd += b'\r\n'
results = self._misc_cmd([cmd], b'decr', noreply)
if noreply:
... | 361,908 |
The memcached "touch" command.
Args:
key: str, see class docs for details.
expire: optional int, number of seconds until the item is expired
from the cache, or zero for no expiry (the default).
noreply: optional bool, True to not wait for the reply (defaults to
... | def touch(self, key, expire=0, noreply=None):
if noreply is None:
noreply = self.default_noreply
key = self.check_key(key)
cmd = b'touch ' + key + b' ' + six.text_type(expire).encode('ascii')
if noreply:
cmd += b' noreply'
cmd += b'\r\n'
r... | 361,909 |
The memcached "stats" command.
The returned keys depend on what the "stats" command returns.
A best effort is made to convert values to appropriate Python
types, defaulting to strings when a conversion cannot be made.
Args:
*arg: extra string arguments to the "stats" command.... | def stats(self, *args):
result = self._fetch_cmd(b'stats', args, False)
for key, value in six.iteritems(result):
converter = STAT_TYPES.get(key, int)
try:
result[key] = converter(value)
except Exception:
pass
return r... | 361,910 |
The memcached "cache_memlimit" command.
Args:
memlimit: int, the number of megabytes to set as the new cache memory
limit.
Returns:
If no exception is raised, always returns True. | def cache_memlimit(self, memlimit):
self._fetch_cmd(b'cache_memlimit', [str(int(memlimit))], False)
return True | 361,911 |
The memcached "flush_all" command.
Args:
delay: optional int, the number of seconds to wait before flushing,
or zero to flush immediately (the default).
noreply: optional bool, True to not wait for the reply (defaults to
self.default_noreply).
Re... | def flush_all(self, delay=0, noreply=None):
if noreply is None:
noreply = self.default_noreply
cmd = b'flush_all ' + six.text_type(delay).encode('ascii')
if noreply:
cmd += b' noreply'
cmd += b'\r\n'
results = self._misc_cmd([cmd], b'flush_all', n... | 361,913 |
Makes the parameter table for the paper, saving it to a tex file in the tables folder.
Also makes two partial parameter tables for the slides.
Parameters
----------
filename : str
Name of the file in which to save output (in the tables directory).
Suffix .tex is automatically added.
... | def makeParameterTable(filename, params):
# Calibrated macroeconomic parameters
macro_panel = "\multicolumn{3}{c}{\\textbf{Macroeconomic Parameters} } \n"
macro_panel += "\\\\ $\\kapShare$ & " + "{:.2f}".format(params.CapShare) + " & Capital's Share of Income \n"
macro_panel += "\\\\ $\\daleth$ ... | 362,109 |
Deploy all required raiden contracts and return a dict of contract_name:address
Args:
max_num_of_token_networks (Optional[int]): The max number of tokens that can be
registered to the TokenNetworkRegistry. If None, the argument is omitted from
the call to the constructor of ... | def deploy_raiden_contracts(
self,
max_num_of_token_networks: Optional[int],
) -> DeployedContracts:
deployed_contracts: DeployedContracts = {
'contracts_version': self.contract_version_string(),
'chain_id': int(self.web3.version.network),
... | 363,726 |
Use join-contracts.py to concatenate all imported Solidity files.
Args:
source_module: a module name to look up contracts_source_path()
contract_name: 'TokenNetworkRegistry', 'SecretRegistry' etc. | def join_sources(source_module: DeploymentModule, contract_name: str):
joined_file = Path(__file__).parent.joinpath('joined.sol')
remapping = {module: str(path) for module, path in contracts_source_path().items()}
command = [
'./utils/join-contracts.py',
'--import-map',
json.dum... | 363,760 |
Calls Etherscan API for verifying the Solidity source of a contract.
Args:
chain_id: EIP-155 chain id of the Ethereum chain
apikey: key for calling Etherscan API
source_module: a module name to look up contracts_source_path()
contract_name: 'TokenNetworkRegistry', 'SecretRegistry' e... | def etherscan_verify_contract(
chain_id: int,
apikey: str,
source_module: DeploymentModule,
contract_name: str,
):
etherscan_api = api_of_chain_id[chain_id]
deployment_info = get_contracts_deployment_info(
chain_id=chain_id,
module=source_module,
)
if... | 363,763 |
Sets the Elasticsearch hosts to use
Args:
hosts (str): A single hostname or URL, or list of hostnames or URLs
use_ssl (bool): Use a HTTPS connection to the server
ssl_cert_path (str): Path to the certificate chain | def set_hosts(hosts, use_ssl=False, ssl_cert_path=None):
if type(hosts) != list:
hosts = [hosts]
conn_params = {
"hosts": hosts,
"timeout": 20
}
if use_ssl:
conn_params['use_ssl'] = True
if ssl_cert_path:
conn_params['verify_certs'] = True
... | 363,975 |
Create Elasticsearch indexes
Args:
names (list): A list of index names
settings (dict): Index settings | def create_indexes(names, settings=None):
for name in names:
index = Index(name)
try:
if not index.exists():
logger.debug("Creating Elasticsearch index: {0}".format(name))
if settings is None:
index.settings(number_of_shards=1,
... | 363,976 |
Updates index mappings
Args:
aggregate_indexes (list): A list of aggregate index names
forensic_indexes (list): A list of forensic index names | def migrate_indexes(aggregate_indexes=None, forensic_indexes=None):
version = 2
if aggregate_indexes is None:
aggregate_indexes = []
if forensic_indexes is None:
forensic_indexes = []
for aggregate_index_name in aggregate_indexes:
if not Index(aggregate_index_name).exists():... | 363,977 |
Saves a parsed DMARC aggregate report to ElasticSearch
Args:
aggregate_report (OrderedDict): A parsed forensic report
index_suffix (str): The suffix of the name of the index to save to
monthly_indexes (bool): Use monthly indexes instead of daily indexes
Raises:
AlreadySaved | def save_aggregate_report_to_elasticsearch(aggregate_report,
index_suffix=None,
monthly_indexes=False):
logger.debug("Saving aggregate report to Elasticsearch")
aggregate_report = aggregate_report.copy()
metadata = ag... | 363,978 |
Saves a parsed DMARC forensic report to ElasticSearch
Args:
forensic_report (OrderedDict): A parsed forensic report
index_suffix (str): The suffix of the name of the index to save to
monthly_indexes (bool): Use monthly indexes instead of daily
... | def save_forensic_report_to_elasticsearch(forensic_report,
index_suffix=None,
monthly_indexes=False):
logger.debug("Saving forensic report to Elasticsearch")
forensic_report = forensic_report.copy()
sample_date = None
... | 363,979 |
Saves aggregate DMARC reports to Kafka
Args:
aggregate_reports (list): A list of aggregate report dictionaries
to save to Kafka
aggregate_topic (str): The name of the Kafka topic | def save_aggregate_reports_to_kafka(self, aggregate_reports,
aggregate_topic):
if (type(aggregate_reports) == dict or
type(aggregate_reports) == OrderedDict):
aggregate_reports = [aggregate_reports]
if len(aggregate_reports) < 1:
... | 363,992 |
Saves forensic DMARC reports to Kafka, sends individual
records (slices) since Kafka requires messages to be <= 1MB
by default.
Args:
forensic_reports (list): A list of forensic report dicts
to save to Kafka
forensic_topic (str): The name of the Kafka topic | def save_forensic_reports_to_kafka(self, forensic_reports, forensic_topic):
if type(forensic_reports) == dict:
forensic_reports = [forensic_reports]
if len(forensic_reports) < 1:
return
try:
logger.debug("Saving forensic reports to Kafka")
... | 363,993 |
Converts a record from a DMARC aggregate report into a more consistent
format
Args:
record (OrderedDict): The record to convert
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
dns_timeout (float): Sets the DNS timeout i... | def _parse_report_record(record, nameservers=None, dns_timeout=2.0,
parallel=False):
if nameservers is None:
nameservers = ["1.1.1.1", "1.0.0.1",
"2606:4700:4700::1111", "2606:4700:4700::1001",
]
record = record.copy()
new_r... | 363,994 |
Parses a DMARC XML report string and returns a consistent OrderedDict
Args:
xml (str): A string of DMARC aggregate report XML
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
timeout (float): Sets the DNS timeout in seconds
... | def parse_aggregate_report_xml(xml, nameservers=None, timeout=2.0,
parallel=False):
errors = []
try:
xmltodict.parse(xml)["feedback"]
except Exception as e:
errors.append(e.__str__())
try:
# Replace XML header (sometimes they are invalid)
... | 363,995 |
Extracts xml from a zip or gzip file at the given path, file-like object,
or bytes.
Args:
input_: A path to a file, a file like object, or bytes
Returns:
str: The extracted XML | def extract_xml(input_):
if type(input_) == str:
file_object = open(input_, "rb")
elif type(input_) == bytes:
file_object = BytesIO(input_)
else:
file_object = input_
try:
header = file_object.read(6)
file_object.seek(0)
if header.startswith(MAGIC_ZIP... | 363,996 |
Parses a file at the given path, a file-like object. or bytes as a
aggregate DMARC report
Args:
_input: A path to a file, a file like object, or bytes
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
dns_timeout (float):... | def parse_aggregate_report_file(_input, nameservers=None, dns_timeout=2.0,
parallel=False):
xml = extract_xml(_input)
return parse_aggregate_report_xml(xml,
nameservers=nameservers,
timeout=dns_time... | 363,997 |
Converts one or more parsed aggregate reports to flat CSV format, including
headers
Args:
reports: A parsed aggregate report or list of parsed aggregate reports
Returns:
str: Parsed aggregate report data in flat CSV format, including headers | def parsed_aggregate_reports_to_csv(reports):
def to_str(obj):
return str(obj).lower()
fields = ["xml_schema", "org_name", "org_email",
"org_extra_contact_info", "report_id", "begin_date", "end_date",
"errors", "domain", "adkim", "aspf", "p", "sp", "pct", "fo",
... | 363,998 |
Converts one or more parsed forensic reports to flat CSV format, including
headers
Args:
reports: A parsed forensic report or list of parsed forensic reports
Returns:
str: Parsed forensic report data in flat CSV format, including headers | def parsed_forensic_reports_to_csv(reports):
fields = ["feedback_type", "user_agent", "version", "original_envelope_id",
"original_mail_from", "original_rcpt_to", "arrival_date",
"arrival_date_utc", "subject", "message_id",
"authentication_results", "dkim_domain", "sou... | 364,000 |
Returns a list of an IMAP server's capabilities
Args:
server (imapclient.IMAPClient): An instance of imapclient.IMAPClient
Returns (list): A list of capabilities | def get_imap_capabilities(server):
capabilities = list(map(str, list(server.capabilities())))
for i in range(len(capabilities)):
capabilities[i] = str(capabilities[i]).replace("b'",
"").replace("'",
... | 364,003 |
Save report data in the given directory
Args:
results (OrderedDict): Parsing results
output_directory: The patch to the directory to save in | def save_output(results, output_directory="output"):
aggregate_reports = results["aggregate_reports"]
forensic_reports = results["forensic_reports"]
if os.path.exists(output_directory):
if not os.path.isdir(output_directory):
raise ValueError("{0} is not a directory".format(output... | 364,005 |
Creates a zip file of parsed report output
Args:
results (OrderedDict): The parsed results
Returns:
bytes: zip file bytes | def get_report_zip(results):
def add_subdir(root_path, subdir):
subdir_path = os.path.join(root_path, subdir)
for subdir_root, subdir_dirs, subdir_files in os.walk(subdir_path):
for subdir_file in subdir_files:
subdir_file_path = os.path.join(root_path, subdir, subdi... | 364,006 |
Initializes the HECClient
Args:
url (str): The URL of the HEC
access_token (str): The HEC access token
index (str): The name of the index
source (str): The source name
verify (bool): Verify SSL certificates
timeout (float): Number of second... | def __init__(self, url, access_token, index,
source="parsedmarc", verify=True, timeout=60):
url = urlparse(url)
self.url = "{0}://{1}/services/collector/event/1.0".format(url.scheme,
url.netloc)
self.acc... | 364,009 |
Saves aggregate DMARC reports to Splunk
Args:
aggregate_reports: A list of aggregate report dictionaries
to save in Splunk | def save_aggregate_reports_to_splunk(self, aggregate_reports):
logger.debug("Saving aggregate reports to Splunk")
if type(aggregate_reports) == dict:
aggregate_reports = [aggregate_reports]
if len(aggregate_reports) < 1:
return
data = self._common_data.... | 364,010 |
Saves forensic DMARC reports to Splunk
Args:
forensic_reports (list): A list of forensic report dictionaries
to save in Splunk | def save_forensic_reports_to_splunk(self, forensic_reports):
logger.debug("Saving forensic reports to Splunk")
if type(forensic_reports) == dict:
forensic_reports = [forensic_reports]
if len(forensic_reports) < 1:
return
json_str = ""
for report... | 364,011 |
Decodes a base64 string, with padding being optional
Args:
data: A base64 encoded string
Returns:
bytes: The decoded bytes | def decode_base64(data):
data = bytes(data, encoding="ascii")
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'=' * (4 - missing_padding)
return base64.b64decode(data) | 364,012 |
Gets the base domain name for the given domain
.. note::
Results are based on a list of public domain suffixes at
https://publicsuffix.org/list/public_suffix_list.dat.
Args:
domain (str): A domain or subdomain
use_fresh_psl (bool): Download a fresh Public Suffix List
Retur... | def get_base_domain(domain, use_fresh_psl=False):
psl_path = os.path.join(tempdir, "public_suffix_list.dat")
def download_psl():
url = "https://publicsuffix.org/list/public_suffix_list.dat"
# Use a browser-like user agent string to bypass some proxy blocks
headers = {"User-Agent": ... | 364,013 |
Queries DNS
Args:
domain (str): The domain or subdomain to query about
record_type (str): The record type to query for
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
time... | def query_dns(domain, record_type, cache=None, nameservers=None, timeout=2.0):
domain = str(domain).lower()
record_type = record_type.upper()
cache_key = "{0}_{1}".format(domain, record_type)
if cache:
records = cache.get(cache_key, None)
if records:
return records
... | 364,014 |
Resolves an IP address to a hostname using a reverse DNS query
Args:
ip_address (str): The IP address to resolve
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
timeout (float): S... | def get_reverse_dns(ip_address, cache=None, nameservers=None, timeout=2.0):
hostname = None
try:
address = dns.reversename.from_address(ip_address)
hostname = query_dns(address, "PTR", cache=cache,
nameservers=nameservers,
timeout=ti... | 364,015 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.