Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
805c5c275e | ||
|
|
83859026be | ||
|
|
5efb942978 | ||
|
|
74f9527832 | ||
|
|
081471fa5d | ||
|
|
291ba82046 | ||
|
|
14ed1783f9 | ||
|
|
74545a6ad1 | ||
|
|
b6be9c9488 | ||
|
|
716e254905 | ||
|
|
161a4e28db | ||
|
|
5af112ebae | ||
|
|
5d36a06987 | ||
|
|
b4f174be47 | ||
|
|
46acaf2e75 | ||
|
|
28c277f369 | ||
|
|
02146e348d | ||
|
|
9df129681d | ||
|
|
a566adc1df | ||
|
|
aa1a8fee93 | ||
|
|
285914f044 | ||
|
|
da2c779bcd | ||
|
|
7259509d9e | ||
|
|
b085e13c4e | ||
|
|
59e84426af | ||
|
|
97f93ebd8e | ||
|
|
35c8889e77 | ||
|
|
dca7e9d599 | ||
|
|
ce856e5626 | ||
|
|
072032e80e | ||
|
|
235e7b5268 | ||
|
|
22fa096271 | ||
|
|
13eb12bf69 | ||
|
|
efa189d0b6 | ||
|
|
111f551a39 | ||
|
|
e0fd81dc1d | ||
|
|
420194ef54 | ||
|
|
632448c249 | ||
|
|
c3405d56e5 | ||
|
|
338824c028 | ||
|
|
6625a4d6c1 | ||
|
|
b1fccaf628 | ||
|
|
568e890c9f | ||
|
|
ff86e4a7c2 | ||
|
|
0f10f22345 |
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Python: HotdogSimulation",
|
||||||
|
"type": "python",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "simulation/SimulationRunner.py",
|
||||||
|
"justMyCode": true,
|
||||||
|
"args": "./HotdogSimulation.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Python: File",
|
||||||
|
"type": "python",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${file}",
|
||||||
|
"justMyCode": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Question 1:
|
||||||
|
# The international standard for floating-point representation is
|
||||||
|
# called the "IEEE 754 Standard for Floating-Point Arithmetic."
|
||||||
|
|
||||||
|
# Question 2:
|
||||||
|
# 32-bit and 64-bit formats are the most widely used ones in practice.
|
||||||
|
|
||||||
|
# Question 3:
|
||||||
|
# My computer supports all these formats
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
supported_formats = np.finfo(np.float32).bits, np.finfo(np.float64).bits
|
||||||
|
print(f"Your computer supports the following floating-point formats: {supported_formats}")
|
||||||
|
|
||||||
|
|
||||||
|
# Question 4:
|
||||||
|
# Using the Pandas multiplication operator (df['Number1'] * df['Number2'])
|
||||||
|
# , the result is automatically converted to a floating-point data type.
|
||||||
|
# On the other hand, when I multiply the numbers using the normal Python
|
||||||
|
# multiplication operator (num1 * num2), the result remains an integer
|
||||||
|
# data type.
|
||||||
|
|
||||||
|
# Question 5:
|
||||||
|
# The size of a floating-point number in memory is primarily determined
|
||||||
|
# by the data type and not the actual value it represents. So the size
|
||||||
|
# of a Python floating-point number does not change as it gets larger.
|
||||||
|
import sys
|
||||||
|
print(sys.getsizeof(70))
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Question 7:
|
||||||
|
# 1. Strings in Python are sequences of Unicode characters, while bytes
|
||||||
|
# are sequences of raw binary data.
|
||||||
|
# 2. Strings in Python are immutable, bytes objects are mutable
|
||||||
|
# 3. Strings in Python are encoded using a specific character encoding,
|
||||||
|
# bytes objects do not have an inherent encoding and represent raw binary
|
||||||
|
# data.
|
||||||
|
import sys
|
||||||
|
|
||||||
|
string_example = "Hello"
|
||||||
|
bytes_example = b"Hello"
|
||||||
|
|
||||||
|
string_size = sys.getsizeof(string_example)
|
||||||
|
bytes_size = sys.getsizeof(bytes_example)
|
||||||
|
|
||||||
|
print("Size of string:", string_size)
|
||||||
|
print("Size of bytes:", bytes_size)
|
||||||
|
|
||||||
|
# Emojis are represented using Unicode characters, which require more
|
||||||
|
# bytes to store compared to ASCII characters. Therefore, if you have
|
||||||
|
# a string that contains emojis, its size will be larger than a string
|
||||||
|
# without emojis.
|
||||||
|
|
||||||
|
def print_string_as_numbers(input_string):
|
||||||
|
for char in input_string:
|
||||||
|
print(ord(char), end=' ')
|
||||||
|
|
||||||
|
# Example usage
|
||||||
|
input_string = "Hello, World!"
|
||||||
|
print_string_as_numbers(input_string)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
print('Hi')
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
GTSP Python Bootcamp
|
GTSP Python Bootcamp
|
||||||
|
|
||||||
This bootcamp is intended for OTP interns with a math and applied analysis
|
This bootcamp is intended for OPT interns with a math and applied analysis
|
||||||
background to get up to speed quickly on how to use Python for practical
|
background to get up to speed quickly on how to use Python for practical
|
||||||
commercial work. It is not intended for large classes above 2-3 study groups
|
commercial work. It is not intended for large classes above 2-3 study groups
|
||||||
of a maximum of 4 students each.
|
of a maximum of 4 students each.
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# A quick brain teaser
|
||||||
|
print('What has a head and a tail but no body?')
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# A coin
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
import sys
|
||||||
|
print(sys.float_info)
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{\rtf1\ansi\ansicpg1252\cocoartf2580
|
||||||
|
\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fnil\fcharset0 HelveticaNeue;\f1\fnil\fcharset0 Menlo-Regular;}
|
||||||
|
{\colortbl;\red255\green255\blue255;\red0\green0\blue0;\red0\green0\blue0;}
|
||||||
|
{\*\expandedcolortbl;;\cssrgb\c0\c0\c0\c87059;\cssrgb\c0\c0\c0\c3922;}
|
||||||
|
\margl1440\margr1440\vieww11520\viewh8400\viewkind0
|
||||||
|
\deftab720
|
||||||
|
\pard\pardeftab720\partightenfactor0
|
||||||
|
|
||||||
|
\f0\fs32 \cf2 \expnd0\expndtw0\kerning0
|
||||||
|
1. What is the name of the international standard for floating-point representation?\
|
||||||
|
\
|
||||||
|
The IEEE-754 standard describes floating-point formats, a way to represent real numbers in hardware.\
|
||||||
|
\
|
||||||
|
\
|
||||||
|
2. How many bits are the floating point numbers defined by that standard allowed to be?\
|
||||||
|
\
|
||||||
|
The floating-point numbers defined by the international standard can be allowed to be of different lengths depending on the specific interchange format. For binary interchange, the formats can be 16 bits, 32 bits, 64 bits, and any multiple of 32 bits \uc0\u8805 128. For decimal interchange, the formats can be any multiple of 32 bits.\
|
||||||
|
\
|
||||||
|
\
|
||||||
|
3. Does your computer support all those formats? Can you think of an easy way to check with only one line of Python?\
|
||||||
|
\
|
||||||
|
import sys\
|
||||||
|
print(sys.float_info)\
|
||||||
|
\
|
||||||
|
scott@MacBook-Pro-6 python-bootcamp % python3 Floating_Point_Formats.py \
|
||||||
|
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)\
|
||||||
|
\
|
||||||
|
\
|
||||||
|
\pard\pardeftab720\sa320\partightenfactor0
|
||||||
|
\cf2 4. Why doesn't this code give the same answers to the two multiplications?\
|
||||||
|
Because they are different operations. The normal Python multiplication operator will multiply two numbers together and return the product. The Pandas multiplication operator, on the other hand, performs element-wise multiplication on the corresponding columns in a DataFrame. In other words, it multiplies the first element in the first column with the first element in the second column, the second element in the first column with the second element in the second column, and so on. \
|
||||||
|
Floating-point arithmetic has a limited precision due to the finite number of bits used to represent floating-point numbers in binary format. This can lead to rounding errors and loss of precision in arithmetic operations, particularly with very large or very small numbers.\
|
||||||
|
\
|
||||||
|
5. You can use
|
||||||
|
\f1\fs27\fsmilli13600 \cf2 \cb3 sys.getsizeof
|
||||||
|
\f0\fs32 \cf2 \cb1 to see how large a Python object is. Does the size of a Python floating-point number change as it gets larger? Why or why not?\
|
||||||
|
The size of a Python floating-point number does not change as it gets larger. This is because Python uses a fixed number of bytes to represent floating-point numbers, regardless of their value.}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Name three practical differences between Python strings and bytes.
|
||||||
|
# Using sys.getsizeof, see how the sizes may be different.
|
||||||
|
# Do emoji change this answer?
|
||||||
|
|
||||||
|
# Encoding
|
||||||
|
# Strings are created using Unicode character points.
|
||||||
|
# While bytes are used to represent actual bytes in memory, which can be encoded using ASCII or UTF-8.
|
||||||
|
|
||||||
|
# Usage
|
||||||
|
# Strings are usually used to represent text.
|
||||||
|
# While bytes are used to represent binary data.
|
||||||
|
|
||||||
|
# Memory Size
|
||||||
|
# Strings take up more memory than bytes, because they are Unicode-based and can contain any character.
|
||||||
|
# While bytes are limited to binary data.
|
||||||
|
|
||||||
|
|
||||||
|
print("---------------------------------------------")
|
||||||
|
print("This is the Memory Size test print out:")
|
||||||
|
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
my_string = "Hello, world!"
|
||||||
|
my_bytes = b'\x48\x65\x6c\x6c'
|
||||||
|
|
||||||
|
print(sys.getsizeof(my_string)) # Prints 62
|
||||||
|
print(sys.getsizeof(my_bytes)) # Prints 37
|
||||||
|
|
||||||
|
print()
|
||||||
|
print('Test the emoji:')
|
||||||
|
|
||||||
|
x = 'pizza' # Prints 54
|
||||||
|
y = b'pizza' # Prints 38
|
||||||
|
z = '🍕' #Prints 80
|
||||||
|
|
||||||
|
print(sys.getsizeof(x))
|
||||||
|
print(sys.getsizeof(y))
|
||||||
|
print(sys.getsizeof(z))
|
||||||
|
|
||||||
|
|
||||||
|
print("---------------------------------------------")
|
||||||
|
|
||||||
|
print("This is the String to Sequence of Numbers print out:")
|
||||||
|
|
||||||
|
def String_to_SequenceofNumbers():
|
||||||
|
my_string = input("Enter a string: ")
|
||||||
|
num_sequence = [ord(c) for c in my_string]
|
||||||
|
print(num_sequence)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
String_to_SequenceofNumbers()
|
||||||
|
|
||||||
|
print("---------------------------------------------")
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# 1. Why does ord("😀") give a different number than 0xf09f9880, which is what the hexdump of the same character yields?
|
||||||
|
#
|
||||||
|
# The ord() function returns the Unicode code point of a character as an integer, which is 128512 for the smiley face.
|
||||||
|
# However, the hexdump command, returns the UTF-8 encoding of character.
|
||||||
|
# The hexadecimal representation of 128512 is 0x1F600.
|
||||||
|
# The UTF-8 encoding of the "😀" character is represented by the sequence of bytes F0 9F 98 80 in hexadecimal.
|
||||||
|
# UTF-8 is one of the encoding schemes used to represent Unicode characters as binary data.
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# 8. Hypothetical Situation: If the dataframe is not formatted or cleaned, while the column storing the tomoto sales data isn't named exactly same as 'Tomato_Sales'
|
||||||
|
# It will raise a KeyError instead.
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# 9. The solution of the hypothetical situation from my question 8:
|
||||||
|
|
||||||
|
def read_tomato_sales(file_name):
|
||||||
|
data = pd.read_csv(file_name)
|
||||||
|
if not pd.api.types.is_numeric_dtype(data["Tomato_Sales"]):
|
||||||
|
raise TypeError("Tomato_Sales column should contain only numeric values")
|
||||||
|
total_sales = data.iloc[:, -1].sum() # This is the key
|
||||||
|
print(f"Total tomato sales: {total_sales}")
|
||||||
|
# read_tomato_sales("tomato_sales_error.csv")
|
||||||
|
|
||||||
|
|
||||||
|
# 10. Different human languages can use various character encodings such as UTF-8, UTF-16, or ASCII.
|
||||||
|
# While using bytes, you can work with raw data without worrying about specific encodings.
|
||||||
|
# This allows us to avoid encoding-related errors and ensures compatibility across different language texts.
|
||||||
|
|
||||||
|
def encode_decode_data():
|
||||||
|
print('-' * 20)
|
||||||
|
data = input("Enter a sentence using any language: ")
|
||||||
|
print('-' * 20)
|
||||||
|
print("The sentence you entered is: {}".format(data))
|
||||||
|
print('-' * 20)
|
||||||
|
encoded_data = data.encode('utf-8')
|
||||||
|
print("This sentence after encoded is: {}".format(encoded_data))
|
||||||
|
print('-' * 20)
|
||||||
|
byte_length = len(encoded_data)
|
||||||
|
print("The byte length of this sentence is: {}".format(byte_length))
|
||||||
|
print('-' * 20)
|
||||||
|
decoded_data = encoded_data.decode()
|
||||||
|
print("This sentence after decoded is: {}".format(decoded_data))
|
||||||
|
print('-' * 20)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run_function = 'function1'
|
||||||
|
|
||||||
|
if run_function == 'function1':
|
||||||
|
encode_decode_data()
|
||||||
|
elif run_function == 'function2':
|
||||||
|
read_tomato_sales(file_name)
|
||||||
|
|
||||||
|
|
||||||
|
# 2.5. REPL stands for Read-Eval-Print Loop.
|
||||||
|
# A REPL is an interactive programming environment that allows you to read input, evaluate expressions or statements, print output, and repeat the process.
|
||||||
|
# It provides a quick way to experiment with code, test small snippets, and get immediate feedback.
|
||||||
|
# The Python REPL allows you to interactively enter Python code and see the results immediately without needing to write a full script and execute it separately.
|
||||||
|
|
||||||
|
|
||||||
|
# 3. The '_' is a convention that holds the value of the last printed expression or the result of the last evaluated expression.
|
||||||
|
# The actual type of the "_" variable depends on the value assigned to it.
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
# Generate two random 64-bit integers
|
||||||
|
num1 = np.random.randint(0, 10 - 1)
|
||||||
|
num2 = np.random.randint(0, 10 - 1)
|
||||||
|
|
||||||
|
# Multiply them together using the normal Python multiplication operator
|
||||||
|
print(f"num1 * num2 = {num1 * num2}")
|
||||||
|
|
||||||
|
# Create a Pandas DataFrame with the generated numbers
|
||||||
|
data = {'Number1': [num1], 'Number2': [num2]}
|
||||||
|
df = pd.DataFrame(data)
|
||||||
|
|
||||||
|
# Multiply the numbers together using the Pandas multiplication operator
|
||||||
|
df['Product'] = df['Number1'] * df['Number2']
|
||||||
|
|
||||||
|
print(df)
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import sys
|
||||||
|
num = 99999999999
|
||||||
|
size = sys.getsizeof(num)
|
||||||
|
print(f"The size of the float is {size} bytes.")
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import time
|
||||||
|
|
||||||
|
i=0
|
||||||
|
while True:
|
||||||
|
print(f"\015{i=}", end='')
|
||||||
|
i += 1
|
||||||
|
time.sleep(0.2)
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
char1 = "u"
|
||||||
|
result1 = ord(char1)
|
||||||
|
print("ASCII value of the character {} is {}.".format(char1, result1))
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"id": "0593e529",
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"from urllib.parse import urlparse\n",
|
||||||
|
"\n",
|
||||||
|
"class JPEGRequestHandler:\n",
|
||||||
|
" def __init__(self, app):\n",
|
||||||
|
" self.app = app\n",
|
||||||
|
"\n",
|
||||||
|
" def __call__(self, environ, start_response):\n",
|
||||||
|
" url = urlparse(environ['REQUEST_URI'])\n",
|
||||||
|
" path = url.path\n",
|
||||||
|
"\n",
|
||||||
|
" if path.endswith('.jpg'):\n",
|
||||||
|
" file_path = path[1:]\n",
|
||||||
|
"\n",
|
||||||
|
" if os.path.isfile(file_path):\n",
|
||||||
|
" with open(file_path, 'rb') as file:\n",
|
||||||
|
" response_body = file.read()\n",
|
||||||
|
" status = '200 OK'\n",
|
||||||
|
" headers = [('Content-type', 'image/jpeg'),\n",
|
||||||
|
" ('Content-Length', str(len(response_body)))]\n",
|
||||||
|
"\n",
|
||||||
|
" start_response(status, headers)\n",
|
||||||
|
" return [response_body]\n",
|
||||||
|
" else:\n",
|
||||||
|
" status = '404 Not Found'\n",
|
||||||
|
" headers = [('Content-type', 'text/plain'),\n",
|
||||||
|
" ('Content-Length', '0')]\n",
|
||||||
|
"\n",
|
||||||
|
" start_response(status, headers)\n",
|
||||||
|
" return []\n",
|
||||||
|
" else:\n",
|
||||||
|
" status = '403 Forbidden'\n",
|
||||||
|
" headers = [('Content-type', 'text/plain'),\n",
|
||||||
|
" ('Content-Length', '0')]\n",
|
||||||
|
"\n",
|
||||||
|
" start_response(status, headers)\n",
|
||||||
|
" return []\n",
|
||||||
|
"\n",
|
||||||
|
"if __name__ == '__main__':\n",
|
||||||
|
" from werkzeug.serving import run_simple\n",
|
||||||
|
" from werkzeug.middleware.dispatcher import DispatcherMiddleware\n",
|
||||||
|
"\n",
|
||||||
|
" app = DispatcherMiddleware(JPEGRequestHandler(app), {'/': app})\n",
|
||||||
|
" run_simple('0.0.0.0', 8000, app, use_reloader=True)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.9.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 5
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import os
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
class JPEGRequestHandler:
|
||||||
|
def __init__(self, app):
|
||||||
|
self.app = app
|
||||||
|
|
||||||
|
def __call__(self, environ, start_response):
|
||||||
|
url = urlparse(environ['REQUEST_URI'])
|
||||||
|
path = url.path
|
||||||
|
|
||||||
|
if path.endswith('.jpg'):
|
||||||
|
file_path = path[1:]
|
||||||
|
|
||||||
|
if os.path.isfile(file_path):
|
||||||
|
with open(file_path, 'rb') as file:
|
||||||
|
response_body = file.read()
|
||||||
|
status = '200 OK'
|
||||||
|
headers = [('Content-type', 'image/jpeg'),
|
||||||
|
('Content-Length', str(len(response_body)))]
|
||||||
|
|
||||||
|
start_response(status, headers)
|
||||||
|
return [response_body]
|
||||||
|
else:
|
||||||
|
status = '404 Not Found'
|
||||||
|
headers = [('Content-type', 'text/plain'),
|
||||||
|
('Content-Length', '0')]
|
||||||
|
|
||||||
|
start_response(status, headers)
|
||||||
|
return []
|
||||||
|
else:
|
||||||
|
status = '403 Forbidden'
|
||||||
|
headers = [('Content-type', 'text/plain'),
|
||||||
|
('Content-Length', '0')]
|
||||||
|
|
||||||
|
start_response(status, headers)
|
||||||
|
return []
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
from werkzeug.serving import run_simple
|
||||||
|
from werkzeug.middleware.dispatcher import DispatcherMiddleware
|
||||||
|
|
||||||
|
app = DispatcherMiddleware(JPEGRequestHandler(app), {'/': app})
|
||||||
|
run_simple('0.0.0.0', 8000, app, use_reloader=True)
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import os
|
||||||
|
from http.server import SimpleHTTPRequestHandler, HTTPServer
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
class JPEGRequestHandler(SimpleHTTPRequestHandler):
|
||||||
|
def do_GET(self):
|
||||||
|
url = urlparse(self.path)
|
||||||
|
path = url.path
|
||||||
|
if path.endswith('.jpg'):
|
||||||
|
file_path = path[1:]
|
||||||
|
|
||||||
|
if os.path.isfile(file_path):
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header('Content-Type', 'image/jpeg')
|
||||||
|
self.end_headers()
|
||||||
|
|
||||||
|
with open(file_path, 'rb') as file:
|
||||||
|
self.wfile.write(file.read())
|
||||||
|
else:
|
||||||
|
self.send_error(404, 'File not found')
|
||||||
|
else:
|
||||||
|
self.send_error(403, 'Only .jpg files are allowed')
|
||||||
|
|
||||||
|
def run(server_class=HTTPServer, handler_class=JPEGRequestHandler, port=8000):
|
||||||
|
server_address = ('', port)
|
||||||
|
httpd = server_class(server_address, handler_class)
|
||||||
|
print(f'Serving JPEGs on port {port}...')
|
||||||
|
httpd.serve_forever()
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run()
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>D3.js Image Loading Time Graph</title>
|
||||||
|
<script src="https://d3js.org/d3.v5.min.js"></script>
|
||||||
|
<style>
|
||||||
|
/* Add some basic styling for the chart */
|
||||||
|
.bar {
|
||||||
|
fill: steelblue;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bar:hover {
|
||||||
|
fill: brown;
|
||||||
|
}
|
||||||
|
|
||||||
|
.axis {
|
||||||
|
font: 10px sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.axis path,
|
||||||
|
.axis line {
|
||||||
|
fill: none;
|
||||||
|
stroke: #000;
|
||||||
|
shape-rendering: crispEdges;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="chart"></div>
|
||||||
|
<div id="stats"></div>
|
||||||
|
<script>
|
||||||
|
// Generate the list of image URLs named kublai0.jpg to kublai118.jpg
|
||||||
|
const numberOfImages = 119;
|
||||||
|
const imagePrefix = 'http://localhost:8000/kublai';
|
||||||
|
const imageExtension = '.jpg';
|
||||||
|
const images = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < numberOfImages; i++) {
|
||||||
|
const imageName = `${imagePrefix}${i}${imageExtension}`;
|
||||||
|
images.push(imageName);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disable caching using cache-buster technique
|
||||||
|
const cacheBuster = (url) => `${url}?${new Date().getTime()}`;
|
||||||
|
|
||||||
|
// Load images and measure their loading times
|
||||||
|
const loadImages = async () => {
|
||||||
|
const loadingTimes = [];
|
||||||
|
|
||||||
|
for (const url of images) {
|
||||||
|
const startTime = performance.now();
|
||||||
|
const img = new Image();
|
||||||
|
img.src = cacheBuster(url);
|
||||||
|
img.style.display = 'none';
|
||||||
|
document.body.appendChild(img);
|
||||||
|
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
img.onload = () => {
|
||||||
|
const endTime = performance.now();
|
||||||
|
loadingTimes.push(endTime - startTime);
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return loadingTimes;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create a D3.js bar chart to visualize loading times
|
||||||
|
const createChart = (data) => {
|
||||||
|
const margin = { top: 20, right: 20, bottom: 30, left: 40 },
|
||||||
|
width = 1280 - margin.left - margin.right,
|
||||||
|
height = 500 - margin.top - margin.bottom;
|
||||||
|
|
||||||
|
const x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
|
||||||
|
const y = d3.scaleLinear().rangeRound([height, 0]);
|
||||||
|
|
||||||
|
const svg = d3.select('#chart')
|
||||||
|
.append('svg')
|
||||||
|
.attr('width', width + margin.left + margin.right)
|
||||||
|
.attr('height', height + margin.top + margin.bottom)
|
||||||
|
.append('g')
|
||||||
|
.attr('transform', `translate(${margin.left},${margin.top})`);
|
||||||
|
|
||||||
|
x.domain(data.map((d, i) => i));
|
||||||
|
y.domain([0, d3.max(data)]);
|
||||||
|
|
||||||
|
svg.append('g')
|
||||||
|
.attr('class', 'axis axis--x')
|
||||||
|
.attr('transform', `translate(0,${height})`)
|
||||||
|
.call(d3.axisBottom(x));
|
||||||
|
|
||||||
|
svg.append('g')
|
||||||
|
.attr('class', 'axis axis--y')
|
||||||
|
.call(d3.axisLeft(y).ticks(10))
|
||||||
|
.append('text')
|
||||||
|
.attr('transform', 'rotate(-90)')
|
||||||
|
.attr('y', 6)
|
||||||
|
.attr('dy', '0.71em')
|
||||||
|
.attr('text-anchor', 'end')
|
||||||
|
.text('Loading Time (ms)');
|
||||||
|
|
||||||
|
svg.selectAll('.bar')
|
||||||
|
.data(data)
|
||||||
|
.enter().append('rect')
|
||||||
|
.attr('class', 'bar')
|
||||||
|
.attr('x', (d, i) => x(i))
|
||||||
|
.attr('y', (d) => y(d))
|
||||||
|
.attr('width', x.bandwidth())
|
||||||
|
.attr('height', (d) => height - y(d));
|
||||||
|
|
||||||
|
const stats = document.getElementById('stats');
|
||||||
|
let textContent = '';
|
||||||
|
let average = 0;
|
||||||
|
let sum = 0;
|
||||||
|
let min = parseFloat(data[0]);
|
||||||
|
let max = parseFloat(data[0]);
|
||||||
|
for(datum of data) {
|
||||||
|
loadingTime = parseFloat(datum)
|
||||||
|
sum = sum + loadingTime
|
||||||
|
if(loadingTime > max) {
|
||||||
|
max = loadingTime;
|
||||||
|
}
|
||||||
|
if(loadingTime < min) {
|
||||||
|
min = loadingTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
average = sum / data.length
|
||||||
|
textContent =
|
||||||
|
'Total: ' + sum +
|
||||||
|
' Average: ' + average +
|
||||||
|
' Min: ' + min +
|
||||||
|
' Max: ' + max;
|
||||||
|
stats.textContent = textContent;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Load images and create the chart
|
||||||
|
(async () => {
|
||||||
|
const loadingTimes = await loadImages();
|
||||||
|
createChart(loadingTimes);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 107 KiB |
|
After Width: | Height: | Size: 75 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 64 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 91 KiB |