示例#1
0
def validateInput(inputString):
    valid = set(string.ascii_letters)
    valid.add(".")
    valid |= set(map(str,range(10)))
    for i in inputString:
        if i not in valid:
            error(inputString,"Caracter invalido en nombre archivo:"+"'{}'".format(i))
示例#2
0
 def __init__(self, space, id, x1, y1, x2, y2, link_type = 1, color = [0,0,255]):
     self.error_details = '' #stores additional information on error to help user fix the issue.
     try:
         self.space = space
         self.id = id
         self.created = False
         self._parse_input(x1, y1, x2, y2, link_type, color) #convert string inputs to appropriate data types
         valid_input = self._check_input(self.x1, self.y1, self.x2, self.y2, self.link_type, self.color) #ensure inputs are in the required data types
         if valid_input: #add link if input is correct                
             self.start = Vec2d(self.x1, self.y1)
             self.end = Vec2d(self.x2, self.y2)
             self.color = self.color + [255]
             if self.link_type == 'D':
                 self.body = pymunk.Body(body_type=pymunk.Body.DYNAMIC)
             else:
                 self.body = pymunk.Body(body_type=pymunk.Body.STATIC)
             self.shape = pymunk.Segment(self.body, self.start, self.end, 5)
             self.shape.filter = pymunk.ShapeFilter(group=2)
             self.shape.mass = 10
             self.shape.friction = 1
             self.shape.color = self.color
             self.space.add(self.body, self.shape)
             self.created = True
         else:
             raise Exception
     except:
         self.error_mssg = 'Invalid input for ' + self.id + '\nPlease ensure all values are in the appropriate format. Refer to documentation for more help.'
         if self.error_details != '':
             self.error_mssg += '\n\nError Details:\n' + self.error_details
         error(self.error_mssg)
         logging.exception('message')
示例#3
0
 def site(self, site):
   try:
     site_is_str = str(site) #check site name is a string
     return site_is_str.lower() #make is lowercase for consistancy
   except Exception as e:
     error(32, str(e)+' vaild.site() error', False)
     return None
示例#4
0
文件: parsing.py 项目: qihqi/pylox
 def primary(self):
     if self.match(TokenType.SUPER):
         keyword = self.previous()
         self.consume(TokenType.DOT, 'Expect . after super')
         method = self.consume(TokenType.IDENTIFIER,
                               'Expect superclass method')
         return SuperExpr(keyword, method)
     if self.match(TokenType.FALSE):
         return Expr.literal(self.previous())
     if self.match(TokenType.TRUE):
         return Expr.literal(self.previous())
     if self.match(TokenType.NIL):
         return Expr.literal(self.previous())
     if self.match(TokenType.NUMBER, TokenType.STRING):
         return Expr.literal(self.previous())
     if self.match(TokenType.THIS):
         return Expr.literal(self.previous())
     if self.match(TokenType.IDENTIFIER):
         return Expr.literal(self.previous())
     if self.match(TokenType.LEFT_PAREN):
         expr = self.expression()
         self.consume(TokenType.RIGHT_PAREN, 'Expect ) after expression')
         return expr
     error.error(self.peek().line, "Expect expression")
     raise ParseError()
示例#5
0
 def time(self, time):
   try:
     time_is_int = int(time)#check time is an interger
     return time_is_int #return the interger
   except Exception as e:
     error(33, str(e)+' vaild.time() error', False)
     return None
示例#6
0
        def visit_Assign(self, node):
            if isinstance(node.value, ast.Subscript) and isinstance(node.value.value, ast.Call):
                subscr = node.value
                call = subscr.value
                
                if len(node.targets) > 1:
                    error.error('Cannot use multiple assignment in array declaration.', node)
                    
                variable_name = node.targets[0].id
                value_type = call.func.id
                declaration_args = call.args

                # Get the indices being accessed.
                shape = slice_node_to_tuple_of_numbers(subscr.slice)

                new_assigns = []
                for indices in itertools.product(*[range(n) for n in shape]):
                    index_name = flattened_array_name(variable_name, indices)
                    new_index_name_node = ast.copy_location(ast.Name(index_name, ast.Store()), node)
                    new_value_type_node = ast.copy_location(ast.Name(value_type, ast.Load()), node)
                    new_declaration_args = [copy.deepcopy(arg) for arg in declaration_args]
                    new_call_node = ast.copy_location(ast.Call(new_value_type_node, new_declaration_args, [], None, None), node)
                    new_assign = ast.Assign([new_index_name_node], new_call_node)
                    new_assign = ast.copy_location(new_assign, node)
                    new_assigns.append(new_assign)
                return new_assigns
            else:
                return node
