Example #1
0
 def start(self):
     self.tcp_sock.listen(5)
     while True:
         (cs, addr) = self.tcp_sock.accept()
         print("Client connected from " + str(addr[0]))
         data = cs.recv(1024)
         data = data.decode()  # expected to receive a string
         try:
             ci = ClientInput(data)
             if ci.t == 'E':
                 print("Client requesting evaluation")
                 ans = polynomials.evaluate(ci.arg1, ci.arguments)
                 msg = "E" + str(ans)
             if ci.t == 'S':
                 print("Client requesting bisection")
                 print("a: " + str(ci.arg1))
                 print("b: " + str(ci.arg2))
                 print("tol: " + str(ci.tol))
                 print("arguments: " + str(ci.arguments))
                 ans = polynomials.bisection(ci.arg1, ci.arg2, ci.arguments,
                                             ci.tol)
                 msg = "S" + str(ans)
                 #print (ans)
         except Exception:
             print("Client sent invalid data")
             msg = "XError parsing data"
         cs.sendall(msg.encode())
Example #2
0
def Evaluate(Identifier, DataArray):
	DataArray = DataArray.replace(Identifier,"")
	print('Received data: '+ DataArray)
	DataArray = DataArray.split(' ')
	print('After spliting: ')
	print(DataArray)
	Xvalue = float(DataArray[0])
	newValues = []
	for s in range(len(DataArray)-1):
		newValues.append(DataArray[s+1])
	print('In an int array: ')
		
	print(newValues)
	print("\nX-value: ")
	print(Xvalue)
	newValues = map(int, newValues)
	result = str(polynomials.evaluate(Xvalue,newValues))
	clientsocket.send("E"+result)
Example #3
0
        logging.info("all data received: " + data_string)
        response = 'response was not properly set'

        values = data_string.split(' ')
        logging.info("values: {}".format(values))
        logging.info("Peter test: {}, number of values: {}".format(values[0][0], len(values)))
        if len(values) <= 1 or values[0][0] not in ACCEPTABLE_REQUEST_TYPES:
            logging.error("Invalid request syntax |{}|".format(data_string))
            response = 'XInvalid request syntax, Your request either did not start with an E or S,' \
                       ' or you had too few arguments'
        else:
            if values[0][0] == ACCEPTABLE_REQUEST_TYPES[0]:
                try:
                    x = float(values[0][1:])
                    poly = [float(x) for x in values[1:]]
                    result = polynomials.evaluate(x, poly)
                    logging.info("Evaluating {} for {}".format(x, poly))
                    print("Result: ", result)
                    response = "E" + str(result)
                except:
                    response = 'Xinvalid numeric format'
            elif values[0][0] == ACCEPTABLE_REQUEST_TYPES[1]:
                try:
                    a = float(values[0][1:])
                    b = float(values[1])
                    poly = [float(x) for x in values[2:len(values) - 1]]
                    tolerance = float(values[len(values) - 1])
                    logging.info("Bisection with a:{}, b{}, poly{}, tolerance{}".format(a, b, poly, tolerance))
                    result = polynomials.bisection(a, b, poly, tolerance)
                    response = "S" + str(result)
                except:
    if len(request) == 0:
        message = "XEmpty request"
        logging.error(" response " + message)
        sock.sendall(message.encode())
        sock.shutdown(1)
    else:
        request_code = request[0]   # assuming the message has at least one character
        if request_code == "E":
            try:
                parameters = request[1:].split(' ')
                args = [float(x) for x in parameters]

                x = args[0]
                poly = args[1:]

                value = polynomials.evaluate(x, poly)

                message = "E" + str(value)
                logging.info("response " + message)
                sock.sendall(message.encode())
                sock.shutdown(1)
            except Exception as ex:
                logging.error("Input value conversion error " + request[1:])
                logging.error(str(ex))
                message = "X Invalid format numeric data: " + request[1:]
                logging.error("response " + message)
                sock.sendall(message.encode())
                sock.shutdown(1)

        elif request_code == "S":
            try:
