예제 #1
0
 def test_sam_error(self):
     status = Status(self._mock_sam_api(False), {"fence": self._mock_fence_api(True)})
     self.assertItemsEqual(status.get(), [
         {"ok": True, "message": "", "subsystem": Subsystems.memcache},
         {"ok": True, "message": "", "subsystem": Subsystems.datastore},
         {"ok": True, "message": "", "subsystem": "fence"},
         {"ok": False, "message": "sam down", "subsystem": Subsystems.sam},
     ])
예제 #2
0
 def test_datastore_error(self):
     status = Status(self._mock_sam_api(True), {"fence": self._mock_fence_api(True)})
     status._datastore_status = MagicMock(return_value=(False, "datastore down"))
     self.assertItemsEqual(status.get(), [
         {"ok": True, "message": "", "subsystem": Subsystems.memcache},
         {"ok": False, "message": "datastore down", "subsystem": Subsystems.datastore},
         {"ok": True, "message": "", "subsystem": "fence"},
         {"ok": True, "message": "", "subsystem": Subsystems.sam},
     ])
예제 #3
0
def search_tweets(trend):
    try:
        search_results = twitter.search(q=trend.query,  lang='es', count='100')
    except TwythonError as e:
        print e
    aux = 0
    for status in search_results.get(u'statuses', []):
        s = Status(status, trend)
        print s.text
        s.save()
예제 #4
0
파일: go.py 프로젝트: ndexbio/ndex-nav
def join_go_terms_with_genes():
    client = pymongo.MongoClient()
    terms = client.go.terms.find()
    status = Status('joining terms with genes').n(terms.count())
    for k, term in enumerate(terms):
        status.log(k)
        genes = client.go.genes.find({'go': term['go']})
        term['genes'] = list(set(g['gene'] for g in genes))
        term['n_genes'] = len(term['genes'])
        client.go.terms.save(term)
    status.stop()
예제 #5
0
 def advance_to_next_game(self):
   # We only need to check the preferred team's game status if we're
   # rotating during mid-innings
   if self.config.rotation_preferred_team_live_mid_inning and not self.is_offday_for_preferred_team():
     preferred_overview = self.fetch_preferred_team_overview()
     if Status.is_live(preferred_overview.status) and not Status.is_inning_break(preferred_overview.inning_state):
       self.current_game_index = self.game_index_for_preferred_team()
       self.overview = preferred_overview
       self.needs_refresh = False
       self.__update_layout_state()
       self.print_overview_debug()
       return self.current_game()
   self.current_game_index = self.__next_game_index()
   return self.current_game()
예제 #6
0
파일: cron.py 프로젝트: hirotoshi/twittmap
  def get(self):

    debug = self.request.get('debug',False)
    self.response.out.write('<ul>')

    #自分宛のreplyを取得
    twitter = TwitterClient()
    replies = twitter.getReplies()
    replies.reverse()
    for reply in replies:
      text = reply['text']
      texts = reply['text'].split()
      #全角スペースに対応
      if len(texts) < 2:
        texts = reply['text'].split(u' ')
      if len(texts) < 2:
        self.response.out.write('<li>[%s] is irregure</li>'%(text)) 
        continue
      keyword = texts[1]
      user    = reply['user']
      #自分のreplyは無視
      if user['screen_name'] == self.username :
        self.response.out.write('<li>[%s] is my status</li>'%(text))
        continue

      #既に処理済みのreplyも無視
      if not Status.isNewStatus( reply['id'] ) :
        self.response.out.write('<li>[%s] is old status</li>'%(text)) 
        continue

      #位置を取得
      finder = LocationFinder()
      loc = finder.find( keyword )
      if not loc:
        #見つからなかった
        mes = self.fail_message%( reply['user']['screen_name'] ,keyword)
      else:
        #見つかった
        mes = self.success_message[loc['type']]%( reply['user']['screen_name'] , loc['title'] , 'L:' + str(loc['lat']) + "," + str(loc['lon']) + ' ' + loc['url'] )

      #返信した内容を保存
      Status.saveStatus( reply,loc,mes )
      #twitterのstatusを更新
      if not debug:
        twitter.sendReply( mes , reply['id'])
      self.response.out.write('<li>[%s]:[%s]</li>'%(keyword,mes) )

    self.response.out.write('</ul>')
예제 #7
0
 def get_status_dict(self):
   # It will returns a serialized status in mem_cache
   serialized_status = memcache.get_multi(self.status_ids,
                                               key_prefix='status')
   # Just copying my status_ids list to make some changes localy
   missing_status_ids = list(self.status_ids)
   game_status = {}
   for status_id, status in serialized_status.iteritems():
     game_status[status_id] = deserialize(status)
     missing_status_ids.remove(status_id)
   
   # Taking the missing status in database and add them in memcache
   if missing_status_ids:
     missing_status = Status.get(missing_status_ids)
     serialized_status = {}
     for status in missing_status:
       game_status[status_id] = deserialize(status)
       serialized_status[status.id] = serialize(status)
       
     memcache.set_multi(serialized_status, key_prefix='status')
   
   # I really dunno why, but the game_status list in this function
   # works like a list of string, and when this function pass to some
   # function or when it returns, game_status assume its really identity
   # that is a list of status, not a list of strings... (crazy, I know)
   self.actualise_status(game_status)
   
   return game_status # Returns a random list of Status playing this game
예제 #8
0
파일: main.py 프로젝트: DataBiosphere/bond
class BondStatusApi(remote.Service):
    def __init__(self):
        sam_base_url = config.get('sam', 'BASE_URL')

        providers = {provider_name: FenceApi(config.get(provider_name, 'FENCE_BASE_URL'))
                     for provider_name in config.sections() if provider_name != 'sam'}

        sam_api = SamApi(sam_base_url)
        self.status_service = Status(sam_api, providers)

    @endpoints.method(
        message_types.VoidMessage,
        StatusResponse,
        path='/status',
        http_method='GET',
        name='status')
    def status(self, request):
        subsystems = self.status_service.get()
        ok = all(subsystem["ok"] for subsystem in subsystems)
        response = StatusResponse(ok=ok,
                                  subsystems=[SubSystemStatusResponse(ok=subsystem["ok"],
                                                                      message=subsystem["message"],
                                                                      subsystem=subsystem["subsystem"])
                                              for subsystem in subsystems])
        if ok:
            return response
        else:
            raise endpoints.InternalServerErrorException(response)
