Пример #1
0
def Main():
    d1 = datetime.datetime.now()
    
    lonelyMan = RenRenSpider()
    lonelyMan.login()
    userID = lonelyMan.getUserID()
    
    checkPaths(userID)
    checkPaths(ownerID=config.ownerID)
 
    albumList = AlbumList(userID,lonelyMan,ownerID=config.ownerID)
    albumList.work()
       
    status = Status(userID,lonelyMan,config.ownerID)
    status.work()
 
    bloglist = BlogList(userID,lonelyMan,config.ownerID)
    bloglist.work()
   
    gossip = Gossip(userID,lonelyMan,config.ownerID)
    gossip.work()
        
    repo = RepoMysql(userID,lonelyMan)
    repo.work()
    
    d2 = datetime.datetime.now()
    print 'all have been done, time: ', d2 - d1
Пример #2
0
def Main():
    d1 = datetime.datetime.now()

    lonelyMan = RenRenSpider()
    lonelyMan.login()
    userID = lonelyMan.getUserID()

    checkPaths(userID)
    checkPaths(ownerID=config.ownerID)

    albumList = AlbumList(userID, lonelyMan, ownerID=config.ownerID)
    albumList.work()

    status = Status(userID, lonelyMan, config.ownerID)
    status.work()

    bloglist = BlogList(userID, lonelyMan, config.ownerID)
    bloglist.work()

    gossip = Gossip(userID, lonelyMan, config.ownerID)
    gossip.work()

    repo = RepoMysql(userID, lonelyMan)
    repo.work()

    d2 = datetime.datetime.now()
    print 'all have been done, time: ', d2 - d1
Пример #3
0
    def __init__(self):
        self.state = State(0)
        self.params = Params()
        self.status = Status(self.params)
        self.sleep_time = 1
        self.pwm_read = PwmRead(
            self.params.pin_mode_in,
            self.params.pin_servo_in,
            self.params.pin_thruster_in,
            self.params.pin_OR,
        )
        self.pwm_out = PwmOut(self.params.pin_servo_out, self.params.pin_thruster_out)
        self.pid = PositionalPID()
        self.logger = Logger()
        self.logger.open()
        # Whether experienced OR mode or not
        self.or_experienced = False

        # setup for ina226
        print("Configuring INA226..")
        self.iSensor = ina226(INA226_ADDRESS, 1)
        self.iSensor.configure(
            avg=ina226_averages_t["INA226_AVERAGES_4"],
        )
        self.iSensor.calibrate(rShuntValue=0.002, iMaxExcepted=1)

        time.sleep(1)

        print("Configuration Done")

        current = self.iSensor.readShuntCurrent()

        print("Current Value is " + str(current) + "A")

        print("Mode is " + str(hex(self.iSensor.getMode())))
Пример #4
0
    def fight(duel_array) :
        count_monsters = len(duel_array)
        if (count_monsters%2 != 0):
            count_monsters -= 1

        random = []
    
        count_range = int(count_monsters/2)

        for ind in range(0,count_range):
            random_num = count_monsters - 1
            control_loop = 0
            while (control_loop == 0):
        
                x = randint(0, random_num)
                if x not in random:
                    random.append(x)
                    control_loop = 1
            

            control_loopi = 0
            while (control_loopi == 0):
                y = randint(0, random_num)
                if y not in random: 
                    random.append(y)
                    control_loopi = 1
          
            Status.combat( duel_array[x] ,duel_array[y] )
            Torneio.duelo( duel_array[x] ,duel_array[y] )
Пример #5
0
    def __init__(self):
        self.config = Config()
        #self.client = pylxd.Client(endpoint=self.config['DEFAULT']['LXD_URL'], cert=(self.config['DEFAULT']['LXD_CERT'], self.config['DEFAULT']['LXD_KEY']), verify=False)
        self.client = pylxd.Client()
        #client.authenticate('ferrari')

        self.status = Status()
    def __init__(self):
        self._time_manager = TimeManager()
        self._params = Params()
        self._status = Status(self._params)
        self.log_time = time.time()
        self._pwm_read = PwmRead(
            self._params.pin_mode_in,
            self._params.pin_servo_in,
            self._params.pin_thruster_in,
            self._params.pin_or,
        )
        self._pwm_out = PwmOut(self._params.pin_servo_out,
                               self._params.pin_thruster_out)
        self._pid = PositionalPID()
        self._logger = Logger()
        self._logger.open()
        # Whether experienced OR mode or not
        self._or_experienced = False

        # setup for ina226
        print("Configuring INA226..")
        try:
            self.i_sensor = ina226(INA226_ADDRESS, 1)
            self.i_sensor.configure(
                avg=ina226_averages_t["INA226_AVERAGES_4"], )
            self.i_sensor.calibrate(rShuntValue=0.002, iMaxExcepted=1)
            self.i_sensor.log()
            print("Mode is " + str(hex(self.i_sensor.getMode())))
        except:
            print("Error when configuring INA226")

        time.sleep(1)

        print("Configuration Done")
Пример #7
0
    def __init__(self, *args):

        Status.__init__(self, *args) 
 
        # init client server params...
        CliServerParams(self)       

        return
Пример #8
0
    def __init__(self, *args):

        Status.__init__(self, *args)

        # init client server params...
        CliServerParams(self)

        return
Пример #9
0
 def __init__(self):
     self.state = State(0)
     self.params = Params()
     self.status = Status(self.params)
     self.sleep_time = 1
     self.pwm_read = PwmRead(self.params.pin_mode_in, self.params.pin_servo_in, self.params.pin_thruster_in)
     self.pwm_out = PwmOut(self.params.pin_servo_out, self.params.pin_thruster_out)
     self.pid = PositionalPID()
     self.logger = Logger()
     self.logger.open()
Пример #10
0
 def open(self, pab, devname):
     logger.info("open %s", devname)
     if mode(pab) == INPUT:
         if dataType(pab) == DISPLAY:
             if recordLength(pab) == 0 or recordLength(pab) == 80:
                 self.tipi_io.send([SUCCESS])
                 self.tipi_io.send([80])
                 self.tipiStatus = Status()
                 self.recordNo = 0
                 return
     self.tipi_io.send([EOPATTR])
Пример #11
0
    def __init__(self, host, timeout, full_scan, gauge, output_window):
        threading.Thread.__init__(self)

        #pull the wx frame for the info box event
        self.output_window = output_window

        #creat messanger object for sending text to panel
        self.message = PanelMessage(output_window)

        #get gauge instance from gui
        self.gauge = gauge

        #get host
        self.host = host

        #boolean to indicate if the scan will do all ports or the smaller set
        self.full_scan = full_scan

        #queue to pass ports to threads
        self.queue = Queue.Queue()

        #empty array that will hold the list of open ports
        self.port_list = []

        #counter to caluclate ports scasnned per second
        self.count = 0

        #passed to threads, how long to wait on port response
        self.timeout = timeout

        #how many threads to run concurently
        self.threadcount = 200

        #list to contain all the threeads generated
        self.threads = []

        #range of ports to scan, set 9999 as default, but changed later if needed
        self.portrange = 9999

        #list of common ports for the shart scan
        self.common_ports = [
            20, 21, 22, 23, 79, 80, 110, 113, 119, 143, 443, 1002, 1720, 5000,
            8080
        ]

        #start Status object, pass actule number of ports to be scanned
        #change some variables depending on the type of scan chosen
        if self.full_scan == True:
            self.status = Status(self.portrange - 1, self.output_window)
        else:
            self.portrange = len(self.common_ports)
            self.status = Status(self.portrange, self.output_window)
            self.threadcount = self.portrange
    def save(self, path) -> Status:
        header = create_svg_header(self._display_dimensions)
        content = header + self._commands + '</svg>\n'

        status = Status(ok=True)
        try:
            with open(path, 'w') as svg_file:
                svg_file.write(content)
        except Exception as e:
            err_str = 'Error writing to {}: {}.'.format(path, str(e))
            status = Status(ok=False, err_str=err_str)
        return status
Пример #13
0
    def __init__(self):
        self.config = Config()
        self.metaQ = Queue('pluto',
                           connection=Redis('windows', 6379, db=1),
                           default_timeout=1 * 3600)
        self.status = Status()

        client = pymongo.MongoClient(
            f"mongodb+srv://explorer:{self.config.MongoPass}@cluster0-eyzcm.mongodb.net/test?retryWrites=true&w=majority"
        )
        self.db = client.plutoQ
        self.cm = ContainerManager()
Пример #14
0
class Cleaner(Actor):
    def __init__(self, cfg_params):
        """
        constructor
        """
        self.status = Status(cfg_params)

    def check(self):
        """
        Check whether no job is still running or not yet retrieved
        """

        task = common._db.getTask()
        upTask = common.scheduler.queryEverything(task['id'])
        self.status.compute(upTask)  # compute the status

        jobTerm = []
        jobSub = []
        for job in task.jobs:
            st = job.runningJob['state']
            if st not in [
                    'KillSuccess', 'SubFailed', 'Created', 'Aborted',
                    'Cleared', 'Cleaned'
            ]:
                if st in ['Terminated']: jobTerm.append(job['jobId'])
                if st in ['SubSuccess']: jobSub.append(job['jobId'])
            pass

        if len(jobTerm) > 0 or len(jobSub) > 0:
            msg = "There are still "
            if len(jobSub) > 0:
                msg = msg + " jobs submitted. Kill them '-kill %s' before '-clean'" % readableList(
                    self, jobSub)
            if (len(jobTerm) > 0 or len(jobSub) > 0):
                msg = msg + "and \nalso"
            if len(jobTerm) > 0:
                msg = msg + " jobs Done. Get their outputs '-get %s' before '-clean'" % readableList(
                    self, jobTerm)
            raise CrabException(msg)
        pass

    def run(self):
        """
        remove all
        """
        if common._db.nJobs() > 0:
            self.check()

        # here I should first purge boss DB if central
        #common.scheduler.clean()
        common.work_space.delete()
        print 'directory ' + common.work_space.topDir() + ' removed'