示例#7
0
        def visit_Assign(self, node):
            if isinstance(node.value, ast.Subscript) and isinstance(node.value.value, ast.Call):
                subscr = node.value
                call = subscr.value
                
                if len(node.targets) > 1:
                    error.error('Cannot use multiple assignment in array declaration.', node)
                    
                variable_name = node.targets[0].id
                value_type = call.func.id
                declaration_args = call.args

                # Get the indices being accessed.
                shape = slice_node_to_tuple_of_numbers(subscr.slice)

                new_assigns = []
                for indices in itertools.product(*[range(n) for n in shape]):
                    index_name = flattened_array_name(variable_name, indices)
                    new_index_name_node = ast.copy_location(ast.Name(index_name, ast.Store()), node)
                    new_value_type_node = ast.copy_location(ast.Name(value_type, ast.Load()), node)
                    new_declaration_args = [copy.deepcopy(arg) for arg in declaration_args]
                    new_call_node = ast.copy_location(ast.Call(new_value_type_node, new_declaration_args, [], None, None), node)
                    new_assign = ast.Assign([new_index_name_node], new_call_node)
                    new_assign = ast.copy_location(new_assign, node)
                    new_assigns.append(new_assign)
                return new_assigns
            else:
                return node
示例#8
0
def cpu(pid=-1):
    if pid == 0:
        return 0
    if pid in cpu_cache:
        return cpu_cache[pid]
    try:
        total_time = get_total_time(pid)
        now = time.time()
        if not pid in total_times:
            total_times[pid] = (now, total_time)
        last_when, last_time = total_times[pid]
        result = (total_time - last_time) / (now - last_when + 0.00001)
        total_times[pid] = (now, total_time)
        cpu_cache[pid] = result
        return result
    except psutil.AccessDenied as e:
        cmd = ps_output = "???"
        try:
            cmd = "ps -p %s -o %%cpu | grep -v CPU" % pid
            ps_output = os.popen(cmd).read() or "0"
            return float(ps_output) / 100
        except:
            error.error("Cannot parse '%s' => '%s' into a float in process.cpu" % (cmd, ps_output))
        return 0
    except (psutil.NoSuchProcess, psutil.ZombieProcess) as e:
        return 0
    except Exception as e:
        log.log("Unhandled Error in process.cpu", e)
        return 0
def time_comparison(time0, time1):
    """
    Compares in-game time   

    Parameters
    ----------
    time0 : tuple
        time data of the form (hour,day,month,year).
    time1 : tuple
        time data of the form (hour,day,month,year).

    Returns
    -------
    bool
        True if time1<=time0.

    """
    if len(time0)!=len(time1):
        error("time_comparison length error")
        return
    
    for i in range(len(time0)):
        print(time0[-i-1],time1[-i-1])
        if time0[-i-1]>time1[-i-1]:
          #  print(True)
            return True
        elif time0[-i-1]<time1[-i-1]:
         #   print(False)
            return False
    print("equal")
    return True
示例#10
0
文件: main.py 项目: laffra/happymac
 def suspend(self, menuItem, pid, battery=False):
     try:
         suspender.suspend_process(pid, manual=True, battery=battery)
     except:
         error.error("Error in menu callback")
     finally:
         self.handle_action()
示例#11
0
文件: main.py 项目: laffra/happymac
 def resume(self, menuItem, pid):
     try:
         suspender.resume_process(pid, manual=True)
     except:
         error.error("Error in menu callback")
     finally:
         self.handle_action()
示例#12
0
 def __init__(self, space, id, sides, vertices, radius, color, obstacle_type):
     self.error_details = ''
     try:
         self.id = id
         self.created = False
         self.space = space
         self._parse_input(sides, vertices, radius, color, obstacle_type) #convert string inputs to appropriate data types
         valid_input = self._check_input(self.sides, self.vertices, self.radius, self.color, self.obstacle_type) #ensure inputs are in the required data types
         if valid_input:
             if self.obstacle_type == 'D':
                 self.body = pymunk.Body(body_type = pymunk.Body.DYNAMIC)
             if self.obstacle_type == 'F':
                 self.body = pymunk.Body(body_type = pymunk.Body.STATIC)
             self.color = self.color + [255]
             if self.sides == 1:
                 self.body.position = self.vertices
                 self.shape = pymunk.Circle(self.body, self.radius)
             elif self.sides == 2:
                 self.shape = pymunk.Segment(self.body, self.vertices[0:2], self.vertices[2:], self.radius)
             else:
                 self.shape = pymunk.Poly(self.body, self._group_vertices(self.vertices), None, self.radius)
             self.shape.friction = 1
             self.shape.mass = 10
             self.shape.color = self.color
             self.space.add(self.body, self.shape)
             self.vertices = self._group_vertices(self.vertices)
             self.created = True
         else:
             raise Exception
     except:
         self.error_mssg = 'Invalid input for ' + self.id + '\nPlease ensure all values are in the appropriate format. Refer to documentation for more help.'
         if self.error_details != '':
             self.error_mssg += '\n\nError Details:\n' + self.error_details
         error(self.error_mssg)