예제 #9
0
파일: net.py 프로젝트: eicesoft/pycached
    def __init__(self, config):
        self.config = config                                                    # 应用程序配置
        self.connections = 0                                                    # 连接客户端列表

        if self.config['savetime'] != 0:    # 不保存数据
            self.thread = PeriodicCallback(self.save_db,
                                       int(self.config['savetime']) * 1000)
            self.thread.start()                                                 # 背景保存服务线程启动

        self.workpool = ThreadPool(int(config['work_pool']))                    # 工作线程池

        self.status = Status(CacheServer.status_fields)                         # 服务器状态
        self.slave_clients = {}                                                 # 同步客户端
        self.is_sync = False                                                    # 是否在同步

        if self.config['master'] is not None:                                   # 从服务器启动
            shutil.rmtree(config['db'])
            self.master_server = PyCachedClient(self.config['master'][0],
                                                self.config['master'][1])
            self.master_server.sync(self.config['port'])
            self.slavepool = None
            self.slave = True                                                   # 是否为Slave模式
        else:                                                                   # 主服务器启动, 需要启动从命令工作线程

            self.slavepool = ThreadPool(int(config['slave_pool']))              # slave Command send pools
            self.slave = False                                                  # 是否为Slave模式

        self.memory = Memory(config['db'])                                      # 缓存服务类
        super(CacheServer, self).__init__()
예제 #10
0
 def stop(self):
   self.active = False
   game_slugs = get_game_slugs()
   
   if self.slug in game_slugs:
     game_slugs.remove(self.slug)
     memcache.set('game_slugs', game_slugs)
   
   
   serialized_status = memcache.get_multi(self.status_ids,
                                          key_prefix='status')
   
   # Just copying my status_ids list to make some changes localy
   missing_status_ids = list(self.status_ids)
   for status_id, status in serialized_status.iteritems():
     deserialized_status = deserialize(status)
     deserialized_status.player.leave_game(self)
     missing_status_ids.remove(status_id)
   
   # Taking the missing status in database
   if missing_status_ids:
     missing_status = Status.get(missing_status_ids)
     for status in missing_status:
       status.player.leave_game(self)
   
   memcache.delete('game'+self.slug)
   self.status_ids = []
   self.put()
예제 #11
0
파일: go.py 프로젝트: ndexbio/ndex-nav
def load_go_terms():
    info = {
        'database': 'go',
        'collection': 'terms',
        'url': 'http://geneontology.org/ontology/go.obo',
        'timestamp': time.time()
    }
    client = pymongo.MongoClient()
    collection = client[info['database']][info['collection']]
    collection.drop()
    with mktemp() as pathname:
        filename = os.path.join(pathname, 'go.obo')
        log.debug('downloading %s to %s', info['url'], filename)
        subprocess.call(['wget', info['url'], '-O', filename])
        with open(filename, 'rt') as fid:
            status = Status(filename, log).fid(fid).start()
            obj = None
            state = None
            for line in fid:
                status.log()
                line = line.strip()
                if line and not line.startswith('!'):
                    if line[0] == '[' and line[-1] == ']':
                        if state == 'Term' and obj:
                            collection.insert(obj)
                        state = line[1:-1]
                        obj = {}
                    elif state == 'Term':
                        key, _, value = line.partition(': ')
                        if value:
                            if key == 'id':
                                obj['go'] = value
                            else:
                                try:
                                    obj[key].append(value)
                                except KeyError:
                                    obj[key] = value
                                except AttributeError:
                                    obj[key] = [obj[key], value]
            status.stop()

    if state == 'Term' and obj:
        collection.insert(obj)

    collection.create_index('go')

    update_info(info)
예제 #12
0
 def read_net(self, event=None):
     if self.reading_net: return gtk.TRUE
     self.reading_net = True
     inKB, outKB = Status.getNet()
     if inKB > 9999: inKB = 999
     if outKB > 999: outKB = 999
     pingTimeGoogle = Status.getPingTime("google.com")
     
     if self.gw == None:
         self.gw = get_gw()
         print "gateway:", self.gw
     if self.gw != None:
         pingTimeGW = Status.getPingTime(self.gw, 2)
         self.statusStr = "%04d" % inKB +":"+"%03d" % outKB +"K/s " + " " + \
                          pingTimeGoogle + "|" + pingTimeGW + "ms"
         if pingTimeGW == "-1":
             try:
                 self.gw = get_gw()
                 print "gateway:", self.gw
             except:
                 pass
         self.statusStr = self.statusStr
     else:
         self.statusStr = strike("NET ")
     print "%.2f " % (time.time() - self.t), self.statusStr
     self.ind.set_label(self.statusStr)
     if self.gw != None:
         fullStatusStr = "UP: %03d" % inKB +"K/s\n"+"DOWN: %03d" % outKB +"K/s\n" + \
                         "Google ping: " + pingTimeGoogle + "ms\n" + \
                         "GW (" + self.gw + ") ping: " + pingTimeGW
     else:
         fullStatusStr = "No network"
     self.netMenuItem.set_label(fullStatusStr)
     self.counter += 1
     icon_name = "network"
     net_level = 5.0
     if outKB >= net_level: 
         icon_name += "-transmit"
     if inKB >= net_level:
         icon_name += "-receive"
     if outKB < net_level and inKB < net_level:
         icon_name += "-idle"
     self.ind.set_icon(icon_name)
     self.t = time.time()
     self.reading_net = False
     return gtk.TRUE
예제 #13
0
파일: main.py 프로젝트: DataBiosphere/bond
    def __init__(self):
        sam_base_url = config.get('sam', 'BASE_URL')

        providers = {provider_name: FenceApi(config.get(provider_name, 'FENCE_BASE_URL'))
                     for provider_name in config.sections() if provider_name != 'sam'}

        sam_api = SamApi(sam_base_url)
        self.status_service = Status(sam_api, providers)
