_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q270300 | Production._does_require_deprecation | test | def _does_require_deprecation(self):
"""
Check if we have to put the previous version into the deprecated list.
"""
for index, version_number in enumerate(self.current_version[0][:2]):
# We loop through the 2 last elements of the version.
if version_number > self.version_yaml[index]:
# The currently read version number is greater than the one we have in
# the version.yaml.
# We return True.
return True
# We return False, we do not need to deprecate anything.
return False | python | {
"resource": ""
} |
q270301 | AutoContinue.backup | test | def backup(self):
"""
Backup the current execution state.
"""
if PyFunceble.CONFIGURATION["auto_continue"]:
# The auto_continue subsystem is activated.
# We initiate the location where we are going to save the data to backup.
data_to_backup = {}
# We get the current counter states.
configuration_counter = PyFunceble.INTERN["counter"]["number"]
# We initiate the data we have to backup.
data_to_backup[PyFunceble.INTERN["file_to_test"]] = {
# We backup the number of tested.
"tested": configuration_counter["tested"],
# We backup the number of up.
"up": configuration_counter["up"],
# We backup the number of down.
"down": configuration_counter["down"],
# We backup the number of invalid.
"invalid": configuration_counter["invalid"],
}
# We initiate the final data we have to save.
# We initiate this variable instead of updating backup_content because
# we do not want to touch the backup_content.
to_save = {}
# We add the backup_content into to_save.
to_save.update(self.backup_content)
# And we overwrite with the newly data to backup.
to_save.update(data_to_backup)
# Finaly, we save our informations into the log file.
Dict(to_save).to_json(self.autocontinue_log_file) | python | {
"resource": ""
} |
q270302 | AutoContinue.restore | test | def restore(self):
"""
Restore data from the given path.
"""
if PyFunceble.CONFIGURATION["auto_continue"] and self.backup_content:
# The auto_continue subsystem is activated and the backup_content
# is not empty.
# We get the file we have to restore.
file_to_restore = PyFunceble.INTERN["file_to_test"]
if file_to_restore in self.backup_content:
# The file we are working with is already into the backup content.
# We initiate the different status to set.
to_initiate = ["up", "down", "invalid", "tested"]
# Because at some time it was not the current status, we have to map
# the new with the old. This way, if someone is running the latest
# version but with old data, we still continue like nothing happend.
alternatives = {
"up": "number_of_up",
"down": "number_of_down",
"invalid": "number_of_invalid",
"tested": "number_of_tested",
}
for string in to_initiate:
# We loop over the status we have to initiate.
try:
# We try to update the counters by using the currently read status.
PyFunceble.INTERN["counter"]["number"].update(
{string: self.backup_content[file_to_restore][string]}
)
except KeyError:
# But if the status is not present, we try with the older index
# we mapped previously.
PyFunceble.INTERN["counter"]["number"].update(
{
string: self.backup_content[file_to_restore][
alternatives[string]
]
}
) | python | {
"resource": ""
} |
q270303 | AdBlock._is_to_ignore | test | def _is_to_ignore(cls, line):
"""
Check if we have to ignore the given line.
:param line: The line from the file.
:type line: str
"""
# We set the list of regex to match to be
# considered as ignored.
to_ignore = [r"(^!|^@@|^\/|^\[|^\.|^-|^_|^\?|^&)"] # , r"(\$|,)(image)"]
for element in to_ignore:
# We loop through the list of regex.
if Regex(line, element, return_data=False).match():
# The currently read line match the currently read
# regex.
# We return true, it has to be ignored.
return True
# Wer return False, it does not has to be ignored.
return False | python | {
"resource": ""
} |
q270304 | AdBlock._handle_options | test | def _handle_options(self, options):
"""
Handle the data from the options.
:param options: The list of options from the rule.
:type options: list
:return: The list of domains to return globally.
:rtype: list
"""
# We initiate a variable which will save our result
result = []
# We initiate the regex which will be used to extract the domain listed
# under the option domain=
regex_domain_option = r"domain=(.*)"
for option in options:
# We loop through the list of option.
try:
# We try to extract the list of domains from the currently read
# option.
domains = Regex(
option, regex_domain_option, return_data=True, rematch=True, group=0
).match()[-1]
if domains:
# We could extract something.
if self.aggressive: # pragma: no cover
result.extend(
[
x
for x in domains.split("|")
if x and not x.startswith("~")
]
)
else:
# We return True.
return True
except TypeError:
pass
# We return the result.
return result | python | {
"resource": ""
} |
q270305 | AdBlock._extract_base | test | def _extract_base(self, element):
"""
Extract the base of the given element.
.. example:
given "hello/world?world=beautiful" return "hello"
:param element: The element we are working with.
:type element: str|list
"""
if isinstance(element, list):
# The given element is a list.
# We get the base of each element of the list.
return [self._extract_base(x) for x in element]
# We get the base if it is an URL.
base = self.checker.is_url_valid(url=element, return_base=True)
if base:
# It is an URL.
# We return the extracted base.
return base
if "/" in element:
# / is in the given element.
# We return the first element before the
# first /
return element.split("/")[0]
# / is not in the given element.
# We return the given element.
return element | python | {
"resource": ""
} |
q270306 | AdBlock._format_decoded | test | def _format_decoded(self, to_format, result=None): # pragma: no cover
"""
Format the exctracted adblock line before passing it to the system.
:param to_format: The extracted line from the file.
:type to_format: str
:param result: A list of the result of this method.
:type result: list
:return: The list of domains or IP to test.
:rtype: list
"""
if not result:
# The result is not given.
# We set the result as an empty list.
result = []
for data in List(to_format).format():
# We loop through the different lines to format.
if data:
# The currently read line is not empty.
if "^" in data:
# There is an accent in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("^"), result)
if "#" in data:
# There is a dash in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("#"), result)
if "," in data:
# There is a comma in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split(","), result)
if "!" in data:
# There is an exclamation mark in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("!"), result)
if "|" in data:
# There is a vertival bar in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("|"), result)
if data:
# The currently read line is not empty.
data = self._extract_base(data)
if data and (
self.checker.is_domain_valid(data)
or self.checker.is_ip_valid(data)
):
# The extraced base is not empty.
# and
# * The currently read line is a valid domain.
# or
# * The currently read line is a valid IP.
# We append the currently read line to the result.
result.append(data)
elif data:
# * The currently read line is not a valid domain.
# or
# * The currently read line is not a valid IP.
# We try to get the url base.
url_base = self.checker.is_url_valid(data, return_base=True)
if url_base:
# The url_base is not empty or equal to False or None.
# We append the url base to the result.
result.append(url_base)
# We return the result element.
return result | python | {
"resource": ""
} |
q270307 | HTTPCode._access | test | def _access(self): # pragma: no cover
"""
Get the HTTP code status.
:return: The matched HTTP status code.
:rtype: int|None
"""
try:
# We try to get the HTTP status code.
if PyFunceble.INTERN["to_test_type"] == "url":
# We are globally testing a URL.
# We get the head of the URL.
req = PyFunceble.requests.head(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
headers=self.headers,
verify=PyFunceble.CONFIGURATION["verify_ssl_certificate"],
)
else:
# We are not globally testing a URL.
# We get the head of the constructed URL.
req = PyFunceble.requests.head(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
headers=self.headers,
)
# And we try to get the status code.
return req.status_code
except (
PyFunceble.requests.exceptions.InvalidURL,
PyFunceble.socket.timeout,
PyFunceble.requests.exceptions.Timeout,
PyFunceble.requests.ConnectionError,
urllib3_exceptions.InvalidHeader,
UnicodeDecodeError, # The probability that this happend in production is minimal.
):
# If one of the listed exception is matched, that means that something
# went wrong and we were unable to extract the status code.
# We return None.
return None | python | {
"resource": ""
} |
q270308 | HTTPCode.get | test | def get(self):
"""
Return the HTTP code status.
:return: The matched and formatted status code.
:rtype: str|int|None
"""
if PyFunceble.HTTP_CODE["active"]:
# The http status code extraction is activated.
# We get the http status code.
http_code = self._access()
# We initiate a variable which will save the list of allowed
# http status code.
list_of_valid_http_code = []
for codes in [
PyFunceble.HTTP_CODE["list"]["up"],
PyFunceble.HTTP_CODE["list"]["potentially_down"],
PyFunceble.HTTP_CODE["list"]["potentially_up"],
]:
# We loop throught the list of http status code.
# We extend the list of valid with the currently read
# codes.
list_of_valid_http_code.extend(codes)
if http_code not in list_of_valid_http_code or http_code is None:
# * The extracted http code is not in the list of valid http code.
# or
# * The extracted http code is equal to `None`.
# We return 3 star in order to mention that we were not eable to extract
# the http status code.
return "*" * 3
# * The extracted http code is in the list of valid http code.
# or
# * The extracted http code is not equal to `None`.
# We return the extracted http status code.
return http_code
# The http status code extraction is activated.
# We return None.
return None | python | {
"resource": ""
} |
q270309 | syntax_check | test | def syntax_check(domain): # pragma: no cover
"""
Check the syntax of the given domain.
:param domain: The domain to check the syntax for.
:type domain: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
"""
if domain and isinstance(domain, str):
# * The given domain is not empty nor None.
# and
# * The given domain is a string.
# We silently load the configuration.
load_config(True)
return Check(domain).is_domain_valid()
# We return None, there is nothing to check.
return None | python | {
"resource": ""
} |
q270310 | is_subdomain | test | def is_subdomain(domain): # pragma: no cover
"""
Check if the given domain is a subdomain.
:param domain: The domain we are checking.
:type domain: str
:return: The subdomain state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
"""
if domain and isinstance(domain, str):
# * The given domain is not empty nor None.
# and
# * The given domain is a string.
# We silently load the configuration.
load_config(True)
return Check(domain).is_subdomain()
# We return None, there is nothing to check.
return None | python | {
"resource": ""
} |
q270311 | ipv4_syntax_check | test | def ipv4_syntax_check(ip): # pragma: no cover
"""
Check the syntax of the given IPv4.
:param ip: The IPv4 to check the syntax for.
:type ip: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`.
"""
if ip and isinstance(ip, str):
# The given IP is not empty nor None.
# and
# * The given IP is a string.
# We silently load the configuration.
load_config(True)
return Check(ip).is_ip_valid()
# We return None, there is nothing to check.
return None | python | {
"resource": ""
} |
q270312 | is_ipv4_range | test | def is_ipv4_range(ip): # pragma: no cover
"""
Check if the given IP is an IP range.
:param ip: The IP we are checking.
:type ip: str
:return: The IPv4 range state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`.
"""
if ip and isinstance(ip, str):
# The given IP is not empty nor None.
# and
# * The given IP is a string.
# We silently load the configuration.
load_config(True)
return Check(ip).is_ip_range()
# We return None, there is nothing to check.
return None | python | {
"resource": ""
} |
q270313 | url_syntax_check | test | def url_syntax_check(url): # pragma: no cover
"""
Check the syntax of the given URL.
:param url: The URL to check the syntax for.
:type url: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`url` is given, we return :code:`None`.
"""
if url and isinstance(url, str):
# The given URL is not empty nor None.
# and
# * The given URL is a string.
# We silently load the configuration.
load_config(True)
return Check(url).is_url_valid()
# We return None, there is nothing to check.
return None | python | {
"resource": ""
} |
q270314 | load_config | test | def load_config(under_test=False, custom=None): # pragma: no cover
"""
Load the configuration.
:param under_test:
Tell us if we only have to load the configuration file (True)
or load the configuration file and initate the output directory
if it does not exist (False).
:type under_test: bool
:param custom:
A dict with the configuration index (from .PyFunceble.yaml) to update.
:type custom: dict
.. warning::
If :code:`custom` is given, the given :code:`dict` overwrite
the last value of the given configuration indexes.
"""
if "config_loaded" not in INTERN:
# The configuration was not already loaded.
# We load and download the different configuration file if they are non
# existant.
Load(CURRENT_DIRECTORY)
if not under_test:
# If we are not under test which means that we want to save informations,
# we initiate the directory structure.
DirectoryStructure()
# We save that the configuration was loaded.
INTERN.update({"config_loaded": True})
if custom and isinstance(custom, dict):
# The given configuration is not None or empty.
# and
# It is a dict.
# We update the configuration index.
CONFIGURATION.update(custom) | python | {
"resource": ""
} |
q270315 | stay_safe | test | def stay_safe(): # pragma: no cover
"""
Print a friendly message.
"""
random = int(choice(str(int(time()))))
if not CONFIGURATION["quiet"] and random % 3 == 0:
print("\n" + Fore.GREEN + Style.BRIGHT + "Thanks for using PyFunceble!")
print(
Fore.YELLOW
+ Style.BRIGHT
+ "Share your experience on "
+ Fore.CYAN
+ "Twitter"
+ Fore.YELLOW
+ " with "
+ Fore.CYAN
+ "#PyFunceble"
+ Fore.YELLOW
+ "!"
)
print(
Fore.GREEN
+ Style.BRIGHT
+ "Have a feedback, an issue or an improvement idea ?"
)
print(
Fore.YELLOW
+ Style.BRIGHT
+ "Let us know on "
+ Fore.CYAN
+ "GitHub"
+ Fore.YELLOW
+ "!"
) | python | {
"resource": ""
} |
q270316 | Core._entry_management_url_download | test | def _entry_management_url_download(self, passed):
"""
Check if the given information is a URL.
If it is the case, it download and update the location of file to test.
:param passed: The url passed to the system.
:type passed: str
:return: The state of the check.
:rtype: bool
"""
if passed and self.checker.is_url_valid(passed):
# The passed string is an URL.
# We get the file name based on the URL.
# We actually just get the string after the last `/` in the URL.
file_to_test = passed.split("/")[-1]
if (
not PyFunceble.path.isfile(file_to_test)
or PyFunceble.INTERN["counter"]["number"]["tested"] == 0
):
# The filename does not exist in the current directory
# or the currently number of tested is equal to 0.
# We download the content of the link.
Download(passed, file_to_test).text()
# The files does exist or the currently number of tested is greater than
# 0.
# We initiate the file we have to test.
PyFunceble.INTERN["file_to_test"] = file_to_test
# We return true to say that everything goes right.
return True
# The passed string is not an URL.
# We do not need to do anything else.
return False | python | {
"resource": ""
} |
q270317 | Core._entry_management_url | test | def _entry_management_url(self):
"""
Manage the loading of the url system.
"""
if (
self.url_file # pylint: disable=no-member
and not self._entry_management_url_download(
self.url_file # pylint: disable=no-member
)
): # pylint: disable=no-member
# The current url_file is not a URL.
# We initiate the filename as the file we have to test.
PyFunceble.INTERN[
"file_to_test"
] = self.url_file | python | {
"resource": ""
} |
q270318 | Core._print_header | test | def _print_header(cls):
"""
Decide if we print or not the header.
"""
if (
not PyFunceble.CONFIGURATION["quiet"]
and not PyFunceble.CONFIGURATION["header_printed"]
):
# * The quiet mode is not activated.
# and
# * The header has not been already printed.
# We print a new line.
print("\n")
if PyFunceble.CONFIGURATION["less"]:
# We have to show less informations on screen.
# We print the `Less` header.
Prints(None, "Less").header()
else:
# We have to show every informations on screen.
# We print the `Generic` header.
Prints(None, "Generic").header()
# The header was printed.
# We initiate the variable which say that the header has been printed to True.
PyFunceble.CONFIGURATION["header_printed"] = True | python | {
"resource": ""
} |
q270319 | Core._file_decision | test | def _file_decision(self, current, last, status=None):
"""
Manage the database, autosave and autocontinue systems for the case that we are reading
a file.
:param current: The currently tested element.
:type current: str
:param last: The last element of the list.
:type last: str
:param status: The status of the currently tested element.
:type status: str
"""
if (
status
and not PyFunceble.CONFIGURATION["simple"]
and PyFunceble.INTERN["file_to_test"]
):
# * The status is given.
# and
# * The simple mode is deactivated.
# and
# * A file to test is set.
# We run the mining logic.
self.mining.process()
# We delete the currently tested element from the mining
# database.
# Indeed, as it is tested, it is already in our
# testing process which means that we don't need it into
# the mining database.
self.mining.remove()
if (
status.lower() in PyFunceble.STATUS["list"]["up"]
or status.lower() in PyFunceble.STATUS["list"]["valid"]
):
# The status is in the list of up status.
if self.inactive_database.is_present():
# The currently tested element is in the database.
# We generate the suspicious file(s).
Generate(PyFunceble.STATUS["official"]["up"]).analytic_file(
"suspicious"
)
# We remove the currently tested element from the
# database.
self.inactive_database.remove()
else:
# The status is not in the list of up status.
# We add the currently tested element to the
# database.
self.inactive_database.add()
# We backup the current state of the file reading
# for the case that we need to continue later.
self.auto_continue.backup()
if current != last:
# The current element is not the last one.
# We run the autosave logic.
AutoSave()
else:
# The current element is the last one.
# We stop and log the execution time.
ExecutionTime("stop", last=True)
# We show/log the percentage.
self.percentage.log()
# We reset the counters as we end the process.
self.reset_counters()
# We backup the current state of the file reading
# for the case that we need to continue later.
self.auto_continue.backup()
# We show the colored logo.
self.colorify_logo()
# We save and stop the script if we are under
# Travis CI.
AutoSave(True)
for index in ["http_code", "referer"]:
# We loop through some configuration index we have to empty.
if index in PyFunceble.INTERN:
# The index is in the configuration.
# We empty the configuration index.
PyFunceble.INTERN[index] = "" | python | {
"resource": ""
} |
q270320 | Core.domain | test | def domain(self, domain=None, last_domain=None):
"""
Manage the case that we want to test only a domain.
:param domain: The domain or IP to test.
:type domain: str
:param last_domain:
The last domain to test if we are testing a file.
:type last_domain: str
:param return_status: Tell us if we need to return the status.
:type return_status: bool
"""
# We print the header.
self._print_header()
if domain:
# A domain is given.
# We format and set the domain we are testing and treating.
PyFunceble.INTERN["to_test"] = self._format_domain(domain)
else:
# A domain is not given.
# We set the domain we are testing and treating to None.
PyFunceble.INTERN["to_test"] = None
if PyFunceble.INTERN["to_test"]:
# The domain is given (Not None).
if PyFunceble.CONFIGURATION["syntax"]:
# The syntax mode is activated.
# We get the status from Syntax.
status = self.syntax_status.get()
else:
# We test and get the status of the domain.
status, _ = self.status.get()
# We run the file decision logic.
self._file_decision(PyFunceble.INTERN["to_test"], last_domain, status)
if PyFunceble.CONFIGURATION["simple"]:
# The simple mode is activated.
# We print the domain and the status.
print(PyFunceble.INTERN["to_test"], status)
# We return the tested domain and its status.
return PyFunceble.INTERN["to_test"], status
# We return None, there is nothing to test.
return None | python | {
"resource": ""
} |
q270321 | Core.url | test | def url(self, url_to_test=None, last_url=None):
"""
Manage the case that we want to test only a given url.
:param url_to_test: The url to test.
:type url_to_test: str
:param last_url:
The last url of the file we are testing
(if exist)
:type last_url: str
"""
# We print the header.
self._print_header()
if url_to_test:
# An url to test is given.
# We set the url we are going to test.
PyFunceble.INTERN["to_test"] = url_to_test
else:
# An URL to test is not given.
# We set the url we are going to test to None.
PyFunceble.INTERN["to_test"] = None
if PyFunceble.INTERN["to_test"]:
# An URL to test is given.
if PyFunceble.CONFIGURATION["syntax"]:
# The syntax mode is activated.
# We get the status from Syntax.
status = self.syntax_status.get()
else:
# The syntax mode is not activated.
# We get the status from URL.
status = self.url_status.get()
# We run the file decision logic.
self._file_decision(PyFunceble.INTERN["to_test"], last_url, status)
if PyFunceble.CONFIGURATION["simple"]:
# The simple mode is activated.
# We print the URL informations.
print(PyFunceble.INTERN["to_test"], status)
# We return the URL we tested and its status.
return PyFunceble.INTERN["to_test"], status
# We return None, there is nothing to test.
return None | python | {
"resource": ""
} |
q270322 | Core.colorify_logo | test | def colorify_logo(cls, home=False):
"""
Print the colored logo based on global results.
:param home: Tell us if we have to print the initial coloration.
:type home: bool
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
to_print = []
if home:
# We have to print the initial logo.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(
PyFunceble.Fore.YELLOW + line + PyFunceble.Fore.RESET
)
elif PyFunceble.INTERN["counter"]["percentage"]["up"] >= 50:
# The percentage of up is greater or equal to 50%.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(
PyFunceble.Fore.GREEN + line + PyFunceble.Fore.RESET
)
else:
# The percentage of up is less than 50%.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(PyFunceble.Fore.RED + line + PyFunceble.Fore.RESET)
print("\n".join(to_print)) | python | {
"resource": ""
} |
q270323 | Core._format_domain | test | def _format_domain(cls, extracted_domain):
"""
Format the extracted domain before passing it to the system.
:param extracted_domain: The extracted domain.
:type extracted_domain: str
:return: The formatted domain or IP to test.
:rtype: str
.. note:
Understand by formating the fact that we get rid
of all the noises around the domain we want to test.
"""
if not extracted_domain.startswith("#"):
# The line is not a commented line.
if "#" in extracted_domain:
# There is a comment at the end of the line.
# We delete the comment from the line.
extracted_domain = extracted_domain[
: extracted_domain.find("#")
].strip()
if " " in extracted_domain or "\t" in extracted_domain:
# A space or a tabs is in the line.
# We remove all whitestring from the extracted line.
splited_line = extracted_domain.split()
# As there was a space or a tab in the string, we consider
# that we are working with the hosts file format which means
# that the domain we have to test is after the first string.
# So we set the index to 1.
index = 1
while index < len(splited_line):
# We loop until the index is greater than the length of
# the splited line.
if splited_line[index]:
# The element at the current index is not an empty string.
# We break the loop.
break
# The element at the current index is an empty string.
# We increase the index number.
index += 1
# We return the last read element.
return splited_line[index]
# We return the extracted line.
return extracted_domain
# The extracted line is a comment line.
# We return an empty string as we do not want to work with commented line.
return "" | python | {
"resource": ""
} |
q270324 | Core._extract_domain_from_file | test | def _extract_domain_from_file(cls):
"""
Extract all non commented lines from the file we are testing.
:return: The elements to test.
:rtype: list
"""
# We initiate the variable which will save what we are going to return.
result = []
if PyFunceble.path.isfile(PyFunceble.INTERN["file_to_test"]):
# The give file to test exist.
try:
with open(PyFunceble.INTERN["file_to_test"]) as file:
# We open and read the file.
for line in file:
# We loop through each lines.
if not line.startswith("#"):
# The currently read line is not a commented line.
# We append the current read line to the result.
result.append(line.rstrip("\n").strip())
except UnicodeDecodeError:
with open(PyFunceble.INTERN["file_to_test"], encoding="utf-8") as file:
# We open and read the file.
for line in file:
# We loop through each lines.
if not line.startswith("#"):
# The currently read line is not a commented line.
# We append the current read line to the result.
result.append(line.rstrip("\n").strip())
else:
# The given file to test does not exist.
# We raise a FileNotFoundError exception.
raise FileNotFoundError(PyFunceble.INTERN["file_to_test"])
# We return the result.
return result | python | {
"resource": ""
} |
q270325 | Core.file | test | def file(self):
"""
Manage the case that need to test each domain of a given file path.
.. note::
1 domain per line.
"""
# We get, format, filter, clean the list to test.
list_to_test = self._file_list_to_test_filtering()
if PyFunceble.CONFIGURATION["idna_conversion"]:
# We have to convert domains to idna.
# We convert if we need to convert.
list_to_test = domain2idna(list_to_test)
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list_to_test).custom_format(Sort.hierarchical)
else:
# The hierarchical sorting is not desired by the user.
# We format the list.
list_to_test = List(list_to_test).custom_format(Sort.standard)
# We initiate a local variable which will save the current state of the list.
not_filtered = list_to_test
try:
# We remove the element which are in the database from the
# current list to test.
list_to_test = List(
list(
set(
list_to_test[PyFunceble.INTERN["counter"]["number"]["tested"] :]
)
- set(PyFunceble.INTERN["flatten_inactive_db"])
)
).format()
_ = list_to_test[-1]
except IndexError:
# Our list to test is the one with the element from the database.
list_to_test = not_filtered[
PyFunceble.INTERN["counter"]["number"]["tested"] :
]
# We delete the undesired variable.
del not_filtered
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list(list_to_test)).custom_format(Sort.hierarchical)
try:
# We test each element of the list to test.
return [self.domain(x, list_to_test[-1]) for x in list_to_test if x]
except IndexError:
# We print a message on screen.
print(PyFunceble.Fore.CYAN + PyFunceble.Style.BRIGHT + "Nothing to test.") | python | {
"resource": ""
} |
q270326 | Core.file_url | test | def file_url(self):
"""
Manage the case that we have to test a file
.. note::
1 URL per line.
"""
# We get, format, clean the list of URL to test.
list_to_test = self._file_list_to_test_filtering()
# We initiate a local variable which will save the current state of the list.
not_filtered = list_to_test
try:
# We remove the element which are in the database from the
# current list to test.
list_to_test = List(
list(
set(
list_to_test[PyFunceble.INTERN["counter"]["number"]["tested"] :]
)
- set(PyFunceble.INTERN["flatten_inactive_db"])
)
).format()
_ = list_to_test[-1]
except IndexError:
# Our list to test is the one with the element from the database.
list_to_test = not_filtered[
PyFunceble.INTERN["counter"]["number"]["tested"] :
]
# We delete the undesired variable.
del not_filtered
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list(list_to_test)).custom_format(Sort.hierarchical)
try:
# We test each URL from the list to test.
return [self.url(x, list_to_test[-1]) for x in list_to_test if x]
except IndexError:
# We print a message on screen.
print(PyFunceble.Fore.CYAN + PyFunceble.Style.BRIGHT + "Nothing to test.") | python | {
"resource": ""
} |
q270327 | Core.switch | test | def switch(
cls, variable, custom=False
): # pylint: disable=inconsistent-return-statements
"""
Switch PyFunceble.CONFIGURATION variables to their opposite.
:param variable:
The variable name to switch.
The variable should be an index our configuration system.
If we want to switch a bool variable, we should parse
it here.
:type variable: str|bool
:param custom:
Let us know if have to switch the parsed variable instead
of our configuration index.
:type custom: bool
:return:
The opposite of the configuration index or the given variable.
:rtype: bool
:raises:
:code:`Exception`
When the configuration is not valid. In other words,
if the PyFunceble.CONFIGURATION[variable_name] is not a bool.
"""
if not custom:
# We are not working with custom variable which is not into
# the configuration.
# We get the current state.
current_state = dict.get(PyFunceble.CONFIGURATION, variable)
else:
# We are working with a custom variable which is not into the
# configuration
current_state = variable
if isinstance(current_state, bool):
# The current state is a boolean.
if current_state:
# The current state is equal to True.
# We return False.
return False
# The current state is equal to False.
# We return True.
return True
# The current state is not a boolean.
# We set the message to raise.
to_print = "Impossible to switch %s. Please post an issue to %s"
# We raise an exception inviting the user to report an issue.
raise Exception(
to_print % (repr(variable), PyFunceble.LINKS["repo"] + "/issues.")
) | python | {
"resource": ""
} |
q270328 | Status.get | test | def get(cls):
"""
Get the status while testing for an IP or domain.
.. note::
We consider that the domain or IP we are currently testing
is into :code:`PyFunceble.INTERN["to_test"]`.
"""
if "to_test" in PyFunceble.INTERN and PyFunceble.INTERN["to_test"]:
expiration_date = ExpirationDate().get()
if expiration_date is False:
return cls.handle(status="invalid")
if expiration_date == PyFunceble.STATUS["official"]["up"]:
return expiration_date, "WHOIS"
return cls.handle(status="inactive")
raise NotImplementedError("We expect `INTERN['to_test']` to be set.") | python | {
"resource": ""
} |
q270329 | URLStatus.handle | test | def handle(self):
"""
Handle the backend of the given status.
"""
# We initiate the source we are going to parse to the Generate class.
source = "URL"
if self.catched.lower() not in PyFunceble.STATUS["list"]["invalid"]:
# The parsed status is not in the list of invalid.
# We generate the status file with the catched status.
Generate(self.catched, source).status_file()
else:
# The parsed status is in the list of invalid.
# We generate the status file with the parsed status.
Generate(self.catched, "SYNTAX").status_file()
# We return the parsed status.
return self.catched | python | {
"resource": ""
} |
q270330 | DirectoryStructure._get_structure | test | def _get_structure(self):
"""
Get the structure we are going to work with.
:return: The structure we have to work with.
:rtype: dict
"""
# We initiate an empty variable which is going to save the location of
# file we are going to download.
structure_file = ""
# We initiate the variable which will save the request instance.
req = ""
if PyFunceble.path.isfile(self.structure):
# The structure path file exist.
# We set it as the destination file.
structure_file = self.structure
elif PyFunceble.path.isfile(self.base + "dir_structure_production.json"):
# * The structure path file does not exist.
# but
# * The production structure path file exist.
# We set it as the destination file
structure_file = self.base + "dir_structure_production.json"
else:
# * The structure path file does not exist.
# and
# * The production structure path file does not exist.
if "dev" not in PyFunceble.VERSION:
# `dev` is not into the local version name.
# We get the production file from the master branch.
req = PyFunceble.requests.get(
PyFunceble.LINKS["dir_structure"].replace("dev", "master")
)
else:
# `dev` is into the local version name.
# We get the production file from the dev branch.
req = PyFunceble.requests.get(
PyFunceble.LINKS["dir_structure"].replace("master", "dev")
)
if structure_file.endswith("_production.json"):
# The destination is the production file.
# And we return the updated the structure from the last read file.
# (with the names from the configuration file).
return self._update_structure_from_config(
Dict().from_json(File(structure_file).read())
)
# The destination is not the production file.
if structure_file.endswith(".json"):
# The destination ends with `.json`.
# And we return the updated the structure from the given file.
# (with the names from the configuration file).
return self._update_structure_from_config(
Dict().from_json(File(structure_file).read())
)
# The destination does not ends with `.json`.
# We return the updated the structure from the link we previously got.
# (with the names from the configuration file).
return self._update_structure_from_config(Dict().from_json(req.text)) | python | {
"resource": ""
} |
q270331 | DirectoryStructure._create_directory | test | def _create_directory(cls, directory, loop=False):
"""
Creates the given directory if it does not exists.
:param directory: The directory to create.
:type directory: str
:param loop: Tell us if we are in the creation loop or not.
:type loop: bool
"""
if not loop and PyFunceble.directory_separator in directory:
# * We are not in the loop.
# and
# * The directory separator in the given directory.
# We split the directories separator.
splited_directory = directory.split(PyFunceble.directory_separator)
# We initiate a variable which will save the full path to create.
full_path_to_create = ""
for single_directory in splited_directory:
# We loop through each directory.
# We append the currently read directory to the full path.
full_path_to_create += single_directory + PyFunceble.directory_separator
# And we create the directory if it does not exist.
cls._create_directory(full_path_to_create, True)
if not PyFunceble.path.isdir(directory):
# The given directory does not exist.
# We update the permission.
# (Only if we are under Travis CI.)
AutoSave.travis_permissions()
# We create the directory.
PyFunceble.mkdir(directory)
# We update the permission.
# (Only if we are under Travis CI.)
AutoSave.travis_permissions() | python | {
"resource": ""
} |
q270332 | DirectoryStructure.delete_uneeded | test | def delete_uneeded(self):
"""
Delete the directory which are not registered into our structure.
"""
# We get the structure we have to apply.
structure = self._get_structure()
# We get the list of key which is implicitly the list of directory we do not bave to delete.
list_of_key = list(structure.keys())
# We move to the content of the parent as we know that we are creating only one directory.
# Note: if one day we will have to create multiple directory, we will have to change
# the following.
structure = structure[list_of_key[0]]
# We also set the parent directory as we are going to construct its childen.
parent_path = list_of_key[0]
if not parent_path.endswith(PyFunceble.directory_separator):
parent_path += PyFunceble.directory_separator
for root, _, _ in PyFunceble.walk(parent_path):
# We loop through each directories of the parent path.
# We fix the path in order to avoid issues.
root = Directory(root).fix_path()
if root.replace(parent_path, "") not in structure:
# The currently read directory is not in our structure.
# We delete it.
PyFunceble.rmtree(root) | python | {
"resource": ""
} |
q270333 | Load._set_path_to_configs | test | def _set_path_to_configs(cls, path_to_config):
"""
Set the paths to the configuration files.
:param path_to_config: The possible path to the config to load.
:type path_to_config: str
:return:
The path to the config to read (0), the path to the default
configuration to read as fallback.(1)
:rtype: tuple
"""
if not path_to_config.endswith(PyFunceble.directory_separator):
# The path to the config does not ends with the directory separator.
# We initiate the default and the parsed variable with the directory separator.
default = parsed = path_to_config + PyFunceble.directory_separator
else:
# The path to the config does ends with the directory separator.
# We initiate the default and the parsed variable.
default = parsed = path_to_config
# We append the `CONFIGURATION_FILENAME` to the parsed variable.
parsed += PyFunceble.CONFIGURATION_FILENAME
# And we append the `DEFAULT_CONFIGURATION_FILENAME` to the default variable.
default += PyFunceble.DEFAULT_CONFIGURATION_FILENAME
# We finaly return a tuple which contain both informations.
return (parsed, default) | python | {
"resource": ""
} |
q270334 | Load._load_config_file | test | def _load_config_file(self):
"""
Load .PyFunceble.yaml into the system.
"""
try:
# We try to load the configuration file.
PyFunceble.CONFIGURATION.update(
Dict.from_yaml(File(self.path_to_config).read())
)
# We install the latest iana configuration file.
self._install_iana_config()
# We install the latest public suffix configuration file.
self._install_psl_config()
# We install the latest directory structure file.
self._install_directory_structure_file()
except FileNotFoundError as exception:
# But if the configuration file is not found.
if PyFunceble.path.isfile(self.path_to_default_config):
# The `DEFAULT_CONFIGURATION_FILENAME` file exists.
# We copy it as the configuration file.
File(self.path_to_default_config).copy(self.path_to_config)
# And we load the configuration file as it does exist (yet).
self._load_config_file()
else:
# The `DEFAULT_CONFIGURATION_FILENAME` file does not exists.
# We raise the exception we were handling.
raise exception | python | {
"resource": ""
} |
q270335 | Load._install_production_config | test | def _install_production_config(self):
"""
Download the production configuration and install it in the
current directory.
"""
# We initiate the link to the production configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
production_config_link = "https://raw.githubusercontent.com/funilrys/PyFunceble/master/.PyFunceble_production.yaml" # pylint: disable=line-too-long
# We update the link according to our current version.
production_config_link = Version(True).right_url_from_version(
production_config_link
)
if not Version(True).is_cloned():
# The current version is not the cloned one.
# We download the link content and save it inside the default location.
#
# Note: We add this one in order to allow the enduser to always have
# a copy of our upstream configuration file.
Download(production_config_link, self.path_to_default_config).text()
# And we download the link content and return the download status.
return Download(production_config_link, self.path_to_config).text() | python | {
"resource": ""
} |
q270336 | Load._install_iana_config | test | def _install_iana_config(cls):
"""
Download `iana-domains-db.json` if not present.
"""
# We initiate the link to the iana configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
iana_link = PyFunceble.CONFIGURATION["links"]["iana"]
# We update the link according to our current version.
iana_link = Version(True).right_url_from_version(iana_link)
# We set the destination of the downloaded file.
destination = PyFunceble.CURRENT_DIRECTORY + "iana-domains-db.json"
if not Version(True).is_cloned() or not PyFunceble.path.isfile(destination):
# The current version is not the cloned version.
# We Download the link content and return the download status.
return Download(iana_link, destination).text()
# We are in the cloned version.
# We do not need to download the file, so we are returning None.
return None | python | {
"resource": ""
} |
q270337 | Load._install_psl_config | test | def _install_psl_config(cls):
"""
Download `public-suffix.json` if not present.
"""
# We initiate the link to the public suffix configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
psl_link = PyFunceble.CONFIGURATION["links"]["psl"]
# We update the link according to our current version.
psl_link = Version(True).right_url_from_version(psl_link)
# We set the destination of the downloaded file.
destination = (
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["public_suffix"]
)
if not Version(True).is_cloned() or not PyFunceble.path.isfile(destination):
# The current version is not the cloned version.
# We Download the link content and return the download status.
return Download(psl_link, destination).text()
# We are in the cloned version.
# We do not need to download the file, so we are returning None.
return None | python | {
"resource": ""
} |
q270338 | Load._install_directory_structure_file | test | def _install_directory_structure_file(cls):
"""
Download the latest version of `dir_structure_production.json`.
"""
# We initiate the link to the public suffix configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
dir_structure_link = PyFunceble.CONFIGURATION["links"]["dir_structure"]
# We update the link according to our current version.
dir_structure_link = Version(True).right_url_from_version(dir_structure_link)
# We set the destination of the downloaded file.
destination = (
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["dir_structure"]
)
if not Version(True).is_cloned() or not PyFunceble.path.isfile(destination):
# The current version is not the cloned version.
# We Download the link content and return the download status.
data = Download(dir_structure_link, destination, return_data=True).text()
File(destination).write(data, overwrite=True)
return True
# We are in the cloned version.
# We do not need to download the file, so we are returning None.
return None | python | {
"resource": ""
} |
q270339 | Merge._merge_values | test | def _merge_values(self):
"""
Simply merge the older into the new one.
"""
to_remove = []
self.new_config = Dict(
Dict(self.upstream_config).merge(PyFunceble.CONFIGURATION)
).remove_key(to_remove) | python | {
"resource": ""
} |
q270340 | Merge._load | test | def _load(self):
"""
Execute the logic behind the merging.
"""
if "PYFUNCEBLE_AUTO_CONFIGURATION" not in PyFunceble.environ:
# The auto configuration environment variable is not set.
while True:
# We infinitly loop until we get a reponse which is `y|Y` or `n|N`.
# We ask the user if we should install and load the default configuration.
response = input(
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.RED
+ "A configuration key is missing.\n"
+ PyFunceble.Fore.RESET
+ "Try to merge upstream configuration file into %s ? [y/n] "
% (
PyFunceble.Style.BRIGHT
+ self.path_to_config
+ PyFunceble.Style.RESET_ALL
)
)
if isinstance(response, str):
# The response is a string
if response.lower() == "y":
# The response is a `y` or `Y`.
# We merge the old values inside the new one.
self._merge_values()
# And we save.
self._save()
print(
PyFunceble.Style.BRIGHT + PyFunceble.Fore.GREEN + "Done!\n"
"Please try again, if it happens again,"
" please fill a new issue."
)
# And we break the loop as we got a satisfied response.
break
elif response.lower() == "n":
# The response is a `n` or `N`.
# We inform the user that something went wrong.
raise Exception("Configuration key still missing.")
else:
# The auto configuration environment variable is set.
# We merge the old values inside the new one.
self._merge_values()
# And we save.
self._save() | python | {
"resource": ""
} |
q270341 | Version.split_versions | test | def split_versions(cls, version, return_non_digits=False):
"""
Convert the versions to a shorter one.
:param version: The version to split.
:type version: str
:param return_non_digits:
Activate the return of the non-digits parts of the splitted
version.
:type return_non_digits: bool
:return: The splitted version name/numbers.
:rtype: list
"""
# We split the version.
splited_version = version.split(".")
# We split the parsed version and keep the digits.
digits = [x for x in splited_version if x.isdigit()]
if not return_non_digits:
# We do not have to return the non digits part of the version.
# We return the digits part of the version.
return digits
# We have to return the non digit parts of the version.
# We split the parsed version and keep the non digits.
non_digits = [x for x in splited_version if not x.isdigit()]
# We return a tuple with first the digits part and finally the non digit parts.
return (digits, non_digits[0]) | python | {
"resource": ""
} |
q270342 | Version.check_versions | test | def check_versions(cls, local, upstream):
"""
Compare the given versions.
:param local: The local version converted by split_versions().
:type local: list
:param upstream: The upstream version converted by split_versions().
:type upstream: list
:return:
- True: local < upstream
- None: local == upstream
- False: local > upstream
:rtype: bool|None
"""
# A version should be in format [1,2,3] which is actually the version `1.2.3`
# So as we only have 3 elements in the versioning,
# we initiate the following variable in order to get the status of each parts.
status = [None, None, None]
for index, version_number in enumerate(local):
# We loop through the local version.
if int(version_number) < int(upstream[index]):
# The local version is less than the upstream version.
# We initiate its status to True which means that we are in
# an old version (for the current version part).
status[index] = True
elif int(version_number) > int(upstream[index]):
# The local version is greater then the upstream version.
# We initiate its status to False which means that we are in
# a more recent version (for the current version part).
status[index] = False
# Otherwise the status stay None which means that there is no change
# between both local and upstream.
if False in status:
# There is a False in the status.
# We return False which means that we are in a more recent version.
return False
if True in status:
# There is a True in the status.
# We return True which means that we are in a older version.
return True
# There is no True or False in the status.
# We return None which means that we are in the same version as upstream.
return None | python | {
"resource": ""
} |
q270343 | Version.is_cloned | test | def is_cloned(cls):
"""
Let us know if we are currently in the cloned version of
PyFunceble which implicitly mean that we are in developement mode.
"""
if not PyFunceble.path.isdir(".git"):
# The git directory does not exist.
# We return False, the current version is not the cloned version.
return False
# We list the list of file which can be found only in a cloned version.
list_of_file = [
".coveragerc",
".coveralls.yml",
".gitignore",
".PyFunceble_production.yaml",
".travis.yml",
"CODE_OF_CONDUCT.md",
"CONTRIBUTING.md",
"dir_structure_production.json",
"MANIFEST.in",
"README.rst",
"requirements.txt",
"setup.py",
"version.yaml",
]
# We list the list of directory which can be found only in a cloned
# version.
list_of_dir = ["docs", "PyFunceble", "tests"]
for file in list_of_file:
# We loop through the list of file.
if not PyFunceble.path.isfile(file):
# The file does not exist in the current directory.
# We return False, the current version is not the cloned version.
return False
# All required files exist in the current directory.
for directory in list_of_dir:
# We loop through the list of directory.
if not PyFunceble.path.isdir(directory):
# The directory does not exist in the current directory.
# We return False, the current version is not the cloned version.
return False
# All required directories exist in the current directory.
# We return True, the current version is a cloned version.
return True | python | {
"resource": ""
} |
q270344 | Generate._handle_non_existant_index | test | def _handle_non_existant_index(cls):
"""
Handle and check that some configuration index exists.
"""
try:
# We try to call the http code.
PyFunceble.INTERN["http_code"]
except KeyError:
# If it is not found.
# We initiate an empty http code.
PyFunceble.INTERN["http_code"] = "*" * 3
try:
# We try to call the referer.
PyFunceble.INTERN["referer"]
except KeyError:
# If it is not found.
# We initate an `Unknown` referer.
PyFunceble.INTERN["referer"] = "Unknown" | python | {
"resource": ""
} |
q270345 | Generate._analytic_host_file_directory | test | def _analytic_host_file_directory(self):
"""
Return the analytic directory to write depending of the matched
status.
"""
# We construct the path to the analytic directory.
output_dir = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["analytic"]["directories"]["parent"]
)
if self.domain_status.lower() in PyFunceble.STATUS["list"]["potentially_up"]:
# The status is in the list of analytic up status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"][
"potentially_up"
]
elif (
self.domain_status.lower() in PyFunceble.STATUS["list"]["potentially_down"]
):
# The status is in the list of analytic down status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"][
"potentially_down"
]
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["suspicious"]:
# The status is in the list of analytic suspicious status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"]["suspicious"]
else:
# The status is not in the list of analytic down or up status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"]["up"]
return output_dir | python | {
"resource": ""
} |
q270346 | Generate.unified_file | test | def unified_file(self):
"""
Generate unified file. Understand by that that we use an unified table
instead of a separate table for each status which could result into a
misunderstanding.
"""
if (
"file_to_test" in PyFunceble.INTERN
and PyFunceble.INTERN["file_to_test"]
and PyFunceble.CONFIGURATION["unified"]
):
# * We are not testing as an imported module.
# and
# * The unified file generation is activated.
# We construct the path of the unified file.
output = (
self.output_parent_dir + PyFunceble.OUTPUTS["default_files"]["results"]
)
if PyFunceble.CONFIGURATION["less"]:
# We have to print less information.
if PyFunceble.HTTP_CODE["active"]:
# The http status code request is activated.
# We construct what we have to print.
to_print = [
self.tested,
self.domain_status,
PyFunceble.INTERN["http_code"],
]
else:
# The http status code request is not activated.
# We construct what we have to print.
to_print = [self.tested, self.domain_status, self.source]
# And we print the informations on file.
Prints(to_print, "Less", output, True).data()
else:
# The unified file generation is not activated.
# We construct what we have to print.
to_print = [
self.tested,
self.domain_status,
self.expiration_date,
self.source,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
]
# And we print the information on file.
Prints(to_print, "Generic_File", output, True).data() | python | {
"resource": ""
} |
q270347 | Generate.status_file | test | def status_file(self): # pylint: disable=inconsistent-return-statements
"""
Generate a file according to the domain status.
"""
if "file_to_test" in PyFunceble.INTERN:
# We are not testing as an imported module.
# We generate the hosts file.
Generate(self.domain_status, self.source, self.expiration_date).info_files()
# We are testing a file content.
# We increase the percentage count.
Percentage(self.domain_status).count()
# We print on screen if needed.
self._prints_status_screen()
if self._do_not_produce_file():
return None
if (
not PyFunceble.CONFIGURATION["no_files"]
and PyFunceble.CONFIGURATION["split"]
):
# * The file non-generation of file is globaly deactivated.
# and
# * We have to split the outputs.
# We print or generate the files.
self._prints_status_file()
else:
# * The file non-generation of file is globaly activated.
# or
# * We do not have to split the outputs.
# We print or generate the unified files.
self.unified_file() | python | {
"resource": ""
} |
q270348 | Generate._do_not_produce_file | test | def _do_not_produce_file(self):
"""
Check if we are allowed to produce a file based from the given
information.
:return:
The state of the production.
True: We do not produce file.
False: We do produce file.
:rtype: bool
"""
if (
Inactive().is_present()
and self.domain_status
in [
PyFunceble.STATUS["official"]["down"],
PyFunceble.STATUS["official"]["invalid"],
]
and PyFunceble.INTERN["to_test"]
not in PyFunceble.INTERN["extracted_list_to_test"]
):
return True
return False | python | {
"resource": ""
} |
q270349 | PublicSuffix._extensions | test | def _extensions(self, line):
"""
Extract the extension from the given line.
:param line: The line from the official public suffix repository.
:type line: str
"""
# We strip the parsed line.
line = line.strip()
if not line.startswith("//") and "." in line:
# * The parsed line is not a commented line.
# and
# * There is a point in the parsed line.
line = line.encode("idna").decode("utf-8")
if line.startswith("*."):
# The parsed line start with `*.`.
# We remove the first two characters.
line = line[2:]
# We we split the points and we get the last element.
# Explanation: The idea behind this action is to
# always get the extension.
extension = line.split(".")[-1]
if extension in self.public_suffix_db:
# The extension is alrady in our database.
# We update the content of the 1st level TDL with
# the content of the suffix.
# In between, we format so that we ensure that there is no
# duplicate in the database index content.
self.public_suffix_db[extension] = List(
self.public_suffix_db[extension] + [line]
).format()
else:
# The extension is not already in our database.
# We append the currently formatted extension and the line content.
self.public_suffix_db.update({extension: [line]}) | python | {
"resource": ""
} |
q270350 | PublicSuffix.load | test | def load(self):
"""
Load the public suffix database into the system.
"""
if not PyFunceble.INTERN["psl_db"]:
# The public database was not already loaded.
# * We read, convert to dict and return the file content.
# and
# * We fill/create the database.
PyFunceble.INTERN["psl_db"] = Dict().from_json(
File(self.destination).read()
) | python | {
"resource": ""
} |
q270351 | Sort.standard | test | def standard(cls, element):
"""
Implement the standard and alphabetical sorting.
:param element: The element we are currently reading.
:type element: str
:return: The formatted element.
:rtype: str
"""
# We remove all special characters and return the formatted string.
return (
Regex(element, cls.regex_replace, replace_with="@funilrys")
.replace()
.replace("@funilrys", "")
) | python | {
"resource": ""
} |
q270352 | Sort.hierarchical | test | def hierarchical(cls, element):
"""
The idea behind this method is to sort a list of domain hierarchicaly.
:param element: The element we are currently reading.
:type element: str
:return: The formatted element.
:rtype: str
.. note::
For a domain like :code:`aaa.bbb.ccc.tdl`.
A normal sorting is done in the following order:
1. :code:`aaa`
2. :code:`bbb`
3. :code:`ccc`
4. :code:`tdl`
This method allow the sorting to be done in the following order:
1. :code:`tdl`
2. :code:`ccc`
3. :code:`bbb`
4. :code:`aaa`
"""
# We initiate a variable which will save the element to sort without
# the extension.
to_sort = ""
# We initiate a variable which will save the full extension.
full_extension = ""
# We convert the parsed element to lower case.
element = element.lower()
# We try to get the url base.
url_base = Check().is_url_valid(element, return_base=True)
if not isinstance(url_base, str):
# The url base is not found.
if "." in element:
# There is point in the parsed element.
# We get the position of the first letter of the extension.
extension_index = element.rindex(".") + 1
# We get the extension from the position of the first letter
# of the extension.
extension = element[extension_index:]
if extension in PyFunceble.INTERN["psl_db"]:
# The extension is in the public suffix database.
for suffix in PyFunceble.INTERN["psl_db"][extension]:
# We loop through the list of suffix of the extracted extension.
# We suffix the sufix with a point.
formatted_suffix = "." + suffix
if element.endswith(formatted_suffix):
# The elements ends with the suffix.
# We get the position of the first character of the suffix in
# the parsed element.
suffix_index = element.rindex(formatted_suffix)
# We update the to_sort variable with the element without the suffix.
to_sort = element[:suffix_index]
# We replace the full extension with the currently read suffix.
full_extension = suffix
# We break the loop, we got what we wanted.
break
if not full_extension:
# The full extension is empty.
# We initiate it with the extension.
full_extension = element[extension_index:]
# We update the to_sort variable with the element without the extension.
to_sort = element[: extension_index - 1]
# We append a point to the full extension because the point has to be
# at the end and not at the begining of the extension.
# To understand: Imagine a miror.
full_extension += "."
# We reverse the to_sort string.
tros_ot = to_sort[::-1]
if "." in tros_ot:
# There is a point in the reversed string.
# We prefix the full extension with the top level
# domain name.
full_extension = (
tros_ot[: tros_ot.index(".")][::-1] + "." + full_extension
)
# We remove the tor level domain from the rest of
# the reversed string.
tros_ot = tros_ot[tros_ot.index(".") + 1 :]
# * We reverse each level of the parsed element.
# and
# * We glue each level of the parsed element with each other.
#
# Note: after this, there is no point anymore.
reversion = full_extension + ".".join(
[x[::-1] for x in tros_ot.split(".")]
)
# We remove all special characters and return the formatted string.
return (
Regex(reversion, cls.regex_replace, replace_with="@funilrys")
.replace()
.replace("@funilrys", "")
)
# We remove all special characters and return the formatted string.
return (
Regex(
to_sort + full_extension,
cls.regex_replace,
replace_with="@funilrys",
)
.replace()
.replace("@funilrys", "")
)
# There is no point in the parsed element.
# We return the parsed element.
return element
# The url base is found.
# We get the position of the element.
protocol_position = element.rindex(url_base)
# We extract the protocol from the element position.
protocol = element[:protocol_position]
# We return the output of this method but with the url base instead of the full url.
return protocol + cls.hierarchical(url_base) | python | {
"resource": ""
} |
q270353 | IANA.load | test | def load(self):
"""
Initiate the IANA database if it is not the case.
"""
if "iana_db" not in PyFunceble.INTERN or not PyFunceble.INTERN["iana_db"]:
# The global database is empty, None or does not exist.
# We update it with the database content.
PyFunceble.INTERN["iana_db"] = self.iana_db | python | {
"resource": ""
} |
q270354 | IANA._referer | test | def _referer(self, extension):
"""
Return the referer for the given extension.
:param extension: A valid domain extension.
:type extension: str
:return: The whois server to use to get the WHOIS record.
:rtype: str
"""
# We get the a copy of the page.
iana_record = self.lookup.whois(
PyFunceble.CONFIGURATION["iana_whois_server"], "hello.%s" % extension
)
if iana_record and "refer" in iana_record:
# The record is not empty.
# We initiate a regex which will extract the referer.
regex_referer = r"(?s)refer\:\s+([a-zA-Z0-9._-]+)\n"
# We try to extract the referer.
matched = Regex(
iana_record, regex_referer, return_data=True, group=1
).match()
if matched:
# The referer was extracted successfully.
# We return the matched referer.
return matched
# * The referer was not extracted successfully.
# or
# * The iana record is empty.
if extension in self.manual_server:
# The extension is in the list of manual entries.
# We return the server which we set manually.
return self.manual_server[extension]
# We return None because we weren't able to get the server to call for
# the given extension.
return None | python | {
"resource": ""
} |
q270355 | IANA._extensions | test | def _extensions(self):
"""
Extract the extention from the given block.
Plus get its referer.
"""
upstream_lines = (
Download(self.iana_url, return_data=True)
.text()
.split('<span class="domain tld">')
)
# We extract the different extension from the currently readed line.
regex_valid_extension = r"(/domains/root/db/)(.*)(\.html)"
for block in upstream_lines:
if "/domains/root/db/" in block:
# The link is in the line.
# We try to extract the extension.
matched = Regex(
block, regex_valid_extension, return_data=True, rematch=True
).match()[1]
if matched:
# The extraction is not empty or None.
# We get the referer.
referer = self._referer(matched)
# We yield the matched extension and its referer.
yield (matched, referer) | python | {
"resource": ""
} |
q270356 | IANA.update | test | def update(self):
"""
Update the content of the `iana-domains-db` file.
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# * The quiet mode is not activated.
# We print on screen what we are doing.
print("Update of iana-domains-db", end=" ")
# We loop through the line of the iana website.
for extension, referer in self._extensions():
if extension not in self.iana_db or self.iana_db[extension] != referer:
# We add the extension to the databae.
self.iana_db[extension] = referer
# We save the content of the constructed database.
Dict(self.iana_db).to_json(self.destination)
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
# We indicate that the work is done without any issue.
print(PyFunceble.INTERN["done"]) | python | {
"resource": ""
} |
q270357 | Mining.mine | test | def mine(self): # pragma: no cover
"""
Search for domain or URL related to the original URL or domain.
:return: The mined domains or URL.
:rtype: dict
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
try:
# We get the history.
history = PyFunceble.requests.get(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
headers=self.headers,
).history
# We initiate a dictionnary which will save the
# list of mined links.
mined = {self.to_get_bare: []}
for element in history:
# We loop through the history.
# We update the element.
element = element.url
if PyFunceble.INTERN["to_test_type"] == "url":
# We are testing a full url.
# We get the element to append.
to_append = Check().is_url_valid(element, return_base=False)
elif PyFunceble.INTERN["to_test_type"] == "domain":
# We are testing a domain.
# We get the element to append.
to_append = Check().is_url_valid(element, return_base=True)
else:
raise Exception("Unknown tested.")
if to_append:
# There is something to append.
if to_append.endswith(":80"):
# The port is present.
# We get rid of it.
to_append = to_append[:-3]
if to_append != self.to_get_bare:
# The element to append is different as
# the element we are globally testing.
# We append the element to append to the
# list of mined links.
mined[self.to_get_bare].append(to_append)
if mined[self.to_get_bare]:
# There is something in the list of mined links.
# We return the whole element.
return mined
# There is nothing in the list of mined links.
# We return None.
return None
except (
PyFunceble.requests.ConnectionError,
PyFunceble.requests.exceptions.Timeout,
PyFunceble.requests.exceptions.InvalidURL,
PyFunceble.socket.timeout,
urllib3_exceptions.InvalidHeader,
UnicodeDecodeError, # The probability that this happend in production is minimal.
):
# Something went wrong.
# We return None.
return None
return None | python | {
"resource": ""
} |
q270358 | Mining._retrieve | test | def _retrieve(self):
"""
Retrieve the mining informations.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if "mined" not in PyFunceble.INTERN:
PyFunceble.INTERN["mined"] = {}
if PyFunceble.path.isfile(self.file):
# Our backup file exist.
# We return the information from our backup.
data = Dict().from_json(File(self.file).read())
# We clean the empty elements.
for file_path in data:
PyFunceble.INTERN["mined"][file_path] = {}
for element in data[file_path]:
if data[file_path][element]:
PyFunceble.INTERN["mined"][file_path][element] = data[
file_path
][element]
return
# * The mining is not activated.
# or
# * Our backup file does not exist.
# We return nothing.
PyFunceble.INTERN["mined"] = {}
return | python | {
"resource": ""
} |
q270359 | Mining._backup | test | def _backup(self):
"""
Backup the mined informations.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
# We backup our mined informations.
Dict(PyFunceble.INTERN["mined"]).to_json(self.file) | python | {
"resource": ""
} |
q270360 | Mining._add | test | def _add(self, to_add):
"""
Add the currently mined information to the
mined "database".
:param to_add: The element to add.
:type to_add: dict
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if PyFunceble.INTERN["file_to_test"] not in PyFunceble.INTERN["mined"]:
# Our tested file path is not into our mined database.
# We initiate it.
PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]] = {}
for element in to_add:
# We loop through the element to add.
if (
element
in PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]]
):
# The element is already into the tested file path database.
# We extent it with our element to add.
PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]][
element
].extend(to_add[element])
else:
# The element is already into the tested file path database.
# We initiate it.
PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]][
element
] = to_add[element]
# We format the added information in order to avoid duplicate.
PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]][
element
] = List(
PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]][
element
]
).format()
# We backup everything.
self._backup() | python | {
"resource": ""
} |
q270361 | Mining.remove | test | def remove(self):
"""
Remove the currently tested element from the mining
data.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["mined"]:
# The currently tested file is in our mined database.
for element in PyFunceble.INTERN["mined"][
PyFunceble.INTERN["file_to_test"]
]:
# We loop through the mined index.
if (
self.to_get_bare
in PyFunceble.INTERN["mined"][
PyFunceble.INTERN["file_to_test"]
][element]
):
# The currently read element content.
# We remove the globally tested element from the currently
# read element content.
PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]][
element
].remove(self.to_get_bare)
# We backup everything.
self._backup() | python | {
"resource": ""
} |
q270362 | Mining.list_of_mined | test | def list_of_mined(cls):
"""
Provide the list of mined so they can be added to the list
queue.
:return: The list of mined domains or URL.
:rtype: list
"""
# We initiate a variable which will return the result.
result = []
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["mined"]:
# The file we are testing is into our mining database.
for element in PyFunceble.INTERN["mined"][
PyFunceble.INTERN["file_to_test"]
]:
# We loop through the list of index of the file we are testing.
# We append the element of the currently read index to our result.
result.extend(
PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]][
element
]
)
# We format our result.
result = List(result).format()
# We return the result.
return result | python | {
"resource": ""
} |
q270363 | Mining.process | test | def process(self): # pragma: no cover
"""
Process the logic and structuration of the mining database.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
# We load the mining logic.
mined = self.mine()
if mined:
# The mined data is not empty or None.
# We add the mined data to the global database.
self._add(mined)
# And we finally backup everything.
self._backup() | python | {
"resource": ""
} |
q270364 | Logs._get_content | test | def _get_content(cls, file):
"""
Get and return the content of the given log file.
:param file: The file we have to get the content from.
:type file: str
:return The content of the given file.
:rtype: dict
"""
if PyFunceble.path.isfile(file):
return Dict().from_json(File(file).read())
return {} | python | {
"resource": ""
} |
q270365 | Logs._write_content | test | def _write_content(cls, content, file):
"""
Write the content into the given file.
:param content: The dict to write.
:type content: dict
:param file: The file to write.
:type file: str
"""
if not PyFunceble.CONFIGURATION["no_files"]:
if not isinstance(content, dict):
content = {}
Dict(content).to_json(file) | python | {
"resource": ""
} |
q270366 | Logs.whois | test | def whois(self, record):
"""
Logs the WHOIS record if needed.
:param record: The record to log.
:type record: str
"""
if PyFunceble.CONFIGURATION["debug"] and PyFunceble.CONFIGURATION["logs"]:
# The debug and the logs subsystem are activated.
if PyFunceble.INTERN["referer"]:
referer = PyFunceble.INTERN["referer"]
else:
referer = None
to_write = {
self.current_time: {
"domain": PyFunceble.INTERN["to_test"],
"record": record,
"referer": referer,
}
}
if self.output:
output = self.output
else:
output = PyFunceble.OUTPUT_DIRECTORY
output += PyFunceble.OUTPUTS["parent_directory"]
output += PyFunceble.OUTPUTS["logs"]["directories"]["parent"]
output += PyFunceble.OUTPUTS["logs"]["filenames"]["whois"]
current_content = self._get_content(output)
current_content.update(to_write)
self._write_content(current_content, output) | python | {
"resource": ""
} |
q270367 | Logs.expiration_date | test | def expiration_date(self, extracted):
"""
Logs the extracted expiration date.
:param extracted: The extracted expiration date (from WHOIS record).
:type extracted: str
"""
if PyFunceble.CONFIGURATION["logs"]:
# The logs subsystem is activated.
if PyFunceble.INTERN["referer"]:
referer = PyFunceble.INTERN["referer"]
else:
referer = None
to_write = {
self.current_time: {
"domain": PyFunceble.INTERN["to_test"],
"expiration_date": extracted,
"whois_server": referer,
}
}
if self.output:
output = self.output
else:
output = PyFunceble.OUTPUT_DIRECTORY
output += PyFunceble.OUTPUTS["parent_directory"]
output += PyFunceble.OUTPUTS["logs"]["directories"]["parent"]
output += PyFunceble.OUTPUTS["logs"]["filenames"]["date_format"]
current_content = self._get_content(output)
current_content.update(to_write)
self._write_content(current_content, output)
if PyFunceble.CONFIGURATION["share_logs"]:
# The logs sharing is activated.
# And we share the logs with the api.
PyFunceble.requests.post(
PyFunceble.LINKS["api_date_format"],
data=to_write[self.current_time],
) | python | {
"resource": ""
} |
q270368 | Logs.referer_not_found | test | def referer_not_found(self, extension):
"""
Logs the case that the referer was not found.
:param extension: The extension of the domain we are testing.
:type extension: str
"""
if PyFunceble.CONFIGURATION["logs"]:
# The logs subsystem is activated.
to_write = {
self.current_time: {
"domain": PyFunceble.INTERN["to_test"],
"extension": extension,
}
}
if self.output:
output = self.output
else:
output = PyFunceble.OUTPUT_DIRECTORY
output += PyFunceble.OUTPUTS["parent_directory"]
output += PyFunceble.OUTPUTS["logs"]["directories"]["parent"]
output += PyFunceble.OUTPUTS["logs"]["filenames"]["no_referer"]
current_content = self._get_content(output)
current_content.update(to_write)
self._write_content(current_content, output)
if PyFunceble.CONFIGURATION["share_logs"]:
# The logs sharing is activated.
# And we share the logs with the api.
PyFunceble.requests.post(
PyFunceble.LINKS["api_no_referer"], data=to_write[self.current_time]
) | python | {
"resource": ""
} |
q270369 | Prints._before_header | test | def _before_header(self):
"""
Print informations about PyFunceble and the date of generation of a file
into a given path, if doesn't exist.
"""
if (
not PyFunceble.CONFIGURATION["no_files"]
and self.output
and not PyFunceble.path.isfile(self.output)
):
# * We are allowed to generate files.
# and
# * And output is given.
# and
# * The given output does not exist.
# We initiate the information about what generated the file.
link = "# File generated by %s\n" % PyFunceble.LINKS["repo"]
# We initiate the information about the generation date of this file.
date_of_generation = (
"# Date of generation: %s \n\n" % PyFunceble.CURRENT_TIME
)
# We initiate a variable which will save the list of
# templates which have to meet in order to write the before
# header informations.
authorized_templates = [
"Generic_File",
PyFunceble.STATUS["official"]["up"],
PyFunceble.STATUS["official"]["down"],
PyFunceble.STATUS["official"]["invalid"],
PyFunceble.STATUS["official"]["valid"],
"Less",
]
if self.template in authorized_templates:
# The current header is in our list of authorized templated.
# We get the header.
header = (
self._header_constructor(self.currently_used_header, None)[0] + "\n"
)
try:
# We try to print the link, the date of generation and the header in the
# given file.
File(self.output).write(link + date_of_generation + header)
except UnboundLocalError:
# We don't have any header.
# We print the link and the date in the given file.
File(self.output).write(link + date_of_generation) | python | {
"resource": ""
} |
q270370 | Prints._header_constructor | test | 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
:param header_separator:
The separator to use between the table header and our data.
:type header_separator: str
:param colomn_separator: The separator to use between each colomns.
:type colomn_separator: str
:return: The data to print in a list format.
:rtype: list
"""
# We initiate a variable which will save the header data.
header_data = []
# We initiate a variable which will save the header sizes.
header_size = ""
# We initiate the glue to set before the size.
before_size = "%-"
# We initiate the glue to set after the size.
after_size = "s"
if header_separator:
# The header separator is not empty.
# We initiate a variable which will save the list of
# separator data.
header_separator_data = []
# We get the length of the data to print.
length_data_to_print = len(data_to_print) - 1
# We initiate an iterator.
i = 0
for data in data_to_print:
# We loop through the list of data.
# We get the size of the currently read data.
size = data_to_print[data]
# We append the data to the header data list.
header_data.append(data)
# We construct the header size.
# Note: our header size is formatted line %s-sizes
# (the s at the end is part of the formatting.)
header_size += before_size + str(size) + after_size
if i < length_data_to_print:
# The iterator is less than the length of data to print.
# We append the the colomn separator to the header size.
header_size += column_separator
if header_separator:
# The header separator is given.
# We append the right size of separator to the list of
# separator data.
header_separator_data.append(header_separator * size)
# We increase the iterator.
i += 1
if header_separator:
# The header separator is given.
return [
# We return the formatted header (like we will do with print('%s' % 'hello'))
header_size % tuple(header_data),
# We return the formatted header separator.
header_size % tuple(header_separator_data),
]
# The header separator is not given.
# We return the formetted header.
return [header_size % tuple(header_data)] | python | {
"resource": ""
} |
q270371 | Prints.header | test | 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 not.
:type do_not_print: bool
"""
if (
not PyFunceble.CONFIGURATION["header_printed"]
or self.template == "Percentage"
or do_not_print
):
# * The header has not been already printed.
# or
# * The template is the `Percentage template`.
# or
# * We are authorized to print something.
if (
self.template.lower() in PyFunceble.STATUS["list"]["generic"]
or self.template == "Generic_File"
):
# * The template is into the list of generic status.
# or
# * The template is equal to `Generic_File`.
# The data to print is the Generic header.
to_print = self.headers["Generic"]
if (
self.template.lower() in PyFunceble.STATUS["list"]["generic"]
and PyFunceble.HTTP_CODE["active"]
):
# * The template is in the list of generic status.
# and
# * the http status code extraction is activated.
# We remove the Analyze Date colomn from the data to print.
to_print = Dict(to_print).remove_key("Analyze Date")
elif self.template.lower() in PyFunceble.STATUS["list"]["up"]:
# The template is in the list of up status.
# We informations to print is the up header.
to_print = self.headers[PyFunceble.STATUS["official"]["up"]]
elif self.template.lower() in PyFunceble.STATUS["list"]["valid"]:
# The template is in the list of valid status.
# We informations to print is the valid header.
to_print = self.headers[PyFunceble.STATUS["official"]["valid"]]
elif self.template.lower() in PyFunceble.STATUS["list"]["down"]:
# The template is in the list of down status.
# We informations to print is the down header.
to_print = self.headers[PyFunceble.STATUS["official"]["down"]]
elif self.template.lower() in PyFunceble.STATUS["list"]["invalid"]:
# The template is in the list of invalid status.
# We informations to print is the invalid header.
to_print = self.headers[PyFunceble.STATUS["official"]["invalid"]]
elif (
self.template == "Less"
or self.template == "Percentage"
or self.template == "HTTP"
): # pylint: disable=line-too-long
# * The template is equal to `Less`.
# or
# * The template is equal to `Percentage`.
# or
# * The template is equal to `HTTP`.
# We get the header with the help of the template name.
to_print = self.headers[self.template]
if self.template == "Less" and not PyFunceble.HTTP_CODE["active"]:
# * The template is equal to `Less`.
# and
# * The http status code extraction is deactivated.
# We append the source index to the header.
to_print["Source"] = 10
if not PyFunceble.HTTP_CODE["active"]:
# * The http status code extraction is deactivated.
# We remove the HTTP Code index from the data to print.
to_print = Dict(to_print).remove_key("HTTP Code")
# We update the currently used header.
self.currently_used_header = to_print
if not do_not_print:
# We are not authorized to print anything.
# We generate the before header.
self._before_header()
for formatted_template in self._header_constructor(to_print):
# We loop through the formatted template.
if not self.only_on_file:
# We do not have to print only on file.
# We print on screen the formatted header template.
print(formatted_template)
if not PyFunceble.CONFIGURATION["no_files"] and self.output:
# An output destination is given.
# We write the file with the formatted header template.
File(self.output).write(formatted_template + "\n") | python | {
"resource": ""
} |
q270372 | Prints._data_constructor | test | 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 size to print it.
:rtype: OrderedDict
:raises:
:code:`Exception`
If the data and the size does not have the same length.
"""
# We initiate a variable which will save what we are going to
# return.
result = PyFunceble.OrderedDict()
if len(self.data_to_print) == len(size):
# The length of the data to print is equal to the length of the given size.
for i in range(len(self.data_to_print)):
# We loop until our iterator is less or equal to the length of the data
# to print.
# We initiate the result index and its size.
result[self.data_to_print[i]] = size[i]
else:
# This should never happend. If it's happens then there is something
# wrong from the inputed data.
raise Exception(
"Inputed: " + str(len(self.data_to_print)) + "; Size: " + str(len(size))
)
# We return the constructed result.
return result | python | {
"resource": ""
} |
q270373 | Prints._size_from_header | test | 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
"""
# We initiate the result we are going to return.
result = []
for data in header:
# We lopp through the header.
# And we append the size to our result.
result.append(header[data])
# We return the result.
return result | python | {
"resource": ""
} |
q270374 | Prints._colorify | test | 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 the coloration.
if (
self.data_to_print[1].lower() in PyFunceble.STATUS["list"]["up"]
or self.data_to_print[1].lower() in PyFunceble.STATUS["list"]["valid"]
):
# The status is in the list of up status.
# We print the data with a green background.
data = PyFunceble.Fore.BLACK + PyFunceble.Back.GREEN + data
elif self.data_to_print[1].lower() in PyFunceble.STATUS["list"]["down"]:
# The status is in the list of down status.
# We print the data with a red background.
data = PyFunceble.Fore.BLACK + PyFunceble.Back.RED + data
else:
# The status is not in the list of up and down status.
# We print the data with a cyan background.
data = PyFunceble.Fore.BLACK + PyFunceble.Back.CYAN + data
# We return the data.
return data | python | {
"resource": ""
} |
q270375 | Prints._json_print | test | 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 of the output.
content = Dict().from_json(File(self.output).read())
if isinstance(content, list):
# The content is a list.
# We extend the content with our data to print.
content.extend(self.data_to_print)
# We format our list.
content = List(content).custom_format(Sort.standard)
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is activated.
# We format our content hierarchicaly
content = List(content).custom_format(Sort.hierarchical)
# We finally save our content into the file.
Dict(content).to_json(self.output)
else:
# The content is not a list.
# We raise an exception.
raise Exception("Output not correctly formatted.")
else:
# The given output does not already exist.
# We save our data to print into the output.
#
# Note: We do not have to take care if self.data_to_print is a list
# formatted or not because this method should not be called if it is
# not the case.
Dict(self.data_to_print).to_json(self.output)
else:
# The given output is empty.
# We raise an exception.
raise Exception("Empty output given.") | python | {
"resource": ""
} |
q270376 | Prints.data | test | 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):
# The data to print is a list.
# We initiate the data we are going to print.
to_print = {}
# We initiate the size we are going to print.
to_print_size = []
# We initiate a variable which will list the list of
# alone case.
alone_cases = ["Percentage", "HTTP"]
# we initiate a variable which will list the list of
# template which does not need a header.
without_header = ["FullHosts", "PlainDomain"]
if self.template.lower() == "json":
# The template is the json template.
if not PyFunceble.CONFIGURATION["no_files"] and self.output:
# * We are allowed to generate file.
# and
# * The given output is not empty.
# We print the json file.
return self._json_print()
# We return nothing.
return None
if self.template not in alone_cases and self.template not in without_header:
# * The template is not in the list of alone case.
# and
# * THe template is not in the list of template without header.
# We get the template we should use.
# Note: We basically only need the self.currently_used_header to be filled.
self.header(True)
# And we get the size from the header.
to_print_size = self._size_from_header(self.currently_used_header)
elif self.template in without_header:
# The template is in the list of template which does not need a header.
for data in self.data_to_print:
# We loop through the list of data to print.
# And we construct the (spacement) size of the data to print.
to_print_size.append(str(len(data)))
else:
# We get the size from the given template name.
to_print_size = self._size_from_header(self.headers[self.template])
# We construct and format the data to print.
to_print = self._data_constructor(to_print_size)
# We print the before header section.
self._before_header()
for data in self._header_constructor(to_print, False):
# We loop through the formatted data.
if self.template.lower() in PyFunceble.STATUS["list"][
"generic"
] or self.template in ["Less", "Percentage"]:
# * The template is in the list of generic status.
# or
# * The template is in a specific list.
if not self.only_on_file:
# We are authorized to print on screen.
# We colorify the data to print.
colorified_data = self._colorify(data)
# And we print the data.
print(colorified_data)
if not PyFunceble.CONFIGURATION["no_files"] and self.output:
# * We are authorized to print on any file.
# and
# * The output is given.
# We write our data into the printed file.
File(self.output).write(data + "\n")
else:
# This should never happend. If it's happens then there's a big issue
# around data_to_print.
raise Exception("Please review Prints().data()") | python | {
"resource": ""
} |
q270377 | ExecutionTime._save | test | 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["logs"]
and "file_to_test" in PyFunceble.INTERN
and PyFunceble.INTERN["file_to_test"]
):
# * We are authorized to work.
# and
# * The generation of logs is activated.
# and
# * We are not testing as an imported module.
# We set the location of the file we are working with.
self.file = (
PyFunceble.OUTPUT_DIRECTORY
+ PyFunceble.OUTPUTS["parent_directory"]
+ PyFunceble.OUTPUTS["logs"]["directories"]["parent"]
+ PyFunceble.OUTPUTS["logs"]["filenames"]["execution_time"]
)
if PyFunceble.path.isfile(self.file):
# The file we are working with exist.
# We get its content so we can directly work with it.
content = Dict().from_json(File(self.file).read())
else:
# The file we are working with does not exist.
# We generate a dummy content.
content = {}
if self.action == "start":
# The action is equal to `start`.
if "final_total" in content and content["final_total"]:
# The final total index exist.
# We delete it.
del content["final_total"]
if "data" in content:
# The data index exist.
# We append the current start time inside it at
# a new sublist.
content["data"].append([PyFunceble.INTERN["start"]])
else:
# The data index does not exist.
# We create the index along with the current start time.
content["data"] = [[PyFunceble.INTERN["start"]]]
elif self.action == "stop":
# The action is equal to `stop`.
try:
# We try to work with the data index.
# We append the end time at the end of the last element
# of data.
#
# Note: It is at the end because we should have as first
# the star time.
content["data"][-1].append(PyFunceble.INTERN["end"])
# We get the start time.
start = content["data"][0][0]
# We get the end time.
end = content["data"][-1][-1]
# We calculate the execution time of the test.
content["current_total"] = self.format_execution_time(start, end)
if last:
# We are at the very end of the file testing.
# We initiate the global execution time.
content["final_total"] = content["current_total"]
# We inform the user about the global execution time.
print(
PyFunceble.Fore.MAGENTA
+ PyFunceble.Style.BRIGHT
+ "Global execution time: "
+ content["final_total"]
)
except KeyError:
# It is not possible to work with the data index because
# it does not exist.
# We ignore the problem.
pass
try:
# We try to save the whole data at its final location.
Dict(content).to_json(self.file)
except FileNotFoundError:
# The directory was not found.
# We construct the output directory
DirectoryStructure()
# And we retry to save the whole data at its final location.
Dict(content).to_json(self.file) | python | {
"resource": ""
} |
q270378 | ExecutionTime._calculate | test | 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.
* :code:`days`
* :code:`hours`
* :code:`minutes`
* :code:`seconds`
as index.
:rtype: dict
"""
if start and end:
# The start and end time is explicitly given.
# We get the difference between the ending and the starting time.
time_difference = int(end) - int(start)
else:
# The start and end time is not explicitly given.
# We get the difference between the ending and the starting time.
time_difference = PyFunceble.INTERN["end"] - PyFunceble.INTERN["start"]
# We initiate an OrderedDict.
# Indeed, we use an ordered dict because we want the structuration and the
# order to stay always the same.
# As a dictionnary is always unordered, we can use it. Otherwise the time will
# not be shown correctly.
data = PyFunceble.OrderedDict()
# We calculate and append the day to our data.
data["days"] = str(time_difference // (24 * 60 * 60)).zfill(2)
# We calculate and append the hours to our data.
data["hours"] = str((time_difference // (60 * 60)) % 24).zfill(2)
# We calculate and append the minutes to our data.
data["minutes"] = str((time_difference % 3600) // 60).zfill(2)
# We calculate and append the minutes to our data.
data["seconds"] = str(time_difference % 60).zfill(2)
# We finaly return our data.
return data | python | {
"resource": ""
} |
q270379 | ExecutionTime.format_execution_time | test | 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.
:rtype: str
"""
# We return the formatted execution time.
return ":".join(list(self._calculate(start, end).values())) | python | {
"resource": ""
} |
q270380 | Clean.file_to_delete | test | 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 cover
# For safety, if it does not ends with the directory separator, we append it
# to its end.
directory += PyFunceble.directory_separator
# We initiate a variable which will save the list of file to delete.
result = []
for root, _, files in PyFunceble.walk(directory):
# We walk in the directory and get all files and sub-directories.
for file in files:
# If there is files in the current sub-directory, we loop
# through the list of files.
if file not in [".gitignore", ".keep"]:
# The file is not into our list of file we do not have to delete.
if root.endswith(PyFunceble.directory_separator):
# The root ends with the directory separator.
# We construct the path and append the full path to the result.
result.append(root + file)
else:
# The root directory does not ends with the directory separator.
# We construct the path by appending the directory separator
# between the root and the filename and append the full path to
# the result.
result.append(
root + PyFunceble.directory_separator + file
) # pragma: no cover
# We return our list of file to delete.
return result | python | {
"resource": ""
} |
q270381 | Clean.databases_to_delete | test | 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_structure file.
result.append(
directory
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["dir_structure"]
)
# We append the iana file.
result.append(
directory + PyFunceble.CONFIGURATION["outputs"]["default_files"]["iana"]
)
# We append the public suffix file.
result.append(
directory
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["public_suffix"]
)
# We append the inactive database file.
result.append(
directory
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["inactive_db"]
)
# We append the mining database file.
result.append(
directory + PyFunceble.CONFIGURATION["outputs"]["default_files"]["mining"]
)
# We append the whois database file.
result.append(
directory + PyFunceble.CONFIGURATION["outputs"]["default_files"]["whois_db"]
)
return result | python | {
"resource": ""
} |
q270382 | Clean.almost_everything | test | 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.
to_delete = self.file_to_delete()
if clean_all: # pragma: no cover
to_delete.extend(self.databases_to_delete())
for file in to_delete:
# We loop through the list of file to delete.
# And we delete the currently read file.
File(file).delete()
if clean_all: # pragma: no cover
Load(PyFunceble.CURRENT_DIRECTORY) | python | {
"resource": ""
} |
q270383 | Hash._hash_file | test | 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(self.path, "rb") as file:
# We open an read the parsed path.
# We read the content.
content = file.read()
# We parse the content to the hash algorithm.
hash_data.update(content)
# And we extract and return the hash.
return hash_data.hexdigest() | python | {
"resource": ""
} |
q270384 | Hash._hash_data | test | 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.data)
# And we extract and return the hash.
return hash_data.hexdigest() | python | {
"resource": ""
} |
q270385 | Hash.get | test | 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
# * The parsed algorithm is in the list of valid algorithms.
if self.algorithm == "all":
# The parsed algorithm is `all`.
# We remove `all` (the first element of the list) from
# the list of valid algorithms because we are going to
# loop through the list of valid algorithms.
del self.valid_algorithms[0]
for algo in self.valid_algorithms:
# We loop through the list of valid algorithms.
if self.path and path.isfile(self.path):
# The file path exist.
# We save the hash into the result variable.
result[algo] = self._hash_file(algo)
elif self.data:
# * The path does not exist.
# and
# * The given data is not empty.
# We save the hash into the result variable.
result[algo] = self._hash_data(algo)
else: # pragma: no cover
# All other case are met.
# We return None.
return None
else:
# The parsed algorithm is a specific one.
if self.path and path.isfile(self.path):
# The file path exist.
# We save the hash into the result variable.
result[self.algorithm] = self._hash_file(self.algorithm)
elif self.data:
# * The path does not exist.
# and
# * The given data is not empty.
# We save the hash into the result variable.
result[self.algorithm] = self._hash_data(self.algorithm)
else:
# All the other case are met.
# We return None.
return None
else: # pragma: no cover
# The parsed algorithm is not in the list of valid algorithms.
return None
if self.algorithm != "all" and self.only_hash:
# * The parsed algorithm is not equal to `all`.
# and
# * We only have to return the selected hash.
# We return the selected algorithm.
return result[self.algorithm]
# * The parsed algorithm is equal to `all`.
# or
# * We do not have to return the selected hash.
# We return all hashes.
return result | python | {
"resource": ""
} |
q270386 | Command.execute | test | 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 and get the output and the error.
(output, error) = process.communicate()
if process.returncode != 0: # pragma: no cover
# The return code is different to 0.
# We return the decoded error.
return self._decode_output(error)
# The return code (or exit code if you prefer) if equal to 0.
# We return the decoded output of the executed command.
return self._decode_output(output) | python | {
"resource": ""
} |
q270387 | Dict.remove_key | test | 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_dictionnary, dict):
# The main dictionnary is a dictionnary
if isinstance(key_to_remove, list):
# The parsed key to remove is a list.
for key in key_to_remove:
# We loop through the list of key to remove.
# We delete the key from the dictionnary.
del self.main_dictionnary[key]
else:
# The parsed key to remove is not a list.
try:
# We delete the given key from the dictionnary.
del self.main_dictionnary[key_to_remove]
except KeyError:
pass
# We return the final dictionnary.
return self.main_dictionnary
# The main dictionnary is not a dictionnary.
# We return None.
return None | python | {
"resource": ""
} |
q270388 | Dict.rename_key | test | 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 to rename the exact index or
the index which looks like the given key(s)
:return: The well formatted dict.
:rtype: dict|None
"""
if isinstance(self.main_dictionnary, dict) and isinstance(key_to_rename, dict):
# * The given main directory is a dictionnary.
# and
# * The given key to rename is a dictionnary.
for old, new in key_to_rename.items():
# We loop through the key to raname.
if strict:
# The strict method is activated.
if old in self.main_dictionnary:
# The old key is in the main dictionnary.
# We initiate the new with the old and remove the old content.
self.main_dictionnary[new] = self.main_dictionnary.pop(old)
else:
# The strict method is not activated.
# We initiate the elements to rename.
to_rename = {}
for index in self.main_dictionnary:
# We loop throught the indexes of the main dictionnary.
if old in index:
# The old key is into the index name.
# We append the index name and the new index to our
# local list to rename.
to_rename.update({index: new[:-1] + index.split(old)[-1]})
# We run this method against the local list to rename in order
# to rename the element.
self.main_dictionnary = Dict(self.main_dictionnary).rename_key(
to_rename, True
)
# We return the final list.
return self.main_dictionnary
# * The given main directory is not a dictionnary.
# or
# * The given key to rename is not a dictionnary.
# We return None.
return None | python | {
"resource": ""
} |
q270389 | Dict.merge | test | 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 index
:code`False`: We follow element (content)
:type strict: bool
:return: The merged dict.
:rtype: dict
"""
# We initiate a variable which will save our result.
result = {}
for element in to_merge:
# We loop throught the given dict to merge.
if element in self.main_dictionnary:
# The currently read element is in the main dict.
if isinstance(to_merge[element], dict) and isinstance(
self.main_dictionnary[element], dict
):
# They are in both side dict.
# We merge the dict tree and save into result.
result[element] = Dict(self.main_dictionnary[element]).merge(
to_merge[element]
)
elif isinstance(to_merge[element], list) and isinstance(
self.main_dictionnary[element], list
):
# They are in both side list.
# We merge the lists and save into result.
result[element] = List(self.main_dictionnary[element]).merge(
to_merge[element], strict
)
else:
# They are not list, not dict.
# We append the currently read element to the result.
result.update({element: to_merge[element]})
else:
# The currently read element is not into the main
# dict.
# We append the currently read element to the result.
result.update({element: to_merge[element]})
for element in self.main_dictionnary:
# We loop through each element of the main dict.
if element not in result:
# The currently read element is not into
# the result.
# We append it to the result.
result[element] = self.main_dictionnary[element]
# We return the result.
return result | python | {
"resource": ""
} |
q270390 | Dict.to_json | test | 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") as file:
# We open the file we are going to write.
# Note: We always overwrite the destination.
# We save the current dictionnary into a json format.
dump(
self.main_dictionnary,
file,
ensure_ascii=False,
indent=4,
sort_keys=True,
)
except UnicodeEncodeError: # pragma: no cover
with open(destination, "w", encoding="utf-8") as file:
# We open the file we are going to write.
# Note: We always overwrite the destination.
# We save the current dictionnary into a json format.
dump(
self.main_dictionnary,
file,
ensure_ascii=False,
indent=4,
sort_keys=True,
) | python | {
"resource": ""
} |
q270391 | Dict.to_yaml | test | 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") as file:
# We open the file we are going to write.
# Note: We always overwrite the destination.
# We save the current dictionnary into a json format.
dump_yaml(
self.main_dictionnary,
file,
encoding="utf-8",
allow_unicode=True,
indent=4,
default_flow_style=flow_style,
) | python | {
"resource": ""
} |
q270392 | Directory.fix_path | test | 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 parsed.
# We initate a variable which will save the splited path.
split_path = []
if self.directory:
# The parsed directory is not empty or equal to None.
if "/" in self.directory:
# We split the separator.
split_path = self.directory.split("/")
elif "\\" in self.directory:
# We split the separator.
split_path = self.directory.split("\\")
else:
split_path = [self.directory]
# We run the same function with the splited_path argument filled.
return self.fix_path(splited_path=[x for x in split_path if x])
# We return the directory.
return self.directory
# We join the splited element with the directory separator as glue.
return directory_separator.join(splited_path) + directory_separator | python | {
"resource": ""
} |
q270393 | File.write | test | 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 with.
:type overwrite: bool
"""
if overwrite or not path.isfile(self.file):
# * We have to overwrite the file data.
# or
# * The file path does not already exist.
with open(self.file, "w", encoding="utf-8", newline="\n") as file:
# We prepare the file for writting.
if data_to_write and isinstance(data_to_write, str):
# * A data to write is given.
# and
# * The data to write is a string
# We write the string into the file.
file.write(data_to_write)
else:
# * We do not have to overwrite the file data.
# or
# * The file path does already exist.
with open(self.file, "a", encoding="utf-8", newline="\n") as file:
# We prepare the file for append writting.
if data_to_write and isinstance(data_to_write, str):
# * A data to write is given.
# and
# * The data to write is a string
# We append the string into the file.
file.write(data_to_write) | python | {
"resource": ""
} |
q270394 | File.read | test | 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 file content.
funilrys = file.read()
except UnicodeDecodeError: # pragma: no cover
with open(self.file, "r") as file:
# We open and read a file.
# We get the file content.
funilrys = file.read()
# We return the file content.
return funilrys | python | {
"resource": ""
} |
q270395 | List.format | test | 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: # pragma: no cover
return self.main_list | python | {
"resource": ""
} |
q270396 | List.merge | test | 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
:return: The merged list.
:rtype: list
"""
# We initiate a variable which will save the
# result
result = []
if strict:
# We are in strict mode.
for index, element in enumerate(to_merge):
# We loop through each element of the list to merge
# to the main dict.
try:
if isinstance(element, dict) and isinstance(
self.main_list[index], dict
):
# The currently read element is a dict.
# We merge its content into the main dict
# and append into the result.
result.append(Dict(self.main_list[index]).merge(element))
elif isinstance(element, list) and isinstance(
self.main_list[index], list
):
# The currently read element is a list.
# We loop through this method.
result.append(List(self.main_list[index]).merge(element))
else:
# The currently read element is not a list
# nor a dict.
# We append the element to the result.
result.append(element)
except IndexError: # pragma: no cover
# The index does not exist.
# Which means that for example one list is bigger
# than the other one.
# We append the element to the result.
result.append(element)
else:
# We are not is strict mode.
# We initiate the result with the main list.
result = self.main_list
for element in to_merge:
# We loop through the element to merge.
if element not in result:
# The currently read element is not
# in the result.
# We append it to the result
result.append(element)
# We return the result.
return result | python | {
"resource": ""
} |
q270397 | Regex.not_matching_list | test | 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))] | python | {
"resource": ""
} |
q270398 | Regex.match | test | 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(self.regex)
# In case we have to use the implementation of ${BASH_REMATCH} we use
# re.findall otherwise, we use re.search
if self.rematch: # pylint: disable=no-member
pre_result = to_match.findall(self.data)
else:
pre_result = to_match.search(self.data)
if self.return_data and pre_result: # pylint: disable=no-member
if self.rematch: # pylint: disable=no-member
for data in pre_result:
if isinstance(data, tuple):
result.extend(list(data))
else:
result.append(data)
if self.group != 0: # pylint: disable=no-member
return result[self.group] # pylint: disable=no-member
else:
result = pre_result.group(
self.group # pylint: disable=no-member
).strip()
return result
if not self.return_data and pre_result: # pylint: disable=no-member
return True
return False | python | {
"resource": ""
} |
q270399 | Regex.replace | test | 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, # pylint: disable=no-member
self.data,
self.occurences, # pylint: disable=no-member
)
return self.data | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.