Example #5
0
                tol = float(tokens[len(tokens) - 1])
                poly = []
                for i in range(2, len(tokens) - 1):
                    poly.append(float(tokens[i]))
                reply = "S" + str(bisection(a, b, poly, tol))
            except ValueError:
                reply = "Xinvalid format numeric data"

    elif message[0] == "E":
        tokens = message[1:].split()
        if len(tokens) < 1:
            reply = "Wrong number of fields in request"
        else:
            try:
                x = float(tokens[0])
                poly = []
                for i in range(1, len(tokens)):
                    poly.append(float(tokens[i]))
                reply = "E" + str(evaluate(x, poly))
            except ValueError:
                reply = "Xinvalid format numeric data"

    else:
        reply = "Invalid Operator:" + str(message[0])

    print("Sending result: " + reply)
    received = reply.encode()
    socket.sendall(received)
    socket.shutdown(1)
    socket.close()
check.close()
Example #6
0
        message = "XEmpty request"
        logging.error(" response " + message)
        sock.sendall(message.encode())
        sock.shutdown(1)
    else:
        request_code = request[
            0]  # assuming the message has at least one character
        if request_code == "E":
            try:
                parameters = request[1:].split(' ')
                args = [float(x) for x in parameters]

                x = args[0]
                poly = args[1:]

                value = polynomials.evaluate(x, poly)

                message = "E" + str(value)
                logging.info("response " + message)
                sock.sendall(message.encode())
                sock.shutdown(1)
            except Exception as ex:
                logging.error("Input value conversion error " + request[1:])
                logging.error(str(ex))
                message = "X Invalid format numeric data: " + request[1:]
                logging.error("response " + message)
                sock.sendall(message.encode())
                sock.shutdown(1)

        elif request_code == "S":
            try:
from polynomials import evaluate, bisection

poly = [-945, 1689, -950, 230, -25, 1]
x = 1.0
a = 0
b = 2
tol = 1e-15

v = evaluate(x, poly)
print(v)

