Last active
January 31, 2021 02:11
-
-
Save raphant/92e93d402ea72a8d52764065bd234e0e to your computer and use it in GitHub Desktop.
Code Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stackoverflow.com/a/7406369 | |
def safe_filename_from_url(url): | |
keepcharacters = ('.', '_', '-') | |
return "".join(c for c in url if c.isalnum() or | |
c in keepcharacters).rstrip()[:MAX_FILENAME_LEN] | |
import requests, json | |
def get_ip_location(x): | |
""" | |
input: | |
x : ip address | |
output: | |
dictionary which contain country,latitude and longitude. | |
""" | |
resp = requests.get("https://geolocation-db.com/jsonp/"+x) | |
data = json.loads(resp.text.split("(")[1].strip(")")) | |
return {"country_code":data["country_code"], 'latitude':data['latitude'],'longitude':data['longitude']} | |
def get_files_in_folder(folder): | |
""" Returns a list of files in folder (including the path to the file) """ | |
filenames = os.listdir(folder) | |
# os.path.join combines paths while dealing with /s and \s appropriately | |
full_filenames = [os.path.join(folder, filename) for filename in filenames] | |
return full_filenames | |
def humanize_bytes(num, suffix='B'): | |
if num is None: | |
num = 0 | |
else: | |
num = int(num) | |
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: | |
if abs(num) < 1024.0: | |
return "%3.1f%s%s" % (num, unit, suffix) | |
num /= 1024.0 | |
return "%.1f%s%s" % (num, 'Yi', suffix) | |
def time_formatter(milliseconds: int) -> str: | |
"""Inputs time in milliseconds, to get beautified time, | |
as string""" | |
seconds, milliseconds = divmod(int(milliseconds), 1000) | |
minutes, seconds = divmod(seconds, 60) | |
hours, minutes = divmod(minutes, 60) | |
days, hours = divmod(hours, 24) | |
tmp = ((str(days) + "d, ") if days else "") + \ | |
((str(hours) + "h, ") if hours else "") + \ | |
((str(minutes) + "m, ") if minutes else "") + \ | |
((str(seconds) + "s, ") if seconds else "") + \ | |
((str(milliseconds) + "ms, ") if milliseconds else "") | |
return tmp[:-2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment