Example #1
0
    def execute_module(self, part=0, streaming=False):
        """Used by ModuleManager to execute module.

        This method also takes care of timestamping the execution time if
        execution was successful.
        """

        if self.instance:
            # this is the actual user function.
            # if something goes wrong, an exception will be thrown and
            # correctly handled by the invoking module manager
            if streaming:
                if part == 0:
                    self.instance.streaming_execute_module()
                else:
                    self.instance.streaming_execute_module(part)

                self.execute_times[part] = counter.counter()
                print "streaming exec stamped:", self.execute_times[part]

            else:
                if part == 0:
                    self.instance.execute_module()
                else:
                    self.instance.execute_module(part)

                # if we get here, everything is okay and we can record
                # the execution time of this part
                self.execute_times[part] = counter.counter()
                print "exec stamped:", self.execute_times[part]
def surrounding():
    logging.info('I am in the surrounding function')
    print(
        'As you check the your surrounding you find a drop of blood on the ground. '
    )
    chance2 = str(
        input('Do you wish to send the blood to testing? Yes or No: '))
    if chance2 == "yes" or chance2 == "Yes":
        print(
            'The forensics team came game and found that the blood found on the floor does not belong to the deceased person'
        )
        chance3 = str(input('do you wish to inspect it? Yes or No: '))
        logging.info('going to call inspected')
        inspected()
    elif chance2 == "no" or chance2 == "No":
        logging.info('did not call inspected')
        print('As you keep looking you find a laptop.')
        chance4 = str(input('Do you want to inspect it? Yes or No: '))
        if chance4 == "yes" or chance4 == "Yes":
            print(
                'You find that the laptop is locked but there is a hint for the password. It reads "I am an english word with three consecutive doulbe letters" '
            )
            logging.info('going to call counter')
            counter()
        else:
            logging.info('Did not go to counter')
            print('Are you kidding me? You are fired')
    else:
        logging.info('did not go to inspected')
        print('This is not a joke.You are fired')
Example #3
0
    def timeStampTransferTime(
        self, outputIndex, consumerInstance, consumerInputIdx,
        streaming=False):
        """Timestamp given transfer time with current time.

        This method is called right after a successful transfer has
        been made.  Depending on the scheduling mode (event-driven or
        hybrid) and whether it's a streaming module that's being
        transferred to, the timestamps are set differently to make
        sure that after a switch between modes, all transfers are
        redone.  Please see the documentation in the scheduler module.

        @param streaming: determines whether a streaming transfer or a
        normal transfer has just occurred.
        """

        if streaming:
            streaming_transfer_time = counter.counter()
            transfer_time = 0
        else:
            transfer_time = counter.counter()
            streaming_transfer_time = 0

        # and set the timestamp
        self.transferTimes[ 
                (outputIndex, consumerInstance, consumerInputIdx)] = \
                transfer_time

        self.streaming_transfer_times[ 
                (outputIndex, consumerInstance, consumerInputIdx)] = \
                streaming_transfer_time
Example #4
0
	def __init__ (self, set, handler, rpc_ar_h, realm='default'):
		self.set = set
		self.handler = handler
		self.realm = realm
		self.ar = rpc_ar_h
		self.pass_count = counter.counter()
		self.fail_count = counter.counter()
Example #5
0
def getData(numMeas):

    duration = 10.0  # added this on 7/Nov/2013

    # Set duration to get ~100 counts instead of arbitrary number:
    count = counter.counter(duration, plotDataBool=False)

    print 'Count is ' + str(count) + ' 1/s.'

    # Number of spokes in one second is cnt.counter(1)/((2.0 * numpy.pi / 100.0)*(180/numpy.pi))
    # The demoninator is actually 3.6
    n = (count * duration) / 3.6  # number of spokes
    duration *= 100.0 / n
    duration = math.ceil(duration)

    print 'Setting duration to ' + str(duration) + ' s.'

    rotorFreqs = zeros(numMeas)  # Create array in which to store rotorFreqs

    for j in range(0, numMeas):  # Take numMeas readings
        while rotorFreqs[
                j] == 0:  # It is possible to have an unsuccessful count. This checks if any previous counts have been successful and allows another count if necessary
            #edit 24/1/2013 by Zach
            #save counter data into new file
            count = counter.counter(duration, plotDataBool=False)
            rotorFreqs[
                j] = count * math.pi / 180  # Angular frequency measurement of inner tube (numerical factor 2pi/100 radians per spoke)
            #writeToFile(count)#, f = 'counter-'+Filename)
        print 'count ' + str(j + 1) + ' of ' + str(
            numMeas) + ' taken successfully. [' + str(rotorFreqs[j]) + ' rads]'
        # Kazem, 3.16.2012 - I added the reporting of data for convenience.
    return rotorFreqs  #Return angular frequencies of inner tube
Example #6
0
 def __init__(*args):
     apply(resolver.__init__, args)
     self = args[0]
     self.cache = {}
     self.forward_requests = counter()
     self.reverse_requests = counter()
     self.cache_hits = counter()
Example #7
0
    def execute_module(self, part=0, streaming=False):
        """Used by ModuleManager to execute module.

        This method also takes care of timestamping the execution time if
        execution was successful.
        """

        if self.instance:
            # this is the actual user function.
            # if something goes wrong, an exception will be thrown and
            # correctly handled by the invoking module manager
            if streaming:
                if part == 0:
                    self.instance.streaming_execute_module()
                else:
                    self.instance.streaming_execute_module(part)

                self.execute_times[part] = counter.counter() 
                print "streaming exec stamped:", self.execute_times[part]

            else:
                if part == 0:
                    self.instance.execute_module()
                else:
                    self.instance.execute_module(part)

                # if we get here, everything is okay and we can record
                # the execution time of this part
                self.execute_times[part] = counter.counter() 
                print "exec stamped:", self.execute_times[part]
def banner():
    while True:
        print "1. Press 1 for running the tokenizer usually"
        print "2. Press 2 for creating the inverted index"
        print "3. Press 3 for creating the vectors for the documents"
        print "4. Press any other number to search"
        choice =  int(raw_input("$ "))
        if not os.path.exists(TEXT):
            print "No Data at All. No Valid Corpus. Please add something to\n" + str(TEXT)
        if not os.path.exists(DATA_PATH):
            print "No Data Existed, Path Created"
            os.mkdir(DATA)
        if not os.path.exists(TOKENS) or choice == 1:
            print "Creating tokens as they don't exist/You Chose To"
            os.mkdir(TOKENS)
            tokenizer()
        if not os.path.exists(INDICES) or choice == 2:
            print "Creating indices as they don't exist"
            os.mkdir(INDICES)
            counter()
        if not os.path.exists(SCORES) or choice == 3:
            print "Creating Vectors as they don't exist"
            os.mkdir(SCORES)
            score()
            mod()
        if choice > 3 or choice == 0:
            print "Search begins"
            break
Example #9
0
 def __init__ (*args):
     apply (resolver.__init__, args)
     self = args[0]
     self.cache = {}
     self.forward_requests = counter()
     self.reverse_requests = counter()
     self.cache_hits = counter()
Example #10
0
    def timeStampTransferTime(self,
                              outputIndex,
                              consumerInstance,
                              consumerInputIdx,
                              streaming=False):
        """Timestamp given transfer time with current time.

        This method is called right after a successful transfer has
        been made.  Depending on the scheduling mode (event-driven or
        hybrid) and whether it's a streaming module that's being
        transferred to, the timestamps are set differently to make
        sure that after a switch between modes, all transfers are
        redone.  Please see the documentation in the scheduler module.

        @param streaming: determines whether a streaming transfer or a
        normal transfer has just occurred.
        """

        if streaming:
            streaming_transfer_time = counter.counter()
            transfer_time = 0
        else:
            transfer_time = counter.counter()
            streaming_transfer_time = 0

        # and set the timestamp
        self.transferTimes[
                (outputIndex, consumerInstance, consumerInputIdx)] = \
                transfer_time

        self.streaming_transfer_times[
                (outputIndex, consumerInstance, consumerInputIdx)] = \
                streaming_transfer_time
Example #11
0
	def __init__ (self, set, handler, authorizer_, realm='default'):
		self.set = set
		self.handler = handler
		self.authorizer = authorizer_
		self.realm = realm
		self.pass_count = counter.counter()
		self.fail_count = counter.counter()
    def __init__(self, ip, port, resolver=None, logger_object=None):
        self.ip = ip
        self.port = port
        asyncore.dispatcher.__init__(self)

        if ":" in ip:
            socket_type = socket.AF_INET6
        else:
            socket_type = socket.AF_INET
        self.create_socket(socket_type, socket.SOCK_STREAM)

        self.handlers = []

        if not logger_object:
            logger_object = logger.file_logger(sys.stdout)

        self.set_reuse_addr()
        self.bind((ip, port))

        # lower this to 5 if your OS complains
        self.listen(1024)

        name = self.socket.getsockname()
        host = name[0]
        port = name[1]

        if not ip:
            self.log_info("Computing default hostname", "warning")
            try:
                ip = socket.gethostbyname(socket.gethostname())
            except socket.error:
                ip = socket.gethostbyname("localhost")
        try:
            self.server_name = socket.gethostbyaddr(ip)[0]
        except socket.error:
            self.log_info("Cannot do reverse lookup", "warning")
            self.server_name = ip  # use the IP address as the "hostname"

        self.server_port = port
        self.total_clients = counter()
        self.total_requests = counter()
        self.exceptions = counter()
        self.bytes_out = counter()
        self.bytes_in = counter()

        if not logger_object:
            logger_object = logger.file_logger(sys.stdout)

        if resolver:
            self.logger = logger.resolving_logger(resolver, logger_object)
        else:
            self.logger = logger.unresolving_logger(logger_object)

        self.log_info(
            "Medusa (V%s) started at %s"
            "\n\tHostname: %s"
            "\n\tPort:%d"
            "\n" % (VERSION_STRING, time.ctime(time.time()), self.server_name, port)
        )
Example #13
0
 def __init__(self, filesystem):
     self.filesystem = filesystem
     # count total hits
     self.hit_counter = counter()
     # count file deliveries
     self.file_counter = counter()
     # count cache hits
     self.cache_counter = counter()
Example #14
0
	def __init__ (self, filesystem):
		self.filesystem = filesystem
		# count total hits
		self.hit_counter = counter()
		# count file deliveries
		self.file_counter = counter()
		# count cache hits
		self.cache_counter = counter()
Example #15
0
    def __init__(self, ip, port, resolver=None, logger_object=None):
        self.ip = ip
        self.port = port
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)

        self.handlers = []

        if not logger_object:
            logger_object = logger.file_logger(sys.stdout)

        self.set_reuse_addr()
        self.bind((ip, port))

        # lower this to 5 if your OS complains
        self.listen(1024)

        host, port = self.socket.getsockname()
        if not ip:
            self.log_info('Computing default hostname', 'warning')
            try:
                ip = socket.gethostbyname(socket.gethostname())
            except socket.error:
                ip = socket.gethostbyname('localhost')
        try:
            self.server_name = socket.gethostbyaddr(ip)[0]
        except socket.error:
            self.log_info('Cannot do reverse lookup', 'warning')
            self.server_name = ip  # use the IP address as the "hostname"

        self.server_port = port
        self.total_clients = counter()
        self.total_requests = counter()
        self.exceptions = counter()
        self.bytes_out = counter()
        self.bytes_in = counter()

        if not logger_object:
            logger_object = logger.file_logger(sys.stdout)

        if resolver:
            self.logger = logger.resolving_logger(resolver, logger_object)
        else:
            self.logger = logger.unresolving_logger(logger_object)

        self.log_info('Medusa (V%s) started at %s'
                      '\n\tHostname: %s'
                      '\n\tPort:%d'
                      '\n' % (
                          VERSION_STRING,
                          time.ctime(time.time()),
                          self.server_name,
                          port,
                      ))
Example #16
0
 def __init__ (self, hostname='127.0.0.1', port=8023):
     self.hostname = hostname
     self.port = port
     self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
     self.set_reuse_addr()
     self.bind ((hostname, port))
     self.log_info('%s started on port %d' % (self.SERVER_IDENT, port))
     self.listen (5)
     self.closed             = 0
     self.failed_auths = 0
     self.total_sessions = counter()
     self.closed_sessions = counter()
Example #17
0
 def __init__(self, hostname='127.0.0.1', port=8023):
     self.hostname = hostname
     self.port = port
     self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.set_reuse_addr()
     self.bind((hostname, port))
     self.log_info('%s started on port %d' % (self.SERVER_IDENT, port))
     self.listen(5)
     self.closed = 0
     self.failed_auths = 0
     self.total_sessions = counter()
     self.closed_sessions = counter()
Example #18
0
	def __init__ (self, handler, passwordPath, realm='default'):

		users = {}
		passwordFile = open(passwordPath)
		for line in passwordFile.readlines():
			fields = string.split(string.strip(line),':')
			users[fields[0]] = fields[1]
		passwordFile.close()

		self.authorizer = dictionary_authorizer (users)
		self.handler = handler
		self.realm = realm
		self.pass_count = counter.counter()
		self.fail_count = counter.counter()
Example #19
0
def thread_func(interval, use_subprocess=False):

    # --- スレッドIDを取得 ---
    thread_id = threading.get_ident()

    # --- カウント開始 ---
    if (use_subprocess):
        command = 'python3 counter.py --thread_id {} --interval {} 2>&1 | tee log_th{}.txt'.format(\
                    thread_id, interval, thread_id)
        subprocess.run(command, shell=True)
    else:
        counter.counter(interval, thread_id)

    return
Example #20
0
def main():
    """Parse command-line arguments and pass them to print_marquee()"""
    parser = argparse.ArgumentParser()
    parser.add_argument("-s", help="String to be used as list of letters (to be counted)")
    args = parser.parse_args()
    counts = counter(list(args.s))
    print counts
Example #21
0
def to_ssa_func(func: Function) -> Function:
    # a map from variable to new variable:
    # init it by putting every argument into the map
    var_map = {arg: arg for arg in func.args}

    # fresh variable generator
    fresh_var = counter(prefix=f"calc_{func.name}")

    def to_ssa_expr(expr):
        if isinstance(expr, ExprVar):
            return ExprVar(var_map[expr.var])

        if isinstance(expr, ExprBop):
            return ExprBop(to_ssa_expr(expr.left), to_ssa_expr(expr.right),
                           expr.bop)

    def to_ssa_stmt(stmt):
        if isinstance(stmt, StmtAssign):
            new_expr = to_ssa_expr(stmt.expr)
            new_var = next(fresh_var)
            var_map[stmt.var] = new_var
            return StmtAssign(new_var, new_expr)

    # to convert each statement one by one:
    new_stmts = [to_ssa_stmt(stmt) for stmt in func.stmts]

    return Function(func.name, func.args, new_stmts, var_map[func.ret])
Example #22
0
 def __init__(self, config):
     self.counter = counter()
     self.counter.bar_breaker = False
     self.counter.pdown_breaker = False
     self.pixiv = pixiv(self.counter, config)
     self.rate = rate(self.counter)
     self.__start()
Example #23
0
 def test_total_count(self):
     total = 0
     s = 'someTextWithoutSpaces'
     counts = counter(list(s))
     for k, v in counts.iteritems():
         total += v
     self.assertEqual(len(s), total)
Example #24
0
 def test_add1(self):
     try:
         add = counter()
         vadd = add.add(1, 9)
         assert (10 == vadd), 'test fail!'
     except AssertionError, msg:
         print msg
Example #25
0
 def test_add1(self):
     try:
         add = counter()
         vadd = add.add(1,9)
         assert(10 == vadd),'test fail!'
     except AssertionError,msg:
         print msg
Example #26
0
def to_ssa_func(func: Function) -> Function:
    # init it by putting every argument into the map
    var_map = {arg: arg for arg in func.args}
    # fresh variable generator
    fresh_var = counter(prefix=f"tac_{func.name}")

    def to_ssa_stmt(stmt):
        new_x = next(fresh_var)
        var_map[stmt.x] = new_x

        new_y = var_map[stmt.y]
        if isinstance(stmt, StmtAssignVar):
            return StmtAssignVar(new_x, new_y)
        else:
            new_z = var_map[stmt.z]

        if isinstance(stmt, StmtAssignAdd):
            return StmtAssignAdd(new_x, new_y, new_z)
        # if isinstance(stmt, StmtAssignSub):
        #     return StmtAssignSub(new_x, new_y, new_z)
        if isinstance(stmt, StmtAssignMul):
            return StmtAssignMul(new_x, new_y, new_z)
        # if isinstance(stmt, StmtAssignDiv):
        #     return StmtAssignDiv(new_x, new_y, new_z)

    # to convert each statement one by one:
    new_stmts = [to_ssa_stmt(stmt) for stmt in func.stmts]

    return Function(func.name, func.args, new_stmts, var_map[func.ret])
Example #27
0
 def test_subtraction1(self):
     try:
         add = counter()
         vadd = add.subtraction(100, 1)
         assert (99 == vadd), 'test fail!'
     except AssertionError, msg:
         print msg
Example #28
0
 def test_subtraction1(self):
     try:
         add = counter()
         vadd = add.subtraction(100, 1)
         assert(99 == vadd),'test fail!'
     except AssertionError,msg:
         print msg
Example #29
0
def motorCalibration(targMin, targMax, numMotorFreqs, motorCalFreq):
    rotorCalFreq = counter.counter(8, plotDataBool=False)* math.pi / 180#Calibration Measurement (numerical factor 2pi/100 radians per spoke)
    calShearRate = GeoConst * rotorCalFreq                  #Calculate shear rate from calibration run
    motorFreqMin = motorCalFreq * targMin / calShearRate    #Calculate Minimum Motor Freq (assume linear relation between motor speed and shear rate)
    motorFreqMax = motorCalFreq * targMax / calShearRate    #Calculate Maximum Motor Freq (assume linear relation between motor speed and shear rate)
    df = (motorFreqMax-motorFreqMin)/(numMotorFreqs-1)      #Use number of freqs to be used and min and max to determine difference between consecutive motor frequencies
    motorFreqs = arange(motorFreqMin, motorFreqMax+df, df)  #Create 1-d array of motor freqs to be used
    return motorFreqs                                       #Return motorFreqs
Example #30
0
 def post(self):
     # decorated
     foo()
     # context
     with counter('%s-%d' % (CONTEXT_COUNTER, random.randint(1, 5))):
         # your logic here
         pass
     self.response.set_status(201)
Example #31
0
    def __init__ (self, authorizer, channel=ftp_channel, hostname=None, ip='0.0.0.0', port=21):
        self.ip = ip
        self.port = port
        self.authorizer = authorizer
        self.channel = channel
        self.thread_id = None
        # Used to signal when all the clients have exited
        self.shutdown_cv = coro.condition_variable()
        # list of ftp_channel instances
        self.clients = []
        self.session_id = 1

        if hostname is None:
            self.hostname = socket.gethostname()
        else:
            self.hostname = hostname

        # statistics
        self.total_sessions = counter()
        self.closed_sessions = counter()
        self.total_files_out = counter()
        self.total_files_in = counter()
        self.total_bytes_out = counter()
        self.total_bytes_in = counter()
        self.total_exceptions = counter()
Example #32
0
 def __init__ (self, server, conn, addr):
     self.channel_number = http_channel.channel_counter.increment()
     self.request_counter = counter()
     asynchat.async_chat.__init__ (self, conn)
     self.server = server
     self.addr = addr
     self.set_terminator ('\r\n\r\n')
     self.in_buffer = ''
     self.creation_time = int (time.time())
     self.check_maintenance()
Example #33
0
	def __init__ (self, server, conn, addr):
		self.channel_number = http_channel.channel_counter.increment()
		self.request_counter = counter()
		asynchat.async_chat.__init__ (self, conn)
		self.server = server
		self.addr = addr
		self.set_terminator ('\r\n\r\n')
		self.in_buffer = ''
		self.creation_time = int (time.time())
		self.check_maintenance()