示例#13
0
 def gen_stmt(stmt):
     if stmt["nodetype"] == AST_ASSIGN:
         if stmt["lhs"] not in symtab:
             error("undeclared variable: %s" % stmt["lhs"])
         expr_loc = gen_expr(stmt["rhs"])
         print("%s = %s;" % (stmt["lhs"], expr_loc))
     elif stmt["nodetype"] == AST_PRINT:
         expr_loc = gen_expr(stmt["expr"])
         if stmt["expr"]["type"] == "int":
             flag = "d"
         else:
             flag = "f"
         print('printf("%%%s\\n", %s);' % (flag, expr_loc))
     elif stmt["nodetype"] == AST_READ:
         id = stmt["id"]["value"]
         if symtab[id] == "int":
             flag = "d"
         else:
             flag = "f"
         print('scanf("%%%s", &%s);' % (flag, id))
     elif stmt["nodetype"] == AST_WHILE:
         expr_loc = gen_expr(stmt["expr"])
         print("while (%s) { " % expr_loc)
         for body_stmt in stmt["body"]:
             gen_stmt(body_stmt)
         gen_expr(stmt["expr"], expr_loc)
         print("}")
示例#14
0
 def return_foreign_speeders(self):#Return all data of foreign cars over speed limit.
   try:
     self.ecx.execute("select d_index, p.p_id, uuid, s_id, time, cam_id, speed from data as d, plates as p where d.speed > 0 and p_foreign = 'TRUE' and p.p_id=d.p_id;")
     result = self.ecx.fetchall()
     return result
   except Exception as e:
     error(13,str(e)+' sql record_speeders() error', True)
示例#15
0
def main():
    if (len(sys.argv) != 2):
        error.error('python histogram.py [file]')
    filename = sys.argv[1]
    content = ''
    try:
        f = open(filename, 'r')
        content = f.read()
        f.close()
    except:
        error.error('error opening file')
    data = parse.parseCSV(content)
    names = data[0][6:]
    values = getValues(data)
    plt.figure(figsize=(25, 15))
    i = 0
    while (i < len(names)):
        plt.subplot(3, 5, i + 1)
        plt.hist(values[names[i]]['Gryffindor'], color='red', alpha=0.6)
        plt.hist(values[names[i]]['Hufflepuff'], color='yellow', alpha=0.6)
        plt.hist(values[names[i]]['Slytherin'], color='green', alpha=0.6)
        plt.hist(values[names[i]]['Ravenclaw'], color='blue', alpha=0.6)
        plt.title(names[i], fontsize=15)
        i += 1
    plt.subplot(3, 5, i + 1)
    handles = [
        Rectangle((0, 0), 1, 1, color=c, ec="k", alpha=0.6)
        for c in ['red', 'yellow', 'green', 'blue']
    ]
    labels = ["Gryffindor", "Hufflepuff", "Slytherin", 'Ravenclaw']
    plt.legend(handles, labels)
    plt.title("Legend", fontsize=15)
    plt.xlabel('grades')
    plt.ylabel('number of students')
    plt.show()
示例#16
0
def handler(event, context):
    """
    delegate work
    """
    try:
        if event['operation'] == 'purchase':
            order_data = event['body-json']
            if validate(order_data) is False:
                return error(400, "Malformed purchase order")
            # add to sqs and intermediate database
            response = accept(event)
            return response

        elif event['operation'] == 'orderqueue':
            response = orderqueue(event)
            return response

        elif event['operation'] == 'orders':
            response = get_orders(event)
            return response

        else:
            return error(500, "Unknown operation")

    except KeyError as err:
        print(err)
        return error(400, "No resource specified")
示例#17
0
def parse(arg_file):
    try:
        with arg_file as file:
            lines = file.readlines()
    except:
        error("error file")
    return lines
示例#18
0
def random(length):
    if length < 1:
        error.error('Invalid length')

    sn = []
    sl = ''

    de = length

    def defapp(a, b):
        si = ord(a)
        se = si + b
        while si < se:
            if len(chr(si)) == 1:
                sn.append(chr(si))
                si = si + 1

    defapp('a', 26)
    defapp('A', 26)
    defapp('0', 10)

    al = 0
    while (al < int(de)):
        sl = sl + sn[randrange(0, 61)]
        al = al + 1

    return sl
示例#19
0
def auth_handler(event, context):
    """
    authorizer
    """
    print(event)

    #check if request is for authorization
    if 'authorizationToken' in event:
        return policy_builder(event, context)

    #signup or login operation
    if 'operation' not in event:
        return error(500, 'No operation specified')

    if 'body-json' not in event:
        return error(400, 'Malformed request')

    operation = event['operation']
    body = event['body-json']

    if operation == 'signup':
        return create_customer(body)
    elif operation == 'login':
        return login_customer(body)
    elif operation == 'verify':
        return verify_customer(body)
    else:
        return error(400, 'Invalid operation')
示例#20
0
def handler(event, context):
    #signup or login operation
    try:
        print(event)
        if 'operation' not in event or 'body-json' not in event:
            return error(400, 'Invalid operation')

        operation = event['operation']

        # update order queued status to created
        if operation == 'order-create':
            update_orders(event)

        # add new orders to queue
        elif operation == 'purchase':
            order = add_order(event)
            return order

        # get status of queued orders
        elif operation == 'orderqueue':
            result = order_queue(event)

            if result is None:
                return error(404, "No order found")
            elif isinstance(result, dict) and 'redirect_url' in result:
                return error(301, result['redirect_url'])

            return result

        else:
            return error(400, 'Invalid operation')

    except KeyError as err:
        print(err)
        return error(400, 'Invalid operation')
示例#21
0
 def time(self, time):
     try:
         time_is_int = int(time)  #check time is an interger
         return time_is_int  #return the interger
     except Exception as e:
         error(33, str(e) + ' vaild.time() error', False)
         return None
示例#22
0
 def cam(self, cam):
     try:
         cam_is_int = int(cam)  #check cam_id is an interger
         return cam_is_int  #return interger
     except Exception as e:
         error(35, str(e) + ' vaild.cam() error', False)
         return None
示例#23
0
 def last_cam(self, p_id, s_id):#Find the time and id of the last cam passed by the car
   self.ecx.execute("SELECT time, cam_id FROM data where p_id = '"+str(p_id)+"' and s_id = '"+str(s_id)+"' order by d_index DESC limit 1;")
   result = self.ecx.fetchone()#fetch from sqlite
   if result == None: #
     error(8,'get last_cam error - '+str(p_id)+' - '+str(s_id)+' - '+str(result), True)
     return False
   return result[0], result[1]
示例#24
0
def parse_num(line, ln_no, path, transform_fn=(lambda x: x)):
    line, label = read(line, (lambda c: c.isalpha() or c == '_'))
    if len(label) != 0:
        if label.upper() not in ops:
            line, offset = parse_offset(line, ln_no, path)
            return (line, Label(label, offset, transform_fn))
        else:
            error.error("'" + label + "' not a valid label", ln_no, path)

    base = 10
    numbers = "0123456789"

    if line.startswith("$"):
        base = 16
        line = line[1:]
        numbers = "0123456789ABCDEF"

    line, result = read(line, (lambda c: c.upper() in numbers))

    if len(result) == 0:
        return (line, None)

    try:
        return (line, int(transform_fn(result), base))
    except ValueError:
        error.error("Invalid number literal", ln_no, path)
示例#25
0
    def set_datastore(self):

        """ Allows user to set the root datastore """

        obj = root_datastore(str(self.root_path))
        value = obj.root_store
        try :
            self.auth_object['sess'].collections.get(str(value))
        except : 
            if internet_on():
                e = error("Incorrect datastore")
            else:
                e = error("Network Error. Check Your Connection")
            return False

        else:
            self.root_path = str(value)
            self.frame.setGeometry(QtCore.QRect(254, 10, 0, 0))
            self.frame_2.setGeometry(QtCore.QRect(254, 10, 0, 0))
            self.dialog.setWindowTitle(_translate("Dialog", self.root_path, None))
            self.create_tree()
            if self.tabWidget.currentIndex() ==1:
                self.save_to_irods()
            else:
                self.create_export_tree()
示例#26
0
def parse_line(line, ln_no, path):
    line = line.strip()

    if line.startswith(";"):
        return []

    nline, label = parse_label(line, ln_no, path)
    if label != None:
        return [label] + parse_line(nline, ln_no, path)

    op = None
    line, literal = parse_literal(line, ln_no, path)
    if not literal:
        line, op = parse_instr(line, ln_no, path)

    if len(line) > 0 and not line.strip().startswith(";"):
        error.error("Unexpected trailing characters '" + line + "'", ln_no,
                    path)

    if literal != None:
        return [literal]

    if op != None:
        return [op]

    return []
示例#27
0
 def cam(self, cam):
   try:
     cam_is_int = int(cam) #check cam_id is an interger
     return cam_is_int #return interger
   except Exception as e:
     error(35, str(e)+' vaild.cam() error', False)
     return None
示例#28
0
 def site(self, site):
     try:
         site_is_str = str(site)  #check site name is a string
         return site_is_str.lower()  #make is lowercase for consistancy
     except Exception as e:
         error(32, str(e) + ' vaild.site() error', False)
         return None
示例#29
0
def toLST(sizeList,opCodeList,tokenList,tabla):
    strings = []
    pre = None
    cont = -1
    for x,y,z in zip(sizeList,opCodeList,tokenList):
        cont+=1
        if z[0][0] == "#":
            pre = z[0][1:]+": "
        elif z[0][0] != "#":
            if len(z) == 3:
                z[1] += "," + z[2]
                del(z[2])
            if pre != None:
                z[0] = pre+z[0]
                pre = None
            if z[0] == "END" and cont == len(sizeList)-1:
                x="0000"
            elif z[0] == "END":
                error([x,y,],"El end no es la ultima instrucción del programa")
            elif cont==len(sizeList)-1:
                strings.append(' {:4s} {:6s}    {:25s}'.format(cleanHex(x),y," ".join(z)))
                strings.append(' {:4s} {:6s}    {:25s}'.format("0000","","END"))
                break
                

            strings.append(' {:4s} {:6s}    {:25s}'.format(cleanHex(x),y," ".join(z)))
    strings.append("\n")
    tabla = tabla.upper().replace("#","")
    strings.append(tabla)
    return strings