Пример #15
0
def getPosts(user,clean=True,maxPosts=100):
    try:
        userName = user.facebookId
        args = {}

        graph = GraphAPI(at)
        profile = graph.get_object(userName)
        posts = graph.get_connections(profile['id'], 'posts', **args)
        statuses = []
        lastUntil = ''
    
        for s in posts['paging']['next'].split('&'):
            if 'limit=' in s:
                args['limit'] = s.split('=')[1]
            if 'until=' in s:
                args['until'] = s.split('=')[1]
        while True:
            isBreak = False
            for data in posts['data']:
                if 'message' not in data:
                    continue
                smessage = str(data['message'].encode("utf-8")).replace('\\n', ' ').replace('\\r', '')[2:-1]
                if clean:
                    smessage = re.sub(r'https?:\/\/[^\s]*','',smessage, flags=re.MULTILINE)
                    smessage = re.sub(r'\\x..','',smessage, flags=re.MULTILINE)
                    smessage = re.sub(r'&amp;','and',smessage, flags=re.IGNORECASE)
                    smessage = re.sub(r'[\s\t]+',' ',smessage, flags=re.IGNORECASE)
                    smessage.replace('#','')

                if validPost(smessage):
                    st = Status()
                    st.statusText = smessage
                    st.id = data['id']
                    statuses.append(st)

            if len(statuses) > maxPosts:
                break
            posts = graph.get_connections(profile['id'], 'posts',**args)
            nargs = {}
            for s in posts['paging']['next'].split('&'):
                if 'limit=' in s:
                    nargs['limit'] = s.split('=')[1]
                if 'until=' in s:
                    nargs['until'] = s.split('=')[1]
            if nargs['until'] == args['until']:
                break
            else:
                args['limit'] = nargs['limit']
                args['until'] = nargs['until']
        return statuses
    except ConnectionError:
        return []
Пример #16
0
    def Put(self, write_options, key, value):
        assert isinstance(write_options, WriteOptions)
        assert isinstance(key, six.binary_type)
        assert isinstance(value, six.binary_type)

        status = Status()
        rocksdb_put(
                self.dbptr_internal,
                write_options.to_rocksdb_internal(),
                key, len(key),
                value, len(value),
                ctypes.byref(status.to_rocksdb_internal()))
        return status
Пример #17
0
    def Open(db_options, dbname):
        assert isinstance(db_options, DBOptions)
        assert isinstance(dbname, six.binary_type)

        status = Status()
        dbptr = rocksdb_open(
                db_options.to_rocksdb_internal(), 
                dbname,
                ctypes.byref(status.to_rocksdb_internal()))
        if dbptr:
            return DB(dbptr), status
        else:
            return None, status
Пример #18
0
class Cleaner(Actor):
    def __init__(self, cfg_params):
        """
        constructor
        """
        self.status = Status(cfg_params)

    def check(self):
        """
        Check whether no job is still running or not yet retrieved
        """

        task = common._db.getTask()
        upTask = common.scheduler.queryEverything(task['id'])
        self.status.compute(upTask) # compute the status

        jobTerm=[]
        jobSub=[]
        for job  in task.jobs:
            st=job.runningJob['state']
            if st not in ['KillSuccess', 'SubFailed', 'Created', 'Aborted', 'Cleared', 'Cleaned']:
                if st in ['Terminated']: jobTerm.append(job['jobId'])
                if st in ['SubSuccess']: jobSub.append(job['jobId'])
            pass

        if len(jobTerm)>0 or len(jobSub)>0:
            msg = "There are still "
            if len(jobSub)>0:
                msg= msg+" jobs submitted. Kill them '-kill %s' before '-clean'"%readableList(self,jobSub)
            if (len(jobTerm)>0 or len(jobSub)>0):
                msg = msg + "and \nalso"
            if len(jobTerm)>0:
                msg= msg+" jobs Done. Get their outputs '-get %s' before '-clean'"%readableList(self,jobTerm)
            raise CrabException(msg)
        pass

    def run(self):
        """
        remove all
        """
        if common._db.nJobs()>0:
            self.check()

        # here I should first purge boss DB if central
        #common.scheduler.clean()
        common.work_space.delete()
        print 'directory '+common.work_space.topDir()+' removed'
Пример #19
0
 def update_contacts(self):
     self._contacts = [
         DummyContact(
             self, 'Echo', 'echo',
             'http://beanies.vn/wp-content/uploads/2014/05/belgian_waffle-1513470.jpg',
             Status(0, 'I will repeat your every message <3'))
     ]
     return True
Пример #20
0
def work(userID, lonelyMan, i):

    checkPaths(ownerID=config.ownerID[i])

    albumList = AlbumList(userID, lonelyMan, ownerID=config.ownerID[i])
    albumList.work()

    status = Status(userID, lonelyMan, config.ownerID[i])
    status.work()

    bloglist = BlogList(userID, lonelyMan, config.ownerID[i])
    bloglist.work()

    gossip = Gossip(userID, lonelyMan, config.ownerID[i])
    gossip.work()

    repo = RepoMysql(userID, lonelyMan)
    repo.work()
Пример #21
0
    def Get(self, read_options, key):
        assert isinstance(read_options, ReadOptions)
        assert isinstance(key, six.binary_type)

        status = Status()
        vallen = ctypes.c_size_t()
        valptr = rocksdb_get(
                self.dbptr_internal,
                read_options.to_rocksdb_internal(),
                key, len(key),
                ctypes.byref(vallen),
                ctypes.byref(status.to_rocksdb_internal()))

        if not status.OK or not valptr:
            return None, status
        else:
            vt = ctypes.c_char * (vallen.value)
            res = ctypes.cast(valptr, ctypes.POINTER(vt))
            return res.contents.value, status
Пример #22
0
class Cell(object):
    def __init__(self, position=None):
        self.status = Status()
        self.position = position

    def is_mine(self):
        return False

    def __str__(self):
        return self.status.__str__()
Пример #23
0
 def __init__(self, columns, rows, max_iterations, alphabet, threshold_proportion, mutator_name):
     self.columns = columns
     self.rows = rows
     self.max_iterations = max_iterations
     self.alphabet = alphabet
     self.status = Status(max_iterations, rows, columns, len(alphabet))
     self.dataset = Dataset(rows= rows, cols = columns, alphabet=alphabet)
     self.data = self.dataset.get_data()
     if mutator_name == 'RandomFlip':
         self.mutator = RandomFlip(self.dataset, 0.3)
     elif mutator_name == 'Exponential':
         self.mutator = ExpMutator(self.dataset, 0.3)
Пример #24
0
    def __init__(self, security=None, status=Status(), ctaTemplate=None, controlRisk=None,
                 enableTrade=False, enableBuy=True, enableShort=True, frequency=None,
                 pricePosi_top = 0, pricePosi_bottom = 4,
                 jqDataAccount='13268108673', jqDataPassword='******'):
        futureMsg = fm.getFutureMsg(security)
        self.enableTrade = enableTrade
        self.enableBuy = enableBuy
        self.enableShort = enableShort
        self.ctaTemplate = ctaTemplate
        self.controlRisk = controlRisk
        self.status = status
        self.jqDataAccount = jqDataAccount
        self.jqDataPassword = jqDataPassword
        self.frequency = frequency

        self.dataRow = 100
        self.pricePosi_top = pricePosi_top
        self.pricePosi_bottom = pricePosi_bottom
        self.lastExeTime = None
        self.security = security
        self.pricePositions = []
        self.maxPosition = dao.readMaxPosition(security)
        self.duo_position = dao.readDuoPosition(security) # 多单持仓手数
        self.kong_position = dao.readKongPosition(security) # 空单持仓手数

        self.writeCtaLog('########################允许交易:' + str(self.enableTrade))
        self.writeCtaLog('########################开多:' + str(self.enableBuy))
        self.writeCtaLog('########################开空:' + str(self.enableShort))
        self.writeCtaLog('########################合约代码:' + str(self.security))
        self.writeCtaLog('########################多单持仓:' + str(self.duo_position))
        self.writeCtaLog('########################空单持仓:' + str(self.kong_position))
        self.writeCtaLog('########################最大持仓:' + str(self.maxPosition))
        self.writeCtaLog('########################策略级别:' + str(self.frequency))
        self.writeCtaLog('########################jqdata账号:' + str(self.jqDataAccount))

        self.dayStartTime = futureMsg['dayStartTime']
        self.dayEndTime = futureMsg['dayEndTime']
        self.noonStartTime = futureMsg['noonStartTime']
        self.noonEndTime = futureMsg['noonEndTime']
        self.afternoonStartTime = futureMsg['afternoonStartTime']
        self.afternoonEndTime = futureMsg['afternoonEndTime']
        try :
            self.nightStartTime = futureMsg['nightStartTime']
            self.nightEndTime = futureMsg['nightEndTime']
        except:
            self.nightStartTime = None
            self.nightEndTime = None

        self.isInit = True
        self.rate = 1
        self.openPrice = None