Example #34
0
    def modify(self, part=0):
        """Used by the ModuleManager to timestamp the modified time.

        This should be called whenever module state has changed in such a way
        as to invalidate the current state of the module.  At the moment,
        this is called by L{applyViewToLogic()} as well as by the
        ModuleManager.

        @param part: indicates the part that has to be modified.
        """

        self.modifiedTimes[part] = counter.counter()
Example #35
0
def getData(numMeas, countTime=10.0):
    rotorFreqs = zeros(numMeas)		               # Create array in which to store rotorFreqs
    for j in range (0, numMeas):                           # Take numMeas readings
        while rotorFreqs[j] == 0:                          # It is possible to have an unsuccessful count. This checks if any previous counts have been successful and allows another count if necessary
            #edit 24/1/2013 by Zach
            #save counter data into new file            
            count = counter.counter(countTime, plotDataBool=False)            
            rotorFreqs[j] = count* math.pi / 180    #Angular frequency measurement of inner tube (numerical factor 2pi/100 radians per spoke)
            #writeToFile(count)#, f = 'counter-'+Filename)
        print 'count ' + str(j + 1) + ' of ' + str(numMeas) + ' taken successfully. [' + str(rotorFreqs[j] * 180/np.pi) + ' degs/sec]'
        # Kazem, 3.16.2012 - I added the reporting of data for convenience.
    return rotorFreqs                                       #Return angular frequencies of inner tube
Example #36
0
    def modify(self, part=0):
        """Used by the ModuleManager to timestamp the modified time.

        This should be called whenever module state has changed in such a way
        as to invalidate the current state of the module.  At the moment,
        this is called by L{applyViewToLogic()} as well as by the
        ModuleManager.

        @param part: indicates the part that has to be modified.
        """

        self.modifiedTimes[part] = counter.counter()
Example #37
0
    def __init__ (
            self,
            authorizer,
            hostname        =None,
            ip              ='',
            port            =21,
            resolver        =None,
            dataports       =None,
            logger_object=logger.file_logger (sys.stdout)
            ):
        self.ip = ip
        self.port = port
        self.authorizer = authorizer

        if hostname is None:
            self.hostname = socket.gethostname()
        else:
            self.hostname = hostname
            
        # use data port range if specified
        if dataports:
            self.port_factory = PortFactory(dataports)
        else:
            self.port_factory = None

        # statistics
        self.total_sessions = counter()
        self.closed_sessions = counter()
        self.total_files_out = counter()
        self.total_files_in = counter()
        self.total_bytes_out = counter()
        self.total_bytes_in = counter()
        self.total_exceptions = counter()
        #
        asyncore.dispatcher.__init__ (self)
        self.create_socket (socket.AF_INET, socket.SOCK_STREAM)

        self.set_reuse_addr()
        self.bind ((self.ip, self.port))
        self.listen (5)

        if not logger_object:
            logger_object = sys.stdout

        if resolver:
            self.logger = logger.resolving_logger (resolver, logger_object)
        else:
            self.logger = logger.unresolving_logger (logger_object)

        self.log_info('FTP server started at %s\n\tAuthorizer:%s\n\tHostname: %s\n\tPort: %d' % (
                time.ctime(time.time()),
                repr (self.authorizer),
                self.hostname,
                self.port)
                )
Example #38
0
def getData(
    numMeas
):  #Goes through all shear rates and samples each one numMeas times; returns angular frequencies of inner tube (called by main)
    rotorFreqs = zeros(numMeas)  #Create array in which to store rotorFreqs
    for j in range(0, numMeas):  #Take numMeas readings
        while rotorFreqs[
                j] == 0:  #It is possible to have an unsuccessful count. This checks if any previous counts have been successful and allows another count if necessary
            rotorFreqs[j] = counter.counter(
                8
            ) * math.pi / 180  #Angular frequency measurement of inner tube (numerical factor 2pi/100 radians per spoke)
        print 'count ' + str(j + 1) + ' of ' + str(
            numMeas) + ' taken successfully.'
    return rotorFreqs  #Return angular frequencies of inner tube
Example #39
0
def getData(
    numMeas
):  # Goes through all shear rates and samples each one numMeas times; returns angular frequencies of inner tube (called by main)
    rotorFreqs = zeros(numMeas)  # Create array in which to store rotorFreqs
    for j in range(0, numMeas):  # Take numMeas readings
        while (
            rotorFreqs[j] == 0
        ):  # It is possible to have an unsuccessful count. This checks if any previous counts have been successful and allows another count if necessary
            rotorFreqs[j] = (
                counter.counter(8) * math.pi / 180
            )  # Angular frequency measurement of inner tube (numerical factor 2pi/100 radians per spoke)
        print "count " + str(j + 1) + " of " + str(numMeas) + " taken successfully."
    return rotorFreqs  # Return angular frequencies of inner tube
Example #40
0
def panel():
    name = request.form.to_dict()
    createConfig(name['rejestracja'])

    server_number = str(counter())
    new_serwer = name['rejestracja']
    updateconf(serwer_file, server_number, new_serwer)

    global current_serwer
    current_serwer = new_serwer

    print(current_serwer)

    return render_template("index.html")