示例#30
0
 def _cmd__G1(self, params):
     'Linear move'
     print("TODO")
     return
     try:
         for axis in 'XYZ':
             if axis in params:
                 v = float(params[axis])
                 pos = self.axis2pos[axis]
                 if not self.absolute_coord:
                     # value relative to position of last move
                     self.last_position[pos] += v
                 else:
                     # value relative to base coordinate position
                     self.last_position[pos] = v + self.base_position[pos]
         if 'E' in params:
             v = float(params['E']) * self.extrude_factor
             if not self.absolute_coord or not self.absolute_extrude:
                 # value relative to position of last move
                 self.last_position[3] += v
             else:
                 # value relative to base coordinate position
                 self.last_position[3] = v + self.base_position[3]
         if 'F' in params:
             gcode_speed = float(params['F'])
             if gcode_speed <= 0.:
                 raise error("Invalid speed in '%s'" % (params['#original'],))
             self.speed = gcode_speed * self.speed_factor
     except ValueError as e:
         raise error("Unable to parse move '%s'" % (params['#original'],))
     self.move_with_transform(self.last_position, self.speed)
示例#31
0
def update_variable_domains(variable_domains, node_list):
    '''Updates variable_domains by inserting mappings from a variable name to the to the number of
    elements in their data domain.

    Program variables are created in assignments of the form
    "{varName} = Var({size})" or "{varName} = Param({size})".

    '''
    for ch in node_list:
        if isinstance(ch, ast.Assign) and len(ch.targets) == 1:
            name = astunparse.unparse(ch.targets[0]).rstrip()
            rhs = ch.value

            if isinstance(rhs, ast.Call):
                decl_name = rhs.func.id
                args = rhs.args
            elif isinstance(rhs, ast.Subscript) and isinstance(rhs.value, ast.Call):
                decl_name = rhs.value.func.id
                args = rhs.value.args
            else:
                continue

            if decl_name not in ["Param", "Var", "Input", "Output"]:
                continue
            
            if len(args) > 1:
                error.error('More than one size parameter in variable declaration of "%s".' % (name), ch)
            size = args[0]

            if isinstance(size, ast.Num):
                if name in variable_domains and variable_domains[name] != size.n:
                    error.fatal_error("Trying to reset the domain of variable '%s' to '%i' (old value '%i')." % (name, size.n, variable_domains[name]), size) 
                variable_domains[name] = size.n
            else:
                error.fatal_error("Trying to declare variable '%s', but size parameters '%s' is not understood." % (name, astunparse.unparse(size).rstrip()), size)
示例#32
0
def main():
    option = sys.argv

    if len(option) == 1:
        error(option, 1, 1)

    elif len(option) > 2:
        data = openfile(option)
        data = compile(data)
        data = assembly(data)

        name = 'a.exe'
        option.pop(0)
        op = 0
        while len(option) > op:
            if option[op] in Option:
                if op + 1 < len(option):
                    name = option[op + 1] + '.exe'

            op += 1

        save(data, name)

    else:
        data = openfile(option)
        data = compile(data)
        data = assembly(data)
示例#33
0
def main():
	if (len(sys.argv) != 2):
		error.error('python logreg_train.py [file]')
	filename = sys.argv[1]
	data = []
	try:
		data = pandas.read_csv(filename)
	except:
		error.error('error opening file')
	data = data.dropna()
	students_house = data['Hogwarts House']
	droping = []
	for x in data:
		if (x not in important):
			droping.append(x)
	data = data.drop(columns=droping)
	results = data.max() - data.min()
	for i in range(len(results)):
		if (results[i] == 0):
			results[i] = 1
	data = (data - data.min()) / results
	for house in houses:
		print(house)
		reg(data, house, students_house)
	open('thetas.json', 'w').close()
	f = open('thetas.json', 'w')
	f.write(json.dumps(output))
	f.close()
示例#34
0
def copy(old_array, new_array):
    if len(new_array) < len(old_array):
        error("New array is too small.")
    else:
        for i in range(0, len(old_array)):
            new_array[i] = old_array[i]
    return new_array
示例#35
0
文件: main.py 项目: laffra/happymac
 def terminate(self, menuItem, pid):
     try:
         process.terminate_pid(pid)
     except:
         error.error("Error in menu callback")
     finally:
         self.handle_action()
示例#36
0
def update_variable_domains(variable_domains, node_list):
    '''Updates variable_domains by inserting mappings from a variable name to the to the number of
    elements in their data domain.

    Program variables are created in assignments of the form
    "{varName} = Var({size})" or "{varName} = Param({size})".

    '''
    for ch in node_list:
        if isinstance(ch, ast.Assign) and len(ch.targets) == 1:
            name = astunparse.unparse(ch.targets[0]).rstrip()
            rhs = ch.value

            if isinstance(rhs, ast.Call):
                decl_name = rhs.func.id
                args = rhs.args
            elif isinstance(rhs, ast.Subscript) and isinstance(rhs.value, ast.Call):
                decl_name = rhs.value.func.id
                args = rhs.value.args
            else:
                continue

            if decl_name not in ["Param", "Var", "Input", "Output"]:
                continue
            
            if len(args) > 1:
                error.error('More than one size parameter in variable declaration of "%s".' % (name), ch)
            size = args[0]

            if isinstance(size, ast.Num):
                if name in variable_domains and variable_domains[name] != size.n:
                    error.fatal_error("Trying to reset the domain of variable '%s' to '%i' (old value '%i')." % (name, size.n, variable_domains[name]), size) 
                variable_domains[name] = size.n
            else:
                error.fatal_error("Trying to declare variable '%s', but size parameters '%s' is not understood." % (name, astunparse.unparse(size).rstrip()), size)
示例#37
0
 def stmt():
     next_tok = peek()
     if next_tok == TOK_ID:
         id = consume(TOK_ID)
         consume(TOK_EQ)
         e = expr()
         consume(TOK_SEMI)
         return astnode(AST_ASSIGN, lhs=id["value"], rhs=e)
     elif next_tok == TOK_PRINT:
         consume(TOK_PRINT)
         e = expr()
         consume(TOK_SEMI)
         return astnode(AST_PRINT, expr=e)
     elif next_tok == TOK_RETURN:
         consume(TOK_RETURN)
         e = expr()
         consume(TOK_SEMI)
         return astnode(AST_RETURN, expr=e)
     elif next_tok == TOK_READ:
         consume(TOK_READ)
         id = consume(TOK_ID)
         consume(TOK_SEMI)
         return astnode(AST_READ, id=id)
     elif next_tok == TOK_WHILE:
         consume(TOK_WHILE)
         e = expr()
         consume(TOK_DO)
         body = stmts()
         consume(TOK_DONE)
         return astnode(AST_WHILE, expr=e, body=body)
     else:
         error("illegal statement")
示例#38
0
 def return_speeders(self):#Return all data of cars over speed limit.
   try:
     self.ecx.execute("SELECT * FROM data where speed > 0 order by d_index DESC;")
     result = self.ecx.fetchall()
     return result
   except Exception as e:
     error(12,str(e)+' sql record_speeders() error', True)
示例#39
0
  def __init__(self):
    try:
      self.rdb = None
      self.rdb = sql.connect('average_check.db')
      self.ecx = self.rdb.cursor()

    except:
      error(1,'sql connect error', True)
示例#40
0
 def get_cam_m(self, cam_id, s_id):#Get the meters along the road the input cam id is
   try:
     self.ecx.execute("select cam_m from cams where s_id = '"+str(s_id)+"' and cam_id = '"+str(cam_id)+"' limit 1;")
     result = self.ecx.fetchone()
     if result == None:
       error(5,'sql get_cam_m() error (no cam) - '+str(s_id)+' - '+str(cam_id), True)
     return float(result[0])
   except Exception as e:
     error(5,str(e)+'sql get_cam_m() error - '+str(result), True)
示例#41
0
 def find_site(self, site_id):#Find the s_id and max speed integer from site_id input string
   try:
     self.ecx.execute("select s_id, s_limit from sites where site_id = '"+str(site_id)+"' limit 1;")
     result = self.ecx.fetchone() #fetchone gets any output from sqlite
     if result == None: #if no output
         error(3,'sql find site() error (none type) - ', True)#error
     return result[0], result[1]#else return item 1 then item 2
   except Exception as e:
     error(3, str(e)+'sql find site() error', True)
示例#42
0
 def get_owner(self, p_id):#Get the owner info string from the p_id
   try:
     self.ecx.execute("select * from owners where p_id= '"+str(p_id)+"' LIMIT 1;")
     result = self.ecx.fetchone()
     if result == None:
       return None
     return result[1], result[2]
   except Exception as e:
     error(18,str(e)+' sql get_owner() error', True)
示例#43
0
 def confidence(self, confidence):
   try:
     confidence_is_float = float(confidence) #check confidence is a real number
     if 0 < confidence_is_float <= 100: #check confidence is a number between 0.1 and 100
       return confidence_is_float #return float
     else:
       return None
   except Exception as e:
     error(34, str(e)+' vaild.confidence() error', False)
     return None
示例#44
0
 def get_site(self, s_id):#Get the site string from the s_id
   try:
     self.ecx.execute("SELECT site_id, s_limit FROM sites where s_id = '"+str(s_id)+"' LIMIT 1;")
     result = self.ecx.fetchone()
     if result == None:
       error(17,' sql get_site() error '+str(s_id), False)
       return None
     return result[0], result[1]
   except Exception as e:
     error(17,str(e)+' sql get_site() error', True)
示例#45
0
 def get_plate(self, p_id):#Get the plate string from the p_id
   try:
     self.ecx.execute("SELECT plate FROM plates where p_id = '"+str(p_id)+"' LIMIT 1;")
     result = self.ecx.fetchone()
     if result == None:
       error(15,' sql get_plate() error '+str(p_id), False)
       return None
     return result[0]
   except Exception as e:
     error(16,str(e)+' sql get_plate() error', True)
