Skip to content

Instantly share code, notes, and snippets.

@SlyCodePanda
Last active March 13, 2020 00:06
Show Gist options
  • Save SlyCodePanda/2e592ea9277a30aad04cf9d204d45c3a to your computer and use it in GitHub Desktop.
Save SlyCodePanda/2e592ea9277a30aad04cf9d204d45c3a to your computer and use it in GitHub Desktop.
prod_id = [1, 2, 3]
prod_name = ["foo", "bar", "baz"]
prod_dict = dict(zip(prod_id, prod_name))
# Find the first element, if any, from an iterable that matches a condition.
def first_match(iterable, check_condition, default_value=None):
return next((i for i in iterable if check_condition(i)), default_value)
# example 01
nums = [1, 2, 4, 0, 5]
first_match(nums, lambda x: x > 9) # Returns nothing.
first_match(nums, lambda x: x > 9, 'no_match') # Returns 'no_match'
import socket
# Create a socket
sock = socket.socket(socket_family, socket_type)
# Create a stream socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Socket family (here Adress Family veriosn 4 or IPv4)
AF_INET
# Socket type TCP connections
SOCKET_STREAM
# Socket type UDP connections
SOCK_DGRAM
# Translate a host name to IPv4 address format
gethostbyname("host")
# Translate a host name to IPv4 address format, extended interface
socket.gethostbyname_ex("host")
# Get the fqdn (fully qualified domain name)
socket.getfqdn("8.8.8.8")
# Returns the host name of the machine
socket.gethostname()
# Exception handling
socket.error
from time import time
from functools import wraps
def timeit(func):
"""
:param func: Decorated function
:return: Execution time for the decorated function
"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time()
result = func(*args, **kwargs)
end = time()
print(f'{func.__name__} executed in {end - start:.4f} seconds')
return result
return wrapper
# Example of use: ----------------------------------------------------------------
import random
# An arbitrary function.
@timeit
def sort_rnd_num():
numbers = [random.randint(100, 200) for _ in range(100000)]
numbers.sort()
return numbers
numbers = sort_rnd_num() # prints 'sort_rnd_num executed in 0.1880 seconds'
# ----------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment