diff --git a/students/robert/Python 200/Session 1/echo_client.py b/students/robert/Python 200/Session 1/echo_client.py new file mode 100644 index 0000000..8e47ecd --- /dev/null +++ b/students/robert/Python 200/Session 1/echo_client.py @@ -0,0 +1,67 @@ +#!/usr/bin/env_python + +import socket +import sys + + +def client(msg, log_buffer=sys.stderr): + server_address = ('localhost', 10000) + # TODO: Replace the following line with your code which will instantiate + # a TCP socket with IPv4 Addressing, call the socket you make 'sock' + # sock = None + sock = socket.socket( + socket.AF_INET, + socket.SOCK_STREAM, + socket.IPPROTO_IP) + print('connecting to {0} port {1}'.format(*server_address), file=log_buffer) + + # TODO: connect your socket to the server here. + sock.connect(('127.0.0.1', 10000)) + + # you can use this variable to accumulate the entire message received back + # from the server + received_message = '' + + # this try/finally block exists purely to allow us to close the socket + # when we are finished with it + try: + print('sending "{0}"'.format(msg), file=log_buffer) + # TODO: send your message to the server here. + # strToSend = 'Hey, can you hear me?' + sock.sendall(msg.encode('utf8')) + strLen = len(msg) + # TODO: the server should be sending you back your message as a series + # of 16-byte chunks. Accumulate the chunks you get to build the + # entire reply from the server. Make sure that you have received + # the entire message and then you can break the loop. + # + # Log each chunk you receive. Use the print statement below to + # do it. This will help in debugging problems + buffer_size = 16 + strReceivedLen = 0 + while True: + chunk = sock.recv(buffer_size) + print('received "{0}"'.format(chunk.decode('utf8')), file=log_buffer) + received_message += chunk + strReceivedLen += len(chunk) + if strLen == strReceivedLen: + break + + finally: + # TODO: after you break out of the loop receiving echoed chunks from + # the server you will want to close your client socket. + sock.close() + print('closing socket', file=log_buffer) + + # TODO: when all is said and done, you should return the entire reply + # you received from the server as the return value of this function. + return received_message + +if __name__ == '__main__': + if len(sys.argv) != 2: + usage = '\nusage: python echo_client.py "this is my message"\n' + # print(usage, file=sys.stderr) + sys.exit(1) + + msg = sys.argv[1] + client(msg) \ No newline at end of file diff --git a/students/robert/Python 200/Session 1/echo_server.py b/students/robert/Python 200/Session 1/echo_server.py new file mode 100644 index 0000000..86f5909 --- /dev/null +++ b/students/robert/Python 200/Session 1/echo_server.py @@ -0,0 +1,94 @@ +#!/usr/bin/env_python + +import socket +import sys + + +def server(log_buffer=sys.stderr): + # set an address for our server + address = ('127.0.0.1', 10000) + # TODO: Replace the following line with your code which will instantiate + # a TCP socket with IPv4 Addressing, call the socket you make 'sock' + # sock = None + sock = socket.socket( + socket.AF_INET, + socket.SOCK_STREAM, + socket.IPPROTO_TCP) + # TODO: You may find that if you repeatedly run the server script it fails, + # claiming that the port is already used. You can set an option on + # your socket that will fix this problem. We DID NOT talk about this + # in class. Find the correct option by reading the very end of the + # socket library documentation: + # http://docs.python.org/3/library/socket.html#example + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + # log that we are building a server + print("making a server on {0}:{1}".format(*address), file=log_buffer) + + # TODO: bind your new sock 'sock' to the address above and begin to listen + # for incoming connections + sock.bind(address) + sock.listen(1) + + try: + # the outer loop controls the creation of new connection sockets. The + # server will handle each incoming connection one at a time. + while True: + print('waiting for a connection', file=log_buffer) + + # TODO: make a new socket when a client connects, call it 'conn', + # at the same time you should be able to get the address of + # the client so we can report it below. Replace the + # following line with your code. It is only here to prevent + # syntax errors + # addr = ('bar', 'baz') + conn, addr = sock.accept() + try: + print('connection - {0}:{1}'.format(*addr), file=log_buffer) + # the inner loop will receive messages sent by the client in + # buffers. When a complete message has been received, the + # loop will exit + while True: + # TODO: receive 16 bytes of data from the client. Store + # the data you receive as 'data'. Replace the + # following line with your code. It's only here as + # a placeholder to prevent an error in string + # formatting + # data = b'' + # print('received "{0}"'.format(data.decode('utf8'))) + buffer_size = 16 + data = conn.recv(buffer_size) + print('received "{0}"'.format(data.decode('utf8'))) + # TODO: Send the data you received back to the client, log + # the fact using the print statement here. It will help in + # debugging problems. + conn.sendall(data) + # .encode('utf8')) + print('sent "{0}"'.format(data.decode('utf8'))) + # TODO: Check here to see if the message you've received is + # complete. If it is, break out of this inner loop. + if not data: + break + + finally: + # TODO: When the inner loop exits, this 'finally' clause will + # be hit. Use that opportunity to close the socket you + # created above when a client connected. + conn.close() + print( + 'echo complete, client connection closed', file=log_buffer + ) + + except KeyboardInterrupt: + # TODO: Use the python KeyboardInterrupt exception as a signal to + # close the server socket and exit from the server function. + # Replace the call to `pass` below, which is only there to + # prevent syntax problems + # pass + sock.close() + print('quitting echo server', file=log_buffer) + + +if __name__ == '__main__': + server() + sys.exit(0) \ No newline at end of file diff --git a/students/robert/Python 200/Session 1/socket_tools.py b/students/robert/Python 200/Session 1/socket_tools.py new file mode 100644 index 0000000..19732fb --- /dev/null +++ b/students/robert/Python 200/Session 1/socket_tools.py @@ -0,0 +1,23 @@ +#!/usr/bin/env_python + +import socket + + +def get_constants(prefix): + return {getattr(socket, n): n for n in dir(socket) if n.startswith(prefix)} + + +families = get_constants('AF_') +types = get_constants('SOCK_') +protocols = get_constants('IPPROTO_') + + +def get_address_info(host, port): + for response in socket.getaddrinfo(host, port): + fam, typ, pro, nam, add = response + print('family: {}'.format(families[fam])) + print('type: {}'.format(types[typ])) + print('protocol: {}'.format(protocols[pro])) + print('canonical name: {}'.format(nam)) + print('socket address: {}'.format(add)) + print() \ No newline at end of file diff --git a/students/robert/Python 200/Session 1/tests.py b/students/robert/Python 200/Session 1/tests.py new file mode 100644 index 0000000..b7f853f --- /dev/null +++ b/students/robert/Python 200/Session 1/tests.py @@ -0,0 +1,47 @@ +#!/usr/bin/env_python + +from echo_client import client +import socket +import unittest + + +class EchoTestCase(unittest.TestCase): + """tests for the echo server and client""" + + def send_message(self, message): + """Attempt to send a message using the client + In case of a socket error, fail and report the problem + """ + try: + reply = client(message) + except socket.error as e: + if e.errno == 61: + msg = "Error: {0}, is the server running?" + self.fail(msg.format(e.strerror)) + else: + self.fail("Unexpected Error: {0}".format(str(e))) + return reply + + def test_short_message_echo(self): + """test that a message short than 16 bytes echoes cleanly""" + expected = "short message" + actual = self.send_message(expected) + self.assertEqual( + expected, + actual, + "expected {0}, got {1}".format(expected, actual) + ) + + def test_long_message_echo(self): + """test that a message longer than 16 bytes echoes in 16-byte chunks""" + expected = "Four score and seven years ago our fathers did stuff" + actual = self.send_message(expected) + self.assertEqual( + expected, + actual, + "expected {0}, got {1}".format(expected, actual) + ) + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/students/robert/Session 8/Circle_Class.py b/students/robert/Session 8/Circle_Class.py new file mode 100644 index 0000000..842682a --- /dev/null +++ b/students/robert/Session 8/Circle_Class.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python + +import math + +class Circle(object): + + # radius = None + def __init__ (self,radius): + self.radius = float(radius) + self.diameter = float(radius*2) + + + + # @property + # def radius(self): + # return int(self.radius) + + # @radius.setter + # def radius(self,value): + # print('In radius setter') + # self.radius = int(value) + + @property + def diameter(self): + return float(self.radius*2) + + @diameter.setter + def diameter(self,value): + self.radius = float(value/2) + + @property + def area(self): + return round((math.pi*(self.radius**2)),6) + + @area.setter + def area(self,value): + # how to just return AttributeError? -- Step 4 + print(AttributeError) + +# from_diameter() missing 1 required positional argument 'Value' -- Step 5 + @classmethod + def from_diameter(cls,value): +# cls.radius = int(value/2) + return cls(float(value/2)) + + def __str__(self): + return('Circle with radius: {}'.format(round(self.radius*2,6))) + + def __repr__(self): + return 'Circle(diameter={})'.format(self.radius*2) + + def __add__(self,other): + total = (self.diameter+other.diameter)/4 + return Circle(total) + + + def __mul__(self,other): + mul = self.diameter/4*other + return Circle(mul) + + def __rmul__(self,other): + rmul = self.diameter/4*other + return Circle(rmul) + + def __eq__(self,other): + return self.diameter/4 == other.diameter/4 + + def __gt__(self,other): + return self.diameter/4 > other.diameter/4 + + def __lt__(self,other): + return self.diameter/4 < other.diameter/4 + + + + + + + + + + + + + + + + + + + + + + + diff --git a/students/robert/Session 8/Circle_Class_Test.py b/students/robert/Session 8/Circle_Class_Test.py new file mode 100644 index 0000000..6edb6fc --- /dev/null +++ b/students/robert/Session 8/Circle_Class_Test.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + + +from Circle_Class import Circle + +import pytest + +from math import pi + + +import unittest +#from Circle_Class import Circle + +def test_init(): + Circle(3) + +def test_radius(): + c = Circle(3) + assert c.radius == 3 + + + +# class Test(): + +# def setUp(self): +# pass + +# def TestCase(self): +# c = Circle(4) +# self.assertEqual(c.radius,float(4)) + + +# if __name__ == '__main__': +# unittest.main() + diff --git a/students/robert/Session 8/Lambda.py b/students/robert/Session 8/Lambda.py new file mode 100644 index 0000000..be85cb2 --- /dev/null +++ b/students/robert/Session 8/Lambda.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python + +# Using Lambda + +def function_builder(n): + + l = [] + + for i in range(n): + l.append(lambda x, e=i: x + e) + + return l + +# Using List Comprehensions + +def function_builder(n): + + l = [lambda x, e=i: x+e for i in range(n)] + + return l + + diff --git a/students/robert/Session 9/Comprehension.py b/students/robert/Session 9/Comprehension.py new file mode 100644 index 0000000..fafd192 --- /dev/null +++ b/students/robert/Session 9/Comprehension.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +# Comprehension Lab + +#Count Even Numbers +def count_evens(array): + + updated_array = [x for x in array if x%2 == 0 or x == 0 ] + return len(updated_array) + + +# comprehension test for dict and set +food_prefs = {"name": "Chris", + "city": "Seattle", + "cake": "chocolate", + "fruit": "mango", + "salad": "greek", + "pasta": "lasagna"} + +def comprehension(dict): + print("{name} is from {city}, and he likes {cake} cake, {fruit} fruit, {salad} salad, and {pasta} pasta".format(**dict)) + + +num = [x for x in range(16)] +nhex = [hex(x) for x in range(16)] + +for x in num: + for y in nhex: + numhex[x] = y + + +numhex = {x:hex(x) for x in range(16)} + + +#fp_copy = food_prefs +fp_copy = {} + +def countA(v): + count = 0 + for x in v: + if x == 'a' or x == 'A': + count+=1 + return count + +for k,v in food_prefs.items(): + fp_copy[k] = countA(v) + + +Nlist = [i for i in range(21)] + +Dlist = [2,3,4] + +s2 = set(x for x in Nlist if x%2 == 0) + +s3 = set(x for x in Nlist if x%3 == 0) + +s4 = set(x for x in Nlist if x%4 == 0) + +#slist = [s2,s3,s4] + +slist = [set(x for x in Nlist if x%t == 0) for t in Dlist ]