Skip to content

Commit

Permalink
3.5
Browse files Browse the repository at this point in the history
- optimised multithread(), now accepts tuple and list objects!
- optimised and improved multiple other functions!
  • Loading branch information
SirDank committed Sep 18, 2023
1 parent 77496aa commit b2c16af
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 70 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ for url in github_downloads("EssentialsX/Essentials"): print(url)
```py
from dankware import github_file_selector
# full url > https://api.github.com/repos/EssentialsX/Essentials/releases/latest
for url in github_file_selector("EssentialsX/Essentials", "remove", ['AntiBuild', 'Discord', 'GeoIP', 'Protect', 'XMPP']): print(url)
for url in github_file_selector("EssentialsX/Essentials", "remove", ('AntiBuild', 'Discord', 'GeoIP', 'Protect', 'XMPP')): print(url)
```
<img width="700" alt="image" style="border-radius:5%" src="https://user-images.githubusercontent.com/52797753/216241961-5359d662-a117-4eb4-b74e-e82b41a895bc.png"><br>

Expand Down Expand Up @@ -252,7 +252,7 @@ print(clr("\n > Is this a randomly coloured string: TRUE | As you can see it do
```py
from dankware import clr, white, white_normal, white_dim, red, red_normal, red_dim
# preset = 3
print(clr("\n > This is a randomly coloured string based on the input colours!",3,colours=[white, white_normal, white_dim, red, red_normal, red_dim]))
print(clr("\n > This is a randomly coloured string based on the input colours!",3,colours=(white, white_normal, white_dim, red, red_normal, red_dim)))
```
<img width="650" alt="image" style="border-radius:5%" src="https://github.com/SirDank/dankware/assets/52797753/1ef2e6b1-0597-494a-8b84-e20efee48415"><br>

Expand Down
147 changes: 83 additions & 64 deletions dankware/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def multithread(function: callable, threads: int = 1, *args, progress_bar: bool
- function: The function to run in multiple threads.
- threads: The number of threads to use.
- *args: Input(s) for the function. Can be a list, a single value.
- *args: Input(s) for the function. Can be a tuple / list / single value.
- progress_bar: Whether to display a progress bar.
"""

Expand All @@ -68,31 +68,30 @@ def multithread(function: callable, threads: int = 1, *args, progress_bar: bool
from shutil import get_terminal_size
from concurrent.futures import ThreadPoolExecutor, as_completed
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeRemainingColumn, TimeElapsedColumn

def submit_task(executor, *args):
return executor.submit(function, *args)


try:

if threads < 1:
raise ValueError("The number of threads must be a positive integer!")

futures = []
executor = ThreadPoolExecutor(max_workers=threads)

if not args:
for _ in range(threads):
futures.append(executor.submit(function))
futures = tuple(executor.submit(function) for _ in range(threads))
else:

input_lists = []

for arg in args:
if isinstance(arg, list):
if isinstance(arg, list) or isinstance(arg, tuple):
input_lists.append(arg)
else:
input_lists.append([arg] * threads)

for task_args in zip(*input_lists):
futures.append(submit_task(executor, *task_args))

futures = tuple(executor.submit(function, *task_args) for task_args in zip(*input_lists))

del input_lists

if progress_bar:
width = get_terminal_size().columns
Expand Down Expand Up @@ -123,10 +122,10 @@ def submit_task(executor, *args):

# --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

def github_downloads(user_repo: str) -> list:
def github_downloads(user_repo: str) -> tuple:

"""
Extracts direct download urls from the latest release on github and returns it as a list
Extracts direct download urls from the latest release on github and returns it as a tuple
- Example Input: USER_NAME/REPO_NAME ( from https://api.github.com/repos/USER_NAME/REPO_NAME/releases/latest )
- Example Output: ['https://github.com/USER_NAME/REPO_NAME/releases/download/VERSION/EXAMPLE.TXT']
Expand All @@ -146,26 +145,26 @@ def github_downloads(user_repo: str) -> list:
try: response = requests.get(f"https://api.github.com/repos/{user_repo}/releases/latest").json(); break
except: input(clr(" > Make sure you are connected to the Internet! Press [ENTER] to try again... ",2))

return [data["browser_download_url"] for data in response["assets"]]
return tuple(data["browser_download_url"] for data in response["assets"])

# --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

def github_file_selector(user_repo: str, filter_mode: str, name_list: list) -> list:
def github_file_selector(user_repo: str, filter_mode: str, name_iterable: tuple) -> tuple:

"""
This function is used to filter the output from github_downloads()
- user_repo = 'USER_NAME/REPO_NAME' ( from https://api.github.com/repos/USER_NAME/REPO_NAME/releases/latest )
- filter_mode = 'add' or 'remove'
- name_list = list of names to be added or removed
- name_iterable = tuple of names to be added or removed
_______________________________________________________________________________________________________________________________________________________________________
[ EXAMPLE ]
```python
from dankware import github_file_selector
for file_url in github_file_selector("EssentialsX/Essentials", "remove", ['AntiBuild', 'Discord', 'GeoIP', 'Protect', 'XMPP']):
for file_url in github_file_selector("EssentialsX/Essentials", "remove", ('AntiBuild', 'Discord', 'GeoIP', 'Protect', 'XMPP')):
print(file_url)
```
Expand All @@ -182,7 +181,7 @@ def github_file_selector(user_repo: str, filter_mode: str, name_list: list) -> l
_______________________________________________________________________________________________________________________________________________________________________
Example Input: "EX_USER/EX_REPO", "add", ["EXAMPLE"]
Example Input: "EX_USER/EX_REPO", "add", ("EXAMPLE")
Example Output: [
'https://github.com/EX_USER/EX_REPO/releases/download/VERSION/EXAMPLE.TXT'
Expand All @@ -194,7 +193,7 @@ def github_file_selector(user_repo: str, filter_mode: str, name_list: list) -> l
_______________________________________________________________________________________________________________________________________________________________________
Example Input: "EX_USER/EX_REPO", "remove", ["EXAMPLE"]
Example Input: "EX_USER/EX_REPO", "remove", ("EXAMPLE")
Example Output: [
'https://github.com/EX_USER/EX_REPO/releases/download/VERSION/TEST.TXT'
Expand All @@ -214,15 +213,13 @@ def github_file_selector(user_repo: str, filter_mode: str, name_list: list) -> l
valid = False
elif filter_mode == "remove":
valid = True
for name in name_list:
for name in name_iterable:
if name in file_url.split('/')[-1]:
if filter_mode == "add":
valid = True
elif filter_mode == "remove":
valid = False
if valid: urls.append(file_url)
valid = not valid
if valid:
urls.append(file_url)

return urls
return tuple(urls)

# --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Expand Down Expand Up @@ -269,10 +266,11 @@ def is_admin() -> bool:
Checks if executed with admin privileges and returns True if found else False
"""

import ctypes

try: return ctypes.windll.shell32.IsUserAnAdmin()
except: return False
if os.name == 'nt':
import ctypes
try: return ctypes.windll.shell32.IsUserAnAdmin()
except: return False
else: return os.getuid() == 0

'''
def run_as_admin() -> None:
Expand Down Expand Up @@ -306,6 +304,9 @@ def export_registry_keys(registry_root: str, registry_path: str, recursive: bool
export_registry_keys('HKEY_CURRENT_USER', r'Software\Google\Chrome\PreferenceMACs')
```
"""

if os.name != 'nt':
raise RuntimeError("This function can only be used on Windows!")

import winreg

Expand Down Expand Up @@ -358,11 +359,11 @@ def exporter(key, registry_root, subkey_path, key_data, recursive) -> None:

# --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

def clr(text: str, preset: int = 1, colour_one: str = white, colour_two: str = red, colours: list = []) -> str:
def clr(text: str, preset: int = 1, colour_one: str = white, colour_two: str = red, colours: tuple = ()) -> str:

"""
this function colours special characters inside the 'symbols' list
this function colours special characters inside the 'symbols' tuple
___________________________________________
Expand All @@ -385,7 +386,7 @@ def clr(text: str, preset: int = 1, colour_one: str = white, colour_two: str = r
___________________________________________
- preset: 4 | to display banners
- text & spl = random (default) / colours inside input list
- text & spl = random (default) / colours inside input tuple
"""

Expand Down Expand Up @@ -437,13 +438,13 @@ def clr(text: str, preset: int = 1, colour_one: str = white, colour_two: str = r
if preset == 3: colour_spl = True
elif preset == 4: colour_spl = False

if colours == []:
if colours == ():
codes = vars(Fore)
colours = [codes[colour] for colour in codes if colour not in ('BLACK', 'WHITE', 'LIGHTBLACK_EX', 'LIGHTWHITE_EX', 'RESET')]
colours = tuple(codes[colour] for colour in codes if colour not in ('BLACK', 'WHITE', 'LIGHTBLACK_EX', 'LIGHTWHITE_EX', 'RESET'))

for _ in range(len(text)):
char = text[_]
if char not in (' ', '\n', '\t'):
if char not in (' ', '\n', '\t', '\r', '\b'):
if colour_spl:
if char in symbols:
text[_] = white + char
Expand Down Expand Up @@ -822,9 +823,11 @@ def err(exc_info, mode = "default") -> str:
value = 1/0
except:
print(clr(err(sys.exc_info()),2))
# OR
print(clr(err(sys.exc_info(),'mini'),2))
```
"""

from traceback import extract_tb

ex_type, ex_value, ex_traceback = exc_info
Expand Down Expand Up @@ -856,6 +859,10 @@ def err(exc_info, mode = "default") -> str:
report = " > {}".format(ex_type.__name__)
if ex_value: report += " | {}".format(ex_value)
report += "\n{}".format('\n'.join(stack_trace))

else:

raise ValueError(f"Invalid Mode: {mode} | Valid Modes: default, mini")

return report

Expand Down Expand Up @@ -943,21 +950,27 @@ def hide_window() -> None:
Hides console window
"""

from ctypes import windll

hWnd = windll.kernel32.GetConsoleWindow()
windll.user32.ShowWindow(hWnd, 0)
if os.name == 'nt':
from ctypes import windll
hWnd = windll.kernel32.GetConsoleWindow()
windll.user32.ShowWindow(hWnd, 0)
else:
import subprocess
subprocess.call(["xdotool", "getactivewindow", "windowminimize"])

def show_window() -> None:

"""
Shows console window
"""

from ctypes import windll

hWnd = windll.kernel32.GetConsoleWindow()
windll.user32.ShowWindow(hWnd, 1)
if os.name == 'nt':
from ctypes import windll
hWnd = windll.kernel32.GetConsoleWindow()
windll.user32.ShowWindow(hWnd, 1)
else:
import subprocess
subprocess.call(["xdotool", "getactivewindow", "windowactivate"])

def hide_window_for(duration: int = 3) -> None:

Expand Down Expand Up @@ -1017,27 +1030,30 @@ def get_path(location: str) -> str:
- Supports: Desktop / Documents / Favorites / Pictures / Videos / Music
"""

try:

import os
import winreg

valid_locations = ("AppData", "Desktop", "Documents", "Personal", "Favorites", "Local AppData", "Pictures", "My Pictures", "Videos", "My Video", "Music", "My Music")

if location in valid_locations:
if os.name == 'nt':

try:

import winreg

if location == "Documents": location = "Personal"
elif location == "Pictures": location = "My Pictures"
elif location == "Videos": location = "My Video"
elif location == "Music": location = "My Music"

key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", access=winreg.KEY_READ)
path = os.path.expandvars(winreg.QueryValueEx(key, location)[0])
return path

else: raise ValueError(f"Invalid location: {location} | Valid locations: {', '.join(valid_locations)}")
valid_locations = ("AppData", "Desktop", "Documents", "Personal", "Favorites", "Local AppData", "Pictures", "My Pictures", "Videos", "My Video", "Music", "My Music")

if location in valid_locations:

if location == "Documents": location = "Personal"
elif location == "Pictures": location = "My Pictures"
elif location == "Videos": location = "My Video"
elif location == "Music": location = "My Music"

key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", access=winreg.KEY_READ)
path = os.path.expandvars(winreg.QueryValueEx(key, location)[0])
return path

else: raise ValueError(f"Invalid location: {location} | Valid locations: {', '.join(valid_locations)}")

except: sys.exit(clr(err(sys.exc_info()),2))
except: sys.exit(clr(err(sys.exc_info()),2))

else: raise RuntimeError("This function is only available on windows!")

# --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Expand All @@ -1060,6 +1076,9 @@ def title(title: str) -> None:
"""

if os.name == 'nt': os.system(f"title {title}")
else:
import subprocess
subprocess.call(["xdotool", "getactivewindow", "set_window", "--name", title])

# --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Expand Down
6 changes: 3 additions & 3 deletions run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def example(num1, num2):
new_list = [1, 2, 3, 4, 5]

def example(num1, num2):
print(num1 * num2)
print(f"{num1} + {num2} = {num1 + num2}")
time.sleep(1)

multithread(example, 10, new_list, 5, progress_bar=False)
Expand Down Expand Up @@ -140,7 +140,7 @@ def gen_new():

COUNTER += 1; print(clr(f"\n___[{COUNTER}]__________________________________________________________________________________\n"))

for url in github_file_selector("EssentialsX/Essentials", "remove", ['AntiBuild', 'Discord', 'GeoIP', 'Protect', 'XMPP']): print(url)
for url in github_file_selector("EssentialsX/Essentials", "remove", ('AntiBuild', 'Discord', 'GeoIP', 'Protect', 'XMPP')): print(url)

COUNTER += 1; print(clr(f"\n___[{COUNTER}]__________________________________________________________________________________\n"))

Expand Down Expand Up @@ -172,7 +172,7 @@ def gen_new():

COUNTER += 1; print(clr(f"\n___[{COUNTER}]__________________________________________________________________________________\n"))

print(clr("\n > This is a randomly coloured string based on the input colours!",3,colours=[white, white_normal, white_dim, red, red_normal, red_dim]))
print(clr("\n > This is a randomly coloured string based on the input colours!",3,colours=(white, white_normal, white_dim, red, red_normal, red_dim)))

COUNTER += 1; print(clr(f"\n___[{COUNTER}]__________________________________________________________________________________\n"))

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

license = "MIT",
name = "dankware",
version = "3.4.5",
version = "3.5",
author = "SirDank",

author_email = "[email protected]",
Expand Down

0 comments on commit b2c16af

Please sign in to comment.