Skip to content

Commit

Permalink
running autopep8 to create errors
Browse files Browse the repository at this point in the history
  • Loading branch information
HyMike committed May 11, 2024
1 parent b16092b commit db0c0df
Show file tree
Hide file tree
Showing 1,259 changed files with 49,983 additions and 34,112 deletions.
Binary file modified .DS_Store
Binary file not shown.
2 changes: 1 addition & 1 deletion tempCodeRunnerFile.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@

driver.get(web)
driver.get(web)
4 changes: 3 additions & 1 deletion top_amz_products/manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "top_amz_products.settings")
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE",
"top_amz_products.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
Expand Down
15 changes: 10 additions & 5 deletions top_amz_products/top_products/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ def home(request):
# trends_overtime = pytrends.interest_over_time()
# print(trends_overtime)

return render(request, 'top_products/home.html', {"best_seller_categories": best_seller_categories, })
return render(request, 'top_products/home.html',
{"best_seller_categories": best_seller_categories, })


# matplot code:
Expand Down Expand Up @@ -174,8 +175,10 @@ def products_trends(request):

graphs = my_plot_view(trending_data)

return render(request, 'top_products/products_trends.html', {'products': formatted_content, 'graphs': graphs, 'category_name': category_name, })
# return render(request, 'top_products/products_stats.html', {"product_images": product_images})
return render(request, 'top_products/products_trends.html',
{'products': formatted_content, 'graphs': graphs, 'category_name': category_name, })
# return render(request, 'top_products/products_stats.html',
# {"product_images": product_images})


def get_trending_data(amz_product_list):
Expand All @@ -198,7 +201,8 @@ def get_trending_data(amz_product_list):
# extract data to dictionary key being time vs value == the value

# create a default dictionary that can be populated
# use the formatted content and their order to populate the title for each of the graph.
# use the formatted content and their order to populate the title for each
# of the graph.


def extract_data(interest_over_time):
Expand All @@ -216,7 +220,8 @@ def extract_data(interest_over_time):
value = int(value_entry['value'])
extracted_value = int(value_entry['extracted_value'])

# If the query is not in the extracted_data dictionary, create a new entry
# If the query is not in the extracted_data dictionary, create a
# new entry
if query not in extracted_data:
extracted_data[query] = {'date': [],
'value': [], 'extracted_value': []}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ class CurrentThreadExecutor(Executor):

def __init__(self) -> None:
self._work_thread = threading.current_thread()
self._work_queue: queue.Queue[Union[_WorkItem, "Future[Any]"]] = queue.Queue()
self._work_queue: queue.Queue[Union[_WorkItem,
"Future[Any]"]] = queue.Queue()
self._broken = False

def run_until_future(self, future: "Future[Any]") -> None:
Expand Down Expand Up @@ -96,7 +97,8 @@ def _submit(
)
# Check they're not too late or the executor errored
if self._broken:
raise RuntimeError("CurrentThreadExecutor already quit or is broken")
raise RuntimeError(
"CurrentThreadExecutor already quit or is broken")
# Add to work queue
f: "Future[_R]" = Future()
work_item = _WorkItem(f, fn, *args, **kwargs)
Expand Down
12 changes: 8 additions & 4 deletions venv/lib/python3.11/site-packages/asgiref/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ def _get_context_id(self):
# If we're thread-critical, we stop here, as we can't share contexts.
if self._thread_critical:
return context_id
# Now, take those and see if we can resolve them through the launch maps
# Now, take those and see if we can resolve them through the launch
# maps
for i in range(sys.getrecursionlimit()):
try:
if context_is_async:
Expand Down Expand Up @@ -102,10 +103,12 @@ def __getattr__(self, key):
if key in storage:
return storage[key]
else:
raise AttributeError(f"{self!r} object has no attribute {key!r}")
raise AttributeError(
f"{self!r} object has no attribute {key!r}")

def __setattr__(self, key, value):
if key in ("_context_refs", "_thread_critical", "_thread_lock", "_attr_name"):
if key in ("_context_refs", "_thread_critical",
"_thread_lock", "_attr_name"):
return super().__setattr__(key, value)
with self._thread_lock:
storage = self._get_storage()
Expand All @@ -117,4 +120,5 @@ def __delattr__(self, key):
if key in storage:
del storage[key]
else:
raise AttributeError(f"{self!r} object has no attribute {key!r}")
raise AttributeError(
f"{self!r} object has no attribute {key!r}")
7 changes: 4 additions & 3 deletions venv/lib/python3.11/site-packages/asgiref/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __init__(self, application, max_applications=1000):
# Initialisation
self.application_instances = {}

### Mainloop and handling
# Mainloop and handling

def run(self):
"""
Expand All @@ -72,7 +72,7 @@ async def application_send(self, scope, message):
"""
raise NotImplementedError("You must implement application_send()")

### Application instance management
# Application instance management