예제 #14
0
 def advance_to_next_game(self):
     # We only need to check the preferred team's game status if we're
     # rotating during mid-innings
     if self.config.rotation_preferred_team_live_mid_inning and not self.is_offday_for_preferred_team(
     ):
         preferred_overview = self.fetch_preferred_team_overview()
         if Status.is_live(
                 preferred_overview.status) and not Status.is_inning_break(
                     preferred_overview.inning_state):
             self.current_game_index = self.game_index_for_preferred_team()
             self.overview = preferred_overview
             self.needs_refresh = False
             self.__update_layout_state()
             self.print_overview_debug()
             return self.current_game()
     self.current_game_index = self.__next_game_index()
     return self.current_game()
예제 #15
0
파일: cpu.py 프로젝트: jamesjweber/PyNES
    def start_up(self):
        """ set the initial values of the registers
            Status (P) = $34
            A, X, Y = 0
            Stack Pointer = $FD
            $4017 = $00 (frame irq enabled)
            $4015 = $00 (all channels enabled)
            $4000-$400F = $00 (disabled)
        """
        # TODO Hex vs Binary
        self.pc_reg = np.uint16(0)
        self.status_reg = Status()
        self.sp_reg = np.uint8(0xFD)

        self.x_reg = np.uint8(0)
        self.y_reg = np.uint8(0)
        self.a_reg = np.uint8(0)
예제 #16
0
파일: main.py 프로젝트: hirotoshi/twittmap
  def get(self):
    twitter = TwitterClient()
    statuses = Status.getStatuses(20)
    user = twitter.getUser( self.username )

    def urlify(txt):
      if txt:
        txt = re.sub('(https?:\/\/[-_.!~*\'()a-zA-Z0-9;/?:@&=+$,%#]+)',  
                 '<a href="\\1">Link</a>', txt)
      return txt

    def getMapUrl(loc,type):
      if not loc:
        return None;

      if type == "google" :
        url = u'http://maps.google.com/staticmap?'
        url += urllib.urlencode( {
          'center'  : str(loc.lat) + ',' + str(loc.lon),
          'markers' : str(loc.lat) + ',' + str(loc.lon),
          'size'    : '460x320',
          'zoom'    : '15',
          'key'     : self.google_key,
        } )
      else :
        url = u'http://tp.map.yahoo.co.jp/mk_map?'
        url += urllib.urlencode( {
          'prop'      : 'clip_map',
          'scalebar'  : 'off',
          'pointer'   : 'off',
          'width'     : '460',
          'height'    : '320',
          'datum'     : 'wgs84',
          'lat'       : loc.lat,
          'lon'       : loc.lon,
          'pin'      : str(loc.lat) + "," + str(loc.lon),
          'sc'        : 4,
        })

      return url
  
    list = []
    for status in statuses:
      list.append( {
          'text'  : status.text,
          'reply' : urlify(status.reply),
          'user_screen_name' : status.user_screen_name,
          'user_profile_image_url' : status.user_profile_image_url,
          'loc_url' : status.loc_url,
          'map'   : getMapUrl( status.loc_point , status.loc_type ),
      })

    values = {
               'list'   : list,
               'user'   : user,
                }
    path = os.path.join(os.path.dirname(__file__), 'main.html')
    self.response.out.write( template.render(path,values))
예제 #17
0
    def start_up(self):
        """
        set the initial values of cpu registers
        status reg: 000100 (irqs disabled)
        x, y, a regs: 0
        stack pointer: $FD
        $4017: 0 (frame irq disabled)
        $4015: 0 (sound channels disabled)
        $4000-$400F: 0 (sound registers)
        """
        # TODO Hex vs binary
        self.pc_reg = np.uint16(0)  # 2 byte
        self.status_reg = Status()
        self.sp_reg = np.uint8(0xFD)

        self.x_reg = np.uint8(0)
        self.y_reg = np.uint8(0)
        self.a_reg = np.uint8(0)
예제 #18
0
 def __init__(self):
     cfg = ConfigParser.ConfigParser()
     cfg.read("/opt/iot-integration/config.ini")
     self.rabbitmq = Rabbitmq(cfg)
     self.device = Device(cfg)
     self.register = Register(cfg)
     self.status = Status(cfg)
     self.controller = Controller(cfg)
     self.db = Db(cfg)
예제 #19
0
def hub_status_update():
    if request.method == 'GET':
        return render_template('status_update.html', status=Status().status)
    elif request.method == 'POST':
        if not (request.form['state'] == '0' or request.form['state'] == '1'):
            abort(400)
        new_status(request.form['state'], request.form['message'],
                   session['username'])
        return redirect('/hub/status')
예제 #20
0
 def _register_status(self, client_id, channel_id, vc_channel_id):
     guild = self._lb.client.get_channel(channel_id).guild
     status = Status(client_id=client_id,
                     guild_id=guild.id,
                     channel_id=channel_id,
                     voice_channel_id=vc_channel_id)
     if status in self._status_list:
         return
     self._status_list.append(status)
예제 #21
0
def update():
    status = Status.instance()
    updates = request.get_data().split("&")
    for u in updates:
        key, value = u.split("=")
        print "updating {0} to {1}".format(key, value)
        status.update(key, value)

    return ""
예제 #22
0
def hub_apply_for_membership():
    if not session.get('application_username'):
        return redirect('/hub/')
    try:
        m = Member(session['application_username'])
    except:
        pass
    else:
        session['username'] = session['application_username']
        del session['application_username']
        return redirect('/hub/')

    db = get_db()
    cur = db.cursor()
    cur.execute('SELECT 1 FROM application WHERE username=?',
                (session['application_username'], ))
    if cur.fetchone():
        cur.close()
        return render_template('membership_apply_thanks.html',
                               status=Status().status)
    cur.close()

    if request.method == 'GET':
        return render_template('membership_apply.html', status=Status().status)
    else:
        try:
            username = session['application_username']
            realname = request.form['realname']
            nickname = request.form['nickname']
            email = request.form['email']
            address = request.form['address']
        except KeyError:
            return redirect('/hub/apply-for-membership')

        cur = db.cursor()
        cur.execute(
            """insert into application (username, realname,
            nickname, email, address, received) values (?, ?, ?, ?, ?, strftime('%s', 'now'))""",
            (username, realname, nickname, email, address))
        db.commit()
        cur.close()

        return render_template('membership_apply_thanks.html',
                               status=Status().status)
class StateMachine:
    def __init__(self, GameServer, name) -> None:
        self.status = Status(name=name)
        self.GameServer = GameServer
        self.turret_controls = TurretMovement(GameServer=GameServer, status=self.status)
        self.body_controls = BodyMovement(GameServer=GameServer, status=self.status)
        self.turret_states = list(map(
            lambda State: State(self.turret_controls, self.body_controls, self.status),
            AVAILABLE_TURRET_STATES
        ))
        self.body_states = list(map(
            lambda State: State(self.turret_controls, self.body_controls, self.status),
            AVAILABLE_BODY_STATES
        ))
        self.current_turret_state_i = 0
        self.current_turret_state = self.turret_states[0]
        self.current_body_state_i = 0
        self.current_body_state = self.body_states[0]

    def update(self, message: Message) -> None:
        self.status.update(message=message)
        logging.info(f"Recieved message {message.type}: {message.payload}")

    def choose_state(self) -> None:
        body_priorities = [
            self.body_states[i].calculate_priority(
                is_current_state=(i == self.current_body_state_i)
            ) for i in range(len(self.body_states))
        ]
        turret_priorities = [
            self.turret_states[i].calculate_priority(
                is_current_state=(i == self.current_turret_state_i)
            ) for i in range(len(self.turret_states))
        ]
        logging.info(f"Body: {body_priorities}\nTurret: {turret_priorities}")
        self.current_body_state_i = body_priorities.index(max(body_priorities))
        self.current_turret_state_i = turret_priorities.index(max(turret_priorities))
        self.current_body_state = self.body_states[self.current_body_state_i]
        self.current_turret_state = self.turret_states[self.current_turret_state_i]

    def perform_current_state(self) -> None:
        logging.info(f"Performing states: {self.current_body_state} {self.current_turret_state}")
        self.current_body_state.perform()
        self.current_turret_state.perform()
예제 #24
0
    def init(cls):
        # Set up Slack
        load_dotenv()
        slack = Slack(os.getenv('QS_TOKEN'))

        # Read statuses
        statuses_raw = Config.read_config('statuses')
        statuses = {
            key: Status.from_dict(statuses_raw[key])
            for key in statuses_raw
        }

        # Read default status stack
        default_statuses = []
        defaults = Config.read_config('defaults')
        try:
            for status in defaults['statuses']:
                default_statuses.append(Status.from_dict(status))
        except KeyError:
            defaults['statuses'] = []

        # Read default Do Not Disturb
        default_dnd = Expiration.from_timestamp(defaults.get('dnd', None))

        # If either the default status or default DND are expired, the config will need to be rewritten
        rewrite = False
        while len(default_statuses) > 0:
            if default_statuses[-1].status_expiration.is_expired():
                default_statuses.pop()
                rewrite = True
            else:
                break

        if default_dnd is not None and default_dnd.is_expired():
            default_dnd = None
            rewrite = True

        config = cls(slack, statuses, default_statuses, default_dnd)

        # Rewrite the config, if needed
        if rewrite:
            config.write_config()

        return config
예제 #25
0
    def __init__(self, clientName, run=True):

        self.clientName = clientName
        self.isrunning = run
        self.localTimestamp = time()
        self.localDateTime = datetime.fromtimestamp(self.localTimestamp)

        logMessage = f'\n\n{self.localDateTime}\nSession created with "{self.clientName}" credentials and run = {run}'
        log.event_log_append(logMessage)
        log.raw_log_append(logMessage)

        # RESTRICTIONS TO BE IMPLEMENTED... WHERE?

        # statuses = [] # [ID, runningOrClosed, crashingInfo, *args]

        self.market = MarketManager()
        self.wait = DEFAULT_WAIT

        if self.isrunning:
            self.sessionID = ID("session")
            logMessage = f'Session has started with session ID: {self.sessionID.partialID}.\n'
            log.event_log_append(logMessage)
            log.raw_log_append(logMessage)

        while self.isrunning:
            log.event_log_append('\nCurrent marketsBuffer = ', self.market.marketsBuffer)
            try:
                self.newStatus = Status(self.clientName, self.market.current())
                self.wait = DEFAULT_WAIT
            except IDOverflowError or IndexError:
                self.statusIDReset = ID("status", getNew=False, reset=True)
                self.isrunning = False
                logMessage = f'\nSession terminated for statusID overflow.\n'
                log.event_log_append(logMessage)
                log.raw_log_append(logMessage)
                break
            """
            except Exception as err:
                if self.wait < MAX_WAIT: self.wait *= WAIT_MULTIPLIER_0
                logMessage = f'\nStatus crashed with error:\n    {err.__repr__()}\n'
                log.event_log_append(logMessage)
                log.raw_log_append(logMessage)
            """

            self.market.set_next_to_current()

            """
            #if newStatus.getMarketData() is different from marketData, update sessionConfig.json
            try: self.lastMarket = newStatus.getMarketData()
            except: self.lastMarket = self.marketsBuffer[0]
            if len(self.marketsBuffer) > 1:
                self.marketsBuffer = self.marketsBuffer[1:]
                self.marketsBuffer.append(self.lastMarket)
            """

            sleep(self.wait)
예제 #26
0
파일: app.py 프로젝트: c-m/mood-meter
def api_statuses_post_list():
    if not request.mimetype == 'application/json':
        return BadRequest("Wrong content-type. Need json.")

    data = request.json
    if 'message' not in data or data['message'] not in STATUS_CHOICES:
        return BadRequest("Missing or invalid message field. "
                          "Possible values: %s." % STATUS_CHOICES)

    status = Status(message=data['message'])
    try:
        session.add(status)
        session.commit()
    except:
        # Not sure what else can happen but.. you never know!
        session.rollback()
        return BadRequest()

    return jsonify(status.serialize())
예제 #27
0
 def __init__(self):
     self.adc = ADCReader()
     self.config = Config()
     self.status = Status()
     self.controller = Controller()
     self.freeze_status = 0
     self.filter_status = 0
     self.last_alert = datetime.datetime.utcfromtimestamp(0)
     self.adclock = threading.Lock()
     Timer(30.0, self.filter_timer).start()
예제 #28
0
 def init():
     Leds.data = Config.getParam("stripes")
     Leds.np = {}
     Leds.cnt = 0
     for s in Leds.data.keys():
         pin = Leds.data[s]["pin"]
         count = Leds.data[s]["size"]
         Leds.cnt += count
         mode = Leds.data[s]["mode"]
         Status.log("Init stripe %s on pin %s" % (s, pin))
         Leds.np[s] = NeoPixel(machine.Pin(pin), count)
         if "leds" in Leds.data[s]:
             for i in range(1, count):
                 if i in Leds.data[s]["leds"]:
                     Leds.np[s][i - 1] = tuple(
                         Leds.fromHtml(Leds.data[s]["leds"][i]))
         Leds.np[s].write()
         if mode == "random":
             Leds.random(s)
예제 #29
0
    def __init__(self, master):
        '''Intialize the game tic-tac-toe'''

        # Save a reference to app root
        self.master = master

        # Load Game Images (Just Once)
        self.load_images()

        # Init game state
        self.player = 0
        self.buttons = []

        # Init Widgets
        self.build_game_board()
        self.build_actions_frame()

        self.status = Status(master)
        self.status.grid(row=0, columnspan=2, pady=10)
예제 #30
0
 def __valid_room_names(self, sender):
     """ Check whether room names given are existing in database. Once there is a non-existing
     room name, return an error code 497 and no message is sent.
 """
     for roomName in self.rooms:
         # if roomName not in self.table.rooms:
         if not self.table.has_room(roomName):
             return MessageStatus(497, "Room not found", True, sender,
                                  roomName, '', self.message)
     return Status(200, "success")
예제 #31
0
 def scan():
     roms = Sensors.ow.scan()
     for rom in roms:
         romid = "".join("%02x" % i for i in rom)
         found = False
         for s in Sensors.data["roms"].keys():
             if romid == Sensors.data["roms"][s]["rom"]:
                 found = True
                 continue
         if not found:
             nid = Sensors.getNextId()
             Sensors.addSensor(nid, romid)
             Status.log("Adding sensor %s[%s]" %
                        (nid, Sensors.data["roms"][nid]["rom"]))
     for s in Sensors.data["roms"].keys():
         if (Status.loops - Sensors.data["roms"][s]["last"]) > 60:
             Status.log("Removing stale sensor %s[%s]" %
                        (s, Sensors.data["roms"][s]["rom"]))
             Sensors.removeSensor(s)
예제 #32
0
파일: views.py 프로젝트: ruijzhan/weiborss
def qiudog(request):
    statuses = Status.get_friends_statuses(30)
    for status in statuses:
        for pic in status.pic_urls:
            pic.thumbnail_pic = pic.thumbnail_pic.replace('thumbnail','large')
        if hasattr(status,'retweeted_status'):
            for pic in status.retweeted_status.pic_urls:
                pic.thumbnail_pic = pic.thumbnail_pic.replace('thumbnail','large')
    lastBuildDate = statuses[0].created_at

    return render_to_response('rss.xhtml',locals())
예제 #33
0
    def test_equality(self):
        s = Status(Status.INIT)

        # testing __eq__
        assert (s == Status.INIT), 'should be true.'
        assert (s == 'I'), 'should be true.'
        assert not (s == 7), 'should be false.'

        assert not (s != Status.INIT), 'should be false.'
        assert not (s != 'I'), 'should be false.'
        assert (s != 7), 'should be true.'
예제 #34
0
파일: tcga.py 프로젝트: ndexbio/ndex-nav
def parse_edges(dir, meta_id, id_to_symbol, id_to_ensembl, threshold):
    for filename in glob.glob(os.path.join(dir, '*.cor')):
        with open(filename) as fid:
            status = Status('processing ' + filename, logger=log).fid(fid).start()
            for line in fid:
                status.log()
                try:
                    source, target, correlation, pvalue = line.split()
                    correlation = float(correlation)
                except Exception as e:
                    log.error(e.message)
                    continue

                if math.fabs(correlation) > threshold:
                    try:
                        yield {'source': id_to_ensembl[source], 'target': id_to_ensembl[target], 'correlation': correlation, 'pvalue': float(pvalue), 'meta': meta_id}
                    except KeyError as e:
                        log.error('could not map identifier %s (%s)', e.message, id_to_symbol.get(e.message))

            status.stop()
예제 #35
0
    def parseRequest(self, URL, artist=None, song=None):
        """Figure out what kind of download option the user wants"""

        statusObject = Status()
        ytdl_cmd_args = []  # append cmd arguments to this

        self.download(URL, ytdl_cmd_args, statusObject)

        #print statusObject.toDict()

        return statusObject
예제 #36
0
 def update(self):
     z = self.vehicle.z
     H_dot_front = self.H.dot(z[15:18])
     H_dot_following = self.H.dot(z[18:21])
     H_dot_self = self.H.dot(self.vehicle.estimated_status)
     self.vehicle.front_estimated_status = Status(*self.mean_(
         self.dummy_front_status_list(z, H_dot_self, H_dot_front,
                                      H_dot_following)))
     self.vehicle.estimated_status = Status(*self.mean_(
         self.dummy_status_list(z, H_dot_self, H_dot_front,
                                H_dot_following)))
     self.vehicle.following_estimated_status = Status(*self.mean_(
         self.dummy_following_status_list(z, H_dot_self, H_dot_front,
                                          H_dot_following)))
     self.vehicle.front_estimated_diff = Status(*self.mean_(
         self.dummy_front_diff_list(z, H_dot_self, H_dot_front,
                                    H_dot_following)))
     self.vehicle.following_estimated_diff = Status(*self.mean_(
         self.dummy_following_diff_list(z, H_dot_self, H_dot_front,
                                        H_dot_following)))
예제 #37
0
 def check():
     t = machine.RTC().datetime()
     for r in Relays.data.keys():
         rel = Relays.data[r]
         pin = machine.Pin(rel["pin"], machine.Pin.OUT)
         toreplace = {"dow": t[6], "hod": t[4], "moy": t[1], "year": t[0]}
         for s in Sensors.data["roms"].keys():
             toreplace["s%s" % s] = Sensors.getValue(s)
         si = rel["condition"]
         for r in toreplace.keys():
             si = si.replace("{%s}" % r, toreplace[r])
         Status.log("Eval condition: %s" % si)
         try:
             if eval(si):
                 pin.value(1)
             else:
                 pin.value(0)
         except Exception:
             Status.log("Bad condition!")
             pass
예제 #38
0
파일: cpu.py 프로젝트: ldesuque/pNES
    def start_up(self):
        #  Set initial values of registers
        #  https://wiki.nesdev.com/w/index.php/CPU_power_up_state
        #  SP = $FD

        self.p_reg = Status()
        self.a_reg = bytes.fromhex('00')
        self.x_reg = bytes.fromhex('00')
        self.y_reg = bytes.fromhex('00')

        self.sp_reg = bytes.fromhex('FD')
예제 #39
0
파일: http.py 프로젝트: limosek/poolcontrol
 def _parseRequest():
     midx = HTTP.data[0].find(" ")
     rest = HTTP.data[0][midx + 1:]
     if midx >= 0:
         HTTP.Method = HTTP.data[0][0:midx]
     else:
         Status.log("Bad HTTP request %s!" % HTTP.data[0])
         HTTP.Valid = False
     uidx = rest.find(" ")
     if uidx >= 0:
         HTTP.Uri = HTTP.urlDecode(rest[0:uidx])
     HTTP.Version = rest[uidx + 1:]
     ridx = HTTP.Uri.find("?")
     if ridx >= 0:
         HTTP.Request = HTTP.Uri[0:ridx]
         HTTP.Params = HTTP.Uri[ridx + 1:]
     else:
         HTTP.Request = HTTP.Uri
         HTTP.Params = ""
     HTTP.Valid = True
예제 #40
0
def main():

    settings = Settings()

    listaCam = []

    status = Status()

    for item in settings.cameras:
        listaCam.append(
            Camera(item[0], item[1], item[2], item[3], item[4], item[5],
                   item[6], status))
예제 #41
0
def parse_input_info(cfg_arr, sts_arr, control=None):
    # read the config and status files
    if cfg_arr:
        config = Config.parse_config_info(cfg_arr, control)
    else:
        config = None
    if sts_arr:
        status = Status.parse_status_info(sts_arr)
    else:
        status = None

    return config, status
예제 #42
0
    def __init__(self, serial: str):
        self.serial = serial
        self.model = "Mock Printer"

        self.status = Status(model="MOCK PRINTER",
                             media_width=62,
                             media_length=0,
                             media_type="Continuous",
                             errors=0,
                             status_type=StatusType.PhaseChange,
                             phase=PhaseState.Receiving,
                             notification=0)
예제 #43
0
파일: main.py 프로젝트: vadegg/mayak_tg_bot
def request_new_places(message):
    send_contact_info(message)
    db_interface.set_status(message.chat.id,
                            Status.create_status("add_place", "if_want"))
    keyboard = ReplyKeyboardMarkup(row_width=2,
                                   resize_keyboard=True,
                                   one_time_keyboard=True)
    keyboard.add(dont_want_to_suggest)
    bot.send_message(message.chat.id, (
        "А ещё ты можешь предложить нам добавить в сервис новое заведение.\n" +
        "Напиши мне название заведения, которое ты хотел бы добавить"),
                     reply_markup=keyboard)
예제 #44
0
def get_platforms(status = None):
    """
    Return all platforms in the system

    Args:
        status (Status): a debug status object

    Return:
        (list of platforms)

    Raises:
        Nothing
    """
    if status is None:
        status = Status()
    platforms = []
    pscanner = PlatformScanner()
    platform_dict = pscanner.get_platforms()
    platform_names = platform_dict.keys()

    if "sim" in platform_names:
        #If sim is in the platform names move it to the back
        platform_names.remove("sim")
        platform_names.append("sim")

    for platform_name in platform_names:
        if status: status.Debug("Platform: %s" % str(platform_name))
        #Get a reference to a platform object (like sim, or dionysus)
        platform_instance = platform_dict[platform_name](status)

        #Scan for instances of that particular platform
        instances_dict = platform_instance.scan()

        for name in instances_dict:
            n = instances_dict[name]
            if n is not None:
                if status: status.Debug("Found a Nysa Instance: %s" % name)
                platforms.append(n)

    return platforms
예제 #45
0
def parse_edges(dir, meta_id, id_to_symbol, id_to_ensembl, threshold):
    for filename in glob.glob(os.path.join(dir, '*.cor')):
        with open(filename) as fid:
            status = Status('processing ' + filename,
                            logger=log).fid(fid).start()
            for line in fid:
                status.log()
                try:
                    source, target, correlation, pvalue = line.split()
                    correlation = float(correlation)
                except Exception as e:
                    log.error(e.message)
                    continue

                if math.fabs(correlation) > threshold:
                    try:
                        yield {
                            'source': id_to_ensembl[source],
                            'target': id_to_ensembl[target],
                            'correlation': correlation,
                            'pvalue': float(pvalue),
                            'meta': meta_id
                        }
                    except KeyError as e:
                        log.error('could not map identifier %s (%s)',
                                  e.message, id_to_symbol.get(e.message))

            status.stop()
예제 #46
0
파일: go.py 프로젝트: ndexbio/ndex-nav
def load_go_genes():
    info = {
        'database': 'go',
        'collection': 'genes',
        'url': 'http://geneontology.org/gene-associations/gene_association.goa_human.gz',
        'timestamp': time.time()
    }
    client = pymongo.MongoClient()
    collection = client[info['database']][info['collection']]
    collection.drop()
    with mktemp() as pathname:
        filename = os.path.join(pathname, 'gene_association.goa_human.gz')
        log.debug('downloading %s to %s', info['url'], filename)
        subprocess.call(['wget', info['url'], '-O', filename])
        log.debug('gunzip %s', filename)
        subprocess.call(['gunzip', filename])
        filename, _ = os.path.splitext(filename)

        with open(filename, 'rt') as fid:
            log.debug('creating a name to emsembl id lookup table from go genes...')
            go_genes = set([line.split('\t')[2] for line in fid if not line.startswith('!')])

        name_to_id = genemania.id_lookup_table(go_genes)

        with open(filename, 'rt') as fid:
            status = Status(filename, log).fid(fid).start()
            for line in fid:
                status.log()
                if not line.startswith('!'):
                    tokens = line.split('\t')
                    obj = {
                        'gene': name_to_id.get(tokens[2]),
                        'go': tokens[4]
                    }
                    collection.insert(obj)
            status.stop()

    update_info(info)
    collection.create_index('go')
    collection.create_index('gene')
예제 #47
0
def init():
	gc.enable()
	Status.init()
	if not Config.init():
		Config.factoryReset()
	Config.init()
	Wifi.init()
	Leds.init()
	Sensors.init()
	Relays.init()
	if Config.getParam("time", "ntp"):
		i = 1
		try:
			while i < 5 and not ntpclient.settime(Config.getParam("time", "ntp"), Config.getParam("time", "offset")):
				Status.log("Getting time from NTP... (%s)" % i)
				i += 1
			rtc = machine.RTC()
			t = rtc.datetime()
		except Exception:
			t = utime.localtime(0)
	else:
		t = utime.localtime(0)
	Status.log('Date: {:04d}.{:02d}.{:02d} {:02d}:{:02d}:{:02d}'.format(t[0], t[1], t[2], t[4], t[5], t[6]))
	# Init timer
	tim = machine.Timer(0)
	tim.init(period=50, mode=machine.Timer.PERIODIC, callback=tick50mS())
예제 #48
0
	def find_status(self):
		from status import Status
		dist = self.sensor.find_distance()

#		self.rgbLed.all_off()

		status = Status(door = self, distance = dist)

		if dist > 20 or dist == 0:
			# Bad reading
			self.rgbLed.blueLed.on()
			self.rgbLed.redLed.off()
			self.rgbLed.greenLed.off()
			status.isError = True
		else:
			if dist > 3:
				status.isDoorUp = False
				self.rgbLed.greenLed.on()
				self.rgbLed.redLed.off()
				self.rgbLed.blueLed.off()
			else:
				status.isDoorUp = True
				self.rgbLed.redLed.on()
				self.rgbLed.greenLed.off()
				self.rgbLed.blueLed.off()

			if dist > 6:
				status.isCarPresent = False
			else:
				status.isCarPresent = True

		return status
예제 #49
0
파일: main.py 프로젝트: vadegg/mayak_tg_bot
def location_recieved(message):

    status = db_interface.get_status(message.chat.id)
    log_location(message)

    if not Status.was_choosed_smth(status):
        bot.send_message(message.chat.id, "Я узнаю, где ты, позже")
        return

    bot.send_message(message.chat.id,
                     "Лучшие места для тебя:",
                     reply_markup=ReplyKeyboardHide())
    db_interface.set_status(message.chat.id, Status.choosed_to_geo(status))

    places_list = places.get_top_of_places(status, message.location)
    for place in places_list:
        keyboard = InlineKeyboardMarkup()
        callback_button = InlineKeyboardButton(text="👍 Интересно!",
                                               callback_data="place_{}".format(
                                                   place[0]))
        keyboard.add(callback_button)
        for m in place[1]:
            bot.send_message(message.chat.id,
                             m,
                             parse_mode='Markdown',
                             reply_markup=keyboard)

    keyboard = ReplyKeyboardMarkup(row_width=1,
                                   resize_keyboard=True,
                                   one_time_keyboard=True)
    button_change_category = KeyboardButton(text=change_category)

    keyboard.add(button_change_category)
    bot.send_message(
        message.chat.id,
        ('Чтобы узнать кодовое слово нажми 👍 под постом\n\n' +
         'Чтобы посмотреть предложения в других категориях нажми' +
         ' "Изменить категорию" ⬇️'),
        reply_markup=keyboard)
예제 #50
0
class DisplayPanel(object):

	def __init__(self, surface, pos, player, images):
		self.surface = surface
		self.pos = pos
		self.player = player
		self.images = images
		
		self.optionsPos = (0,0)
		self.optionsRect = pygame.Rect(self.optionsPos, (Cell.size * 12, Cell.size * 6))
		self.options = Options(self.surface.subsurface(self.optionsRect), self.optionsPos, self.player, images)
		
		self.statusPos = (0, Cell.size * 6 + Cell.size)
		self.statusRect = pygame.Rect(self.statusPos, (Cell.size * 12, Cell.size))
		self.status = Status(self.surface.subsurface(self.statusRect), self.statusPos, self.player, images)
		
		self.logPos = (0, Cell.size * 7 + (Cell.size * 2))
		self.logRect = pygame.Rect(self.logPos, (Cell.size * 12, Cell.size * 8))
		self.log = Output(self.surface.subsurface(self.logRect), self.logPos, self.player.log)
		
		
	def draw(self):
		self.options.draw()
		self.status.draw()
		self.log.draw()
		
	def notify(self, pos, event):
		vec = Vector2(pos)
		vec -= self.pos
		
		point = (int(vec[0]), int(vec[1]))
		if self.optionsRect.collidepoint(point):
			self.options.notify(point, event)
			
		if self.statusRect.collidepoint(point):
			self.status.notify(point, event)
			
		if self.logRect.collidepoint(point):
			self.log.notify(point, event)
예제 #51
0
 def __init__(self, game=None):
     self.token = 'Token ' + token
     self.base_url = base_url
     self.next_action_time = time.time()
     self.current_room = Room()
     self.queue = Queue()
     self.game = game
     self.actions = Actions(self)
     self.status = Status()
     self.init()
     self.has_dash = True
     self.has_flight = True
     self.last_examine = dict()
예제 #52
0
 def run(self):
     i = 0
     statusStr = " Init... "
     while(self.parent.alive.isSet()):
         if self.mustExit: return
         # update stats every 2s
         if not (i % 2):
             #                statusStr = Status.getCpuPerc() + " | " + 
             #                statusStr = Status.getTemp() + " | " + 
             statusStr = Status.getNet() + " | " + \
                 Status.getPingTime()
             self.parent.updateText(statusStr)
             temp = Status.getTemp()
             if temp < 50: iconNum = 1
             elif temp < 70: iconNum = 2
             elif temp < 80: iconNum = 3
             elif temp < 90: iconNum = 4
             else: iconNum = 5
             self.parent.setIcon("/home/sah/dev/indicators/temperature-%d-icon.png" % iconNum)
             self.parent.updateTempMenuItem("%.1f C" % temp)
         time.sleep(1)
         i += 1
예제 #53
0
 def check_temp(self):
     if self.checking_temp: return True
     self.checking_temp = True
     (temp, temp_str) = Status.getTemp()
     if temp < 60: iconNum = 1
     elif temp < 70: iconNum = 2
     elif temp < 80: iconNum = 3
     elif temp < 90: iconNum = 4
     else: iconNum = 5
     self.ind.set_icon("temperature-%d-icon" % iconNum)
     self.temp_mitem.set_label(temp_str)
     self.checking_temp = False
     return True
예제 #54
0
 def enter_game(self, game):
   game_status = self.get_game_status(game)
   
   if not game_status:
     query = Status.all()
     query.filter('game =', game)
     query.filter('player =', self)
     game_status = query.get()
     
     if not game_status:
       game_status = Status(player=self, game=game, playing=True)
       
   
   game_status.playing = True
   game_status.put()
   
   if game_status.id not in self.status_ids:
     self.status_ids.append(game_status.id)
     self.persist = True # It says that it should be saved in database
     self.put()
   
   # IT IS VERY WRONG, PLAYER SHOULD BE PUT IN A LIST,
   # AND THE LIST SHOULD BE ADDED TO GAME EACH create_match.
   game_status.game.add_status(game_status)
예제 #55
0
 def read_net(self, event=None):
     if self.reading_net: return gtk.TRUE
     self.reading_net = True
     inKB, outKB = Status.getNet()
     if inKB > 999: inKB = 999
     if outKB > 999: outKB = 999
     self.statusStr = "%03d" % inKB +":"+"%03d" % outKB +"K/s " + " " + \
         Status.getPingTime("192.168.2.1") + " " + Status.getPingTime("google.com") 
     self.counter += 1
     print "%.2f " % (time.time() - self.t), self.statusStr
     self.ind.set_label(self.statusStr)
     self.netMenuItem.set_label(self.statusStr)
     icon_name = "network"
     net_level = 5.0
     if outKB >= net_level: 
         icon_name += "-transmit"
     if inKB >= net_level:
         icon_name += "-receive"
     if outKB < net_level and inKB < net_level:
         icon_name = "idle-network"
     self.ind.set_icon(icon_name)
     self.t = time.time()
     self.reading_net = False
     return gtk.TRUE
예제 #56
0
파일: peer.py 프로젝트: Arreth/ECE454P1
 def init( self, host, port, peers, dirName ):
     logging.info( 'Initializing new peer ' + self.getPeerKey( host, port ) )
     self.filesDir = dirName
     self.host = host
     self.port = port
     self.peers = peers
     self.peerKey = self.getPeerKey( host, port )
     self.activePeers = {}
     self.waitingQueries = []
     self.joined = False
     self.status = Status( self.peerKey )
     self.status.registerPeer( self.peerKey, {} )
     self.sender = Sender( self )
     self.rQueue = Queue()
     self.shutdownFlag = False
     self.start()
예제 #57
0
	def __init__(self, surface, pos, player, images):
		self.surface = surface
		self.pos = pos
		self.player = player
		self.images = images
		
		self.optionsPos = (0,0)
		self.optionsRect = pygame.Rect(self.optionsPos, (Cell.size * 12, Cell.size * 6))
		self.options = Options(self.surface.subsurface(self.optionsRect), self.optionsPos, self.player, images)
		
		self.statusPos = (0, Cell.size * 6 + Cell.size)
		self.statusRect = pygame.Rect(self.statusPos, (Cell.size * 12, Cell.size))
		self.status = Status(self.surface.subsurface(self.statusRect), self.statusPos, self.player, images)
		
		self.logPos = (0, Cell.size * 7 + (Cell.size * 2))
		self.logRect = pygame.Rect(self.logPos, (Cell.size * 12, Cell.size * 8))
		self.log = Output(self.surface.subsurface(self.logRect), self.logPos, self.player.log)
예제 #58
0
파일: cpu.py 프로젝트: PyAndy/Py3NES
    def start_up(self):
        """
        set the initial values of cpu registers
        status reg: 000100 (irqs disabled)
        x, y, a regs: 0
        stack pointer: $FD
        $4017: 0 (frame irq disabled)
        $4015: 0 (sound channels disabled)
        $4000-$400F: 0 (sound registers)
        """
        # TODO Hex vs binary
        self.pc_reg = np.uint16(0)  # 2 byte
        self.status_reg = Status()
        self.sp_reg = np.uint8(0xFD)

        self.x_reg = np.uint8(0)
        self.y_reg = np.uint8(0)
        self.a_reg = np.uint8(0)
예제 #59
0
    def from_backup(self, backupdir):
        assert os.path.isdir(backupdir)
        my_log = logging.getLogger('backup')

        if self.backup:
            my_log.warning('The backup will be produced but can not be used for another run.')

        self.stat = Status(logged=True)
        try:
            self.stat.load_backup(backupdir)
        except SystemExit:
            my_log.critical('Could not load backup from:\n{}'.format(backupdir))
            sys.exit(1)

        pipeline_position = self.stat.variables["status"]

        if pipeline_position == 6:
            my_log.critical("Please re-run the pipeline.. "
                             "There is no secure way to find the correct point to start from")
            sys.exit(1)

        # init all variables
        for variable_name in self.stat.variables:
            val = self.stat.variables[variable_name]
            setattr(self, variable_name, val)   # same as self.variable_name = val

        self.sqlite_taxonomy = taxonomy_ncbi.TaxonomyNcbi(self.config.ncbi_tax_db)

        if pipeline_position < 1:
            self.process_ncbi()
        if pipeline_position < 2:
            self.tree_process()
        if pipeline_position < 3:
            self.map_genomes_on_tree()
        if pipeline_position < 4:
            self.generate_seq(done_files=self.stat.files.keys())
        if pipeline_position < 5:
            self.sample_specific(done_files=self.stat.files.keys())
        if pipeline_position < 6:
            self.generate_kmer_features()
        if pipeline_position < 7:
            self.build_models()