Example #41
0
 def __init__ (self, server, sock, addr):
     asynchat.async_chat.__init__ (self, sock)
     self.server = server
     self.addr = addr
     self.set_terminator ('\r\n')
     self.data = ''
     # local bindings specific to this channel
     self.local_env = {}
     # send timestamp string
     self.timestamp = str(time.time())
     self.count = 0
     self.line_counter = counter()
     self.number = int(server.total_sessions.as_long())
     self.multi_line = []
     self.push (self.timestamp + '\r\n')
Example #42
0
def motorCalibration(
    targMin, targMax, numMotorFreqs, motorCalFreq
):  #Calibrates the viscometer so that the minimum shear rate is close to targMin, the maximum shear rate is close to maxSR, and the others are equally spaced in between (called by main)
    rotorCalFreq = counter.counter(
        8
    ) * math.pi / 180  #Calibration Measurement (numerical factor 2pi/100 radians per spoke)
    calShearRate = GeoConst * rotorCalFreq  #Calculate shear rate from calibration run
    motorFreqMin = motorCalFreq * targMin / calShearRate  #Calculate Minimum Motor Freq (assume linear relation between motor speed and shear rate)
    motorFreqMax = motorCalFreq * targMax / calShearRate  #Calculate Maximum Motor Freq (assume linear relation between motor speed and shear rate)
    df = (motorFreqMax - motorFreqMin) / (
        numMotorFreqs - 1
    )  #Use number of freqs to be used and min and max to determine difference between consecutive motor frequencies
    motorFreqs = arange(motorFreqMin, motorFreqMax + df,
                        df)  #Create 1-d array of motor freqs to be used
    return motorFreqs  #Return motorFreqs
Example #43
0
def setting(debug = False):
    database = False
    global Branch
    if (input("Setup new Branch? (y or N)").lower() == 'y'):
        print("Setup new Branch database wait ... ")
        database = True
    infile = open("C:/Users/Xprize/Documents/solfdev/MyfirstSoftware/Final_Solfware/Branch_backend/setting.txt", encoding="utf8")
    # infile = open("setting.txt", encoding="utf8")
    counter_typee = {}
    for line in infile:
        if (line == "\n"):
            continue
        data = ((line.split('\n'))[0])
        data = data.strip()  # remove tail&head space
        data = data.replace("\t", "")
        data = data.split()
        if (data[0] == "branch"):
            Branch = str(data[1])
            if(database):
                db.collection(Branch).document(u'Queue').set({})
                db.collection(Branch).document(u'Data').set({})
                db.collection(Branch).document(u'QueuePush').collection(u'ticket').document(u'frist').set({})

        elif (data[0] == "countertype"):
            counter_types = data[2].split(",")
            counter_name_setup = data[1]
            if(database):
                db.collection(Branch).document('Data').update({str("Last_")+str(counter_name_setup) : counter_name_setup[-1:].upper() + "000"})
                db.collection(Branch).document('Data').update({str("Next_")+str(counter_name_setup) : counter_name_setup[-1:].upper() + "001"})
                db.collection(Branch).document(u'Data').update({counter_name_setup:counter_types})
            for i in counter_types:
                counter_typee[i] = data[1]
        
        elif (data[0] == "counter"):
            t = counter(name=data[3],counter_type= data[2] , sw_data= data[1],debug = debug,Branchinput = Branch)
            sw_object[data[1]] = t

        elif(data[0] == "avg_data"):
            if(database):
                db.collection(Branch).document('Data').update({str("Avg_")+str(data[1]) : int(data[2])}) #read form setting.txt
                db.collection(Branch).document('Data').update({str("Count_")+str(data[1]) : 0})

    if (database):
        db.collection(Branch).document(u'Data').update(counter_typee)

    if (debug):
        print(sw_object)
        print(counter_typee)
Example #44
0
 def __init__ (self, server, sock, addr):
     asynchat.async_chat.__init__ (self, sock)
     self.server = server
     self.addr = addr
     self.set_terminator ('\r\n')
     self.data = ''
     # local bindings specific to this channel
     self.local_env = sys.modules['__main__'].__dict__.copy()
     self.push ('Python ' + sys.version + '\r\n')
     self.push (sys.copyright+'\r\n')
     self.push ('Welcome to %s\r\n' % self)
     self.push ("[Hint: try 'from __main__ import *']\r\n")
     self.prompt()
     self.number = server.total_sessions.as_long()
     self.line_counter = counter()
     self.multi_line = []
Example #45
0
    def __init__ (
            self,
            authorizer,
            hostname        =None,
            ip              ='',
            port            =21,
            resolver        =None,
            logger_object=logger.file_logger (sys.stdout)
            ):
        self.ip = ip
        self.port = port
        self.authorizer = authorizer

        if hostname is None:
            self.hostname = socket.gethostname()
        else:
            self.hostname = hostname

        # statistics
        self.total_sessions = counter()
        self.closed_sessions = counter()
        self.total_files_out = counter()
        self.total_files_in = counter()
        self.total_bytes_out = counter()
        self.total_bytes_in = counter()
        self.total_exceptions = counter()
        #
        asyncore.dispatcher.__init__ (self)
        self.create_socket (socket.AF_INET, socket.SOCK_STREAM)

        self.set_reuse_addr()
        self.bind ((self.ip, self.port))
        self.listen (5)

        if not logger_object:
            logger_object = sys.stdout

        if resolver:
            self.logger = logger.resolving_logger (resolver, logger_object)
        else:
            self.logger = logger.unresolving_logger (logger_object)

        self.log_info('FTP server started at %s\n\tAuthorizer:%s\n\tHostname: %s\n\tPort: %d' % (
                time.ctime(time.time()),
                repr (self.authorizer),
                self.hostname,
                self.port)
                )
Example #46
0
 def __init__ (self, module, uri_base=None, debug=None):
     self.module = module
     self.debug = debug
     if self.debug:
         self.last_reload=self.module_mtime()
     self.hits = counter.counter()
     
     # if uri_base is unspecified, assume it
     # starts with the published module name
     #
     if not uri_base:	
         uri_base="/%s" % module.__name__
     elif uri_base[-1]=="/":	# kill possible trailing /
         uri_base=uri_base[:-1]
     self.uri_base=uri_base
     
     uri_regex='%s.*' % self.uri_base
     self.uri_regex = regex.compile(uri_regex)
Example #47
0
def motorCalibration(
    targMin, targMax, numMotorFreqs, motorCalFreq
):  # Calibrates the viscometer so that the minimum shear rate is close to targMin, the maximum shear rate is close to maxSR, and the others are equally spaced in between (called by main)
    rotorCalFreq = (
        counter.counter(8) * math.pi / 180
    )  # Calibration Measurement (numerical factor 2pi/100 radians per spoke)
    calShearRate = GeoConst * rotorCalFreq  # Calculate shear rate from calibration run
    motorFreqMin = (
        motorCalFreq * targMin / calShearRate
    )  # Calculate Minimum Motor Freq (assume linear relation between motor speed and shear rate)
    motorFreqMax = (
        motorCalFreq * targMax / calShearRate
    )  # Calculate Maximum Motor Freq (assume linear relation between motor speed and shear rate)
    df = (motorFreqMax - motorFreqMin) / (
        numMotorFreqs - 1
    )  # Use number of freqs to be used and min and max to determine difference between consecutive motor frequencies
    motorFreqs = arange(motorFreqMin, motorFreqMax + df, df)  # Create 1-d array of motor freqs to be used
    return motorFreqs  # Return motorFreqs
Example #48
0
    def __init__(self,
                 authz,
                 ssl_ctx,
                 host=None,
                 ip='',
                 port=21,
                 resolver=None,
                 log_obj=None):
        """Initialise the server."""
        self.ssl_ctx = ssl_ctx
        self.ip = ip
        self.port = port
        self.authorizer = authz

        if host is None:
            self.hostname = socket.gethostname()
        else:
            self.hostname = host

        self.total_sessions = counter()
        self.closed_sessions = counter()
        self.total_files_out = counter()
        self.total_files_in = counter()
        self.total_bytes_out = counter()
        self.total_bytes_in = counter()
        self.total_exceptions = counter()

        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((self.ip, self.port))
        self.listen(5)

        if log_obj is None:
            log_obj = sys.stdout

        if resolver:
            self.logger = logger.resolving_logger(resolver, log_obj)
        else:
            self.logger = logger.unresolving_logger(
                logger.file_logger(sys.stdout))

        l = 'M2Crypto (Medusa) FTP/TLS server started at %s\n\tAuthz: %s\n\tHostname: %s\n\tPort: %d'
        self.log_info(l % (time.ctime(time.time()), repr(
            self.authorizer), self.hostname, self.port))
Example #49
0
def test_counter():

    clk = Signal(bool(0))
    reset = ResetSignal(1, active=0, async=True)
    control = Signal(intbv(0)[2:])
    data = Signal(intbv(0)[8:])
    step = Signal(intbv(1)[4:])
    count = Signal(modbv(0, min=0, max=2**8))
    cnt_inst = counter(reset, clk, control, data, step, count)

    half_clk_period = 1
    clk_period = 2 * half_clk_period

    @always(delay(half_clk_period))
    def clk_gen():
        clk.next = not clk

    @instance
    def stimulus():
        reset.next = 0
        yield delay(clk_period)
        reset.next = 1
        yield delay(clk_period)
        reset.next = 1
        step.next = 3
        data.next = 0b11010010
        yield delay(clk_period)
        control.next = 1
        yield delay(3 * clk_period)
        control.next = 2
        yield delay(3 * clk_period)
        control.next = 2
        yield delay(3 * clk_period)
        control.next = 3
        yield delay(3 * clk_period)
        control.next = 3
        yield delay(3 * clk_period)

        raise StopSimulation

    return cnt_inst, clk_gen, stimulus
