Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _header_constructor(
cls, data_to_print, header_separator="-", column_separator=" "
):
"""
Construct header of the table according to template.
:param data_to_print:
The list of data to print into the header of the table.
:type data_to_print: list
:p... |
def header(
self, do_not_print=False
): # pragma: no cover pylint: disable=too-many-branches
"""
Management and creation of templates of header.
Please consider as "header" the title of each columns.
:param do_not_print:
Tell us if we have to print the header or... |
def _data_constructor(self, size):
"""
Construct the table of data according to given size.
:param size: The maximal length of each string in the table.
:type size: list
:return:
A dict with all information about the data and how to which what
maximal si... |
def _size_from_header(cls, header):
"""
Get the size of each columns from the header.
:param header:
The header template we have to get the size from.
:type header: dict
:return: The maximal size of the each data to print.
:rtype: list
"""
#... |
def _colorify(self, data):
"""
Retun colored string.
:param data: The string to colorify.
:type data: str
:return: A colored string.
:rtype: str
"""
if self.template in ["Generic", "Less"]:
# The template is in the list of template that need... |
def _json_print(self): # pragma: no cover
"""
Management of the json template.
"""
if self.output:
# The given output is not empty.
if PyFunceble.path.isfile(self.output):
# The given output already exist.
# We get the content o... |
def data(self): # pragma: no cover pylint: disable=inconsistent-return-statements
"""
Management and input of data to the table.
:raises:
:code:`Exception`
When self.data_to_print is not a list.
"""
if isinstance(self.data_to_print, list):
... |
def _save(self, last=False): # pragma: no cover
"""
Save the current time to the file.
:param last:
Tell us if we are at the very end of the file testing.
:type last: bool
"""
if (
self._authorization()
and PyFunceble.CONFIGURATION["... |
def _calculate(cls, start=None, end=None):
"""
calculate the difference between starting and ending time.
:param start: A starting time.
:type start: int|str
:param stop: A ending time.
:type stop: int|str
:return:
A dict with following as index.
... |
def format_execution_time(self, start=None, end=None):
"""
Format the calculated time into a human readable format.
:param start: A starting time.
:type start: int|str
:param stop: A ending time.
:type stop: int|str
:return: A human readable date.
:rtyp... |
def file_to_delete(cls):
"""
Return the list of file to delete.
"""
# We initiate the directory we have to look for.
directory = PyFunceble.OUTPUT_DIRECTORY + PyFunceble.OUTPUTS["parent_directory"]
if not directory.endswith(PyFunceble.directory_separator): # pragma: no... |
def databases_to_delete(cls): # pragma: no cover
"""
Set the databases files to delete.
"""
# We initiate the directory we have to look for.
directory = PyFunceble.CURRENT_DIRECTORY
# We initate the result variable.
result = []
# We append the dir_stru... |
def almost_everything(self, clean_all=False):
"""
Delete almost all discovered files.
:param clean_all:
Tell the subsystem if we have to clean everything instesd
of almost everything.
:type clean_all: bool
"""
# We get the list of file to delete.... |
def _hash_file(self, algo):
"""Get the hash of the given file
:param algo: The algorithm to use.
:type algo: str
:return: The hexdigest of the data.
:rtype: str
"""
# We het the algorithm function.
hash_data = getattr(hashlib, algo)()
with open... |
def _hash_data(self, algo):
"""
Get hash of the given data.
:param algo: The algorithm to use.
:type algo: str
"""
# We het the algorithm function.
hash_data = getattr(hashlib, algo)()
# We set the data into our hashlib.
hash_data.update(self.da... |
def get(self):
"""
Return the hash of the given file
"""
# We initiate a variable which will save the result we are going
# to return.
result = {}
if self.algorithm in self.valid_algorithms:
# * The parsed path exist.
# and
# ... |
def execute(self):
"""
Execute the given command.
:return: The output of the command.
:rtype: str
"""
# We initiate a process and parse the command to it.
process = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=True)
# We communicate the command a... |
def run(self):
"""
Run the given command and yield each line(s) one by one.
.. note::
The difference between this method and :code:`self.execute()`
is that :code:`self.execute()` wait for the process to end
in order to return its output.
"""
... |
def remove_key(self, key_to_remove):
"""
Remove a given key from a given dictionary.
:param key_to_remove: The key(s) to delete.
:type key_to_remove: list|str
:return: The dict without the given key(s).
:rtype: dict|None
"""
if isinstance(self.main_dict... |
def rename_key(self, key_to_rename, strict=True):
"""
Rename the given keys from the given dictionary.
:param key_to_rename:
The key(s) to rename.
Expected format: :code:`{old:new}`
:type key_to_rename: dict
:param strict:
Tell us if we have ... |
def merge(self, to_merge, strict=True):
"""
Merge the content of to_merge into the given main dictionnary.
:param to_merge: The dictionnary to merge.
:type to_merge: dict
:param strict:
Tell us if we have to strictly merge lists.
:code:`True`: We follow... |
def to_json(self, destination):
"""
Save a dictionnary into a JSON file.
:param destination:
A path to a file where we're going to
write the converted dict into a JSON format.
:type destination: str
"""
try:
with open(destination, "w"... |
def to_yaml(self, destination, flow_style=False):
"""
Save a dictionnary into a YAML file.
:param destination:
A path to a file where we're going to write the
converted dict into a JSON format.
:type destination: str
"""
with open(destination, "w... |
def fix_path(self, splited_path=None):
"""
Fix the path of the given path.
:param splited_path: A list to convert to the right path.
:type splited_path: list
:return: The fixed path.
:rtype: str
"""
if not splited_path:
# A splited path is p... |
def write(self, data_to_write, overwrite=False):
"""
Write or append data into the given file path.
:param data_to_write: The data to write.
:type data_to_write: str
:param overwrite:
Tell us if we have to overwrite the
content of the file we are working... |
def read(self):
"""
Read a given file path and return its content.
:return: The content of the given file path.
:rtype: str
"""
try:
with open(self.file, "r", encoding="utf-8") as file:
# We open and read a file.
# We get the... |
def format(self):
"""
Return a well formatted list. Basicaly, it's sort a list and remove duplicate.
:return: A sorted, without duplicate, list.
:rtype: list
"""
try:
return sorted(list(set(self.main_list)), key=str.lower)
except TypeError: # pragm... |
def custom_format(self, key_method, reverse=False):
"""
Return a well formatted list. With the key_method as a function/method to format
the elements before sorting.
:param key_method:
A function or method to use to format the
readed element before sorting.
... |
def merge(self, to_merge, strict=True):
"""
Merge to_merge into the given main list.
:param to_merge: The list to merge.
:type to_merge: list
:param strict:
Tell us if we have to respect index (True)
or not (False).
:type strict: bool
:r... |
def not_matching_list(self):
"""
Return a list of string which don't match the
given regex.
"""
pre_result = comp(self.regex)
return [x for x in self.data if not pre_result.search(str(x))] |
def match(self):
"""
Used to get exploitable result of re.search
:return: The data of the match status.
:rtype: mixed
"""
# We initate this variable which gonna contain the returned data
result = []
# We compile the regex string
to_match = comp(... |
def replace(self):
"""
Used to replace a matched string with another.
:return: The data after replacement.
:rtype: str
"""
if self.replace_with: # pylint: disable=no-member
return substrings(
self.regex,
self.replace_with, #... |
def text(self):
"""
Download the given link and return or save its :code:`requests.text`
at the given destination.
:rtype: mixed
:raises:
:code:`Exception`
If the status code is not :code:`200`.
"""
try:
# We request the ... |
def count(self):
"""
Count the number of domain for each status.
"""
if self.status:
# The status is parsed.
# We increase the number of tested.
PyFunceble.INTERN["counter"]["number"]["tested"] += 1
if (
self.status.lower... |
def _calculate(cls):
"""
Calculate the percentage of each status.
"""
# We map the current state/counters of the different status.
percentages = {
"up": PyFunceble.INTERN["counter"]["number"]["up"],
"down": PyFunceble.INTERN["counter"]["number"]["down"],
... |
def log(self):
"""
Print on screen and on file the percentages for each status.
"""
if (
PyFunceble.CONFIGURATION["show_percentage"]
and PyFunceble.INTERN["counter"]["number"]["tested"] > 0
):
# * We are allowed to show the percentage on scree... |
def is_url_valid(self, url=None, return_base=False, return_formatted=False):
"""
Check if the given URL is valid.
:param url: The url to validate.
:type url: str
:param return_base:
Allow us the return of the url base (if URL formatted correctly).
:type retu... |
def is_domain_valid(
self, domain=None, subdomain_check=False
): # pylint:disable=too-many-return-statements, too-many-branches
"""
Check if the given domain is a valid.
:param domain: The domain to validate.
:type domain: str
:param subdomain_check:
Ac... |
def is_subdomain(self, domain=None):
"""
Check if the given subdomain is a subdomain.
:param domain: The domain to validate.
:type domain: str
:return: The validity of the subdomain.
:rtype: bool
"""
if domain:
# A domain is given.
... |
def is_ip_valid(self, ip_to_check=None):
"""
Check if the given IP is a valid IPv4.
:param ip_to_check: The IP to test.
:type ip_to_check: str
:return: The validity of the IP.
:rtype: bool
.. note::
We only test IPv4 because for now we only them for... |
def is_ip_range(self, ip_to_check=None):
"""
Check if the given IP is a valid IPv4.
:param ip_to_check: The IP to test.
:type ip_to_check: str
:return: The validity of the IP.
:rtype: bool
.. note::
We only test IPv4 because for now we only them for... |
def get(cls):
"""
Execute the logic behind the Syntax handling.
:return: The syntax status.
:rtype: str
"""
if PyFunceble.INTERN["to_test_type"] == "domain":
# We are testing for domain or ip.
if Check().is_domain_valid() or Check().is_ip_valid(... |
def _reformat_historical_formating_error(self): # pragma: no cover
"""
Format the old format so it can be merged into the newer format.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We construct the possible path... |
def _merge(self):
"""
Merge the real database with the older one which
has already been set into :code:`PyFunceble.INTERN["inactive_db"]`
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We get the content of... |
def _retrieve(self):
"""
Return the current content of the inactive-db.json file.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We get, format and initiate the historical database file.
self._reformat_... |
def _backup(self):
"""
Save the current database into the inactive-db.json file.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We save the current database state into the database file.
Dict(PyFunceble... |
def _timestamp(self):
"""
Get the timestamp where we are going to save our current list.
:return: The timestamp to append with the currently tested element.
:rtype: int|str
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is act... |
def add(self):
"""
Save the current :code.`PyFunceble.CONFIGURATION['to_test']`
into the current timestamp.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We get the timestamp to use as index.
t... |
def remove(self):
"""
Remove all occurence of :code:`PyFunceble.CONFIGURATION['to_test']`
from the database.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
if PyFunceble.INTERN["file_to_test"] in PyFunceble.I... |
def content(cls):
"""
Get the content of the database.
:return: The content of the database.
:rtype: list
"""
# We initiate a variable which will save what we are going to return.
result = []
if (
PyFunceble.CONFIGURATION["inactive_database"... |
def is_present(cls):
"""
Check if the currently tested element is into the database.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
if PyFunceble.INTERN["to_test"] in PyFunceble.INTERN[
"flatten_inact... |
def _retrieve(self):
"""
Retrieve the data from the database.
"""
if self._authorization() and "whois_db" not in PyFunceble.INTERN:
# The usage of the whois database is activated.
if PyFunceble.path.isfile(self.whois_db_path):
# The database file... |
def _backup(self):
"""
Backup the database into its file.
"""
if self._authorization():
# We are authorized to work.
# We backup the current state of the datbase.
Dict(PyFunceble.INTERN["whois_db"]).to_json(self.whois_db_path) |
def is_in_database(self):
"""
Check if the element is into the database.
"""
if (
self._authorization()
and PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["whois_db"]
and PyFunceble.INTERN["to_test"]
in PyFunceble.INTERN["whois_db"... |
def is_time_older(self):
"""
Check if the current time is older than the one in the database.
"""
if (
self._authorization()
and self.is_in_database()
and int(
PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
... |
def get_expiration_date(self):
"""
Get the expiration date from the database.
:return: The expiration date from the database.
:rtype: str|None
"""
if self._authorization() and self.is_in_database() and not self.is_time_older():
# * We are authorized to work.... |
def add(self):
"""
Add the currently tested element into the database.
"""
if self._authorization():
# We are authorized to work.
if self.epoch < int(PyFunceble.time()):
state = "past"
else:
state = "future"
... |
def travis_permissions(cls):
"""
Set permissions in order to avoid issues before commiting.
"""
if PyFunceble.CONFIGURATION["travis"]:
try:
build_dir = PyFunceble.environ["TRAVIS_BUILD_DIR"]
commands = [
"sudo chown -R trav... |
def _travis(self):
"""
Logic behind autosave under Travis CI.
"""
if PyFunceble.CONFIGURATION["travis"]:
try:
_ = PyFunceble.environ["TRAVIS_BUILD_DIR"]
time_autorisation = False
try:
time_autorisation = in... |
def nslookup(cls):
"""
Implementation of UNIX nslookup.
"""
try:
# We try to get the addresse information of the given domain or IP.
if "current_test_data" in PyFunceble.INTERN: # pragma: no cover
# The end-user want more information whith his t... |
def whois(cls, whois_server, domain=None, timeout=None): # pragma: no cover
"""
Implementation of UNIX whois.
:param whois_server: The WHOIS server to use to get the record.
:type whois_server: str
:param domain: The domain to get the whois record from.
:type domain: s... |
def get(cls): # pragma: no cover
"""
Execute the logic behind the URL handling.
:return: The status of the URL.
:rtype: str
"""
if Check().is_url_valid() or PyFunceble.CONFIGURATION["local"]:
# * The url is valid.
# or
# * We are tes... |
def _get_version():
"""
This function will extract the version from PyFunceble/__init__.py
"""
to_match = comp(r'VERSION\s=\s"(.*)"\n')
extracted = to_match.findall(
open("PyFunceble/__init__.py", encoding="utf-8").read()
)[0]
return ".".join([x for x in extracted.split(".") if x.i... |
def get(self):
"""
Return the referer aka the WHOIS server of the current domain extension.
"""
if not PyFunceble.CONFIGURATION["local"]:
# We are not running a test in a local network.
if self.domain_extension not in self.ignored_extension:
# Th... |
def _register_servicer(self, servicer):
"""register serviser
:param servicer: servicer
"""
name = servicer.__name__
if name in self._servicers:
raise exceptions.ConfigException(
'servicer duplicated: {}'.format(name))
add_func = self._get_serv... |
def _register_extension(self, name, ext):
"""register extension
:param name: extension name
:param ext: extension object
"""
ext.init_app(self)
if name in self._extensions:
raise exceptions.ConfigException(
'extension duplicated: {}'.format(na... |
def _get_current_object(self):
"""Get current object.
This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
"""
loc = object.__getattribute__(self, '_Proxy__local')
... |
def standard_paths():
"""Yield paths to standard modules."""
for is_plat_spec in [True, False]:
path = distutils.sysconfig.get_python_lib(standard_lib=True,
plat_specific=is_plat_spec)
for name in os.listdir(path):
yield name
... |
def standard_package_names():
"""Yield standard module names."""
for name in standard_paths():
if name.startswith('_') or '-' in name:
continue
if '.' in name and name.rsplit('.')[-1] not in ['so', 'py', 'pyc']:
continue
yield name.split('.')[0] |
def unused_import_line_numbers(messages):
"""Yield line numbers of unused imports."""
for message in messages:
if isinstance(message, pyflakes.messages.UnusedImport):
yield message.lineno |
def unused_import_module_name(messages):
"""Yield line number and module name of unused imports."""
pattern = r'\'(.+?)\''
for message in messages:
if isinstance(message, pyflakes.messages.UnusedImport):
module_name = re.search(pattern, str(message))
module_name = module_name... |
def star_import_used_line_numbers(messages):
"""Yield line number of star import usage."""
for message in messages:
if isinstance(message, pyflakes.messages.ImportStarUsed):
yield message.lineno |
def star_import_usage_undefined_name(messages):
"""Yield line number, undefined name, and its possible origin module."""
for message in messages:
if isinstance(message, pyflakes.messages.ImportStarUsage):
undefined_name = message.message_args[0]
module_name = message.message_args... |
def unused_variable_line_numbers(messages):
"""Yield line numbers of unused variables."""
for message in messages:
if isinstance(message, pyflakes.messages.UnusedVariable):
yield message.lineno |
def duplicate_key_line_numbers(messages, source):
"""Yield line numbers of duplicate keys."""
messages = [
message for message in messages
if isinstance(message, pyflakes.messages.MultiValueRepeatedKeyLiteral)]
if messages:
# Filter out complex cases. We don't want to bother trying ... |
def create_key_to_messages_dict(messages):
"""Return dict mapping the key to list of messages."""
dictionary = collections.defaultdict(lambda: [])
for message in messages:
dictionary[message.message_args[0]].append(message)
return dictionary |
def check(source):
"""Return messages from pyflakes."""
if sys.version_info[0] == 2 and isinstance(source, unicode):
# Convert back to original byte string encoding, otherwise pyflakes
# call to compile() will complain. See PEP 263. This only affects
# Python 2.
try:
... |
def extract_package_name(line):
"""Return package name in import statement."""
assert '\\' not in line
assert '(' not in line
assert ')' not in line
assert ';' not in line
if line.lstrip().startswith(('import', 'from')):
word = line.split()[1]
else:
# Ignore doctests.
... |
def multiline_import(line, previous_line=''):
"""Return True if import is spans multiples lines."""
for symbol in '()':
if symbol in line:
return True
# Ignore doctests.
if line.lstrip().startswith('>'):
return True
return multiline_statement(line, previous_line) |
def multiline_statement(line, previous_line=''):
"""Return True if this is part of a multiline statement."""
for symbol in '\\:;':
if symbol in line:
return True
sio = io.StringIO(line)
try:
list(tokenize.generate_tokens(sio.readline))
return previous_line.rstrip().e... |
def filter_from_import(line, unused_module):
"""Parse and filter ``from something import a, b, c``.
Return line without unused import modules, or `pass` if all of the
module in import is unused.
"""
(indentation, imports) = re.split(pattern=r'\bimport\b',
strin... |
def break_up_import(line):
"""Return line with imports on separate lines."""
assert '\\' not in line
assert '(' not in line
assert ')' not in line
assert ';' not in line
assert '#' not in line
assert not line.lstrip().startswith('from')
newline = get_line_ending(line)
if not newline... |
def filter_code(source, additional_imports=None,
expand_star_imports=False,
remove_all_unused_imports=False,
remove_duplicate_keys=False,
remove_unused_variables=False,
ignore_init_module_imports=False,
):
"""Yield code ... |
def get_messages_by_line(messages):
"""Return dictionary that maps line number to message."""
line_messages = {}
for message in messages:
line_messages[message.lineno] = message
return line_messages |
def filter_star_import(line, marked_star_import_undefined_name):
"""Return line with the star import expanded."""
undefined_name = sorted(set(marked_star_import_undefined_name))
return re.sub(r'\*', ', '.join(undefined_name), line) |
def filter_unused_import(line, unused_module, remove_all_unused_imports,
imports, previous_line=''):
"""Return line if used, otherwise return None."""
if multiline_import(line, previous_line):
return line
is_from_import = line.lstrip().startswith('from')
if ',' in line... |
def filter_unused_variable(line, previous_line=''):
"""Return line if used, otherwise return None."""
if re.match(EXCEPT_REGEX, line):
return re.sub(r' as \w+:$', ':', line, count=1)
elif multiline_statement(line, previous_line):
return line
elif line.count('=') == 1:
split_line ... |
def filter_duplicate_key(line, message, line_number, marked_line_numbers,
source, previous_line=''):
"""Return '' if first occurrence of the key otherwise return `line`."""
if marked_line_numbers and line_number == sorted(marked_line_numbers)[0]:
return ''
return line |
def dict_entry_has_key(line, key):
"""Return True if `line` is a dict entry that uses `key`.
Return False for multiline cases where the line should not be removed by
itself.
"""
if '#' in line:
return False
result = re.match(r'\s*(.*)\s*:\s*(.*),\s*$', line)
if not result:
... |
def is_literal_or_name(value):
"""Return True if value is a literal or a name."""
try:
ast.literal_eval(value)
return True
except (SyntaxError, ValueError):
pass
if value.strip() in ['dict()', 'list()', 'set()']:
return True
# Support removal of variables on the rig... |
def useless_pass_line_numbers(source):
"""Yield line numbers of unneeded "pass" statements."""
sio = io.StringIO(source)
previous_token_type = None
last_pass_row = None
last_pass_indentation = None
previous_line = ''
for token in tokenize.generate_tokens(sio.readline):
token_type = t... |
def filter_useless_pass(source):
"""Yield code with useless "pass" lines removed."""
try:
marked_lines = frozenset(useless_pass_line_numbers(source))
except (SyntaxError, tokenize.TokenError):
marked_lines = frozenset()
sio = io.StringIO(source)
for line_number, line in enumerate(si... |
def get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
else:
return '' |
def get_line_ending(line):
"""Return line ending."""
non_whitespace_index = len(line.rstrip()) - len(line)
if not non_whitespace_index:
return ''
else:
return line[non_whitespace_index:] |
def fix_code(source, additional_imports=None, expand_star_imports=False,
remove_all_unused_imports=False, remove_duplicate_keys=False,
remove_unused_variables=False, ignore_init_module_imports=False):
"""Return code with all filtering run on it."""
if not source:
return source
... |
def fix_file(filename, args, standard_out):
"""Run fix_code() on a file."""
encoding = detect_encoding(filename)
with open_with_encoding(filename, encoding=encoding) as input_file:
source = input_file.read()
original_source = source
isInitFile = os.path.basename(filename) == '__init__.py'
... |
def detect_encoding(filename, limit_byte_check=-1):
"""Return file encoding."""
try:
with open(filename, 'rb') as input_file:
encoding = _detect_encoding(input_file.readline)
# Check for correctness of encoding.
with open_with_encoding(filename, encoding) as input_fi... |
def _detect_encoding(readline):
"""Return file encoding."""
try:
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_tokenize.detect_encoding(readline)[0]
return encoding
except (LookupError, SyntaxError, UnicodeDecodeError):
return 'latin-1' |
def _split_comma_separated(string):
"""Return a set of strings."""
return set(text.strip() for text in string.split(',') if text.strip()) |
def is_python_file(filename):
"""Return True if filename is Python file."""
if filename.endswith('.py'):
return True
try:
with open_with_encoding(
filename,
None,
limit_byte_check=MAX_PYTHON_FILE_DETECTION_BYTES) as f:
text = f.rea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.