def get_or_create_application_instance(self, scope_id, scope):
"""
Expand Down Expand Up @@ -142,7 +142,8 @@ async def application_checker(self):
try:
del self.application_instances[scope_id]
except KeyError:
# Exception handling might have already got here before us. That's fine.
# Exception handling might have already got here before
# us. That's fine.
pass

async def application_exception(self, exception, application_details):
Expand Down
30 changes: 20 additions & 10 deletions venv/lib/python3.11/site-packages/asgiref/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,15 @@ def _restore_context(context: contextvars.Context) -> None:
# inspect.iscoroutinefunction(), whilst also removing the _is_coroutine marker.
# The latter is replaced with the inspect.markcoroutinefunction decorator.
# Until 3.12 is the minimum supported Python version, provide a shim.
# Django 4.0 only supports 3.8+, so don't concern with the _or_partial backport.
# Django 4.0 only supports 3.8+, so don't concern with the _or_partial
# backport.

if hasattr(inspect, "markcoroutinefunction"):
iscoroutinefunction = inspect.iscoroutinefunction
markcoroutinefunction: Callable[[_F], _F] = inspect.markcoroutinefunction
else:
iscoroutinefunction = asyncio.iscoroutinefunction # type: ignore[assignment]
# type: ignore[assignment]
iscoroutinefunction = asyncio.iscoroutinefunction

def markcoroutinefunction(func: _F) -> _F:
func._is_coroutine = asyncio.coroutines._is_coroutine # type: ignore
Expand Down Expand Up @@ -144,12 +146,14 @@ class AsyncToSync(Generic[_P, _R]):
launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}

# Keeps track of which CurrentThreadExecutor to use. This uses an asgiref
# Local, not a threadlocal, so that tasks can work out what their parent used.
# Local, not a threadlocal, so that tasks can work out what their parent
# used.
executors = Local()

# When we can't find a CurrentThreadExecutor from the context, such as
# inside create_task, we'll look it up here from the running event loop.
loop_thread_executors: "Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]" = {}
loop_thread_executors: "Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]" = {
}

def __init__(
self,
Expand Down Expand Up @@ -243,7 +247,8 @@ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
)

if not (self.main_event_loop and self.main_event_loop.is_running()):
# Make our own event loop - in a new thread - and run inside that.
# Make our own event loop - in a new thread - and run inside
# that.
loop = asyncio.new_event_loop()
self.loop_thread_executors[loop] = current_executor
loop_executor = ThreadPoolExecutor(max_workers=1)
Expand Down Expand Up @@ -405,7 +410,8 @@ class SyncToAsync(Generic[_P, _R]):
)

# Maintaining a weak reference to the context ensures that thread pools are
# erased once the context goes out of scope. This terminates the thread pool.
# erased once the context goes out of scope. This terminates the thread
# pool.
context_to_thread_executor: "weakref.WeakKeyDictionary[ThreadSensitiveContext, ThreadPoolExecutor]" = (
weakref.WeakKeyDictionary()
)
Expand All @@ -421,13 +427,15 @@ def __init__(
or _iscoroutinefunction_or_partial(func)
or _iscoroutinefunction_or_partial(getattr(func, "__call__", func))
):
raise TypeError("sync_to_async can only be applied to sync functions.")
raise TypeError(
"sync_to_async can only be applied to sync functions.")
self.func = func
functools.update_wrapper(self, func)
self._thread_sensitive = thread_sensitive
markcoroutinefunction(self)
if thread_sensitive and executor is not None:
raise TypeError("executor must not be set when thread_sensitive is True")
raise TypeError(
"executor must not be set when thread_sensitive is True")
self._executor = executor
try:
self.__self__ = func.__self__ # type: ignore
Expand Down Expand Up @@ -503,7 +511,8 @@ def __get__(
func = functools.partial(self.__call__, parent)
return functools.update_wrapper(func, self.func)

def thread_handler(self, loop, source_task, exc_info, func, *args, **kwargs):
def thread_handler(self, loop, source_task,
exc_info, func, *args, **kwargs):
"""
Wraps the sync application with exception handling.
"""
Expand All @@ -517,7 +526,8 @@ def thread_handler(self, loop, source_task, exc_info, func, *args, **kwargs):
current_thread = threading.current_thread()
if AsyncToSync.launch_map.get(source_task) == current_thread:
# Our parent task was launched from this same thread, so don't make
# a launch map entry - let it shortcut over us! (and stop infinite loops)
# a launch map entry - let it shortcut over us! (and stop infinite
# loops)
parent_set = False
else:
self.launch_map[current_thread] = source_task
Expand Down
5 changes: 4 additions & 1 deletion venv/lib/python3.11/site-packages/asgiref/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ def __init__(self, application, scope):
self.input_queue = asyncio.Queue()
self.output_queue = asyncio.Queue()
self.future = asyncio.ensure_future(
self.application(scope, self.input_queue.get, self.output_queue.put)
self.application(
scope,
self.input_queue.get,
self.output_queue.put)
)

async def wait(self, timeout=1):
Expand Down
3 changes: 2 additions & 1 deletion venv/lib/python3.11/site-packages/asgiref/timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ def _do_enter(self) -> "timeout":
return self

self._cancel_at = self._loop.time() + self._timeout
self._cancel_handler = self._loop.call_at(self._cancel_at, self._cancel_task)
self._cancel_handler = self._loop.call_at(
self._cancel_at, self._cancel_task)
return self

def _do_exit(self, exc_type: Type[BaseException]) -> None:
Expand Down
12 changes: 8 additions & 4 deletions venv/lib/python3.11/site-packages/asgiref/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ async def __call__(self, scope, receive, send):
while True:
message = await receive()
if message["type"] != "http.request":
raise ValueError("WSGI wrapper received a non-HTTP-request message")
raise ValueError(
"WSGI wrapper received a non-HTTP-request message")
body.write(message.get("body", b""))
if not message.get("more_body"):
break
Expand Down Expand Up @@ -88,7 +89,8 @@ def build_environ(self, scope, body):
corrected_name = "CONTENT_TYPE"
else:
corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
# HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
# HTTPbis say only ASCII chars are allowed in headers, but we
# latin1 just in case
value = value.decode("latin1")
if corrected_name in environ:
value = environ[corrected_name] + "," + value
Expand Down Expand Up @@ -144,15 +146,17 @@ def run_wsgi_app(self, body):
self.sync_send(self.response_start)
# If the application supplies a Content-Length header
if self.response_content_length is not None:
# The server should not transmit more bytes to the client than the header allows
# The server should not transmit more bytes to the client than
# the header allows
bytes_allowed = self.response_content_length - bytes_sent
if len(output) > bytes_allowed:
output = output[:bytes_allowed]
self.sync_send(
{"type": "http.response.body", "body": output, "more_body": True}
)
bytes_sent += len(output)
# The server should stop iterating over the response when enough data has been sent
# The server should stop iterating over the response when enough
# data has been sent
if bytes_sent == self.response_content_length:
break
# Close connection
Expand Down
3 changes: 2 additions & 1 deletion venv/lib/python3.11/site-packages/certifi/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ def where() -> str:
return _CACERT_PATH

def contents() -> str:
return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii")
return files("certifi").joinpath(
"cacert.pem").read_text(encoding="ascii")

elif sys.version_info >= (3, 7):

Expand Down
27 changes: 17 additions & 10 deletions venv/lib/python3.11/site-packages/charset_normalizer/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,13 @@ def from_bytes(
length: int = len(sequences)

if length == 0:
logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.")
logger.debug(
"Encoding detection on empty bytes, assuming utf_8 intention.")
if explain:
logger.removeHandler(explain_handler)
logger.setLevel(previous_logger_level or logging.WARNING)
return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")])
return CharsetMatches(
[CharsetMatch(sequences, "utf_8", 0.0, False, [], "")])

if cp_isolation is not None:
logger.log(
Expand Down Expand Up @@ -223,14 +225,14 @@ def from_bytes(
str(
sequences[: int(50e4)]
if strip_sig_or_bom is False
else sequences[len(sig_payload) : int(50e4)],
else sequences[len(sig_payload): int(50e4)],
encoding=encoding_iana,
)
else:
decoded_payload = str(
sequences
if strip_sig_or_bom is False
else sequences[len(sig_payload) :],
else sequences[len(sig_payload):],
encoding=encoding_iana,
)
except (UnicodeDecodeError, LookupError) as e:
Expand Down Expand Up @@ -338,7 +340,7 @@ def from_bytes(
and not is_multi_byte_decoder
):
try:
sequences[int(50e3) :].decode(encoding_iana, errors="strict")
sequences[int(50e3):].decode(encoding_iana, errors="strict")
except UnicodeDecodeError as e:
logger.log(
TRACE,
Expand All @@ -349,7 +351,8 @@ def from_bytes(
tested_but_hard_failure.append(encoding_iana)
continue

mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0
mean_mess_ratio: float = sum(
md_ratios) / len(md_ratios) if md_ratios else 0.0
if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up:
tested_but_soft_failure.append(encoding_iana)
logger.log(
Expand Down Expand Up @@ -477,10 +480,12 @@ def from_bytes(
)
or (fallback_u8 is not None)
):
logger.debug("Encoding detection: utf_8 will be used as a fallback match")
logger.debug(
"Encoding detection: utf_8 will be used as a fallback match")
results.append(fallback_u8)
elif fallback_ascii:
logger.debug("Encoding detection: ascii will be used as a fallback match")
logger.debug(
"Encoding detection: ascii will be used as a fallback match")
results.append(fallback_ascii)

if results:
Expand All @@ -490,7 +495,8 @@ def from_bytes(
len(results) - 1,
)
else:
logger.debug("Encoding detection: Unable to determine any suitable charset.")
logger.debug(
"Encoding detection: Unable to determine any suitable charset.")

if explain:
logger.removeHandler(explain_handler)
Expand Down Expand Up @@ -561,7 +567,8 @@ def from_path(


def is_binary(
fp_or_path_or_payload: Union[PathLike, str, BinaryIO, bytes], # type: ignore[type-arg]
# type: ignore[type-arg]
fp_or_path_or_payload: Union[PathLike, str, BinaryIO, bytes],
steps: int = 5,
chunk_size: int = 512,
threshold: float = 0.20,
Expand Down
Loading

0 comments on commit db0c0df

Please sign in to comment.