def getnum(string=''):
    import error
    while True:
        try: n = eval(input(string))
        except (SyntaxError, NameError, ZeroDivisionError) as e:
            error.error(str(e))
            print('please try again')
            pass
        else: break
    return n
示例#47
0
文件: assembler.py 项目: nickik/PVM
def read_file(filename):
    with open(filename) as fd:
        symboltable = {}
        try:
            instructions = assemble(fd, symboltable)
            bytecode = resolve(instructions, symboltable)
        except error.AssemblerError as asmerr:
            error.error(asmerr)

    return bytecode
示例#48
0
 def get_cam_id(self, site_cam_id, s_id):#Get the actual cam_id relative to the program rather than the cam_id relative to the site id
   try:
     self.ecx.execute("SELECT cam_id FROM cams where site_cam_id = '"+str(site_cam_id)+"' and s_id = '"+str(s_id)+"' LIMIT 1;")
     result = self.ecx.fetchone()
     if result == None:
       error(14,' sql get_cam_id() error '+str(site_cam_id)+' '+str(s_id), True)
       return None
     return result[0]
   except Exception as e:
     error(14,str(e)+' sql get_cam_id() error', True)
示例#49
0
 def add_plate(self, plate, foreign=False):#To add a p_id or get the existing p_id for a number plate
   try:
     foreign = str(foreign).upper() #make the bool into a upper string
     self.ecx.execute("select (1) from plates where plate = '"+plate+"' limit 1;") #check if plate exsists
     if self.ecx.fetchone() == None: #if not, enter plate
       self.ecx.execute("INSERT INTO plates (plate, p_foreign) VALUES ('"+plate+"', '"+foreign+"');")
       self.rdb.commit()#commit insert
     self.ecx.execute("select p_id from plates where plate = '"+plate+"';")#get the p_id
     return self.ecx.fetchone()[0]#Return the p_id
   except Exception as e:
      error(4,str(e)+'sql add_plate() error', True) #should be no error
示例#50
0
文件: typestr.py 项目: TheKK/Shedskin
def dynamic_variable_error(gx, node, types, conv2):
    if not node.name.startswith('__'):  # XXX startswith
        classes = polymorphic_cl(gx, types_classes(types))
        lcp = lowest_common_parents(classes)
        if node.parent:
            varname = "%s" % node
        else:
            varname = "'%s'" % node
        if [t for t in types if isinstance(t[0], python.Function)]:
            error.error("Variable %s has dynamic (sub)type: {%s, function}" % (varname, ', '.join(sorted(conv2.get(cl.ident, cl.ident) for cl in lcp))), gx, node, warning=True)
        else:
            error.error("Variable %s has dynamic (sub)type: {%s}" % (varname, ', '.join(sorted(conv2.get(cl.ident, cl.ident) for cl in lcp))), gx, node, warning=True)
示例#51
0
 def cam_first(self, curr_cam_m, time, p_id, s_id):#Find if the cam passed is the first of this trip
   try:
     if curr_cam_m == 0: #if first cam on road
       return True
     self.ecx.execute("SELECT time FROM data where p_id = '"+str(p_id)+"' and s_id = '"+str(s_id)+"' order by d_index DESC limit 1;")
     result = self.ecx.fetchone()
     if result == None:
       #error(9,' sql cam_first() error '+str(curr_cam_m)+' '+str(time)+' '+str(p_id)+' '+str(s_id), False)
       return True
     return (result[0] < time - 3600)# if older than 1 Hour
   except Exception as e:
     error(10,str(e)+' sql cam_first() error', True)
示例#52
0
文件: syntax.py 项目: jorants/civilpy
def splitComma(tokens):
    bits = []
    last = 0
    for i in range(len(tokens)):
        t = tokens[i]
        if type(t) is COMMA:
            bit = tokens[last:i]
            if bit == []:
                error(t.fn,t.row,t.col,"Double comma")
            bits += [bit]
            last = i+1
    bits+=[tokens[last:]]
    return bits
示例#53
0
  def uuid(self, uuid_string): #https://gist.github.com/ShawnMilo/7777304
    try:
        val = uuid.UUID(uuid_string, version=4) #check UUID is valid to the UUID spec
    except ValueError as e:
        # If it's a value error, then the string
        # is not a valid hex code for a UUID.
        error(36, str(e)+' vaild.cam() error', False)
        return None

    # If the uuid_string is a valid hex code,
    # but an invalid uuid4,
    # UUID will convert it to a valid uuid4.

    return str(val)