Example #50
0
def compile_func(func: calc.Function) -> tac.Function:
    tac_stmts = []
    fresh_var = counter(f"tmp_{func.name}")

    def compile_expr(expr):
        if isinstance(expr, calc.ExprVar):
            return expr.var
        if isinstance(expr, calc.ExprBop):
            left = compile_expr(expr.left)
            right = compile_expr(expr.right)
            new_x = next(fresh_var)
            if expr.bop is calc.BOp.ADD:
                tac_stmts.append(tac.StmtAssignAdd(new_x, left, right))
            elif expr.bop is calc.BOp.SUB:
                tac_stmts.append(
                    tac.StmtAssignSub(new_x, compile_expr(expr.left),
                                      compile_expr(expr.right)))
            elif expr.bop is calc.BOp.MUL:
                tac_stmts.append(tac.StmtAssignMul(new_x, left, right))
            elif expr.bop is calc.BOp.DIV:
                tac_stmts.append(
                    tac.StmtAssignDiv(new_x, compile_expr(expr.left),
                                      compile_expr(expr.right)))

            # tac_stmts.append(tac.StmtAssignAdd(next(fresh_var), compile_expr(expr.left), compile_expr(expr.right) ))

            return new_x

    def compile_stmt(stmt):
        if isinstance(stmt, calc.StmtAssign):
            tac_stmts.append(
                tac.StmtAssignVar(stmt.var, compile_expr(stmt.expr)))

    for calc_stmt in func.stmts:
        compile_stmt(calc_stmt)
    return tac.Function(func.name, func.args, tac_stmts, func.ret)
Example #51
0
    def __init__(self, authz, ssl_ctx, host=None, ip='', port=21, resolver=None, 
                 dataports=None, log_obj=None, callback=None):
        """Initialise the server."""
        self.ssl_ctx = ssl_ctx
        self.ip = ip
        self.port = port
        self.authorizer = authz
        self.callback = callback

        if host is None:
            self.hostname = socket.gethostname()
        else:
            self.hostname = host

        # use data port range if specified
        if dataports:
            self.port_factory = ftp_server.PortFactory(dataports)
        else:
            self.port_factory = None

        self.total_sessions = counter()
        self.closed_sessions = counter()
        self.total_files_out = counter()
        self.total_files_in = counter()
        self.total_bytes_out = counter()
        self.total_bytes_in = counter()
        self.total_exceptions = counter()

        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((self.ip, self.port))
        self.listen(5)
        
        self.log_obj = log_obj

        l = 'M2Crypto (Medusa) FTP/TLS server started at %s\n\tAuthz: %s\n\tHostname: %s\n\tPort: %d'
        self.log_info(l % (time.ctime(time.time()), repr(self.authorizer), self.hostname, self.port))
Example #52
0
    def __init__(self, authz, ssl_ctx, host=None, ip='', port=21, resolver=None, log_obj=None):
        """Initialise the server."""
        self.ssl_ctx = ssl_ctx
        self.ip = ip
        self.port = port
        self.authorizer = authz

        if host is None:
            self.hostname = socket.gethostname()
        else:
            self.hostname = host

        self.total_sessions = counter()
        self.closed_sessions = counter()
        self.total_files_out = counter()
        self.total_files_in = counter()
        self.total_bytes_out = counter()
        self.total_bytes_in = counter()
        self.total_exceptions = counter()

        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((self.ip, self.port))
        self.listen(5)

        if log_obj is None:
            log_obj = sys.stdout

        if resolver:
            self.logger = logger.resolving_logger(resolver, log_obj)
        else:
            self.logger = logger.unresolving_logger(logger.file_logger(sys.stdout))

        l = 'M2Crypto (Medusa) FTP/TLS server started at %s\n\tAuthz: %s\n\tHostname: %s\n\tPort: %d'
        self.log_info(l % (time.ctime(time.time()), repr(self.authorizer), self.hostname, self.port))
                fo = open ('/export/pynfs-log.txt','r')
                total = int( fo.read())
                fo.close()
                os.system('cat /export/pynfs-results.log| grep "Of those" | cut -d " " -f5 > /export/pynfs-log.txt')
                fo = open ('/export/pynfs-log.txt','r')
                failures=int(fo.read())
                fo.close()
                os.system('cat /export/pynfs-results.log| grep "Of those" | cut -d " " -f9 > /export/pynfs-log.txt')
                fo = open ('/export/pynfs-log.txt','r')
                passed=int(fo.read())
                fo.close()


                print "===============================Pynfs tests================================================"
                print "TOTAL           : %d " %total
                print "FAILURES        : %d " %failures
                print "PASS            : %d " %passed

                new_failures = failures - known_failures
                if new_failures > 0 :
	                if total == "568" :
		                print "PYNFS TESTS                   : FAIL"
			        print "Check /export/pynfs-results.log for results"

                else:
	                        print "PYNFS TESTS                   : PASS"
	                        counter.counter(1)
                print "====================================PYNFS TESTS END=========================================="
else:
        print "Mount failed,skipping pynfs tests."
Example #54
0
#Unit test4 : Removing the files created;

def test2_4():
        try:
                for i in range(1,10):
                        s="file"
                        s+=str(i)
                        os.remove("/mnt/ganesha-mnt/%s"%s)
        except OSError as ex :
                print (ex)
                print "Test 2.4:FAIL"
        else:
                success("2.4")
		global count
		count = count + 1

test2_1()
test2_2()
test2_3()
test2_4()

if count == 4:
        print "FILE TESTS                   : PASS"
	counter(1)
else:
	print "FILE TESTS                   : FAIL"

print "==============================FILE TESTS END==============================="