SENCE 2023 Examples - 1. Semester¶
Secret messages¶
In [1]:
Copied!
from itertools import cycle
import base64
from itertools import cycle
import base64
Key definition¶
In [2]:
Copied!
KEY = """THIS IS A SUPER SECRET CODE. ONLY SHARE IT WITH A TRUSTED PERSON.
SHARE IT ONCE, BEFORE SENDING ANY MESSAGE. DO NOT SEND IT WITH THE ENCRYPTED MESSAGE.
It should be random and long.
This isn't random or very long. An alternative would be
secrets.token_bytes(4096)
, written to a file.
This method is very secure for the first message, but weak if
multiple messages are encoded with the same key.
"""
KEY = """THIS IS A SUPER SECRET CODE. ONLY SHARE IT WITH A TRUSTED PERSON.
SHARE IT ONCE, BEFORE SENDING ANY MESSAGE. DO NOT SEND IT WITH THE ENCRYPTED MESSAGE.
It should be random and long.
This isn't random or very long. An alternative would be
secrets.token_bytes(4096)
, written to a file.
This method is very secure for the first message, but weak if
multiple messages are encoded with the same key.
"""
Secret message¶
In [3]:
Copied!
MESSAGE = """My super secret message. Just a test.😀🤯"""
MESSAGE = """My super secret message. Just a test.😀🤯"""
Functions¶
In [4]:
Copied!
def encode_message(message: str, key: str = KEY) -> bytes:
"""Encode message with key as one-time pad"""
pairs = zip(message.encode(), cycle(key.encode()))
encrypted = [a ^ b for a, b in pairs]
return base64.b85encode(bytes(encrypted))
def decode_message(encoded_message: bytes, key: str = KEY) -> str:
"""Decode message with key as one-time pad"""
encoded_bytes = base64.b85decode(encoded_message)
decrypted = bytes(a ^ b for a, b in
zip(encoded_bytes, cycle(key.encode())))
return decrypted.decode()
def encode_message(message: str, key: str = KEY) -> bytes:
"""Encode message with key as one-time pad"""
pairs = zip(message.encode(), cycle(key.encode()))
encrypted = [a ^ b for a, b in pairs]
return base64.b85encode(bytes(encrypted))
def decode_message(encoded_message: bytes, key: str = KEY) -> str:
"""Decode message with key as one-time pad"""
encoded_bytes = base64.b85decode(encoded_message)
decrypted = bytes(a ^ b for a, b in
zip(encoded_bytes, cycle(key.encode())))
return decrypted.decode()
Encode¶
In [5]:
Copied!
encoded_message = encode_message(MESSAGE)
encoded_message
# This message could be shared safely over an untrusted channel.
encoded_message = encode_message(MESSAGE)
encoded_message
# This message could be shared safely over an untrusted channel.
Out[5]:
b'88K-fRXH|NVN*6XA|NIJJ|Hk5Br`>AZw@eBRBtbAEkz(aZ=%|`$)vyY<^'
Decode¶
In [6]:
Copied!
decode_message(encoded_message.decode())
decode_message(encoded_message.decode())
Out[6]:
'My super secret message. Just a test.😀🤯'
In [7]:
Copied!
decode_message(b'88K-fRXH|NVN*6XA|NIJJ|Hk5Br`>AZw@eBRBtbAEkz(aZ=%|`$)vyY<^')
decode_message(b'88K-fRXH|NVN*6XA|NIJJ|Hk5Br`>AZw@eBRBtbAEkz(aZ=%|`$)vyY<^')
Out[7]:
'My super secret message. Just a test.😀🤯'
Merit-Order¶
Contour Plots¶
Seaborn has been updated (current version in Anaconda : 0.12.2), and sns.kdeplot
has a slightly different syntax than before
In [8]:
Copied!
# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris')
# set seaborn style
sns.set_style("white")
# Basic 2D density plot
sns.kdeplot(data=df, x='sepal_width', y='sepal_length')
plt.show()
# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris')
# set seaborn style
sns.set_style("white")
# Basic 2D density plot
sns.kdeplot(data=df, x='sepal_width', y='sepal_length')
plt.show()
In [9]:
Copied!
# Custom the color, add shade and bandwidth
sns.kdeplot(data=df, x='sepal_width', y='sepal_length', cmap="Reds", fill=True, bw_adjust=.5)
plt.show()
# Custom the color, add shade and bandwidth
sns.kdeplot(data=df, x='sepal_width', y='sepal_length', cmap="Reds", fill=True, bw_adjust=.5)
plt.show()
In [10]:
Copied!
# Add thresh parameter
sns.kdeplot(data=df, x='sepal_width', y='sepal_length', cmap="Blues", fill=True, thresh=0)
plt.show()
# Add thresh parameter
sns.kdeplot(data=df, x='sepal_width', y='sepal_length', cmap="Blues", fill=True, thresh=0)
plt.show()
Map with connections between cities¶
In [11]:
Copied!
# libraries
#! pip install basemap
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
# libraries
#! pip install basemap
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
In [12]:
Copied!
# Set the plot size for this notebook:
plt.rcParams["figure.figsize"]=15,12
# Set the plot size for this notebook:
plt.rcParams["figure.figsize"]=15,12
In [13]:
Copied!
# A basic map
m=Basemap(llcrnrlon=-100, llcrnrlat=20, urcrnrlon=30, urcrnrlat=70, projection='merc')
m.drawmapboundary(fill_color='#A6CAE0', linewidth=0)
m.fillcontinents(color='grey', alpha=0.7, lake_color='grey')
m.drawcoastlines(linewidth=0.1, color="white");
# A basic map
m=Basemap(llcrnrlon=-100, llcrnrlat=20, urcrnrlon=30, urcrnrlat=70, projection='merc')
m.drawmapboundary(fill_color='#A6CAE0', linewidth=0)
m.fillcontinents(color='grey', alpha=0.7, lake_color='grey')
m.drawcoastlines(linewidth=0.1, color="white");
In [14]:
Copied!
# Background map
m=Basemap(llcrnrlon=-100, llcrnrlat=20, urcrnrlon=30, urcrnrlat=70, projection='merc')
m.drawmapboundary(fill_color='#A6CAE0', linewidth=0)
m.fillcontinents(color='grey', alpha=0.7, lake_color='grey')
m.drawcoastlines(linewidth=0.1, color="white")
# Add a connection between new york and London
startlat = 40.78; startlon = -73.98
arrlat = 51.53; arrlon = 0.08
m.drawgreatcircle(startlon, startlat, arrlon, arrlat, linewidth=2, color='orange');
# Background map
m=Basemap(llcrnrlon=-100, llcrnrlat=20, urcrnrlon=30, urcrnrlat=70, projection='merc')
m.drawmapboundary(fill_color='#A6CAE0', linewidth=0)
m.fillcontinents(color='grey', alpha=0.7, lake_color='grey')
m.drawcoastlines(linewidth=0.1, color="white")
# Add a connection between new york and London
startlat = 40.78; startlon = -73.98
arrlat = 51.53; arrlon = 0.08
m.drawgreatcircle(startlon, startlat, arrlon, arrlat, linewidth=2, color='orange');
In [15]:
Copied!
# Dataframe: list of a few cities with their coordinates:
import pandas as pd
import pandas as pd
cities = {
'city': ["Paris", "Melbourne", "Saint.Petersburg", "Abidjan", "Montreal", "Nairobi", "Salvador"],
'lon': [2, 145, 30.32, -4.03, -73.57, 36.82, -38.5],
'lat': [49, -38, 59.93, 5.33, 45.52, -1.29, -12.97]
}
df = pd.DataFrame(cities, columns = ['city', 'lon', 'lat'])
df
# Dataframe: list of a few cities with their coordinates:
import pandas as pd
import pandas as pd
cities = {
'city': ["Paris", "Melbourne", "Saint.Petersburg", "Abidjan", "Montreal", "Nairobi", "Salvador"],
'lon': [2, 145, 30.32, -4.03, -73.57, 36.82, -38.5],
'lat': [49, -38, 59.93, 5.33, 45.52, -1.29, -12.97]
}
df = pd.DataFrame(cities, columns = ['city', 'lon', 'lat'])
df
Out[15]:
city | lon | lat | |
---|---|---|---|
0 | Paris | 2.00 | 49.00 |
1 | Melbourne | 145.00 | -38.00 |
2 | Saint.Petersburg | 30.32 | 59.93 |
3 | Abidjan | -4.03 | 5.33 |
4 | Montreal | -73.57 | 45.52 |
5 | Nairobi | 36.82 | -1.29 |
6 | Salvador | -38.50 | -12.97 |
In [16]:
Copied!
# Background map
m=Basemap(llcrnrlon=-179, llcrnrlat=-60, urcrnrlon=179, urcrnrlat=70, projection='cyl')
m.drawmapboundary(fill_color='white', linewidth=0)
m.fillcontinents(color='#f2f2f2', alpha=0.7)
m.drawcoastlines(linewidth=0.1, color="white")
# Loop on every pair of cities to add the connection
for startIndex, startRow in df.iterrows():
for endIndex in range(startIndex + 1, len(df.index)):
endRow = df.iloc[endIndex]
# print(f"{startRow.city} -> {endRow.city}")
m.drawgreatcircle(startRow.lon, startRow.lat, endRow.lon, endRow.lat, linewidth=1, color='#69b3a2');
# Add city names
for i, row in df.iterrows():
plt.annotate(row.city, xy=m(row.lon+3, row.lat), verticalalignment='center')
# Background map
m=Basemap(llcrnrlon=-179, llcrnrlat=-60, urcrnrlon=179, urcrnrlat=70, projection='cyl')
m.drawmapboundary(fill_color='white', linewidth=0)
m.fillcontinents(color='#f2f2f2', alpha=0.7)
m.drawcoastlines(linewidth=0.1, color="white")
# Loop on every pair of cities to add the connection
for startIndex, startRow in df.iterrows():
for endIndex in range(startIndex + 1, len(df.index)):
endRow = df.iloc[endIndex]
# print(f"{startRow.city} -> {endRow.city}")
m.drawgreatcircle(startRow.lon, startRow.lat, endRow.lon, endRow.lat, linewidth=1, color='#69b3a2');
# Add city names
for i, row in df.iterrows():
plt.annotate(row.city, xy=m(row.lon+3, row.lat), verticalalignment='center')
In [17]:
Copied!
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
In [18]:
Copied!
my_variable = np.random.normal(loc=10, scale=5, size=500)
my_variable = np.random.normal(loc=10, scale=5, size=500)
In [19]:
Copied!
# Create the swarm plot
sns.swarmplot(y=my_variable)
# Customization
plt.title('Swarm Plot of My Variable (y-axis)') # Set the title
plt.ylabel('My variable') # Set the label for the y-axis
plt.show() # Display the chart
# Create the swarm plot
sns.swarmplot(y=my_variable)
# Customization
plt.title('Swarm Plot of My Variable (y-axis)') # Set the title
plt.ylabel('My variable') # Set the label for the y-axis
plt.show() # Display the chart