示例#54
0
 def plate(self, plate):
   try:#validate the plate against known plate patterns
     plate_out = plate.replace(" ", "").upper()#take out spaces and convert all leters to uppercase
     plate_valid = re.compile("([A-Z]{2}[0-9]{2}[A-Z]{3}$)") #uk plate regex pattern
     #validate foreign plates- asume no characters and only numbers and letters
     f_plate_valid = re.compile("^[a-zA-Z.\d]{1,13}$")
     if plate_valid.match(plate_out): #if british
       return plate.upper(), False #return plate all uppercase and with no foreign tag
     elif f_plate_valid.match(plate_out): #if foreign
       return plate, True #return plate how it came, with foreign tag
     else: #return none type, because plate matched no rules
       return None, None
   except:
     error(31,'valid.plate() error', False)
     return None
示例#55
0
文件: imperfect.py 项目: foosa/qudy
    def __init__(self, *args, **keyword_args):
        
        # Pull out last argument.  It should be an instance of the
        # error class.  If it instead a string, interpret the string
        # as a name of an error function.
        
        err = args[ len(args) - 1 ]
        if isinstance( err, error.error ):
            self.error = err
            
        elif isinstance( err, str ):
            self.error = error.error( err )
            
        else:
            raise SyntaxError("Final argument must be an error object.")
        
        # For the remaining arguments, use propagator's __init__
        # function to produce the relevant methods and objects.
        
        propagator.__init__( self, *args[0:len(args)-1], **keyword_args )

        # Save an ideal set of controls
        self.ideal_control = self.control.copy()
        
        # Update the error
        self.update_error()
示例#56
0
def repl():
    blam = input("What file would you like to use(Please include .html/.java/.py/etc)\n")
    blm = input("what would you like to replace?\n")
    bl = input("what would you like to replace it with?\n")

    file = open(blam, "r")
    file2 = file.read()
    file.close()
    file = open(blam, "w")
    if file2.find(blm) != -1:

        file.write(file2.replace(blm, bl))

        print("Action completed!")
    else:
        e.error()
示例#57
0
def player_view(request, name, mode, url, p):
    exists = False
    if p.exists():
        p = p.values()[0]
        exists = True
        tdelta = datetime.now() - datetime.strptime(str(p['updated']), "%Y-%m-%d %H:%M:%S")
        if tdelta.seconds + (tdelta.days * 86400) < 900:
            return render_to_response('player.html', {'stats': p, 'mode': mode, 'view': "player"})
    else:
        if mode is "rnk":
            update_player_count()
    data = get_json(url)
    if data is not None:
        # if account id is 0 send fancy error page.
        if int(data['account_id']) is 0:
            return render_to_response('player_error.html', {'name': name})
        p = player_math(data, mode)
        player_save(p, mode)
        return render_to_response('player.html', {'stats': p, 'mode': mode, 'view': "player"})
    else:
        # server down, show old results
        if exists:
            return render_to_response('player.html', {'stats': p, 'mode': mode, 'view': "player", 'fallback': True})
        else:
            return error(request, "S2 server down or name is incorrect. Try another name or gently refreshing the page.")
示例#58
0
文件: syntax.py 项目: jorants/civilpy
def getFunHeader(tokens):
    fn,row,col = tokens[0].fn,tokens[0].row,tokens[0].col
    if not isRetType(tokens[0]) or not type(tokens[1]) is ID or not type(tokens[2]) is LRB:
        return 0,None
    args = tokens[2:]
    close = getClosing(args)
    if close == None:
        error(fn,row,col,"Bracket not closed before the end of the statment.")
    args = args[1:close-1]
    arguments = []
    bits = splitComma(args)
    for x in bits:
        if len(x)!=2 or not isType(x[0]) or not type(x[1]) is ID:
            error(x[0].fn,x[0].row,x[0].col,"Faulty argument")
        arguments+=[Param(x[0].fn,x[0].row,x[0].col,x[0],x[1].val)]
    return close+2,FunHeader(fn,row,col,tokens[0],tokens[1].val,arguments);
示例#59
0
文件: typestr.py 项目: TheKK/Shedskin
def typestr(gx, types, parent=None, cplusplus=True, node=None, check_extmod=False, depth=0, check_ret=False, var=None, tuple_check=False, mv=None):
    try:
        ts = typestrnew(gx, types, cplusplus, node, check_extmod, depth, check_ret, var, tuple_check, mv=mv)
    except RuntimeError:
        if not mv.module.builtin and isinstance(node, python.Variable) and not node.name.startswith('__'):  # XXX startswith
            if node.parent:
                varname = repr(node)
            else:
                varname = "'%s'" % node.name
            error.error("Variable %s has dynamic (sub)type" % varname, gx, node, warning=True)
        ts = 'pyobj *'
    if cplusplus:
        if not ts.endswith('*'):
            ts += ' '
        return ts
    return '[' + ts + ']'
示例#60
0
def save (name, n_inter, umbrales):
    num_iter = 10 #Número de comprobaciones en cada llamada a la función "error".
    f = open(name, "w")
    for i in range (len(t_upla_inter)):
        f.write(str(t_upla_inter[i]) + '\n')
        for j in range (len(t_upla_umbrales)):
            sol = error.error(t_upla_inter[i], num_iter, t_upla_umbrales)
            f.write(str(sol) + '\n')