r = bisection(a, b, poly, tol)
print(r)
Example #8
0
            if len(list_of_parts) < 2:
                raise Exception("Too few arguments"
                                )  # Caught if there aren't enough arguments

            # If we are sending an polynomials.evaluate request, it will start with E
            # followed by the value of x
            # i.e. E1.0 is evaluate given polynomial where 1.0 is the value of x
            for i in range(1, len(list_of_parts)):
                list_of_parts[i] = int(list_of_parts[i])

            print("Printing the list of parts after converting")
            print(list_of_parts)
            print("xval is: " + list_of_parts[0][1:] + " poly is: " +
                  str(list_of_parts[1:]))

            result = evaluate(float(list_of_parts[0][1:]), list_of_parts[1:])
            print("result " + str(result))
            response_status = 'E'
            response_message = str(result)
        elif client_data[0] == "S":
            if len(list_of_parts) < 4:
                raise Exception("Too few arguments"
                                )  # Caught if there aren't enough arguments

            if float(list_of_parts[len(list_of_parts) - 1]) < 0:
                raise Exception(
                    "Invalid tolerance"
                )  # According to polynomials.py, tolerances should be greater than 0

            elif float(list_of_parts[len(list_of_parts) - 1]) == 0:
                raise Exception("Invalid tolerance"
                result = too_few_args_error()
                end_connection(response_tag="X", result=result, sock=sock)

            # data[0] = float(data[0].replace("E",""))
            data.pop(0)
            i = 0
            while i < len(data):
                try:
                    data[i] = float(data[i])
                except:
                    result = string_to_float_error(data[i])
                    end_connection(response_tag="X", result=result, sock=sock)
                    exit(0)
                i += 1
                try:
                    result = polynomials.evaluate(x, data)
                except:
                    break

        elif "S" in data[0]:
            response_tag = "S"
            try:
                a = float(data[0].replace("S", ""))
                data[0] = a
            except:
                result = string_to_float_error(data[0].replace("S", ""))
                end_connection(response_tag="X", result=result, sock=sock)

            try:
                b = data[1]
            except:
Example #10
0
from polynomials import evaluate, bisection

# Evaluate
print("=========== Evaluate ===========")

message = "E1.0 -945 1689 -950 230 -25 1"

argsStr = message[1:].split(' ')
args = [float(x) for x in argsStr]

x = args[0]
poly = args[1:]
result = evaluate(x, poly)
print("Evaluation: " + str(result))
print("===============================\n")

# Bisection
print("========== Bisection ==========")

message = "S0 2 -945 1689 -950 230 -25 1 1e-15"

argsStr = message[1:].split(' ')
args = [float(x) for x in argsStr]

a = args[0]
b = args[1]
poly = args[2:8]
tol = args[8]

print('a: ' + str(a))
print('b: ' + str(b))
Example #11
0
    client_data = ""
    # get data from the client
    while len(bytes) > 0:
        client_data += bytes.decode()
        bytes = sock.recv(2048)

    # parse and process the data from the client

    if client_data[0] == 'E':
        try:
            print("Received Data Before Splitting: " + client_data)
            list_of_parts = client_data.split(' ')
            print("Data After Split: " + str(list_of_parts))
            xVal = float(list_of_parts[0][1:])
            poly = list(map(int, list_of_parts[1:]))
            result = polynomials.evaluate(xVal, poly)
            print("Evaluate Polynomial Calculation Completed: " + str(result))
        except:
            # signal an error
            # error response
            response_status = 'X:'
            response_message = ' Invalid Format Numeric Data to Evaluate!'
            logging.error(response_message)
    elif client_data[0] == 'S':
        try:
            print("Received Data Before Splitting: " + client_data)
            list_of_parts = client_data.split(' ')
            print("Data After Split: " + str(list_of_parts))
            aVal = int(list_of_parts[0][1:])
            bVal = int(list_of_parts[1])
            polyBisec = list(map(int, list_of_parts[2:-1]))
     and non integer Polynomials.
     '''
     if (len(request) < 4 or len(request) > 4):
         error = ['X', "Missing arguments."]
         err(error)
         print("Shutting down server.")
         c.close()
     elif not (all(isinstance(item, int) for item in request[3])):
         error = ['X', "Invalid number format."]
         err(error)
         print("Shutting down server.")
         c.close()
     else:
         x = request[1]
         poly = request[3]
         temp = polynomials.evaluate(x, poly)
         success = ['E', temp]
         #c.send(success)
         eval(success)
         print("Server finished. Shutting down.")
         c.close()
 elif request[0] == 'S':
     '''
     Error checking for request type 'X'.
     I've tested for missing arguments
     and non integer polynomials.
     '''
     if (len(request) < 8 or len(request) > 8):
         error = ['X', "Missing Arguments"]
         #c.send(error)
         err(error)
Example #13
0
            test_string = data.decode()

            print("Server received: " + test_string)
            try:

                # Evaluate expression
                if test_string.split(' ').pop(0)[0] is 'E':

                    try:
                        if len(test_string.split(' ')) is 1:
                            conn.sendall(str.encode("XToo few arguments "))

                        else:
                            x = float(test_string.split(' ').pop(0)[1:])
                            poly = list(map(int, test_string[5:].split(' ')))
                            result = str(polynomials.evaluate(x, poly))

                            print("Sending back to client... E" + result)
                            conn.sendall(str.encode("E" + result))

                    except:
                        conn.sendall(
                            str.encode("Could not convert string to float"))

                #evaluate bisection
                if test_string.split(' ').pop(0)[0] is 'S':

                    try:
                        if len(test_string.split(' ')) is 1:
                            conn.sendall(str.encode("XToo few arguments "))