Пример #25
0
def getTweets(user,clean=True,includeRetweets=False,maxTweets=1000000,includeOtherMentions=True):
    twitter_access_token_key,twitter_access_token_secret,twitter_consumer_key,twitter_consumer_secret = Config.getTwitterKeys()
    api = TwitterAPI(twitter_access_token_key,twitter_access_token_secret, twitter_consumer_key, twitter_consumer_secret)

    tweets = []
    li = api.fetch_by_user_names(user.twitterId,clean = clean)
    
    while li is not None and len(li) > 0:
        if "errors" in li and li["errors"][0]["code"] == 88:
            return []
        for tweet in li:
            tweetText = str(tweet['text'].encode("utf-8")).replace('\\n', ' ').replace('\\r', '').strip()[2:-1]
            if not includeRetweets and tweetText.startswith('RT'):
                continue
            if not includeOtherMentions and "@" in tweet['text']:
                continue
            if clean:
                tweetText = re.sub(r'https?:\/\/[^\s]*','',tweetText, flags=re.MULTILINE)
                tweetText = re.sub(r'\\x..','',tweetText, flags=re.MULTILINE)
                tweetText = re.sub(r'&amp;','and',tweetText, flags=re.IGNORECASE)
                tweetText = re.sub(r'[\s\t]+',' ',tweetText, flags=re.IGNORECASE)
                tweetText.replace('#','')
                tweetText = re.sub('^\s*rt\s',' ',tweetText,flags=re.IGNORECASE)
                if not validTweet(tweetText):
                    continue
                
            st = Status()
            st.id = tweet['id']
            st.likes = tweet['favorite_count']
            st.shares = tweet['retweet_count']
            st.CreatedOn = tweet['created_at']
            st.statusType = 1
            st.statusText = tweetText
            st.language = tweet["lang"]

            tweets.append(st)
        minId = min(tweets,key=lambda p:p.id).id
        li = api.fetch_by_user_names(user.twitterId,id= minId - 1,clean = clean)
        if len(tweets) > maxTweets or li is None or len(li) < 10:
            break
    return tweets
Пример #26
0
def dijkstra(graph, time_diff):
    ''' 
    Calculates the shortest path from a starting node to any other node in a given graph 
    using the Dijkstra algorithm and taking into account time tables.
    :param int graph.n_vertices: The number of nodes in the graph
    :param dict graph.edges: A dictionary with the form {(edge_start, edge_end): edge_weight}
    :param dict graph.neighbors: A dictionary with the form {node: [adjacent_nodes]}
    :param int graph.origin: The starting node in the graph
    '''
    if (graph.neighbors.get(graph.origin) is None):
        return [graph.origin], {graph.origin: 0}
    status = Status(graph)
    computeOriginNode(graph, status, time_diff)
    while status.priority_queue:
        computeNextNode(graph, status, time_diff) 
    return status.parents, status.weights
def run(size):
    status = Status(size, [[0 for x in range(size)] for y in range(size)])
    queen = Queen(size)
    i = 1
    check_set = 0
    while True:
        check_set = queen.set_queen(status)
        if check_set == size:
            """print the combination, set queen postion value is y-dir value
            queen number decremented and go back to previous status as normal"""
            status.return_comb()
            status.stat_arr[queen.pos_y][queen.pos_x] = queen.pos_y
            queen.number -= 1
            status.back_status(queen)
        elif check_set > 0:
            queen.move_queen(status)
        else:
            status.back_status(queen)
Пример #28
0
class Tasks(Command):

    # Dictionnary containing timestamp as a key and Status msg as a Value

    def __init__(self, receiver):
        super(Tasks, self).__init__(receiver)
        self.status = Status()  # Tester si on voit bien default message

    @abc.abstractmethod
    def execute(self):
        pass

    def toString(self):
        print("Begin: {tsb} \n End:{tse} \n Delta:{tsd} \n Message:{msg} \n".
              format(tsb=self.status.beginTimeStamp,
                     tse=self.status.endTimeStamp,
                     tsd=self.status.computeTimes(),
                     msg=self.status.message))
Пример #29
0
 def opprett_statuser(self):     #Oppretter status-objekter
     try:
         status_info_string = self.hent_JSON("https://gbfs.urbansharing.com/oslobysykkel.no/station_status.json")
         updated_at = status_info_string['last_updated']
         statuser = status_info_string['data']['stations']
     except:
         self.funnet_feil("Kunne ikke opprette statuser. ")
         return
     if not statuser:
         funnet_feil("Ingen stasjoner funnet. ")
         return
     alle_statuser = []
     for status in statuser:
         try:
             ny_status = Status(updated_at, status['station_id'], status['is_installed'],
                                 + status['is_renting'], status['num_bikes_available'],
                                 + status['num_docks_available'], status['last_reported'], status['is_returning'])
             alle_statuser.append(ny_status)
         except:
             self.funnet_feil("Feil ved opprettelse av status. ")
     return alle_statuser
Пример #30
0
class Driver:
    def __init__(self):
        self.state = State(0)
        self.params = Params()
        self.status = Status(self.params)
        self.sleep_time = 1
        self.pwm_read = PwmRead(self.params.pin_mode_in,
                                self.params.pin_servo_in,
                                self.params.pin_thruster_in)
        self.pwm_out = PwmOut(self.params.pin_servo_out,
                              self.params.pin_thruster_out)
        self.pid = PositionalPID()
        self.logger = Logger()
        self.logger.open()

    def load(self, filename):
        print('loading', filename)
        f = open(filename, "r")

        line = f.readline()
        line = f.readline()
        self.state.time_limit = int(line.split()[1])  # Time Limit
        line = f.readline()
        self.sleep_time = float(line.split()[1])  # Sleep time

        line = f.readline()
        line = f.readline()
        line = f.readline()
        p = float(line.split()[1])  # P
        line = f.readline()
        i = float(line.split()[1])  # I
        line = f.readline()
        d = float(line.split()[1])  # D
        self.pid.setPID(p, i, d)

        line = f.readline()
        line = f.readline()
        line = f.readline()
        num = int(line.split()[1])  # Number of waypoints
        line = f.readline()
        for i in range(num):
            line = f.readline()
            self.status.waypoint.addPoint(float(line.split()[0]),
                                          float(line.split()[1]))
        f.close()
        return

    def doOperation(self):
        while self.state.inTimeLimit():
            self.readPWM()
            self.readGps()

            mode = self.getMode()
            if mode == 'RC':
                self.remoteControl()
            elif mode == 'AN':
                self.autoNavigation()

            self.outPWM()
            self.printLog()
            time.sleep(self.sleep_time)
        return

    def getMode(self):
        return self.status.mode

    def updateMode(self):
        mode_duty_ratio = self.pwm_read.pulse_width[0]
        if mode_duty_ratio < 1500:
            self.status.mode = 'RC'
        elif mode_duty_ratio >= 1500:
            self.status.mode = 'AN'
        return

    def readGps(self):
        self.status.readGps()
        self.updateMode()
        #if self.status.isGpsError():
        #self.status.mode = 'RC'
        return

    def updateStatus(self):
        status = self.status
        status.calcTargetDirection()
        status.calcTargetDistance()
        status.updateTarget()
        return

    def readPWM(self):
        self.pwm_read.measurePulseWidth()
        self.pwm_out.servo_pulsewidth = self.pwm_read.pulse_width[1]
        self.pwm_out.thruster_pulsewidth = self.pwm_read.pulse_width[2]
        return

    def outPWM(self):
        self.pwm_out.updatePulsewidth()
        return

    def autoNavigation(self):
        self.updateStatus()
        boat_direction = self.status.boat_direction
        target_direction = self.status.target_direction
        servo_pulsewidth = self.pid.getStepSignal(target_direction,
                                                  boat_direction)
        self.pwm_out.servo_pulsewidth = servo_pulsewidth
        self.pwm_out.thruster_pulsewidth = 1880
        return

    def remoteControl(self):
        # Do nothing
        return

    def printLog(self):
        timestamp_string = self.status.timestamp_string
        mode = self.getMode()
        latitude = self.status.latitude
        longitude = self.status.longitude
        speed = self.status.speed
        direction = self.status.boat_direction
        servo_pw = self.pwm_out.servo_pulsewidth
        thruster_pw = self.pwm_out.thruster_pulsewidth
        t_direction = self.status.target_direction
        t_distance = self.status.target_distance
        target = self.status.waypoint.getPoint()
        t_latitude = target[0]
        t_longitude = target[1]
        print(timestamp_string)
        print(
            '[%s MODE] LAT=%.7f, LON=%.7f, SPEED=%.2f [km/h], DIRECTION=%lf' %
            (mode, latitude, longitude, speed, direction))
        print('DUTY (SERVO, THRUSTER):       (%lf, %lf) [us]' %
              (servo_pw, thruster_pw))
        print('TARGET (LATITUDE, LONGITUDE): (%lf, %lf)' %
              (t_latitude, t_longitude))
        print('TARGET (DIRECTION, DISTANCE): (%lf, %lf [m])' %
              (t_direction, t_distance))
        print('')
        log_list = [
            timestamp_string, mode, latitude, longitude, direction, t_latitude,
            t_longitude, servo_pw, thruster_pw, t_direction, t_distance
        ]
        self.logger.write(log_list)
        return

    def finalize(self):
        self.logger.close()
        self.pwm_out.finalize()
        return
Пример #31
0
 def __init__(self, cfg_params):
     """
     constructor
     """
     self.status = Status(cfg_params)
Пример #32
0
    def __init__(
        self,
        torrentIdent,
        globalStatus,
        connStatsCache,
        connStatus,
        remotePeerId,
        scheduler,
        conn,
        direction,
        remotePeerAddr,
        inMeasureParent,
        outMeasureParent,
        outLimiter,
        inLimiter,
    ):

        log = Logger("BtConnection", "%-6s - %-6s - ", torrentIdent, conn.fileno())
        inRate, outRate = connStatsCache.get(torrentIdent, remotePeerAddr, remotePeerId)

        Connection.__init__(
            self,
            connStatus,
            scheduler,
            conn,
            direction,
            remotePeerAddr,
            inRate,
            outRate,
            inMeasureParent,
            outMeasureParent,
            outLimiter,
            inLimiter,
            Messages.getMessageLength,
            Messages.decodeMessage,
            4,
            140000,
            Messages.generateKeepAlive,
            log,
        )

        # ident
        self.torrentIdent = torrentIdent

        # peer
        self.remotePeerId = remotePeerId
        self.remoteClient = peerIdToClient(remotePeerId)

        # conn stats cache
        self.connStatsCache = connStatsCache

        # piece status
        self.status = Status(globalStatus.getPieceAmount(), globalStatus)

        # choke and interest state
        self.localInterest = False
        self.remoteInterest = False
        self.localChoke = True
        self.remoteChoke = True

        # requests
        self.outRequestsInFlight = 0
        self.outRequestQueue = []
        self.outRequestHandles = {}
        self.maxInRequests = self._calculateMaxAmountOfInRequests()
        self.inRequestQueue = []
        self.inRequestInfo = {}

        # events
        self.requestTimeoutEvent = None
Пример #33
0
class BtConnection(Connection):
    def __init__(
        self,
        torrentIdent,
        globalStatus,
        connStatsCache,
        connStatus,
        remotePeerId,
        scheduler,
        conn,
        direction,
        remotePeerAddr,
        inMeasureParent,
        outMeasureParent,
        outLimiter,
        inLimiter,
    ):

        log = Logger("BtConnection", "%-6s - %-6s - ", torrentIdent, conn.fileno())
        inRate, outRate = connStatsCache.get(torrentIdent, remotePeerAddr, remotePeerId)

        Connection.__init__(
            self,
            connStatus,
            scheduler,
            conn,
            direction,
            remotePeerAddr,
            inRate,
            outRate,
            inMeasureParent,
            outMeasureParent,
            outLimiter,
            inLimiter,
            Messages.getMessageLength,
            Messages.decodeMessage,
            4,
            140000,
            Messages.generateKeepAlive,
            log,
        )

        # ident
        self.torrentIdent = torrentIdent

        # peer
        self.remotePeerId = remotePeerId
        self.remoteClient = peerIdToClient(remotePeerId)

        # conn stats cache
        self.connStatsCache = connStatsCache

        # piece status
        self.status = Status(globalStatus.getPieceAmount(), globalStatus)

        # choke and interest state
        self.localInterest = False
        self.remoteInterest = False
        self.localChoke = True
        self.remoteChoke = True

        # requests
        self.outRequestsInFlight = 0
        self.outRequestQueue = []
        self.outRequestHandles = {}
        self.maxInRequests = self._calculateMaxAmountOfInRequests()
        self.inRequestQueue = []
        self.inRequestInfo = {}

        # events
        self.requestTimeoutEvent = None

    ##internal functions - socket

    def _gotMessage(self, msg):
        if msg[0] == 7:
            # a piece part
            if self._hasThisInRequest(msg[1][0], msg[1][1], len(msg[1][2])):
                # a valid one even
                assert self.requestTimeoutEvent is not None, "got data for a request but no request timeout exists?!"
                if self._amountOfInRequests() == 1:
                    self.sched.removeEvent(self.requestTimeoutEvent)
                    self.requestTimeoutEvent = None
                else:
                    self.sched.rescheduleEvent(self.requestTimeoutEvent, timedelta=120)
                self.inRate.updatePayloadCounter(len(msg[1][2]))

    def _close(self):
        Connection._close(self)

        # store inRate and outRate
        self.connStatsCache.store(self.torrentIdent, self.remotePeerAddr, self.remotePeerId, self.inRate, self.outRate)

        # clear piece status
        self.status.clear()

        # set interest and choke states to defaults
        self.localInterest = False
        self.remoteInterest = False
        self.localChoke = True
        self.remoteChoke = True

        # remove requests
        self._delAllOutRequests()
        self._delAllInRequests()

    ##internal functions - inrequests

    def _addInRequest(self, pieceIndex, offset, length, callback=None, callbackArgs=[], callbackKw={}):
        assert self.remoteChoke == False, "requesting but choked?!"

        # add timeout
        if self.requestTimeoutEvent is None:
            self.requestTimeoutEvent = self.sched.scheduleEvent(
                self.timeout, timedelta=120, funcArgs=["request timed out"]
            )

        # add request
        messageId = self._queueSend(Messages.generateRequest(pieceIndex, offset, length))
        inRequest = (pieceIndex, offset, length)
        assert not inRequest in self.inRequestInfo, "queueing an already queued request?!"
        self.inRequestQueue.append(inRequest)
        self.inRequestInfo[inRequest] = {
            "messageId": messageId,
            "func": callback,
            "funcArgs": callbackArgs,
            "funcKw": callbackKw,
        }

    def _getInRequestsOfPiece(self, pieceIndex):
        requests = set([inRequest[1] for inRequest in self.inRequestQueue if inRequest[0] == pieceIndex])
        return requests

    def _finishedInRequest(self, pieceIndex, offset, length):
        # try to find the request and delete it if found
        inRequest = (pieceIndex, offset, length)
        self.inRequestQueue.remove(inRequest)
        del self.inRequestInfo[inRequest]

    def _cancelInRequest(self, pieceIndex, offset, length):
        # try to find the request, send cancel and then delete it
        inRequest = (pieceIndex, offset, length)
        self.inRequestQueue.remove(inRequest)
        requestInfo = self.inRequestInfo.pop(inRequest)
        if not self._abortSend(requestInfo["messageId"]):
            # the request was already send
            self._queueSend(Messages.generateCancel(pieceIndex, offset, length))

    def _delAllInRequests(self):
        for requestInfo in self.inRequestInfo.itervalues():
            # call callback of failed request
            self._abortSend(requestInfo["messageId"])
            if requestInfo["func"] is not None:
                apply(requestInfo["func"], requestInfo["funcArgs"], requestInfo["funcKw"])
        self.inRequestQueue = []
        self.inRequestInfo = {}

    def _hasThisInRequest(self, pieceIndex, offset, length):
        return (pieceIndex, offset, length) in self.inRequestInfo

    def _amountOfInRequests(self):
        return len(self.inRequestQueue)

    def _calculateMaxAmountOfInRequests(self):
        if self.remoteClient.startswith("Azureus"):
            limit = 16

        elif self.remoteClient.startswith("I2PRufus"):
            limit = 16

        elif self.remoteClient.startswith("I2PSnark"):
            limit = 32

        elif self.remoteClient.startswith("PyBit") and " " in self.remoteClient:
            version = tuple((int(digit) for digit in self.remoteClient.split(" ")[1].split(".")))
            if version < (0, 0, 9):
                limit = 32
            else:
                limit = 64

        elif self.remoteClient.startswith("Robert"):
            limit = 31

        else:
            # I2P-Bt and unknown
            limit = 16

        return limit

    def _getMaxAmountOfInRequests(self):
        return self.maxInRequests

    ##internal functions - outrequests

    def _sendOutRequest(self):
        # queue one outrequest in the outbuffer
        outRequest = self.outRequestQueue.pop(0)
        try:
            # try to get data
            data = self.outRequestHandles.pop(outRequest)()
        except StorageException:
            # failed to get data
            self.log.error("Failed to get data for outrequest:\n%s", logTraceback())
            data = None
            self._fail("could not get data for outrequest")

        if data is not None:
            # got data
            if not len(data) == outRequest[2]:
                self.log.error("Did not get enough data for outrequest: expected %i, got %i!", outRequest[2], len(data))
                self._fail("could not get data for outrequest")
            else:
                message = Messages.generatePiece(outRequest[0], outRequest[1], data)
                self.outRequestsInFlight += 1
                self._queueSend(message, self._outRequestGotSend, [outRequest[2]])

    def _outRequestGotSend(self, dataSize):
        self.outRate.updatePayloadCounter(dataSize)
        self.outRequestsInFlight -= 1
        assert self.outRequestsInFlight == 0, "multiple out requests in flight?!"
        assert len(self.outRequestQueue) == len(
            self.outRequestHandles
        ), "out of sync: queue length %i but %i handles!" % (len(self.outRequestQueue), len(self.outRequestHandles))
        if len(self.outRequestQueue) > 0 and self.outRequestsInFlight == 0:
            self._sendOutRequest()

    def _addOutRequest(self, pieceIndex, offset, length, dataHandle):
        self.outRequestQueue.append((pieceIndex, offset, length))
        self.outRequestHandles[(pieceIndex, offset, length)] = dataHandle
        if self.outRequestsInFlight == 0:
            # no outrequest is currently being send, send one directly
            self._sendOutRequest()

    def _hasThisOutRequest(self, pieceIndex, offset, length):
        return (pieceIndex, offset, length) in self.outRequestHandles

    def _getAmountOfOutRequests(self):
        return len(self.outRequestQueue)

    def _delOutRequest(self, pieceIndex, offset, length):
        # try to find the request and delete it if found
        outRequest = (pieceIndex, offset, length)
        if outRequest in self.outRequestHandles:
            self.outRequestQueue.remove(outRequest)
            del self.outRequestHandles[outRequest]

    def _delAllOutRequests(self):
        self.outRequestQueue = []
        self.outRequestHandles.clear()

    ##internal functions - choking and interest

    def _setLocalInterest(self, value):
        if value == False and self.localInterest == True:
            # changing to negative, we were interested before
            assert self._amountOfInRequests() == 0, "Local Requests are running and we are not interested?"
            # self._cancelAllInRequests()
            self._queueSend(Messages.generateNotInterested())
            self.localInterest = value
        elif value == True and self.localInterest == False:
            self._queueSend(Messages.generateInterested())
            self.localInterest = value

    def _setRemoteInterest(self, value):
        if value == False and self.remoteInterest == True:
            self.setLocalChoke(True)
            self.remoteInterest = value

        elif value == True and self.remoteInterest == False:
            self.remoteInterest = value

    def _setLocalChoke(self, value):
        if value == True and self.localChoke == False:
            # choking
            self._delAllOutRequests()
            self._queueSend(Messages.generateChoke())
            self.localChoke = value

        elif value == False and self.localChoke == True:
            self._queueSend(Messages.generateUnChoke())
            self.localChoke = value

    def _setRemoteChoke(self, value):
        if value == True and self.remoteChoke == False:
            # choked us, delete all incomming requests
            self._delAllInRequests()
            self.remoteChoke = value

        elif value == False and self.remoteChoke == True:
            self.remoteChoke = value

    ##internal functions - other

    def _getScore(self):
        ratio = self._getPayloadRatio()
        score = ratio + (ratio * self.inRate.getAveragePayloadRate())
        return score

    ##external functions - choking and interested

    def localChoked(self):
        self.lock.acquire()
        value = self.localChoke
        self.lock.release()
        return value

    def remoteChoked(self):
        self.lock.acquire()
        value = self.remoteChoke
        self.lock.release()
        return value

    def localInterested(self):
        self.lock.acquire()
        value = self.localInterest
        self.lock.release()
        return value

    def remoteInterested(self):
        self.lock.acquire()
        value = self.remoteInterest
        self.lock.release()
        return value

    def setLocalInterest(self, value):
        self.lock.acquire()
        if not self.closed:
            self._setLocalInterest(value)
        self.lock.release()

    def setRemoteInterest(self, value):
        self.lock.acquire()
        if not self.closed:
            self._setRemoteInterest(value)
        self.lock.release()

    def setLocalChoke(self, value):
        self.lock.acquire()
        if not self.closed:
            self._setLocalChoke(value)
        self.lock.release()

    def setRemoteChoke(self, value):
        self.lock.acquire()
        if not self.closed:
            self._setRemoteChoke(value)
        self.lock.release()

    ##external functions - inrequests

    def addInRequest(self, pieceIndex, offset, length, failFunc=None, failFuncArgs=[], failFuncKw={}):
        self.lock.acquire()
        assert not self.remoteChoke, "uhm, we are not allowed to make requests?!"
        if not self.closed:
            self._addInRequest(pieceIndex, offset, length, failFunc, failFuncArgs, failFuncKw)
        self.lock.release()

    def getInRequestsOfPiece(self, pieceIndex):
        self.lock.acquire()
        requests = self._getInRequestsOfPiece(pieceIndex)
        self.lock.release()
        return requests

    def finishedInRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        if not self.closed:
            self._finishedInRequest(pieceIndex, offset, length)
        self.lock.release()

    def cancelInRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        if not self.closed:
            self._cancelInRequest(pieceIndex, offset, length)
        self.lock.release()

    def hasThisInRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        value = self._hasThisInRequest(pieceIndex, offset, length)
        self.lock.release()
        return value

    def getAmountOfInRequests(self):
        self.lock.acquire()
        value = self._amountOfInRequests()
        self.lock.release()
        return value

    def getMaxAmountOfInRequests(self):
        self.lock.acquire()
        value = self._getMaxAmountOfInRequests()
        self.lock.release()
        return value

    ##internal functions - outrequests

    def addOutRequest(self, pieceIndex, offset, length, dataHandle):
        self.lock.acquire()
        if not self.closed:
            self._addOutRequest(pieceIndex, offset, length, dataHandle)
        self.lock.release()

    def hasThisOutRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        value = self._hasThisOutRequest(pieceIndex, offset, length)
        self.lock.release()
        return value

    def delOutRequest(self, pieceIndex, offset, length):
        self.lock.acquire()
        self._delOutRequest(pieceIndex, offset, length)
        self.lock.release()

    def getAmountOfOutRequests(self):
        self.lock.acquire()
        value = self._getAmountOfOutRequests()
        self.lock.release()
        return value

    ##external functions - get info

    def getStatus(self):
        self.lock.acquire()
        obj = self.status
        self.lock.release()
        return obj

    def getScore(self):
        self.lock.acquire()
        score = self._getScore()
        self.lock.release()
        return score

    def getRemotePeerId(self):
        self.lock.acquire()
        value = self.remotePeerId
        self.lock.release()
        return value

    def getTorrentIdent(self):
        self.lock.acquire()
        value = self.torrentIdent
        self.lock.release()
        return value

    ##external functions - stats

    def getStats(self):
        self.lock.acquire()
        stats = {}
        stats["id"] = self.connIdent
        stats["addr"] = self.conn.getpeername()
        stats["direction"] = self.direction
        stats["connectedInterval"] = time() - self.connectTime
        stats["totalConnectedInterval"] = self.inRate.getTotalRunTime()
        stats["peerProgress"] = self.status.getPercent()
        stats["peerClient"] = self.remoteClient
        stats["inRawBytes"] = self.inRate.getTotalTransferedBytes()
        stats["outRawBytes"] = self.outRate.getTotalTransferedBytes()
        stats["inPayloadBytes"] = self.inRate.getTotalTransferedPayloadBytes()
        stats["outPayloadBytes"] = self.outRate.getTotalTransferedPayloadBytes()
        stats["inRawSpeed"] = self.inRate.getCurrentRate()
        stats["outRawSpeed"] = self.outRate.getCurrentRate()
        stats["localInterest"] = self.localInterest
        stats["remoteInterest"] = self.remoteInterest
        stats["localChoke"] = self.localChoke
        stats["remoteChoke"] = self.remoteChoke
        stats["localRequestCount"] = len(self.inRequestQueue)
        stats["remoteRequestCount"] = self.outRequestsInFlight + len(self.outRequestQueue)
        stats["avgInRawSpeed"] = self.inRate.getAverageRate() * 1024
        stats["avgOutRawSpeed"] = self.outRate.getAverageRate() * 1024
        stats["avgInPayloadSpeed"] = self.inRate.getAveragePayloadRate() * 1024
        stats["avgOutPayloadSpeed"] = self.outRate.getAveragePayloadRate() * 1024
        stats["score"] = self._getScore()
        stats["payloadRatio"] = self._getPayloadRatio()
        stats["protocolOverhead"] = (
            100.0 * (stats["inRawBytes"] + stats["outRawBytes"] - stats["inPayloadBytes"] - stats["outPayloadBytes"])
        ) / max(stats["inPayloadBytes"] + stats["outPayloadBytes"], 1.0)
        self.lock.release()
        return stats
Пример #34
0
 def run_script(self, script_id):
     """ Runs script on this Server. """
     href = self.href + "/run_script"
     params = {'right_script': script_id}
     response, content = self.rsapi.request(href, params, method="POST")
     return Status(response.get('location'), self.rsapi)
Пример #35
0
class Game:
    __WIDTH = 64
    __HEIGHT = 24
    __NPLAYER = 6
    __normalWaitTime = 0
    __eventWaitTime = 0
    __eventTurn = False
    __nTurn = 0
    DEBUGMODE = False
    teamA = TeamA()
    teamB = TeamB()
    __score_a = 0
    __score_b = 0
    players = []
    playerOfTeamA = []
    playerOfTeamB = []
    ball = None
    ballOwner = None
    __screen = [[]]
    __statusA = Status()
    __statusB = Status()
    __orderA = Order()
    __orderB = Order()
    delay_time = 0

    # public _Game() {
    # 	this(1000, 500);
    # }
    def __init__(self, normalWaitTime, eventWaitTime):
        self.__normalWaitTime = normalWaitTime
        self.__eventWaitTime = eventWaitTime
        self.__eventTurn = False
        self.__nTurn = 0
        self.teamA = TeamA()
        self.teamB = TeamB()
        self.__score_a = 0
        self.__score_b = 0

    def run(self):
        self.__initialize(0)
        self.__printScr()
        self.__delay(self.delay_time)
        while True:
            self.__nTurn += 1
            self.clearScr()
            self.onetick()
            self.__applyOrder(self.__orderA, self.__orderB)
            self.__printScr()
            goalCheck = self.goalCheck()
            if goalCheck == 1:
                self.__eventTurn = True
                self.__initialize(2)
            elif goalCheck == 2:
                self.__eventTurn = True
                self.__initialize(1)

            if self.__endCheck() == 1:
                print("end game")
                if self.__score_a > self.__score_b: return 1
                elif self.__score_b > self.__score_a: return 2
                else: return 0
            if self.__eventTurn:
                self.__delay(self.delay_time * 5)
                self.__eventTurn = False
            else:
                self.__delay(self.delay_time)

    def __initialize(self, starter):
        self.__screen = [[None for _ in range(self.__HEIGHT)]
                         for _ in range(self.__WIDTH)]
        self.playerOfTeamA = [0] * 6
        self.playerOfTeamA[0] = Player(0, ((self.__WIDTH - 1) / 2) - 25,
                                       self.__HEIGHT / 2 - 4, 30, 30, 40)
        self.playerOfTeamA[1] = Player(1, ((self.__WIDTH - 1) / 2) - 24,
                                       self.__HEIGHT / 2 - 2, 25, 40, 50)
        self.playerOfTeamA[2] = Player(2, ((self.__WIDTH - 1) / 2) - 23,
                                       self.__HEIGHT / 2, 20, 50, 35)
        self.playerOfTeamA[3] = Player(3, ((self.__WIDTH - 1) / 2) - 24,
                                       self.__HEIGHT / 2 + 2, 25, 40, 50)
        self.playerOfTeamA[4] = Player(4, ((self.__WIDTH - 1) / 2) - 25,
                                       self.__HEIGHT / 2 + 4, 30, 30, 40)
        self.playerOfTeamA[5] = Player(5, ((self.__WIDTH - 1) / 2) - 28,
                                       self.__HEIGHT / 2, 50, 50, 55)
        self.playerOfTeamB = [0] * 6
        self.playerOfTeamB[0] = Player(6, ((self.__WIDTH - 1) / 2) + 26,
                                       self.__HEIGHT / 2 - 4, 30, 30, 40)
        self.playerOfTeamB[1] = Player(7, ((self.__WIDTH - 1) / 2) + 25,
                                       self.__HEIGHT / 2 - 2, 25, 40, 50)
        self.playerOfTeamB[2] = Player(8, ((self.__WIDTH - 1) / 2) + 24,
                                       self.__HEIGHT / 2, 20, 50, 35)
        self.playerOfTeamB[3] = Player(9, ((self.__WIDTH - 1) / 2) + 25,
                                       self.__HEIGHT / 2 + 2, 25, 40, 50)
        self.playerOfTeamB[4] = Player(10, ((self.__WIDTH - 1) / 2) + 26,
                                       self.__HEIGHT / 2 + 4, 30, 30, 40)
        self.playerOfTeamB[5] = Player(11, ((self.__WIDTH - 1) / 2) + 29,
                                       self.__HEIGHT / 2, 50, 50, 55)
        self.players = [0] * 12

        for i in range(len(self.players)):
            if i < 6: self.players[i] = self.playerOfTeamA[i]
            else: self.players[i] = self.playerOfTeamB[i - 6]

        if starter == 0:
            self.__score_a = 0
            self.__score_b = 0
            self.__nTurn = 0
            if self.__throwCoinWithProbability(50):
                self.ball = Ball(self.playerOfTeamA[2].x,
                                 self.playerOfTeamA[2].y)
                self.ballOwner = self.playerOfTeamA[2]
                self.playerOfTeamA[2].getBall(self.ball)
            else:
                self.ball = Ball(self.playerOfTeamB[2].x,
                                 self.playerOfTeamB[2].y)
                self.ballOwner = self.playerOfTeamB[2]
                self.playerOfTeamB[2].getBall(self.ball)
        elif starter == 1:
            self.ball = Ball(self.playerOfTeamA[2].x, self.playerOfTeamA[2].y)
            self.ballOwner = self.playerOfTeamA[2]
            self.playerOfTeamA[2].getBall(self.ball)
        elif starter == 2:
            self.ball = Ball(self.playerOfTeamB[2].x, self.playerOfTeamB[2].y)
            self.ballOwner = self.playerOfTeamB[2]
            self.playerOfTeamB[2].getBall(self.ball)

        for p in self.players:
            self.__screen[int(p.x)][int(p.y)] = p

    def onetick(self):
        ballOwner = -1 if self.ballOwner == None else self.ballOwner.getId()
        self.__statusA.setStatus(self.__generateUnitInfo(False), ballOwner,
                                 self.__nTurn)
        self.teamA.execute(self.__statusA, self.__orderA)
        ballOwnerForB = 0
        if ballOwner == -1: ballOwnerForB = -1
        elif ballOwner < 6: ballOwnerForB = ballOwner + 6
        else: ballOwnerForB = ballOwner - 6
        self.__statusB.setStatus(self.__generateUnitInfo(False), ballOwnerForB,
                                 self.__nTurn)
        self.teamB.execute(self.__statusB, self.__orderB)

    def __generateUnitInfo(self, mirror):
        result = [0] * 13
        if mirror:
            result[0] = Unit(self.ball, True)
            for i in range(1, 13):
                if i <= 6: result[i] = Unit(self.playerOfTeamB[i - 1], True)
                else: result[i] = Unit(self.playerOfTeamA[i - 7], True)
        else:
            result[0] = Unit(self.ball)
            for i in range(1, 13):
                if i <= 6: result[i] = Unit(self.playerOfTeamA[i - 1])
                else: result[i] = Unit(self.playerOfTeamB[i - 7])
        return result

    def __applyOrder(self, oa, obr):
        ob = Order(obr, True)
        for p in self.playerOfTeamA:
            p.move(oa.dx[p.getNumber()], oa.dy[p.getNumber()])
            self.__screen[int(p.x)][int(p.y)] = p
        for p in self.playerOfTeamB:
            p.move(ob.dx[p.getNumber()], ob.dy[p.getNumber()])
            self.__screen[int(p.x)][int(p.y)] = p
        self.__contendCheck()
        self.__passCheck()
        self.__ballCheck()

    def __contendCheck(self):
        for i in range(self.__NPLAYER * 2):
            contendingPlayers = []
            for j in range(i + 1, self.__NPLAYER * 2):
                if self.players[i].isSamePositionWith(self.players[j]):
                    contendingPlayers.append(self.players[j])
            if len(contendingPlayers) >= 1:
                contendingPlayers.append(self.players[i])
                self.__contend(contendingPlayers)

    def __contend(self, players):
        rlength = 0
        winner = -1
        for p in players:
            rlength += p.getStrength()
        if rlength == 0:
            winner = self.getRandom(0, len(players) - 1)
        else:
            r = self.getRandom(0, rlength - 1)
            rm = rM = 0
            for i in range(len(players)):
                rM += players[i].getStrength()
                if r >= rm and r < rM:
                    winner = i
                    break
                rm = rM
        wx = int(players[winner].x)
        wy = int(players[winner].y)
        for i in range(len(players)):
            if i == winner:
                players[i].winContending()
                self.__screen[wx][wy] = self.players[i]
            else:
                if players[i].isBallOwner():
                    ix = wx + self.getRandom(-3, 3)
                    iy = wy + self.getRandom(-3, 3)
                    #screen!=none이여야 하나? ^^^^^^^^^^^^^^^^^^^^
                    while (ix < 0 or ix >= self.__WIDTH or iy < 0
                           or iy >= self.__HEIGHT
                           ) or self.__screen[int(ix)][int(iy)] != None:
                        print("a")
                        ix = wx + self.getRandom(-3, 3)
                        iy = wy + self.getRandom(-3, 3)
                    self.ball.fly2(ix, iy)
                    self.ballOwner = None

                ix = int(wx + self.getRandom(-3, 3))
                iy = int(wy + self.getRandom(-3, 3))
                count = 0
                while (ix < 0 or ix >= self.__WIDTH or iy < 0
                       or iy >= self.__HEIGHT) or (
                           self.__screen[int(ix)][int(iy)] != None):
                    count += 1
                    ix = int(wx + self.getRandom(-3, 3))
                    iy = int(wy + self.getRandom(-3, 3))
                self.__screen[int(ix)][int(iy)] = players[i]

    def __passCheck(self):
        if self.ballOwner != None:
            passtarget = None
            if (
                    self.ballOwner.getId() >= 0 and self.ballOwner.getId() < 6
            ) and self.__orderA.passto >= 0 and self.ballOwner != self.playerOfTeamA[
                    self.__orderA.passto]:
                passtarget = self.playerOfTeamA[self.__orderA.passto]
            elif (
                    self.ballOwner.getId() >= 6 and self.ballOwner.getId() < 12
            ) and self.__orderB.passto >= 0 and self.ballOwner != self.playerOfTeamB[
                    self.__orderB.passto]:
                passtarget = self.playerOfTeamB[self.__orderB.passto]
            else:
                return
            m = n = 0
            if self.ballOwner.getX() == passtarget.getX():
                yV = int((passtarget.getY() - self.ballOwner.getY()) /
                         abs(passtarget.getY() - self.ballOwner.getY()))
                for i in range(self.ballOwner.getY(),
                               passtarget.getY() - yV, yV):
                    if self.__screen[int(
                            self.ballOwner.getX())][int(i)] != None:
                        print("intercepted")
                        self.ballOwner.throwBall()
                        interceptPlayer = self.__screen[int(
                            self.ballOwner.getX())][int(i)]
                        interceptPlayer.getBall(self.ball)
                        self.ballOwner = interceptPlayer
                        return
            else:
                m = (self.ballOwner.getY() - passtarget.getY()) / (
                    self.ballOwner.getX() - passtarget.getX())
                n = self.ballOwner.getY() - m * self.ballOwner.getX()
                xV = int((passtarget.getX() - self.ballOwner.getX()) /
                         abs(passtarget.getX() - self.ballOwner.getX()))
                i = int(self.ballOwner.getX() + xV)
                while i != passtarget.getX():
                    i += xV
                    fi = int(m * i + n + 0.4)
                    if self.__screen[int(i)][int(fi)] != None:
                        print("intercepted")
                        self.ballOwner.throwBall()
                        interceptPlayer = self.__screen[int(i)][int(fi)]
                        interceptPlayer.getBall(self.ball)
                        self.ballOwner = interceptPlayer
                        return
            d = int(self.ballOwner.getDistance(passtarget))
            if d > 5:
                r = self.getRandom(0, self.ballOwner.getPass() + d * 5 - 1)
                if r < self.ballOwner.getPass():
                    self.ballOwner.throwBall()
                    passtarget.getBall(self.ball)
                    self.ballOwner = passtarget
                #공이 날라갔을 경우
                else:
                    self.ballOwner.throwBall()
                    ix = passtarget.getX() + self.getRandom(-2, 2)
                    iy = passtarget.getY() + self.getRandom(-2, 2)
                    while (ix < 0 or ix > self.__WIDTH or iy < 0 or
                           iy >= self.__HEIGHT) or (ix == passtarget.getX() and
                                                    iy == passtarget.getY()):
                        ix = passtarget.getX() + self.getRandom(-2, 2)
                        iy = passtarget.getY() + self.getRandom(-2, 2)
                    self.ball.fly2(ix, iy)
                    self.ballOwner = None
            #pass 성공된 경우
            else:
                self.ballOwner.throwBall()
                passtarget.getBall(self.ball)
                self.ballOwner = passtarget

    def __ballCheck(self):
        if self.ballOwner != None:
            self.ball.dribbled(self.ballOwner)
        else:
            if self.__screen[self.ball.getX()][self.ball.getY()] != None:
                self.ballOwner = self.__screen[self.ball.getX()][
                    self.ball.getY()]
                self.ballOwner.getBall(self.ball)

    def getRandom(self, m, n):
        return int(random.randint(m, n))

    def __throwCoinWithProbability(self, probability):
        if probability < 0 or probability > 100:
            print("probability error")
            return False
        r = int(random.random() * 100)
        if r < probability: return True
        else: return False

    def __printScr(self):
        # if self.ballOwner==None: self.__screen[self.ball.x][self.ball.y]=self.ball
        print(f'Score: {self.__score_a} : {self.__score_b} ')
        print(f' Turn: {self.__nTurn}')

        print(
            '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'
        )
        for i in range(self.__HEIGHT):
            print_list = list()
            if i < self.__HEIGHT / 2 - 5 or i >= self.__HEIGHT / 2 + 5:
                print('%', end='')
            else:
                print(" ", end='')
            for j in range(self.__WIDTH):
                if self.__screen[j][i] == None: print_list.append(" ")
                else:
                    if self.__screen[j][i].getId(
                    ) >= 0 and self.__screen[j][i].getId() < 6:
                        print_list.append(
                            chr(ord('a') + self.__screen[j][i].getNumber()))
                    elif self.__screen[j][i].getId(
                    ) >= 6 and self.__screen[j][i].getId() < 12:
                        print_list.append(
                            str(1 + self.__screen[j][i].getNumber()))
            print("".join(print_list), end='')
            if i < self.__HEIGHT / 2 - 5 or i >= self.__HEIGHT / 2 + 5:
                print('%')
            else:
                print(" ")
        print(
            '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'
        )
        os.system('cls')

    def clearScr(self):
        # System.out.println("\033[H\033[2J");
        # System.out.flush();
        self.__screen = [[None for _ in range(self.__HEIGHT)]
                         for _ in range(self.__WIDTH)]
        sys.stdout.flush()

    def goalCheck(self):
        if self.ballOwner != None:
            if self.ballOwner.getId() >= 0 and self.ballOwner.getId() < 6:
                if self.ballOwner.getX(
                ) == self.__WIDTH - 1 and self.ballOwner.getY(
                ) >= self.__HEIGHT / 2 - 5 and self.ballOwner.getY(
                ) < self.__HEIGHT / 2 + 5:
                    self.__score_a += 1
                    return 1
            elif self.ballOwner.getId() >= 6 and self.ballOwner.getId() < 12:
                if self.ballOwner.getX() == 0 and (
                        self.ballOwner.getY() >= self.__HEIGHT / 2 - 5
                        and self.ballOwner.getY() < self.__HEIGHT / 2 + 5):
                    self.__score_b += 1
                    return 2
        return -1

    def __endCheck(self):
        if self.__nTurn < 1000: return 0
        elif self.__nTurn == 1000: return 1

    def __delay(self, n):
        try:
            time.sleep(n)
        except:
            traceback.print_exc()
Пример #36
0
def run_detector():
    # import os
    # os.environ['SDL_VIDEODRIVER'] = 'windib'
    # os.environ['SDL_VIDEODRIVER'] = 'directx'


    parser = OptionParser(usage="""\
    Detect SnapMyinfo QRcodes in a live video stream

    Usage: %prog [options] camera_index
    """)

    parser.add_option('-f','--fs','--fullscreen',
                      dest="fullscreen", default=False,
                      action='store_true',
                      help="""Run the Live Decoder full screen.""")

    parser.add_option('--hw','--hw_accel',
                    dest="hw_accel", default=False,
                    action='store_true',
                    help="""Runs pygame with the directx hw driver (if avail). Automatically assumes fullscreen.""")

    parser.add_option('-s','--scale',
                    dest="scale", default=4.0,
                    action='store', type="float",
                    help="""Sets the precision of code tracking. Valid values are >1.0 and less than 8.0. Lower values represent more accurate tracking, but consume more CPU.""")

    parser.add_option('--flip',
                    dest="flip", default=False,
                    action='store_true',
                    help="""Flip the video image horizontally before processing.""")

    parser.add_option('-m','--max_cards',
                    dest="tracker_count", default=3, type="int",
                    action="store",
                    help="""The number of simultaneous snap codes that can be tracked in the video stream.""")


    parser.add_option('--nv','--no_video',
                    dest="no_video", default=False, 
                    action="store_true",
                    help="""A debugging option, turns off the video stream from the web cam.""")

    parser.add_option('-d','--debug',
                    dest="debug", default=False, 
                    action="store_true",
                    help="""Debugging option, turns on fps display and additional tracking data on the display.""")


    opts, args = parser.parse_args()

    import os
    os.environ['SDL_VIDEODRIVER'] = 'windib'
    if opts.hw_accel:
        os.environ['SDL_VIDEODRIVER'] = 'directx'
        opts.fullscreen = True

    # initialize pygame
    pygame.init()

    display_size = (800,600)
    video_size = (1280,720)
    
    # scale is roughly equivalent to tracking precision
    # the higher the scale, the less precise, but faster, the gross
    # tracking will be scale of 1 means 1:1 tracking, but can be slow
    # recommend 2-4 as a good scale/precision factor. higher res images
    # usually benefit from higher scale
    scale = opts.scale
    
    
    # this can be used to throttle the max framerate processed. 0 means no throttle
    max_frame_rate = 30
    
    names =  [args[0]]
    name = names[0]

    if not opts.no_video:
        # connect to web camera and set the webcam options
        capture = cvCreateCameraCapture( int(name) )
        cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, video_size[0] )
        cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, video_size[1] )
    
        # query the camera once to get the camera properties
        # the frame is just a throwaway
        cvQueryFrame( capture )

        # get the camera properties
        (o_width,o_height) = [cvGetCaptureProperty(capture, prop) for prop in [CV_CAP_PROP_FRAME_WIDTH,CV_CAP_PROP_FRAME_HEIGHT]]
        video_size = (int(o_width),int(o_height))
    else:
        blank = cvCreateImage(video_size,8,3)
        cvZero(blank)

    # create the pygame display
    flags = 0
    if opts.fullscreen:
        flags = pygame.FULLSCREEN
    if opts.hw_accel:
        flags = flags|pygame.HWSURFACE|pygame.DOUBLEBUF

    display_layer = pygame.display.set_mode( display_size,  flags ) 

    video = pygame.Surface(video_size).convert()

    # set the window name
    pygame.display.set_caption('Live Detector') 

    # some debug information
    # print the current driver being used
    print 'Driver %s\nVideo Input Resolution: %s\nDisplay Resolution: %s\n' % (pygame.display.get_driver(), video_size, display_size)

    # for convert to work, pygame video mode has to be set
    image_buffer = ImageBuffer(video_size,display_size,scale)
    if opts.no_video:
        image_buffer.frame_buffer = cvCreateImage(video_size,8,3)
        # blank = cvCreateImage(video_size,8,3)
        # cvZero(blank)
    worker = GrossTracker(image_buffer) 
    
    # pool of tracker objects
    pool = TrackerPool(image_buffer, opts.tracker_count)
    thread_objects.append(pool)


    status = Status()
    
    connector = Connector(pool,status)
    connector.start()
    thread_objects.append(connector)
    
    # for i in range(4):
    #     win_name = "thread-%d" % i
    #     cvNamedWindow(win_name, CV_WINDOW_AUTOSIZE)
    
    pyg_clock = pygame.time.Clock()
    update_count = 0
    last_rects = []
    last_fills = []
    hud_last_fills = []

    if opts.debug:
        dbg = DebugDisplay()

    snap_logo = pygame.image.load('./images/snap_logo.png').convert_alpha()
    
    still = False
    running = True
    fps = 0.0
    while running:
        pyg_clock.tick(max_frame_rate)
        if update_count > 20:
            fps = pyg_clock.get_fps()
            update_count = 0
        update_count += 1

        # get the pygame events
        events = pygame.event.get()
        for e in events:
            # 'quit' event key
            if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
                running = False
            elif e.type == KEYDOWN and e.unicode == u't':
                still = True
            
            
        # take a frame from the web camera
        if opts.no_video:
            cvCopy(blank,image_buffer.frame_buffer)
        else:
            image_buffer.frame_buffer = cvQueryFrame( capture )

        if opts.flip:
            cvFlip(image_buffer.frame_buffer,image_buffer.frame_buffer,1)
            
        # update the image buffer with the latest frame
        image_buffer.update()

        # analyze the small frame to find collapsed candidates
        squares = worker.analyze_frame()        

        # check squares and assign a tracker if new
        pool.check(squares)
        # update all trackers
        pool.update()

        status.update()
        
        # clear the paint buffer
        for rect in last_rects:
            pygame.gfxdraw.rectangle(image_buffer.paint_buffer, rect, Color(0,0,0))
        last_rects = []
        
        for blank in last_fills:
            image_buffer.paint_buffer.fill((0,0,0),blank)
        last_fills = []


        for blank in hud_last_fills:
            image_buffer.hud_buffer.fill((0,0,0,0),blank)
        hud_last_fills = []



        # draw the sprite and tracker boundaries
        # boundaries will be replaced (or turned off)
        pool.sort_active()
        for t_id in pool.active_trackers:
            #rect = pool.trackers[t_id].get_bound_rect()
            center = pool.trackers[t_id].get_avg_center(2)

            frame_color = Color(128,255,128)
            if pool.trackers[t_id].sprite:
                # print str(dir(pool.trackers[t_id].sprite))
                sprite_size = pool.trackers[t_id].sprite.get_size()
                # print str(sprite_size)
                x_diff = sprite_size[0] / 2.0
                y_diff = sprite_size[1] / 2.0
                
                # frame_color = Color(250,250,255)
                
                rect = pygame.Rect(center.x * image_buffer.display_scale[0] - x_diff, center.y * image_buffer.display_scale[1] - y_diff, sprite_size[0],sprite_size[1])
                # pygame.gfxdraw.rectangle(image_buffer.paint_buffer, rect, pool.trackers[t_id].color)
                # last_rects.append(rect)
                #if pool.trackers[t_id].user_id:
                image_buffer.paint_buffer.blit(pool.trackers[t_id].sprite,(rect.x ,rect.y ))
                last_fills.append(rect) #pygame.Rect(rect.x ,rect.y ,closer_img.size[0],closer_img.size[1]))
            else:
                # rect = pygame.Rect(center.x * scale - 100, center.y * scale - 100, 200,200)
                # 
                # 
                # pygame.gfxdraw.rectangle(image_buffer.paint_buffer, rect, frame_color)
                # last_rects.append(rect)

                #c = pygame.Color(164,229,135,150)
                #c1 = pygame.Color(164,229,135,255)
                c = pygame.Color(229,229,135,200)
                # c1 = pygame.Color(229,229,135,255)

                pygame.gfxdraw.filled_polygon(image_buffer.hud_buffer, pool.trackers[t_id].get_bounding_points(),c)
                # pygame.gfxdraw.polygon(image_buffer.hud_buffer, pool.trackers[t_id].get_bounding_points(),c1)
                # pygame.gfxdraw.rectangle(image_buffer.hud_buffer, rect, frame_color)
                # pygame.gfxdraw.filled_polygon(image_buffer.hud_buffer, pool.trackers[t_id].get_bounding_points(),c)
                hud_last_fills.append(pool.trackers[t_id].get_bound_rect())
                


        # draw the orphans and frame rate display
        # debug for now, lets me know when it's trying to lock onto something
        if opts.debug:
            fps_sprite = dbg.gen_sprite('''%.2f fps''' % fps)
            image_buffer.hud_buffer.blit(fps_sprite,(image_buffer.display_size[0]-100,10))
            fps_rect = pygame.Rect(video_size[0]-100,10, dbg.size[0], dbg.size[1])
            hud_last_fills.append(fps_rect)
            
            for orphans in pool.orphan_frames:
                for orphan in orphans:
                    orphan = pygame.Rect(orphan.x * image_buffer.display_scale[0], orphan.y * image_buffer.display_scale[1], orphan.width * image_buffer.display_scale[0], orphan.height * image_buffer.display_scale[1])
                    pygame.gfxdraw.rectangle(image_buffer.paint_buffer, orphan, Color(190,255,190))
                    last_rects.append(orphan)

        # no data in the frame buffer means we're done
        if not image_buffer.frame_buffer:
            break

        # Surf_dat array is not oriented the same way as the pyame display so
        # first it's transposed. Then the
        # the surface RGB values are not the same as the cameras
        # this means that two of the channels have to be swapped in the numpy
        # array before being blit'ted onto the array
        surf_dat = image_buffer.frame_buffer.as_numpy_array().transpose(1,0,2)[...,...,::-1]
        
        # blit_array zaps anything on the surface and completely replaces it with the array, much
        # faster than converting the bufer to a surface and bliting it
        # replaces video with the data in surf_dat
        surfarray.blit_array(video,surf_dat)
        
        # this resizes the video surface and stores it in display_layer. Completely
        # overwrites whatever is in display_layer
        pygame.transform.scale(video, image_buffer.display_size, display_layer)
        
        # blit the paint buffer onto the surface. Paint buffer has a chromakey so all black values will show through
        display_layer.blit(image_buffer.paint_buffer,(0,0))

        # the "HUD" is added next. 
        display_layer.blit(image_buffer.hud_buffer,(0,0))

        # Write out the status sprite to the display_layer
        if status.sprite:
            display_layer.blit(status.sprite,(10,image_buffer.display_size[1] - status.height - 10 ))


        # finally watermark the screen with the company logo and name of the product
        # putting it here means it always shows above the other layers
        logo_size = snap_logo.get_size()
        display_layer.blit(snap_logo,(image_buffer.display_size[0]-logo_size[0]-10 , image_buffer.display_size[1]-logo_size[1]-10))


        if still == True:
            pygame.image.save(display_layer, 'test.jpg')
            still = False

        # flip() actually displays the surface
        pygame.display.flip()

    # we've left the loop
    # exit
    print 'exiting...'
Пример #37
0
    def __init__(self,
                 data,
                 chunk_size,
                 hosts,
                 niceness,
                 slave_script,
                 show_output=0,
                 result=None,
                 redistribute=1,
                 verbose=1):
        """
        @param data: dict of items to be proessed {id:object}.
        @type  data: dict
        @param chunk_size: number of items that are processed by a job
        @type  chunk_size: int
        @param hosts: list of host-names
        @type  hosts: [str]
        @param niceness: nice dictionary [host-name: niceness]
        @type  niceness: dict
        @param slave_script: absolute path to slave-script
        @type  slave_script: str
        @param result: items which have already been processed
                       (ie. they are contained in result) are not
                       processed again.
        @type  result: dict
        @param redistribute: at the end, send same job out several times
                             (default: 1)
        @type  redistribute: 1|0
        @param verbose: verbosity level (default: 1)
        @type  verbose: 1|0
        """
        PVMMasterSlave.__init__(self, verbose=verbose)

        ## change names of multiple hosts
        d = {}

        for host in hosts:
            if host in d:
                d[host] += 1
            else:
                d[host] = 1

        unique_list = []

        for host, number in d.items():
            if number > 1:

                for i in range(number):
                    nickname = host + '_%d' % i

                    d = {'host': host, 'nickname': nickname}

                    unique_list.append(d)
            else:
                d = {'host': host, 'nickname': host}

                unique_list.append(d)

        exe = ExeConfigCache.get('xterm')
        exe.validate()
        self.xterm_bin = exe.bin

        self.hosts = unique_list
        self.niceness = niceness
        self.data = data
        self.slave_script = slave_script
        self.chunk_size = chunk_size

        self.current_pos = 0
        self.show_output = show_output

        self.verbose = verbose

        if result is None:
            result = {}

        self.result = result

        ## set-up status for results
        items = []

        for key in data.keys():
            if not key in self.result:
                items.append(key)

        self.status = Status(items, redistribute=redistribute)

        self.__finished = 0

        if verbose: print 'Processing %d items ...' % len(items)
Пример #38
0
 def __init__(self, position=None):
     self.status = Status()
     self.position = position
Пример #39
0
def getSeries(filename, weighted):
    '''network_name = "networks_low_couple/" + filename.split('/')[-1]

	# commented code block 	
		fp=open(network_name,'r')
		line=fp.readline()
		line=line.rstrip()
		n_layer=int(line)
		layer={}
		node_l={}
		l_ID=1
		edge_l={}
		edge_c={}
		# f_el = open(filename+'_edges_list_commod'+str(g), 'w')
		for i in range(0,n_layer):
			line=fp.readline()
			line=line.rstrip()
			line=line.split()
			layer[l_ID]=set()
			##print line
			for n in line:
				layer[l_ID].add(int(n))
			line=fp.readline()
			line=int(line.rstrip())
			n_edge=line
			##print n_edge
			edge_l[l_ID]=n_edge
			for j in range(0,n_edge):
				line=fp.readline()
				line=line.rstrip()
				line=line.split()
				n1=int(line[0])
				n2=int(line[1]) 
				if n1 not in node_l:
					node_l[n1]=set()
				node_l[n1].add(n2)	  
				if n2 not in node_l:
					node_l[n2]=set()
				node_l[n2].add(n1)
				# f_el.write(str(n1-1)+' '+str(n2-1)+'\n')

			l_ID+=1
			
		line=fp.readline()
		line=line.rstrip()
		n_couple=int(line)
		##print n_couple
		node_c={}	   
		top={}
		bot={}
		c_ID=1
		couple={}

		for i in range(0,n_couple):
			line=fp.readline()
			##print line
			line=line.rstrip()
			line=line.split()
			top[c_ID]=int(line[0])
			bot[c_ID]=int(line[1])
			
			couple[c_ID]=layer[top[c_ID]].union(layer[bot[c_ID]])
			
			line=fp.readline()
			line=int(line.rstrip())
			n_edge=line
			##print n_edge
			edge_c[c_ID]=n_edge
			count_edge = 0
			for j in range(0,n_edge):
				line=fp.readline()
				line=line.rstrip()
				line=line.split()
				n1=int(line[0])
				n2=int(line[1])
				if n1 not in node_c:
					node_c[n1]=set()
				node_c[n1].add(n2)
				if n2 not in node_c:
					node_c[n2]=set()
				node_c[n2].add(n1)  
				count_edge += 1
				# f_el.write(str(n1-1)+' '+str(n2-1)+'\n')
			edge_c[c_ID] = count_edge
			c_ID=c_ID+1

		line=fp.readline()
		line=line.rstrip()
		##print line
		n_comm=int(line)
		commu={}
		com_ID=1
		for i in range(0,n_comm):
			line=fp.readline()
			line=line.rstrip()
			line=line.split()
			commu[com_ID]=set()
			for n in line:
				commu[com_ID].add(int(n))
			com_ID+=1	   
		mu=0'''

    #with open(filename+'_ml_network.pickle') as handle:
    #	fnetwork = pickle.load(handle)
    ml_network, layer, node_l, node_c, top, bot, couple, edge_l, edge_c, mu, commu = read_raw_network(
        filename, weighted)

    #ml_network =build_network(layer, node_l, node_c, top, bot, couple, edge_l, edge_c)
    #with open(filename+'_ml_network.pickle', 'w') as handle:
    #	 pickle.dump([ml_network, layer, node_l, node_c, top, bot, couple, edge_l, edge_c, mu, commu], handle)
    dendogram, mod = louvain(ml_network, layer, node_l, node_c, top, bot,
                             couple, edge_l, edge_c, mu)

    status = Status()
    status.layer = layer
    status.node_l = node_l
    status.node_c = node_c
    status.top = top
    status.bot = bot
    status.edge_l = edge_l
    status.edge_c = edge_c
    status.couple = couple
    status.mu = mu
    mod_old = mod
    commu = _get_com_wise_nodes(
        partition_at_level(dendogram,
                           len(dendogram) - 1))
    #commu =_get_commu_dict(partition_at_level(dendogram, len(dendogram)-1))
    mod = __modularity(commu, status, ml_network)
    #print "--------- BEF RET ---------"
    #print mod_old, mod
    #print "----------------"

    return mod, dendogram