コード例 #1
0
def assistant(command):

	if "how are you" in command:
		speak("i am well")
	elif "open " in command:
		reg_ex = re.search("open (.*)", command)
		chrome.open(reg_ex)
	elif "set up my desktop" in command:
		chrome.setupDesktop()
	elif "what date is today" in command:
		date.date()
	elif "what time is it" in command:
		date.time()
	elif "application" in command:
		reg_ex = re.search("application (.*)", command)
		application = reg_ex.group(1)
		aplication.open(application)
	elif "hello" in command:
		date.welcome()
	elif "help me" in command:
		help()
	elif "make a joke" in command:
		joke.makeJoke()
	elif "tell me about" in command:
		reg_ex = re.search('tell me about (.*)', command)
		chrome.about(reg_ex)
	elif "shut down" in command:
		speak('Bye bye Sir. Have a nice day')
		sys.exit()					
	elif "what is the weather in" in command:
		reg_ex = re.search('what is the weather in(.*)', command)
		weather.tellWeather(reg_ex)
	elif "i go outside" in command:
		speak("don't be idiot and stay at home")
コード例 #2
0
ファイル: main.py プロジェクト: rodneyxr/Python-Programs
def gameLoop():
    player = None
    line = ''
    print("Enter a command or type 'exit' to stop playing.")
    while line != "exit":
        line = input("> ")
        cmd = line.split()
        if cmd[0] == "help":
            help.help(cmd)
        if cmd[0] == "login":
            if len(cmd) != 2:
                print("** Invalid use of 'login'\n** Use: login <username>")
                continue
            player = login(cmd[1])
            print("Successfully logged in!")
        if cmd[0] == "save":
            if player == None:
                print("** You must login first!\n** Use: login <username>")
                continue
            try:
                player.save()
                print("Player save successful.")
            except Exception as e:
                print(e)
        if cmd[0] == "encrypt":
            msg = utils.simple_encrypt(line[len(cmd[0]) + 1:])
            print(msg)
        if cmd[0] == "decrypt":
            msg = utils.simple_decrypt(line[len(cmd[0]) + 1:])
            print(msg)
コード例 #3
0
def calcy():
    cmd = input(colorama.Fore.CYAN + "$>> " + colorama.Fore.RESET)
    if cmd == "help":
        help.help()
    elif cmd == "add":
        a = (colorama.Fore.GREEN + "Type a number: " + colorama.Fore.RESET)
        b = (colorama.Fore.GREEN + "Type a number: " + colorama.Fore.RESET)
        d = calcym.add(a,b)
        e = str(d)
        print (e)
    else:
        print (colorama.Fore.RED + "ERROR: WRONG COMMAND" + colorama.Fore.RESET)
        print (colorama.Fore.RED + "RUNTIME ERROR" + colorama.Fore.RESET)
    while cmd == "add" or "help":
        print (colorama.Fore.MAGENTA + "CALCY 1.0" + colorama.Fore.RESET)
        print (colorama.Fore.MAGENTA + "Type 'help' to view a list of commands." + colorama.Fore.RESET)
        cmd = input(colorama.Fore.CYAN + "$>> " + colorama.Fore.RESET)
        if cmd == "help":
            help.help()
        elif cmd == "add":
            a = (colorama.Fore.GREEN + "Type a number: " + colorama.Fore.RESET)
            b = (colorama.Fore.GREEN + "Type a number: " + colorama.Fore.RESET)
            d = calcym.add(a,b)
            e = str(d)
            print (e)
        else:
            print (colorama.Fore.RED + "ERROR: WRONG COMMAND" + colorama.Fore.RESET)
            print (colorama.Fore.RED + "RUNTIME ERROR" + colorama.Fore.RESET)
コード例 #4
0
def main():
    while (1):

        usr_inp = raw_input(">>>")

        if usr_inp == "":
            usr_inp = raw_input(">>>")

        elif usr_inp == "exit" or usr_inp == "quit":
            quit()

        elif usr_inp == "help":
            help()

        elif usr_inp == "clear":
            os.system("clear")
            main()

        elif usr_inp == "stream":
            stream()

        else:
            print("tweet_stream_analysis: " + usr_inp +
                  " : command not recognised")
            main()
コード例 #5
0
ファイル: menu.py プロジェクト: Ro9ueAdmin/Brutus
def menu():
	initialize()
	while 1:
		usr_inp=raw_input("brutus>")

		if usr_inp=="":
			usr_inp=raw_input("brutus>")

		elif usr_inp=="quit" or usr_inp=="exit":
			quit()

		elif usr_inp=="help":
			print("\n")
			help()	

		elif usr_inp=="clear":
			os.system("clear")
		
		elif usr_inp=="ssh":
			ssh_brute()

		elif usr_inp=="ftp":
			ftp_brute()

		elif usr_inp=="smtp":
			smtp()

		elif usr_inp=="facebook":
			facebook_brute()

		elif usr_inp=="twitter":
			twitter_brute()

		else:
			print(usr_inp+": command not recognised ~brutus")
コード例 #6
0
ファイル: task.py プロジェクト: zhanghonged/0911
def exect(minfo,ccc):
  if len(sys.argv) > 1:
    if sys.argv[1] == '--help' and len(sys.argv) == 2:
      print help.help()
    if sys.argv[1] == '--version' and len(sys.argv) == 2:
      ver=help.version()
      print "version is %s" %ver
    for j,k in minfo.items():
      user=j.split(':')[0]
      host=j.split(':')[1]
      port=int(j.split(':')[2])
      password=k
      if sys.argv[1] in ['--help','--version'] and len(sys.argv) == 2:
        pass
      elif sys.argv[1] == 'run' and len(sys.argv) == 3:
        print 'exec host is                                                %s ' %host
        print sys.argv[1:]
        date=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        log='%s %s start run command:' %(date,host)
        addlog.wlog(log)
        r=run_cmd(user,password,host,port,sys.argv[2])
        r.run()
      elif sys.argv[1] == 'put' and len(sys.argv) == 4:
        print 'exec host is                                                %s ' %host
        print sys.argv[1:]
        date=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        log='%s %s start put' %(date,host)
        addlog.wlog(log)
        addlog.wlog(sys.argv[1:])
        p=uad(user,password,host,port,sys.argv[2],sys.argv[3])
        p.tran_put()
      elif sys.argv[1] == 'get' and len(sys.argv) == 4:
        print 'exec host is                                                %s ' %host
        print sys.argv[1:]
        date=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        log='%s %s start get' %(date,host)
        addlog.wlog(log)
        addlog.wlog(sys.argv[1:])
        p=uad(user,password,host,port,sys.argv[2],sys.argv[3])
        p.tran_get()
      else:
        print 'Is Wrong,Please input again'
  else:
    for j,k in minfo.items():
      user=j.split(':')[0]
      host=j.split(':')[1]
      port=int(j.split(':')[2])
      password=k
      print 'exec host is                                                %s ' %host
      date=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
      log='%s %s start:' %(date,host)
      addlog.wlog(log)
      r=run_cmd(user,password,host,port,ccc)
      r.run()
コード例 #7
0
def get_input(board, level):
    move = util.key_pressed()
    row = playerindex_row(board)
    col = playerindex_col(board)
    if move == "d":
        if board[row][col + 1] == "O":
            return 1
        elif board[row][col + 1] == "E":
            fight.fight_sys(level)
            board[row][col] = " "
            board[row][col + 1] = "X"
        elif board[row][col + 1] == " ":
            board[row][col] = " "
            board[row][col + 1] = "X"
        elif board[row][col + 1] == "S":
            shop.shop(level)
    elif move == "a":
        if board[row][col - 1] == " ":
            board[row][col] = " "
            board[row][col - 1] = "X"
        elif board[row][col - 1] == "E":
            fight.fight_sys(level)
            board[row][col] = " "
            board[row][col - 1] = "X"
        elif board[row][col - 1] == "S":
            shop.shop(level)
    elif move == "s":
        if board[row + 1][col] == " ":
            board[row][col] = " "
            board[row + 1][col] = "X"
        elif board[row + 1][col] == "E":
            fight.fight_sys(level)
            board[row][col] = " "
            board[row + 1][col] = "X"
        elif board[row + 1][col] == "S":
            shop.shop(level)
    elif move == "w":
        if board[row - 1][col] == " ":
            board[row][col] = " "
            board[row - 1][col] = "X"
        elif board[row - 1][col] == "E":
            fight.fight_sys(level)
            board[row][col] = " "
            board[row - 1][col] = "X"
        elif board[row - 1][col] == "S":
            shop.shop(level)
    elif move == "h":
        help.help()
    elif move == "i":
        inventory_sys.inventory()
    elif move == "q":
        util.clear_screen()
        sys.exit()
    return 0
コード例 #8
0
def KatanaCheckActionGlobalCommands(action):
    if action[:len(EXIT)] == EXIT or action[:len(EXIT)] == EXIT_SHORT: exit()
    elif action[:len(HELP)] == HELP or action[:len(HELP_SHORT)] == HELP_SHORT:
        help.help()
    elif action[:len(UPDATE)] == UPDATE or action[:len(UPDATE_SHORT
                                                       )] == UPDATE_SHORT:
        updatekatana.update()
    elif action[:len(CLEAR)] == CLEAR or action[:len(CLEAR_SHORT
                                                     )] == CLEAR_SHORT:
        subprocess.call('clear', shell=True)
    else:
        Desing.Helper()
コード例 #9
0
ファイル: menu.py プロジェクト: R34prZ/rock-paper-scissor
def menu():

    # so i'm also defining the score variable here in order to try to save the score even after quiting to the menu

    print("-" * 50)
    print("Nice! You can choose:")
    print("HELP, START, QUIT, SCORE")
    print("-" * 50)

    global HINTS
    HINTS = [
        "If you type anything other than Y or N in game you can continue playing.",
        "Don't underestimate the computer...it starts with ties...",
        "I don't really know how to make a good score option lol",
        "I made a score thingy hehe boi",
        "You can type MENU to go back to the...ãhhh...menu? ",
        "Actually typing MENU doesn't really work lol",
        "Don't use the score option before setting a name",
        "You can type the commands in lower case",
        "Actually, the menu command now works hehe"
    ]

    p_choice = str(input("What you choose? "))

    if p_choice.lower() == "help":
        help.help()

    elif p_choice.lower() == "start":
        print("HINT:" + " " + choice(HINTS))
        start.start()

    elif p_choice.lower() == "quit":
        print("Quitting to main panel...")
        print("HINT:" + " " + choice(HINTS))
        sleep(0.5)

    elif p_choice.lower() == "score":
        if score.player_score > 0:
            print("Ok computing the score...")
            sleep(1)
            print(f"{start.name} score is {score.player_score}")
            print("Going back to menu...")
            sleep(1)
            menu()
        else:
            print("You don't have a score yet, try that after playing!")
            sleep(0.5)
            print("Going back to menu...")
            sleep(0.5)
            menu()
コード例 #10
0
 def __init__(self, parent, presenter, config, icons, **kwargs):
     wx.MiniFrame.__init__(self, parent,-1, 'Compare mass spectra...', size=(-1, -1), 
                           style=wx.DEFAULT_FRAME_STYLE & ~wx.RESIZE_BORDER)
     
     self.parent = parent
     self.presenter = presenter
     self.config = config
     self.icons = icons
     
     self.help = help()
     
     self.currentItem = None
     self.kwargs = kwargs   
     self.current_document = self.kwargs['current_document']
     self.document_list = self.kwargs['document_list']
             
     # make gui items
     self.makeGUI()
                   
     self.Centre()
     self.Layout()
     self.SetFocus()
     
     # bind
     wx.EVT_CLOSE(self, self.onClose)
     self.Bind(wx.EVT_CHAR_HOOK, self.OnKey)
コード例 #11
0
ファイル: control.py プロジェクト: cldog/cldog-backdoor
def control():
    func=raw_input('[cldog] ^_^ ')
    type(func)
    if func == ':proxy':
        proxy.netSet()
    if func == ':set':
        set.set()
    if func ==':help':
        help.help()
    if func == ':shell':
        shell.shell()
    if func == ':sql-set':
        sqlset.sqlSet()
    if func == ':sql':
        sql.sql()
    if func == ':exit':
        exit(0)
コード例 #12
0
def controller(actionInput, player, welt):
    if actionInput == "north":
        nextPlaceId = player.currentPlace.north[1]
        actions.go(nextPlaceId, player, welt)
    elif actionInput == "east":
        nextPlaceId = player.currentPlace.east[1]
        actions.go(nextPlaceId, player, welt)
    elif actionInput == "south":
        nextPlaceId = player.currentPlace.south[1]
        actions.go(nextPlaceId, player, welt)
    elif actionInput == "west":
        nextPlaceId = player.currentPlace.west[1]
        actions.go(nextPlaceId, player, welt)
    elif actionInput == "help":
        help()
    else:
        print "Ich befuerchte das geht nicht?!"
コード例 #13
0
ファイル: intigos.py プロジェクト: intigos/intigoscli
def main():
    authenticate()
    if len(sys.argv) <= 1:
        help();
        return
    cmd = sys.argv[1]
    if cmd in COMMANDS:
      try:
        COMMANDS[cmd]()
      except ConnectionError:
        print "intigos: There was an error contacting the server. Try again in a few moments"
      except HttpServerError, e:
        print "intigos: There was an error contacting the server. Try again in a few moments"
        if DEBUG:
          print json.loads(e.response.text)['traceback']
      except HttpClientError, e:
        if e.response.status_code == 401:
          print "intigos: You are not allowed to see this information."
コード例 #14
0
ファイル: bpmain.py プロジェクト: vesellov/bitdust.devel
def help():
    """
    Same thing, calls ``p2p.help.help()`` to show detailed instructions.
    """
    try:
        import help
        return help.help()
    except:
        return ''
コード例 #15
0
ファイル: __init__.py プロジェクト: willingc/frescobaldi
 def event(self, ev):
     if ev == QKeySequence.HelpContents:
         help.help("search_replace")
         ev.accept()
         return True
     elif ev.type() == QEvent.KeyPress:
         modifiers = int(ev.modifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
         if ev.key() == Qt.Key_Tab and modifiers == 0:
             # prevent Tab from reaching the View widget
             self.window().focusNextChild()
             ev.accept()
             return True
         elif ev.key() == Qt.Key_Backtab and modifiers & ~Qt.SHIFT == 0:
             # prevent Tab from reaching the View widget
             self.window().focusPreviousChild()
             ev.accept()
             return True
     return super(Search, self).event(ev)
コード例 #16
0
def handle_message(event):
    if (event.message.text == "おみくじ" or event.message.text == "おみくじをひく"):
        omikuji(event, line_bot_api)
    elif (event.message.text == '闇鍋ガチャ' or event.message.text == '闇鍋'):
        yaminabe(event, line_bot_api)
    elif (event.message.text == '参拝' or event.message.text == 'デバック神社'):
        debugjinja(event, line_bot_api)
    elif (event.message.text == 'ヘルプ'):
        help(event, line_bot_api)
    elif (event.message.text == 'qiita'):
        qiita(event, line_bot_api)

    else:
        '''
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=event.message.text)
        )
        '''
        command(event, line_bot_api)
コード例 #17
0
def MainMenu():
    user = "******"
    while True:
        print("What Should I Do?")
        print("1. ls")
        print("2. nmap")
        print("3. ssh")
        print("4. help")
        print(">")
        userinput = input()
        userinput = error_checking(userinput, 4)
        if userinput == 1:
            ls()
        if userinput == 2:
            nmap()
        if userinput == 3:
            if ssh() == True:
                return
        if userinput == 4:
            help.help(2)
コード例 #18
0
ファイル: main.py プロジェクト: kyohei-horikawa/MyDict
def handler():
    if len(sys.argv) > 1:
        # myDict init
        if sys.argv[1] == 'init':
            init.initialize()
        # myDict add
        elif sys.argv[1] == 'add' or sys.argv[1] == '-a':
            add.add()

        elif sys.argv[1] == 'show' or sys.argv[1] == '-s':
            # myDict show
            if len(sys.argv) == 2:
                show.showAllCategories()

            elif len(sys.argv) == 3:
                # myDict show all
                if sys.argv[2] == 'all':
                    show.showAll()
                # myDict show <category>
                else:
                    show.showItemsInCategory(sys.argv[2])
            # myDict show <category> <name>
            elif len(sys.argv) == 4:
                show.showItem(sys.argv[2], sys.argv[3])
        # myDicy help
        elif sys.argv[1] == 'help' or sys.argv[1] == '-h':
            help.help()

        # myDict find <item>
        elif sys.argv[1] == 'find' or sys.argv[1] == '-f':
            find.find(sys.argv[2])

        # myDict export
        elif sys.argv[1] == 'export' or sys.argv[1] == '-e':
            if len(sys.argv) == 2:
                # myDict export all
                if sys.argv[2] == 'all':
                    export.exportAll()
                # myDict export <category>
                else:
                    export.exportSelectedItem()
コード例 #19
0
ファイル: task_thread.py プロジェクト: zhanghonged/0911
def exect(minfo,ccc):
  if len(sys.argv) > 1:
    if sys.argv[1] == '--help' and len(sys.argv) == 2:
      print help.help()
    if sys.argv[1] == '--version' and len(sys.argv) == 2:
      ver=help.version()
      print "version is %s" %ver
    for j,k in minfo.items():
      user=j.split(':')[0]
      host=j.split(':')[1]
      port=int(j.split(':')[2])
      password=k
      if sys.argv[1] in ['--help','--version'] and len(sys.argv) == 2:
        pass
      elif sys.argv[1] == 'run' and len(sys.argv) == 3:
        print 'exec host is                                                %s ' %host
        print sys.argv[1:]
        r=run_cmd(user,password,host,port,sys.argv[2])
        r.start()
      elif sys.argv[1] == 'put' and len(sys.argv) == 4:
        print 'exec host is                                                %s ' %host
        print sys.argv[1:]
        p=tran_put(user,password,host,port,sys.argv[2],sys.argv[3])
        p.start()
      elif sys.argv[1] == 'get' and len(sys.argv) == 4:
        print 'exec host is                                                %s ' %host
        print sys.argv[1:]
        p=tran_get(user,password,host,port,sys.argv[2],sys.argv[3])
        p.start()
      else:
        print 'Is Wrong,Please input again'
  else:
    for j,k in minfo.items():
      user=j.split(':')[0]
      host=j.split(':')[1]
      port=int(j.split(':')[2])
      password=k
      print 'exec host is                                                %s ' %host
      r=run_cmd(user,password,host,port,ccc)
      r.start()
コード例 #20
0
ファイル: daVinci.py プロジェクト: Ritvik19/daVinci
def make_reply(msg):
    reply = None
    mode = None
    if msg is not None:
        msg = msg.split()
        print(msg)
        if msg[0] == '/help':
            reply = help.help()
            mode = 0
        elif msg[0] == '/woof':
            reply = webscraping.woof()
            mode = 2
        elif msg[0] == '/cric':
            reply = webscraping.cricbuzz()
            mode = 0
        elif msg[0] == '/wiki':
            reply = webscraping.wiki(' '.join(msg[1:]))
            mode = 0
        elif msg[0] == '/dict':
            reply = webscraping.cambridge(' '.join(msg[1:]))
            mode = 0
        elif msg[0] == '/hastebin':
            reply = webscraping.haste(' '.join(msg[1:]))
            mode = 0
        elif msg[0] == '/code':
            reply = webscraping.stackoverflow(' '.join(msg[1:]))
            mode = 0
        elif msg[0] == '/apod':
            reply = webscraping.apod()
            mode = 3 if len(reply) == 2 else 0
        elif msg[0] == '/pic':
            reply = webscraping.upsplash(' '.join(msg[1:]))
            mode = 2
        elif msg[0] == '/qod':
            reply = webscraping.theysaidso()
            mode = 3
        elif msg[0] == '/weather':
            reply = webscraping.weather(' '.join(msg[1:]))
            mode = 0
        elif msg[0] == '/eval':
            reply = core.pyeval(' '.join(msg[1:]))
            mode = 0
        elif msg[0] == '/medium' or re.search(r'https://link\.medium\.com/.*', ' '.join(msg)):
            reply = webscraping.medium(' '.join(msg[1:]))
            mode = 0
        elif msg[0] == '/inspyre':
            reply = datascience.inspyre(' '.join(msg[1:]))
            mode = 0
        else:
            reply = chat.reply(' '.join(msg))
            mode = 0
    return reply, mode
コード例 #21
0
ファイル: widget.py プロジェクト: WedgeLeft/frescobaldi
 def __init__(self, dockwidget):
     super(QuickInsert, self).__init__(dockwidget)
     self._dockwidget = weakref.ref(dockwidget)
     # filled in by ButtonGroup subclasses
     self.actionDict = {}
     
     layout = QVBoxLayout()
     self.setLayout(layout)
     layout.setContentsMargins(0, 0, 0, 0)
     
     self.helpButton = QToolButton(
         icon = icons.get("help-contents"),
         autoRaise = True,
         clicked = lambda: help.help(quickinsert_help))
     self.directionLabel = QLabel()
     self.direction = QComboBox()
     self.direction.addItems(['', '', ''])
     self.direction.setItemIcon(0, icons.get("go-up"))
     self.direction.setItemIcon(2, icons.get("go-down"))
     self.direction.setCurrentIndex(1)
     hor = QHBoxLayout()
     hor.setContentsMargins(0, 0, 0, 0)
     hor.addWidget(self.helpButton)
     hor.addWidget(self.directionLabel)
     hor.addWidget(self.direction)
     layout.addLayout(hor)
     
     self.toolbox = QToolBox(self)
     widgets.toolboxwheeler.ToolBoxWheeler(self.toolbox)
     layout.addWidget(self.toolbox)
     
     for cls in (
             articulations.Articulations,
             dynamics.Dynamics,
             spanners.Spanners,
             barlines.BarLines,
         ):
         widget = cls(self)
         self.toolbox.addItem(widget, widget.icon(), '')
     
     app.translateUI(self)
     help.openWhatsThis(self)
     
     # restore remembered current page
     name = QSettings().value("quickinsert/current_tool", "", type(""))
     if name:
         for i in range(self.toolbox.count()):
             if name == self.toolbox.widget(i).__class__.__name__.lower():
                 self.toolbox.setCurrentIndex(i)
                 break
     self.toolbox.currentChanged.connect(self.slotCurrentChanged)
コード例 #22
0
ファイル: config.py プロジェクト: Achifaifa/kirino
  def options(self,restricted):
    """
    Game options menu. 

    This allows modification of the general options, such as key mappings, autosave, etc.

    If the restricted parameter is 1, it hides the options that should not be changed during the game (fog, etc)
    """

    global autosave
    global fog
    while 1: 
      common.version()
      print "Options \n"
      if not self.autosave: print "1.- Autosave [off]"
      if self.autosave:     print "1.- Autosave [on]"
      print "    Saves the character between floors"
      if not self.fog and not restricted:   print "2.- Fog [off]"
      if     self.fog and not restricted:   print "2.- Fog [on]"
      if restricted   and     self.fog:     print "2.- Fog [on] [Locked]"
      if restricted   and not self.fog:     print "2.- Fog [off] [Locked]"
      print "    Hides the dungeon out of view range"
      print "3.- Game over message: %s"%(self.gomsg)
      print "    Message displayed when the game ends"
      print "4.- Key mapping \n"
      print "--"
      print "9.- Help"
      print "0.- Go back"
      print "->",
      opmen=common.getch()
      if opmen=="1": self.autosave=not self.autosave
      if opmen=="2" and not restricted: self.fog=not self.fog
      if opmen=="3": self.gomsg=raw_input("New message?>")
      if opmen=="4": self.keymap(restricted)
      if opmen=="9": help.help()
      if opmen=="0":
        self.saveoptions()
        break
コード例 #23
0
    def choose(
            choice):  #raw data that write(string) prints to the screen as text
        mainWindow.delete(0, END)
        if (choice == ">>> 1"):
            startMenu()
            write("")
            write(">>> You choose: Continue!")

        elif (choice == ">>> 2"):
            startMenu()
            write("")
            write(">>> You choose: New Game!")

        elif (choice == ">>> 3"):
            startMenu()
            write("")
            write(">>> You choose: Load Game!")

        elif (choice == ">>> 4"):
            startMenu()
            write("")
            write(">>> You choose: Settings!")

        elif (choice == ">>> 5"):
            raise SystemExit

        elif (choice == ">>> help"):
            help()
            if choice == ">>> ":
                startMenu()
                write(">>> You choose: help!")
        else:
            startMenu()
            write("")
            if choice != ">>> ":
                write(">>> That is not a valid command!")
            else:
                write("")
コード例 #24
0
ファイル: cli.py プロジェクト: pabloxxl/revi
    def __init__(self, config):
        lg.debug("cli::__init__")
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        self.stdscr.keypad(1)
        curses.curs_set(0)

        self.maxY, self.maxX = self.stdscr.getmaxyx()

        self.MAX_LIST_ITEMS = self.maxY - BOTTOM_OFFSET - 2

        lg.debug("Maximum number for items is " +
                 str(self.MAX_LIST_ITEMS))
        self.MODE = mode.VIM

        hm = config.get("history_max", 5)

        self.browser = config.get("browser", None)
        self.history = history(hm)

        self.currObject = None

        self.msg = None
        self.setMsg("Revi started, config loaded from file, "
                    "word peace achieved")

        self.drawLoading()

        l = listing("", rLimit=self.MAX_LIST_ITEMS)
        if l.ok:
            self.setCurrentObject(l)
        else:
            self.setCurrentObject(error(l.status))

        if self.MODE is mode.VIM:
            self.eval = eval_vim(self.stdscr)
        else:
            # self.eval = eval_emacs(self.stdscr)
            pass

        self.help = help()
コード例 #25
0
ファイル: ~halbrdbot.py プロジェクト: halbrd/halbrdBot
    def MessageStatus(self, msg, status):
        if status == Skype4Py.cmsReceived or status == Skype4Py.cmsSent:
            # I have no idea what this line does other than it makes the bot respond to its own messages, and it only works in private chat
            #if not msg.Sender.Handle in self.blacklist:
            if msg.Body[0] == "!" and msg.Sender.Handle != "everythingbot":
                print "[" + str(datetime.now(
                ))[:-7] + "] " + msg.Sender.Handle + ": " + msg.Body

            # !help
            if re.match("!help(?!\S)", msg.Body):
                msg.Chat.SendMessage(help())

            # !ping
            elif re.match("!ping(?!\S)", msg.Body):
                msg.Chat.SendMessage(ping())

            # !members
            elif re.match("!members(?!\S)", msg.Body):
                msg.Chat.SendMessage(members(msg.Chat.Members))

            # !profile
            elif re.match("!profile(?!\S)", msg.Body):
                try:
                    skypeName = msg.Body[9:]
                    msg.Chat.SendMessage(profile(skypeName, msg.Chat.Members))
                except IndexError:
                    msg.Chat.SendMessage(
                        "Skype username required for profile lookup.")

            # !orangecrush
            # If you're reading this on the Github repo, congratulations on being the first to figure out that it's been public all along.
            elif re.match("!orangecrush(?!\S)", msg.Body):
                msg.Chat.SendMessage("!orangecrush")

            # !lenny
            elif re.match("!lenny(?!\S)", msg.Body):
                msg.Chat.SendMessage(self._lenny)

            # !friendcodes
            elif re.match("!friendcodes(?!\S)", msg.Body) or re.match(
                    "!fc(?!\S)", msg.Body):
                msg.Chat.SendMessage(friendcodes())

            # !gostats
            elif re.match("!gostats(?!\S)", msg.Body):
                msg.Chat.SendMessage("http://csgo-stats.com/" + msg.Body[9:])

            # !tableflip
            elif re.match("!tableflip(?!\S)", msg.Body):
                msg.Chat.SendMessage(self._tableflip)

            # !tableset
            elif re.match("!tableset(?!\S)", msg.Body):
                msg.Chat.SendMessage(self._tableset)

            # !coinflip
            elif re.match("!coinflip(?!\S)", msg.Body):
                msg.Chat.SendMessage(coinflip())

            # URL titles

            # This is the opt-into title code.
            #elif re.match("!title(?!\S)", msg.Body):
            #    if re.match('!title http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE):
            #        url = re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE)
            #        msg.Chat.SendMessage(url_get(url.group(0)))
            #    else:
            #        msg.Chat.SendMessage("Invalid URL.")

            # This is the opt-out of title code.
            elif re.search(
                    'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
                    msg.Body, re.IGNORECASE) and not re.search(
                        "!nt(?!\S)",
                        msg.Body) and msg.Sender.Handle != "everythingbot":
                url = re.search(
                    'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
                    msg.Body, re.IGNORECASE)
                msg.Chat.SendMessage(url_get(url.group(0)))

            # !removebot
            elif re.match("!removebot(?!\S)", msg.Body):
                if removebot(msg.Sender.Handle):
                    msg.Chat.Leave()

            # !restartbot
            elif re.match("!restartbot(?!\S)", msg.Body):
                if removebot(msg.Sender.Handle):
                    msg.Chat.SendMessage("Restarting bot.")
                    execfile("~halbrdbot.py")
                    sys.exit()

            # !twitch (channel)
            # !gostats
            elif re.match("!twitch(?!\S)", msg.Body):
                # msg.Chat.SendMessage("http://twitch.tv/" + msg.Body[8:])
                msg.Chat.SendMessage(twitch(msg.Body[8:]))

            # !requestfunction (string)
            #elif re.match("!requestfunction(?!\S)", msg.Body):
            #    msg.Chat.SendMessage(requestfunction(msg.Sender.Handle, msg.Body[17:]))

            #elif msg.Body == "!chatname":
            #    msg.Chat.SendMessage(msg.Chat.Name)

            # !hug
            elif re.match("!hug(?!\S)",
                          msg.Body) and msg.Sender.Handle != "everythingbot":
                msg.Chat.SendMessage(hug(msg.Sender.FullName, msg.Body[5:]))

            # !bothug
            elif re.match("!bothug(?!\S)", msg.Body):
                msg.Chat.SendMessage(bothug(msg.Body[8:]))

            # !blacklist
            #elif re.match("!blacklist(?!\S)", msg.Body):
            #    msg.Chat.SendMessage(blacklist(msg.Sender.Handle, msg.Body[11:]))

            # !strats
            elif re.match("!strats(?!\S)", msg.Body):
                msg.Chat.SendMessage(strats(msg.Body[8:]))

            # !lwc
            elif re.match("!lwc(?!\S)", msg.Body):
                msg.Chat.SendMessage(
                    "Literally who cares.\nhttp://lynq.me/lwc.mp4")

            # lmao
            # Keep this as the last thing that gets checked
            elif re.search(
                    "l+ *m+ *a+ *o+", msg.Body,
                    re.IGNORECASE) and msg.Sender.Handle != "everythingbot":
                msg.Chat.SendMessage("ayyy")
コード例 #26
0
ファイル: intigos.py プロジェクト: intigos/intigos-cla
def main():
  STATES = {'D':('Development',bcolors.WARNING), '':("Unknown",bcolors.FAIL)}
  if len(sys.argv) <= 1:
    help();
    return
  app = sys.argv[1]
  if app == "pack":
    print "Packing project into game.zip..."
    pack()
  elif app == "validate":
    verify_game_auth()
    print "Everything seems to be ok."
  elif app == "listgames":
    print "Listing your games:"
    print 
    games = get_all_games()
    for game in games:
      print bcolors.HEADER + game['name'] + bcolors.ENDC + ":"
      print "  Game Id : " + game['game_id']
      state = STATES[game['status']]
      print "  Status  : " + state[1] + state[0] + bcolors.ENDC
      print 
  elif app == "auth":
    update_tokens()
    return
  elif app == "submit":
    submit()
  elif app == "wait":
    STATES = {'U':('Pending',bcolors.OKBLUE), 'T':("Processed",bcolors.OKGREEN), 'E':("Error",bcolors.FAIL)}
    collect = {}
    for sub in get_submited():
      if sub['game']['key'] in collect:
        collect[sub['game']['key']].append(sub)
      else:
        collect[sub['game']['key']] = [ sub ]
    for key in collect.keys():
      game = collect[key]
      print bcolors.HEADER + "%s" % (game[0]['game']['name']) + bcolors.ENDC + ":"

      print "  Game ID : %s" % game[0]['game']['key']
      for ver in game[:5]:
        print
        print ("  Submited on %s by" + bcolors.OKGREEN + " %s " + bcolors.ENDC) % (ver['submission_date'].replace("T"," "), ver['user']['username'])
        state = STATES[ver['status']]
        print "      Status : " + state[1] + state[0] + bcolors.ENDC
        print "      Digest : " + ver['digest']
  elif app == "start":
    if len(sys.argv) < 3:
      print "You must specify a project name.\n\nusage: intigos start <project name>"
    start(sys.argv[2])
    return;
  elif app == "run":
    try:
      opts, args = getopt.getopt(sys.argv[2:], 'a:,', ['addr='])
    except getopt.GetoptError, err:
      print str(err) # will print something like "option -a not recognized"
      sys.exit(2)
    addr = 'localhost:8000'
    for o, a in opts:
      if o in ("-a", "--addr"):
        addr = a
    run(addr=addr)
コード例 #27
0
ファイル: contextmenu.py プロジェクト: WedgeLeft/frescobaldi
 def help():
     import help
     help.help("music_view")
コード例 #28
0
ファイル: __init__.py プロジェクト: aspiers/frescobaldi
 def showHelp(self):
     help.help(self.pagelist.currentItem().help)
コード例 #29
0
 def on_btn_help_clicked(self):
     help.help()
コード例 #30
0
            elif pp.pay():
                print("Payment successfull")
            else:
                print(
                    "Payment unsuccessfull! Enter valid usernames or amount!")
        elif n == 5:  #receive
            if login_status:  #works only if user is logged in
                rec.receive()
            else:
                print("Please login")
        elif n == 6:  #Converting amount
            if login_status:  #works only if user is logged in
                ct.convert()
            else:
                print("Please login")
        elif n == 7:  #Display conversion rates
            if login_status:  #works only if user is logged in
                dr.display()
            else:
                print("Please login")
        elif n == 8:  #help and FAQs
            if login_status:  #works only if user is logged in
                hf.help()
            else:
                print("Please login")
        elif n == 9:  #log out and exit the program
            print("Successfully logged out! Thank you!")
            break
        else:
            print("Enter valid number")
コード例 #31
0
def initialMenu(screen, clock):
    background = (255, 255, 255)
    breakflag = 0
    playBgm(0)

    # 图片及位置
    background = pygame.image.load(path("res/bg/bg_main.png")).convert()  #背景图
    title = pygame.image.load(path("res/pic/title.png")).convert_alpha()  #标题
    titlePos = (340, 100)
    startButton = pygame.image.load(
        path("res/button/start.png")).convert_alpha()  #开始游戏
    startPos0 = (540, 345)
    startPos1 = (540, 340)
    handbookButton = pygame.image.load(
        path("res/button/handbook.png")).convert_alpha()  #图鉴
    handbookPos0 = (400, 445)
    handbookPos1 = (400, 440)
    helpButton = pygame.image.load(
        path("res/button/help.png")).convert_alpha()  #帮助文档
    helpPos0 = (400, 545)
    helpPos1 = (400, 540)
    settingButton = pygame.image.load(
        path("res/button/setting.png")).convert_alpha()  #设置
    settingPos0 = (680, 445)
    settingPos1 = (680, 440)
    quitButton = pygame.image.load(
        path("res/button/quit.png")).convert_alpha()  #退出游戏
    quitPos0 = (680, 545)
    quitPos1 = (680, 540)
    startPos = startPos0
    handbookPos = handbookPos0
    helpPos = helpPos0
    settingPos = settingPos0
    quitPos = quitPos0

    while True:

        for event in pygame.event.get():
            x, y = pygame.mouse.get_pos()
            #   按键位置移动
            if x > startPos0[0] and x < startPos0[0] + startButton.get_width() \
                    and y > startPos0[1] and y < startPos0[1] + startButton.get_height():
                startPos = startPos1
            else:
                startPos = startPos0

            if x > handbookPos0[0] and x < handbookPos0[0] + handbookButton.get_width() \
                    and y > handbookPos0[1] and y < handbookPos0[1] + handbookButton.get_height():
                handbookPos = handbookPos1
            else:
                handbookPos = handbookPos0

            if x > helpPos0[0] and x < helpPos0[0] + helpButton.get_width() \
                    and y > helpPos0[1] and y < helpPos0[1] + helpButton.get_height():
                helpPos = helpPos1
            else:
                helpPos = helpPos0

            if x > settingPos0[0] and x < settingPos0[0] + settingButton.get_width() \
                    and y > settingPos0[1] and y < settingPos0[1] + settingButton.get_height():
                settingPos = settingPos1
            else:
                settingPos = settingPos0

            if x > quitPos0[0] and x < quitPos0[0] + quitButton.get_width() \
                    and y > quitPos0[1] and y < quitPos0[1] + quitButton.get_height():
                quitPos = quitPos1
            else:
                quitPos = quitPos0

            #   退出游戏
            if event.type == pygame.QUIT:
                sys.exit()
                breakflag = 1

            if event.type == MOUSEBUTTONDOWN:
                if x > startPos0[0] and x < startPos0[0] + startButton.get_width() \
                        and y > startPos0[1] and y < startPos0[1] + startButton.get_height():
                    selectMode(screen, clock)
                    breakflag = 1
                    # here to start the game function

                if x > handbookPos0[0] and x < handbookPos0[0] + handbookButton.get_width() \
                        and y > handbookPos0[1] and y < handbookPos0[1] + handbookButton.get_height():
                    from handbook import handbook
                    handbook(screen, clock)
                    # here to the handbook function

                if x > helpPos0[0] and x < helpPos0[0] + helpButton.get_width() \
                        and y > helpPos0[1] and y < helpPos0[1] + helpButton.get_height():
                    from help import help
                    help(screen, clock)
                    # here to start the help function

                if x > settingPos0[0] and x < settingPos0[0] + settingButton.get_width() \
                        and y > settingPos0[1] and y < settingPos0[1] + settingButton.get_height():
                    from settings import settings
                    screen, isBgmOn = settings(screen, clock, False)
                    settings(screen, clock, True)
                    # here to the setting function

                elif x > quitPos0[0] and x < quitPos0[0] + quitButton.get_width() \
                        and y > quitPos0[1] and y < quitPos0[1] + quitButton.get_height():
                    # print('game ended!')
                    sys.exit()
        # 填充背景和内容
        screen.blit(background, (0, 0))
        screen.blit(title, titlePos)
        screen.blit(startButton, startPos)
        screen.blit(handbookButton, handbookPos)
        screen.blit(helpButton, helpPos)
        screen.blit(settingButton, settingPos)
        screen.blit(quitButton, quitPos)
        # 说明文字
        # screen.blit(font.render("用上下左右键来控制", True, (166, 100, 30)), (300, 50))
        # 更新画面
        pygame.display.update()
        # 帧率
        clock.tick(40)
        if breakflag == 1:
            break
コード例 #32
0
ファイル: cli.py プロジェクト: pabloxxl/revi
 def performHelp(self):
     """Enter help"""
     self.setCurrentObject(help())
コード例 #33
0
ファイル: intigos.py プロジェクト: intigos/intigos-cla
        print
        print ("  Submited on %s by" + bcolors.OKGREEN + " %s " + bcolors.ENDC) % (ver['submission_date'].replace("T"," "), ver['user']['username'])
        state = STATES[ver['status']]
        print "      Status : " + state[1] + state[0] + bcolors.ENDC
        print "      Digest : " + ver['digest']
  elif app == "start":
    if len(sys.argv) < 3:
      print "You must specify a project name.\n\nusage: intigos start <project name>"
    start(sys.argv[2])
    return;
  elif app == "run":
    try:
      opts, args = getopt.getopt(sys.argv[2:], 'a:,', ['addr='])
    except getopt.GetoptError, err:
      print str(err) # will print something like "option -a not recognized"
      sys.exit(2)
    addr = 'localhost:8000'
    for o, a in opts:
      if o in ("-a", "--addr"):
        addr = a
    run(addr=addr)
  elif app == "help":
    help()
    return
  else:
    help()
    return
    
  
if __name__ == '__main__':
  main()
コード例 #34
0
def KatanaCheckActionGlobalCommands(action):
	if     action[:len(EXIT)]        == EXIT   or action[:len(EXIT)]        == EXIT_SHORT  : exit()
	elif   action[:len(HELP)]        == HELP   or action[:len(HELP_SHORT)]  == HELP_SHORT  : help.help()
	elif   action[:len(UPDATE)]      == UPDATE or action[:len(UPDATE_SHORT)]== UPDATE_SHORT: updatekatana.update()
	elif   action[:len(CLEAR)]       == CLEAR  or action[:len(CLEAR_SHORT)] == CLEAR_SHORT : subprocess.call('clear', shell=True)
	else: Desing.Helper()
コード例 #35
0
ファイル: main.py プロジェクト: skairunner/lunabot
    is_specced = False
    is_willpowered = False
    while args[0] in ["spec", "wp"]:
        if args[0] == "spec":
            is_specced = True
        elif args[0] == "wp":
            is_willpowered = True
        args = args[1:]

    pool = int(args[0])
    args = args[1:]
    await handle_roll(ctx, pool, args, is_specced, is_willpowered)


rollspec_decorator = help(
    "[dicepool] [difficulty=6] [comment...]", "Roll with specialization",
    "Roll with specialization, counting 10s as two successes. If difficulty is not specified, defaults to 6. The comment is optional."
)


@rollspec_decorator
@client.command(name='rs')
@handle_error
async def rollspec_short(ctx, pool: int, *args):
    await handle_roll(ctx, int(pool), args, True)


@rollspec_decorator
@client.command(name='rollspec')
@handle_error
async def rollspec_long(ctx, pool: int, *args):
    await handle_roll(ctx, int(pool), args, True)
コード例 #36
0
ファイル: terminal.py プロジェクト: MachineAi/EMIT
def parse_args(coordinator, arg):

    if ''.join(arg).strip() != '':
        if arg[0] == 'help':
            if len(arg) == 1:
                elog.info(h.help())
            else:
                elog.info(h.help_function(arg[1]))

        elif arg[0] == 'add' :
            if len(arg) == 1:
                elog.info(h.help_function('add'))
            else:
                coordinator.add_model(arg[1])

        elif arg[0] == 'remove':
            if len(arg) == 1:
                elog.info(h.help_function('remove'))
            else:
                coordinator.remove_model_by_id(arg[1])

        elif arg[0] == 'link':
            if len(arg) != 5:
                elog.info(h.help_function('link'))
            else:
                coordinator.add_link(arg[1],arg[2],arg[3],arg[4])

        elif arg[0] == 'showme':
            if len(arg) == 1:
                elog.info(h.help_function('showme'))
            else:
                coordinator.get_configuration_details(coordinator, arg[1])

        elif arg[0] == 'connect_db':
            if len(arg) == 1:
                elog.info(h.help_function('connect_db'))
            else:
                coordinator.connect_to_db(arg[1:])

        elif arg[0] == 'default_db':
            if len(arg) == 1:
                elog.info(h.help_function('default_db'))
            else:
                coordinator.set_default_db(arg[1:])

        elif arg[0] == 'run':
            elog.info('Running Simulation in Feed Forward Mode')
            coordinator.run_simulation()

        elif arg[0] == 'load':
            if len(arg) == 1:
                elog.info(h.help_function('load'))
            else:
                coordinator.load_simulation(arg[1:])

        elif arg[0] == 'db':
            if len(arg) == 1:
                elog.info(h.help_function('db'))
            else:
                coordinator.show_db_results(arg[1:])



        #todo: show database time series that are available

        elif arg[0] == 'info': print h.info()

        else:
            print 'Command not recognized.  Type "help" for a complete list of commands.'
コード例 #37
0
ファイル: create_man.py プロジェクト: zzmjohn/i-pi
Creates a latex file, corresponding to a section of the manual, for each of
the classes specified in help.py. It uses help.py to generate information 
about the tags for each class, and will include cross-references so that the
title of each tag corresponding to a different class will also be a hyperlink
in the manual to the section corresponding to that class.

Note that any new input class type must be added to the objects 
dictionary in help.py and the latex help file must be added to the end of 
the manual.lyx file for it to be included in the automatic help generation.

Also creates an xml file with the full list of all the tags.
"""

import os
from help import help, objects
from help_list import help_list, list_objects

if not os.path.exists("input_docs"):
    os.mkdir("input_docs")

help(xml=True, prefix="manual")
for opt in objects:
    help(latex=True,
         levels=1,
         option=opt,
         prefix=("input_docs/" + opt),
         standalone=False)
for opt in list_objects:
    help_list(option=opt, prefix=("input_docs/" + opt), standalone=False)
コード例 #38
0
def start():
    """Sar analyzeer App"""
    st.title = "SAR Analyzer"
    menu = ["Login", "Signup", "Help"]
    choice = st.sidebar.selectbox("Menu", menu)
    sql_stuff.create_tables()
    config_c = helpers.configuration({})

    if choice == "Help":
        help.help()

    elif choice == "Login":
        username = st.sidebar.text_input("Username")
        password = st.sidebar.text_input("Password", type='password')
        if st.sidebar.checkbox("Login"):
            if sql_stuff.login_user(username, password):
                upload_dir = f'{Config.upload_dir}/{username}'
                os.system(f'mkdir -p {upload_dir}')
                sar_files = os.listdir(upload_dir)
                st.sidebar.success(f"Logged in as {username}")

                col1, col2 = st.columns(2)
                config_c.update_conf({
                    'username': username,
                    'upload_dir': upload_dir,
                    'sar_files': sar_files,
                    'cols': [col1, col2]
                })
                if sql_stuff.get_role(username) == "admin":
                    task = st.sidebar.selectbox("Tasks", [
                        "Analyze Data", "Manage Sar Files", "DB Management",
                        "Redis Management", "TODO", "Self Service",
                        "User Management", "Info"
                    ])
                else:
                    task = st.sidebar.selectbox("Tasks", [
                        "Analyze Data", "Manage Sar Files", "Self Service",
                        "Info"
                    ])

                if task == "Manage Sar Files":
                    mng_sar.file_mng(upload_dir, col2, username)
                elif task == "Analyze Data":
                    analyze.analyze(upload_dir, config_c, username)
                elif task == "DB Management":
                    db_mng.db_mgmt(username, col2)
                elif task == "TODO":
                    todo.todo()
                elif task == "Redis Management":
                    try:
                        redis_mng.redis_tasks(col2)
                    except:
                        #st.markdown('Redis server seeems to be offline')
                        ''
                elif task == "Info":
                    info.info()
                    info.usage()
                    info.code()

                elif task == 'Self Service':
                    ss.self_service(username)
                elif task == 'User Management':
                    ss.admin_service()

            else:
                st.warning("You don't exist or your password does not match")
        else:
            st.header("Please login to use this app")
    elif (choice) == "Signup":
        st.subheader("Create an Account")
        new_user = st.text_input("Username")
        new_password = st.text_input("Password", type='password')

        if st.button("Signup"):
            if sql_stuff.add_userdata(new_user, new_password):
                st.success("You have successfully created an valid Account")
                st.info("Goto Login Menu to login")
            else:
                st.warning(f'User {new_user} already exists')
コード例 #39
0
 def on_btn_help_clicked(self):
     ''' '''
     help.help()
コード例 #40
0
    async def commandParser(self, message, globalCall):

        messageContent = message.content.lower()

        # Casino Module
        if (messageContent.startswith(globalCall + "c ")):
            gambleTime = CasinoModule()
            await gambleTime.commandReciever(message)
            return

        # Help message
        if (messageContent == globalCall + "help"):
            myHelp = help()
            await myHelp.myEmbed(message)
            return

        # Convert Currency
        if (messageContent.startswith(globalCall + "currency")):
            newCurrency = currency()
            await newCurrency.currencyConverter(message)
            return

        # Search workshop
        if (messageContent.startswith((globalCall + 'sws'))):
            searchWorkshop = sws()
            await message.channel.send("Searching the workshop. Please wait..."
                                       )
            searchIt = searchWorkshop.theMain(message.content)
            if not searchIt:
                await message.channel.send(
                    "That's a fat error from me dawg. The search came up empty."
                )
                return
            else:
                await message.channel.send(searchIt)
                return

        # Get random Seinfeld quote
        if (messageContent.startswith((globalCall + 'seinfeldme'))):
            getSeinfeldQuote = seinfeldme()
            await getSeinfeldQuote.getQuote(message)
            return

        # Get random ketal quote
        if (messageContent.startswith((globalCall + 'ketalquote'))):
            getKetalQuote = ketalquote()
            await getKetalQuote.getQuote(message)
            return

        # Get random Squidski fact
        if (messageContent.startswith((globalCall + 'squidskifact'))):
            squidFact = squidskifact()
            await squidFact.getQuote(message)
            return

        # Give/Remove Pings role
        if (messageContent.startswith((globalCall + 'pings'))):
            myPings = pings()
            await myPings.changePingRoleState(message)
            return

        # Admin only commands (Administrator only)
        if (((messageContent).split(" "))[0].startswith(globalCall +
                                                        "helpadmin")):
            myAdminCommands = helpadmin()
            await myAdminCommands.checkPerms(message)
            return

        # Purge messages (Administrator Only)
        if (((messageContent).split(" "))[0].startswith(globalCall + "purge")):
            myPurge = purge()
            await myPurge.purger(message)
            return

        # Ping the Pings role (Administrator Only)
        if (messageContent.startswith((globalCall + 'rolepinger'))):
            myPinger = rolepinger()
            await myPinger.pinger(message)
            return

        # Mute a bad user (Administrator Only)
        if (messageContent.startswith((globalCall + 'mute'))):
            myMuter = mute()
            await myMuter.mute_users(message)
            return

        # Checks if is bruh moment
        if (messageContent.startswith((globalCall + 'bruhmoment'))):
            myBruh = bruhmoment()
            await myBruh.isBruhMoment(message)
            return

    # Searches the Steam Workshop via the API
        if (messageContent.startswith((globalCall + 'wtest'))):
            mySAPI = apiworkshopsearch()
            args = message.content.split(" ")
            await mySAPI.requestInfo(message, args[1], " ".join(args[2:]))
            return

        # Pulls a random line from the Source Engine fanfictions
        if (messageContent.startswith((globalCall + 'fanfic'))):
            getFanfic = fanfic()
            await getFanfic.getLine(message)
            return

        # Search VDC
        if (messageContent.startswith((globalCall + 'v'))):
            searchVDC = VDCsearch()
            await searchVDC.searchTheVDC(message)
            return
コード例 #41
0
ファイル: parser.py プロジェクト: flygeneticist/kirino
def parse(words,player,dungeon,config):
  """
  Main parsing function. 

  Splits the string and identifies action, target and options

  Needs a string to be parsed and player, dungeon and config objects.

  Returns an action code and a message if needed.

  0) No action
    Look sentences only return a description of the place
    Empty, weird or non-interpretable sentences return an error string

  1) Move
    11 north
    12 south
    13 east
    14 west
    15 northeast
    16 northwest
    17 southeast
    18 southwest

    19 down (next floor)

  3) "use" actions
    31 use stairs (next floor)

  4) Combat actions
    Pending

  5) Configuration

  6) Help
    61 Help keys (Show key mapping)
    62 General help (Brings the help menu up)

  It evaluates the verb in the first position and the options next
  e.g.: go north, hit zombie, run southeast, walk nw, equip itemname, etc.
  If the first word of the string is not a verb (i.e. I want to walk north) a random generic error message will be returned.
  """

  #puts all the words from the input in a list
  keyw=words.split()
  if len(words)==0:
    return 0, random.choice(errors)+"\n"
  
  #Look for the first word (Verb) in the dictionary
  while 1:
    action=""
    for key,value in dictionary.iteritems():
      for a in value:
        if keyw[0]==a:
          action=key
          break
    break

  #Process the verb
  try:
    if len(action)==0:
      try:
        insistor[keyw[0]]+=1
      except KeyError:
        insistor[keyw[0]]=1
      if insistor[keyw[0]]<=2:
        return 0,random.choice(errors)+" \n"
      if 2<insistor[keyw[0]]<=5:
        return 0,"Still trying to do that? \n"
      if insistor[keyw[0]]>5:
        return 0,"Can't you stop talking about this %s thing? \n"%keyw[0]
    else:
      #Identified movement command, process rest of the string
      if action=="move":
        if keyw[1]=="north" or keyw[1]=="n":  return 11,""
        if keyw[1]=="south" or keyw[1]=="s":  return 12,""
        if keyw[1]=="east" or keyw[1]=="e": return 13,""
        if keyw[1]=="west" or keyw[1]=="w": return 14,""
        if keyw[1]=="northeast" or keyw[1]=="north-east" or keyw[1]=="ne":  return 15,""
        if keyw[1]=="northwest" or keyw[1]=="north-west" or keyw[1]=="nw":  return 16,""
        if keyw[1]=="southeast" or keyw[1]=="south-east" or keyw[1]=="se":  return 17,""
        if keyw[1]=="southwest" or keyw[1]=="south-west" or keyw[1]=="sw":  return 18,""
        if keyw[1]=="down": return 19,""
      if action=="look":  return look(dungeon,player)
      if action=="use": return use()
      if action=="equip": return equip()
      if action=="unequip": return equip()
      if action=="fight": return fight()
      if action=="cfg": return 5,""
      if action=="help":
        try:
          if keyw[1]=="keys": return 61,""
        except IndexError:
          help.help()
          return 62,""
      if action=="quit":
        return 9,""
  except IndexError:
    return 0,random.choice(errors)+"\n"
コード例 #42
0
ファイル: console.py プロジェクト: alex14324/AbsoulteZero
                    elif command.startswith('config '):
                        try:
                            argument = command.split(' ')[1]
                            if argument == "save":
                                xmllib.save()
                            elif argument == "remove":
                                xmllib.remove()
                            else:
                                print color.ReturnError(
                                    'Unrecognized argument "%s".' % argument)
                        except Exception, e:
                            print color.ReturnError(
                                'Configuration error -> %s.' % str(e))
                    elif command == "modules":
                        print "\n" + color.ReturnTabulate(
                            modulehelper.ListModules(),
                            ['Name', 'Description'], "simple") + "\n"
                    elif command == "exit":
                        TCPhandler.Helper.DisconnectImplants()
                        os._exit(0)
                    elif command == "help":
                        print help.help()

                    else:
                        print color.ReturnError(
                            'Command "%s" unrecognized, type <<help>> for command list.'
                            % command)
            except KeyboardInterrupt:
                print '\n' + color.ReturnError('Type "exit" to quit.')
コード例 #43
0
ファイル: command_line.py プロジェクト: vesellov/datahaven
def run(opts, args, overDict, pars):
    """
    The entry point, this is called from `p2p.dhnmain` to process command line arguments.
    """
    print 'Copyright 2006, DataHaven.NET LTD. of Anguilla. All rights reserved.'
    
    if overDict:
        settings.override_dict(overDict)
    dhnio.init()
    settings.init()
    if not opts or opts.debug is None:
        dhnio.SetDebug(0)

    appList = dhnio.find_process([
        'dhnmain.exe',
        'dhnmain.py',
        'dhn.py',
        'regexp:^/usr/bin/python\ +/usr/bin/datahaven.*$',
        ])
    running = len(appList) > 0
   
    cmd = ''
    if len(args) > 0:
        cmd = args[0].lower()
    
    #---help---
    if cmd in ['help', 'h']:
        import help
        if len(args) >= 2 and args[1].lower() == 'schedule':
            print help.schedule_format()
        elif len(args) >= 2 and args[1].lower() == 'settings':
            print settings.uconfig().print_all()
        else:
            print help.help()
            print pars.format_option_help()
        return 0
    
    #---backup---
    elif cmd in ['backup', 'backups', 'bk']:
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_backups(opts, args, overDict)

    #---restore---
    elif cmd in ['restore', 're']:
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_restore(opts, args, overDict)

    #---schedule---
    elif cmd in ['schedule', 'shed', 'sched', 'sh']:
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_schedule(opts, args, overDict)

    #---suppliers---
    elif cmd in [ 'suppliers', 'supplier', 'sup', 'supp', 'sp', ]:
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_suppliers(opts, args, overDict)
    
    #---customers---
    elif cmd in [ 'customers', 'customer', 'cus', 'cust', 'cs', ]:
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_customers(opts, args, overDict)

    #---register---
    elif cmd == 'register':
        if running:
            print 'DataHaven.NET already started.\n'
            return 0
        return cmd_register(opts, args, overDict)

    #---recover---
    elif cmd == 'recover':
        if running:
            print 'DataHaven.NET already started.\n'
            return 0
        return cmd_recover(opts, args, overDict)

    #---key---
    elif cmd == 'key':
        return cmd_key(opts, args, overDict)

    #---stats---
    elif cmd in [ 'stats', 'st' ]:
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_stats(opts, args, overDict)

    #---version---
    elif cmd in [ 'version', 'v', 'ver' ]:
        revnum = dhnio.ReadTextFile(settings.RevisionNumberFile()).strip()
        repo, location = misc.ReadRepoLocation()
        print 'revision:  ', revnum
        print 'repository:', repo
        return 0

    #---states---
    elif cmd in [ 'states', 'sta', 'automats', 'auto' ]:
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_states(opts, args, overDict)

    #---reconnect---
    elif cmd in [ 'reconnect', ]:
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_reconnect(opts, args, overDict)
        
    #---set---
    elif cmd == 'set':
        if len(args) == 1 or args[1].lower() in [ 'help', '?' ]:
            import help
            print help.settings_help()
            return 0
        if not running:
            cmd_set_directly(opts, args, overDict)
            return 0
        return cmd_set_request(opts, args, overDict)
    
    #---memory---
    elif cmd == 'memory':
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_memory(opts, args, overDict)
    
    #---money---
    elif cmd == 'money':
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_money(opts, args, overDict)
    
    elif cmd == 'storage':
        if not running:
            print 'DataHaven.NET is not running at the moment\n'
            return 0
        return cmd_storage(opts, args, overDict)
    
#    elif cmd == 'uninstall':
#        return cmd_uninstall(opts, args, overDict)
    
    return 2
コード例 #44
0
ファイル: ~halbrdbot.py プロジェクト: Dragons-Ire/halbrdBot
    def MessageStatus(self, msg, status):
        if status == Skype4Py.cmsReceived or status == Skype4Py.cmsSent:
            # I have no idea what this line does other than it makes the bot respond to its own messages, and it only works in private chat
            #if not msg.Sender.Handle in self.blacklist:
            if msg.Body[0] == "!" and msg.Sender.Handle != "everythingbot":
                print "[" + str(datetime.now())[:-7] + "] " + msg.Sender.Handle + ": " + msg.Body

            # !help
            if re.match("!help(?!\S)", msg.Body):
                msg.Chat.SendMessage(help())

            # !ping
            elif re.match("!ping(?!\S)", msg.Body):
                msg.Chat.SendMessage(ping())

            # !members
            elif re.match("!members(?!\S)", msg.Body):
                msg.Chat.SendMessage(members(msg.Chat.Members))

            # !profile
            elif re.match("!profile(?!\S)", msg.Body):
                try:
                    skypeName = msg.Body[9:]
                    msg.Chat.SendMessage(profile(skypeName, msg.Chat.Members))
                except IndexError:
                    msg.Chat.SendMessage("Skype username required for profile lookup.")

            # !orangecrush
            # If you're reading this on the Github repo, congratulations on being the first to figure out that it's been public all along.
            elif re.match("!orangecrush(?!\S)", msg.Body):
                msg.Chat.SendMessage("!orangecrush")

            # !lenny
            elif re.match("!lenny(?!\S)", msg.Body):
                msg.Chat.SendMessage(self._lenny)

            # !friendcodes
            elif re.match("!friendcodes(?!\S)", msg.Body) or re.match("!fc(?!\S)", msg.Body):
                msg.Chat.SendMessage(friendcodes())

            # !gostats
            elif re.match("!gostats(?!\S)", msg.Body):
                msg.Chat.SendMessage("http://csgo-stats.com/" + msg.Body[9:])

            # !tableflip
            elif re.match("!tableflip(?!\S)", msg.Body):
                msg.Chat.SendMessage(self._tableflip)

            # !tableset
            elif re.match("!tableset(?!\S)", msg.Body):
                msg.Chat.SendMessage(self._tableset)

            # !coinflip
            elif re.match("!coinflip(?!\S)", msg.Body):
                msg.Chat.SendMessage(coinflip())

            # URL titles

            # This is the opt-into title code.
            #elif re.match("!title(?!\S)", msg.Body):
            #    if re.match('!title http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE):
            #        url = re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE)
            #        msg.Chat.SendMessage(url_get(url.group(0)))
            #    else:
            #        msg.Chat.SendMessage("Invalid URL.")

            # This is the opt-out of title code.
            elif re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE) and not re.search("!nt(?!\S)", msg.Body) and msg.Sender.Handle != "everythingbot":
                url = re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE)
                msg.Chat.SendMessage(url_get(url.group(0)))

            # !removebot
            elif re.match("!removebot(?!\S)", msg.Body):
                if removebot(msg.Sender.Handle):
                    msg.Chat.Leave()

            # !restartbot
            elif re.match("!restartbot(?!\S)", msg.Body):
                if removebot(msg.Sender.Handle):
                    msg.Chat.SendMessage("Restarting bot.")
                    execfile("~halbrdbot.py")
                    sys.exit()

            # !twitch (channel)
            # !gostats
            elif re.match("!twitch(?!\S)", msg.Body):
               # msg.Chat.SendMessage("http://twitch.tv/" + msg.Body[8:])
                msg.Chat.SendMessage(twitch(msg.Body[8:]))

            # !requestfunction (string)
            #elif re.match("!requestfunction(?!\S)", msg.Body):
            #    msg.Chat.SendMessage(requestfunction(msg.Sender.Handle, msg.Body[17:]))

            #elif msg.Body == "!chatname":
            #    msg.Chat.SendMessage(msg.Chat.Name)

            # !hug
            elif re.match("!hug(?!\S)", msg.Body) and msg.Sender.Handle != "everythingbot":
                msg.Chat.SendMessage(hug(msg.Sender.FullName, msg.Body[5:]))

            # !bothug
            elif re.match("!bothug(?!\S)", msg.Body):
                msg.Chat.SendMessage(bothug(msg.Body[8:]))

            # !blacklist
            #elif re.match("!blacklist(?!\S)", msg.Body):
            #    msg.Chat.SendMessage(blacklist(msg.Sender.Handle, msg.Body[11:]))

            # !strats
            elif re.match("!strats(?!\S)", msg.Body):
                msg.Chat.SendMessage(strats(msg.Body[8:]))

            # !lwc
            elif re.match("!lwc(?!\S)", msg.Body):
                msg.Chat.SendMessage("Literally who cares.\nhttp://lynq.me/lwc.mp4")





            # lmao
            # Keep this as the last thing that gets checked
            elif re.search("l+ *m+ *a+ *o+", msg.Body, re.IGNORECASE) and msg.Sender.Handle != "everythingbot":
                msg.Chat.SendMessage("ayyy")
コード例 #45
0
    states, specTraits = [find_id_state_like("PERM")
                          ], get_specified_traits("ALL_TRAITS")
    return sxs.get_first_ids(N_PROFILES_TO_CHANGE, states, specTraits)


def __get_test_ids(pxs):
    """gets the ids only from the test tagged profiles"""
    tagged_profiles = __get_test_tagged_profiles(pxs)
    global debug
    if debug:
        output_tagged_profile_sequence(tagged_profiles)

    return [tp.id for tp in tagged_profiles]


if __name__ == "__main__":
    if '-?' in sys.argv or '-h' in sys.argv:
        import help
        help.help()
        sys.exit(0)

    if '-profile' in sys.argv:
        import profile
        profile.run('test()')
        sys.exit(0)
    if '-profile2' in sys.argv:
        import profile
        profile.run('test()', 'test_profile.prof')
        sys.exit(0)
    test()
コード例 #46
0
    time.sleep(3)
    if (load(args.Direktori)
        ):  # F14 load -> True kalau foldernya ada, -> False kalau gada

        role = ""
        user_id = 0

        user_input = input(">>> ")

        while (role == ""):
            if (user_input == "login"):  # F02
                tuple_login = login(role, user_id)
                role = tuple_login[0]
                user_id = tuple_login[1]
            elif (user_input == "help"):  # F16
                help(role)
            elif (user_input == "exit"):  # F17
                exit(role)
            else:
                print("Silahkan login terlebih dahulu!")

            print()
            user_input = input(">>> ")

        load_inventori(user_id)

        while (user_input != "exit"):
            if (user_input == "register"):  # F01
                register(role)
            elif (user_input == "login"):  # F02 Sudah dijalankan
                print("Anda sudah login!")
コード例 #47
0
ファイル: mainwindow.py プロジェクト: jan-warchol/frescobaldi
    def showManual(self):
        """Shows the user guide, called when user presses F1."""
        import help

        help.help("contents")
コード例 #48
0
ファイル: main.py プロジェクト: gitter-badger/CalcyColor-1
#<startsettings>
import help
import calcy
import calcym
import colorama
colorama.init()
#</startsettings>
#<main>#
print (colorama.Fore.MAGENTA + "CALCY 1.0" + colorama.Fore.RESET)
print (colorama.Fore.MAGENTA + "Type 'help' to view a list of commands." + colorama.Fore.RESET)
cmd = input(colorama.Fore.CYAN + "$>> " + colorama.Fore.RESET)
if cmd == "help":
    help.help()
elif cmd == "add":
    a = (colorama.Fore.GREEN + "Type a number: " + colorama.Fore.RESET)
    b = (colorama.Fore.GREEN + "Type a number: " + colorama.Fore.RESET)
    d = calcym.add(a,b)
    e = str(d)
    print (e)
else:
    print (colorama.Fore.RED + "ERROR: WRONG COMMAND" + colorama.Fore.RESET)
    calcy.calcy()
while cmd == "add" or "help":
    print (colorama.Fore.MAGENTA + "CALCY 1.0" + colorama.Fore.RESET)
    print (colorama.Fore.MAGENTA + "Type 'help' to view a list of commands." + colorama.Fore.RESET)
    cmd = input(colorama.Fore.CYAN + "$>> " + colorama.Fore.RESET)
    if cmd == "help":
        help.help()
    elif cmd == "add":
        a = (colorama.Fore.GREEN + "Type a number: " + colorama.Fore.RESET)
        b = (colorama.Fore.GREEN + "Type a number: " + colorama.Fore.RESET)
コード例 #49
0
ファイル: widget.py プロジェクト: WedgeLeft/frescobaldi
 def slotHelp(self):
     """Called when the user clicks the small help button."""
     help.help(snippet_help)
コード例 #50
0
ファイル: create_man.py プロジェクト: LixinZheng123/i-pi
You should have received a copy of the GNU General Public License
along with this program. If not, see <http.//www.gnu.org/licenses/>.


Creates a latex file, corresponding to a section of the manual, for each of
the classes specified in help.py. It uses help.py to generate information 
about the tags for each class, and will include cross-references so that the
title of each tag corresponding to a different class will also be a hyperlink
in the manual to the section corresponding to that class.

Note that any new input class type must be added to the objects 
dictionary in help.py and the latex help file must be added to the end of 
the manual.lyx file for it to be included in the automatic help generation.

Also creates an xml file with the full list of all the tags.
"""

import os
from help import help, objects
from help_list import help_list, list_objects

if not os.path.exists("input_docs"):
   os.mkdir("input_docs")

help(xml=True, prefix="manual")
for opt in objects:
   help(latex=True, levels=1, option=opt, prefix=("input_docs/" + opt), standalone=False)
for opt in list_objects:
   help_list(option=opt, prefix=("input_docs/" + opt), standalone=False)
コード例 #51
0
    def handle_key(self, key):
        if key == editor.KEY_ENTER:
            line = self.get_cur_line()
            log.info("Enter pressed: %s" % line)
            op_no = self.cur_operand_no(line)
            self.show_status("Enter pressed: %s, %s" % (self.col, op_no))
            if isinstance(line, engine.DisasmObj):
                to_addr = None
                if op_no >= 0:
                    o = line[op_no]
                    to_addr = o.get_addr()
                if to_addr is None:
                    o = line.get_operand_addr()
                    if o:
                        to_addr = o.get_addr()
                self.goto_addr(to_addr, from_addr=line.ea)
        elif key == editor.KEY_ESC:
            if self.addr_stack:
                self.show_status("Returning")
                self.goto_addr(self.addr_stack.pop())
        elif key == b"q":
            return editor.KEY_QUIT
        elif key == b"c":
            addr = self.cur_addr()
            self.show_status("Analyzing at %x" % addr)
            engine.add_entrypoint(addr)
            engine.analyze(self.analyze_status)
            self.update_model()
        elif key == b"d":
            addr = self.cur_addr()
            fl = self.model.AS.get_flags(addr)
            if fl not in (self.model.AS.DATA, self.model.AS.UNK):
                self.show_status("Undefine first")
                return
            if fl == self.model.AS.UNK:
                self.model.AS.set_flags(addr, 1, self.model.AS.DATA, self.model.AS.DATA_CONT)
            else:
                sz = self.model.AS.get_unit_size(addr)
                self.model.undefine(addr)
                sz *= 2
                if sz > 4: sz = 1
                self.model.AS.set_flags(addr, sz, self.model.AS.DATA, self.model.AS.DATA_CONT)
            self.update_model()
        elif key == b"a":
            addr = self.cur_addr()
            fl = self.model.AS.get_flags(addr)
            if fl != self.model.AS.UNK:
                self.show_status("Undefine first")
                return
            sz = 0
            label = "s_"
            while True:
                b = self.model.AS.get_byte(addr)
                fl = self.model.AS.get_flags(addr)
                if not (0x20 <= b <= 0x7e or b in (0x0a, 0x0d)):
                    if b == 0:
                        sz += 1
                    break
                if fl != self.model.AS.UNK:
                    break
                c = chr(b)
                if c < '0' or c in string.punctuation:
                    c = '_'
                label += c
                addr += 1
                sz += 1
            if sz > 0:
                self.model.AS.set_flags(self.cur_addr(), sz, self.model.AS.STR, self.model.AS.DATA_CONT)
                self.model.AS.make_unique_label(self.cur_addr(), label)
                self.update_model()
        elif key == b"u":
            addr = self.cur_addr()
            self.model.undefine(addr)
            self.update_model()
        elif key == b"o":
            addr = self.cur_addr()
            line = self.get_cur_line()
            o = line.get_operand_addr()
            if not o:
                self.show_status("Cannot convert operand to offset")
                return
            if o.type != idaapi.o_imm or not self.model.AS.is_valid_addr(o.get_addr()):
                self.show_status("Cannot convert operand to offset: #%s: %s" % (o.n, o.type))
                return

            if self.model.AS.get_arg_prop(addr, o.n, "type") == idaapi.o_mem:
                self.model.AS.set_arg_prop(addr, o.n, "type", idaapi.o_imm)
                self.model.AS.del_xref(addr, o.get_addr(), idaapi.dr_O)
            else:
                self.model.AS.set_arg_prop(addr, o.n, "type", idaapi.o_mem)
                label = self.model.AS.get_label(o.get_addr())
                if not label:
                    self.model.AS.make_auto_label(o.get_addr())
                self.model.AS.add_xref(addr, o.get_addr(), idaapi.dr_O)
            self.update_model(True)
        elif key == b";":
            addr = self.cur_addr()
            comment = self.model.AS.get_comment(addr) or ""
            res = self.dialog_edit_line(line=comment, width=60)
            if res:
                self.model.AS.set_comment(addr, res)
            self.update_screen()
        elif key == b"n":
            addr = self.cur_addr()
            label = self.model.AS.get_label(addr)
            def_label = self.model.AS.get_default_label(addr)
            s = label or def_label
            while True:
                res = self.dialog_edit_line(line=s)
                if not res:
                    break
                if res == def_label:
                    res = addr
                else:
                    if self.model.AS.label_exists(res):
                        s = res
                        self.show_status("Duplicate label")
                        continue
                self.model.AS.set_label(addr, res)
                if not label:
                    # If it's new label, we need to add it to model
                    self.update_model()
                    return
                break
            self.update_screen()
        elif key == b"g":

            F = npyscreen.FormBaseNew(name='Go to', lines=6, columns=40, show_atx=4, show_aty=4)
            e = F.add(LabelEntry, name="Labels")
            e.set_choices(self.model.AS.get_label_list())

            def h_enter_key(input):
                if not e.value:
                    # Hitting Enter with empty text entry opens autocomplete dropbox
                    e.auto_complete(input)
                else:
                    F.exit_editing()
            e.add_handlers({curses.ascii.CR: h_enter_key})

            F.add(npyscreen.FixedText, value="Press Tab to auto-complete", editable=False)
            F.edit()
            self.update_screen()
            if e.value:
                if '0' <= e.value[0] <= '9':
                    res = int(e.value, 0)
                else:
                    res = self.model.AS.resolve_label(e.value)

                self.goto_addr(res, from_addr=self.cur_addr())
        elif key == editor.KEY_F1:
            help.help(self)
            self.update_screen()
        elif key == b"S":
            save_state(project_dir)
            self.show_status("Saved.")
コード例 #52
0
def dohelp():
    help.help()
コード例 #53
0
ファイル: checkercli.py プロジェクト: ecaoili24/checker_CLI
import sys
import os
import requests
import json
from time import sleep
from random import randint, uniform
from credentials import getToken
from help import help
from check import check, set_check, get_loc_status

if __name__ == "__main__":
    token = getToken()
    if len(sys.argv) > 1:
        command = sys.argv[1]
        if (command in set(["-h", "--help"])):
            help()
        elif (command == "run"):
            dry = -1
            if len(sys.argv) > 2:
                flag = sys.argv[2]
                if len(flag) > 2 and flag[:2] == "-d":
                    try:
                        dry = int(flag[2:])
                    except:
                        print("Not a valid value for `n`!")

            if dry == -1:
                os.system("echo 'Replace this with git push code'")
            os.system("echo 'Replace this with checker API code'")
        elif (command == "status"):
            if len(sys.argv) > 2:
コード例 #54
0
ファイル: scratchabit.py プロジェクト: aeppert/ScratchABit
    def handle_key_unprotected(self, key):
        if key == editor.KEY_ENTER:
            line = self.get_cur_line()
            log.info("Enter pressed: %s" % line)
            op_no = self.cur_operand_no(line)
            self.show_status("Enter pressed: %s, %s" % (self.col, op_no))
            if isinstance(line, engine.DisasmObj):
                to_addr = None
                if op_no >= 0:
                    o = line[op_no]
                    to_addr = o.get_addr()
                if to_addr is None:
                    o = line.get_operand_addr()
                    if o:
                        to_addr = o.get_addr()
                self.goto_addr(to_addr, from_addr=line.ea)
        elif key == editor.KEY_ESC:
            if self.addr_stack:
                self.show_status("Returning")
                self.goto_addr(self.addr_stack.pop())
        elif key == b"q":
            return editor.KEY_QUIT
        elif key == b"c":
            addr = self.cur_addr()
            self.show_status("Analyzing at %x" % addr)
            engine.add_entrypoint(addr, False)
            engine.analyze(self.analyze_status)
            self.update_model()
        elif key == b"d":
            addr = self.cur_addr()
            fl = self.model.AS.get_flags(addr)
            if fl not in (self.model.AS.DATA, self.model.AS.UNK):
                self.show_status("Undefine first")
                return
            if fl == self.model.AS.UNK:
                self.model.AS.set_flags(addr, 1, self.model.AS.DATA, self.model.AS.DATA_CONT)
            else:
                sz = self.model.AS.get_unit_size(addr)
                self.model.undefine_unit(addr)
                sz *= 2
                if sz > 4: sz = 1
                self.model.AS.set_flags(addr, sz, self.model.AS.DATA, self.model.AS.DATA_CONT)
            self.update_model()
        elif key == b"a":
            addr = self.cur_addr()
            fl = self.model.AS.get_flags(addr)
            if fl != self.model.AS.UNK:
                self.show_status("Undefine first")
                return
            sz = 0
            label = "s_"
            while True:
                b = self.model.AS.get_byte(addr)
                fl = self.model.AS.get_flags(addr)
                if not (0x20 <= b <= 0x7e or b in (0x0a, 0x0d)):
                    if b == 0:
                        sz += 1
                    break
                if fl != self.model.AS.UNK:
                    break
                c = chr(b)
                if c < '0' or c in string.punctuation:
                    c = '_'
                label += c
                addr += 1
                sz += 1
            if sz > 0:
                self.model.AS.set_flags(self.cur_addr(), sz, self.model.AS.STR, self.model.AS.DATA_CONT)
                self.model.AS.make_unique_label(self.cur_addr(), label)
                self.update_model()
        elif key == b"u":
            addr = self.cur_addr()
            self.model.undefine_unit(addr)
            self.update_model()
        elif key == b"o":
            addr = self.cur_addr()
            line = self.get_cur_line()
            o = line.get_operand_addr()
            if not o:
                self.show_status("Cannot convert operand to offset")
                return
            if o.type != idaapi.o_imm or not self.model.AS.is_valid_addr(o.get_addr()):
                self.show_status("Cannot convert operand to offset: #%s: %s" % (o.n, o.type))
                return

            if self.model.AS.get_arg_prop(addr, o.n, "type") == idaapi.o_mem:
                self.model.AS.set_arg_prop(addr, o.n, "type", idaapi.o_imm)
                self.model.AS.del_xref(addr, o.get_addr(), idaapi.dr_O)
            else:
                self.model.AS.make_arg_offset(addr, o.n, o.get_addr())
            self.update_model(True)
        elif key == b";":
            addr = self.cur_addr()
            comment = self.model.AS.get_comment(addr) or ""
            res = self.dialog_edit_line(line=comment, width=60)
            if res:
                self.model.AS.set_comment(addr, res)
            self.update_screen()
        elif key == b"n":
            addr = self.cur_addr()
            label = self.model.AS.get_label(addr)
            def_label = self.model.AS.get_default_label(addr)
            s = label or def_label
            while True:
                res = self.dialog_edit_line(line=s)
                if not res:
                    break
                if res == def_label:
                    res = addr
                else:
                    if self.model.AS.label_exists(res):
                        s = res
                        self.show_status("Duplicate label")
                        continue
                self.model.AS.set_label(addr, res)
                if not label:
                    # If it's new label, we need to add it to model
                    self.update_model()
                    return
                break
            self.update_screen()
        elif key == b"g":

            F = npyscreen.FormBaseNew(name='Go to', lines=6, columns=40, show_atx=4, show_aty=4)
            e = F.add(LabelEntry, name="Labels")
            e.set_choices(self.model.AS.get_label_list())

            def h_enter_key(input):
                if not e.value:
                    # Hitting Enter with empty text entry opens autocomplete dropbox
                    e.auto_complete(input)
                else:
                    F.exit_editing()
            e.add_handlers({curses.ascii.CR: h_enter_key})

            F.add(npyscreen.FixedText, value="Press Tab to auto-complete", editable=False)
            F.edit()
            self.update_screen()
            if e.value:
                if '0' <= e.value[0] <= '9':
                    res = int(e.value, 0)
                else:
                    res = self.model.AS.resolve_label(e.value)

                self.goto_addr(res, from_addr=self.cur_addr())
        elif key == editor.KEY_F1:
            help.help(self)
            self.update_screen()
        elif key == b"S":
            save_state(project_dir)
            self.show_status("Saved.")
        elif key == b"\x11":  # ^Q
            F = npyscreen.Popup(name='Problems list', lines=18)
            class IssueList(npyscreen.MultiLine):
                def display_value(self, vl):
                    return "%08x %s" % vl
            lw = F.add(IssueList, name="Problems")
            #lw.return_exit = True
            lw.values = self.model.AS.get_issues()
            lw.add_handlers({curses.ascii.CR: lambda key: (lw.h_select_exit(key), F.exit_editing(), 1)})
            F.edit()
            self.update_screen()
            if lw.value is not None:
                val = lw.values[lw.value][0]
                self.goto_addr(val, from_addr=self.cur_addr())
        elif key == b"i":
            off, area = self.model.AS.addr2area(self.cur_addr())
            props = area[engine.PROPS]
            percent = 100 * off / (area[engine.END] - area[engine.START] + 1)
            func = self.model.AS.lookup_func(self.cur_addr())
            func = self.model.AS.get_label(func.start) if func else None
            self.show_status("Area: 0x%x %s (%s): %.1f%%, func: %s" % (
                area[engine.START], props.get("name", "noname"), props["access"], percent, func
            ))
        elif key == b"W":
            class TextSaveModel:
                def __init__(self, f, ctrl):
                    self.f = f
                    self.ctrl = ctrl
                    self.cnt = 0
                def add_line(self, addr, line):
                    line = ("%08x " % addr) + line.indent + line.render() + "\n"
                    self.f.write(line)
                    if self.cnt % 256 == 0:
                        self.ctrl.show_status("Writing: 0x%x" % addr)
                    self.cnt += 1
            out_fname = "out.lst"
            with open(out_fname, "w") as f:
                engine.render_partial(TextSaveModel(f, self), 0, 0, 10000000)
            self.show_status("Disassembly listing written: " + out_fname)
        elif key in (b"/", b"?"):  # "/" and Shift+"/"
            class FoundException(Exception): pass
            class TextSearchModel:
                def __init__(self, substr, ctrl):
                    self.search = substr
                    self.ctrl = ctrl
                    self.cnt = 0
                def add_line(self, addr, line):
                    line = line.render()
                    if self.search in line:
                        raise FoundException(addr)
                    if self.cnt % 256 == 0:
                        self.ctrl.show_status("Searching: 0x%x" % addr)
                    self.cnt += 1
            if key == b"/":
                F = npyscreen.FormBaseNew(name='Text Search', lines=5, columns=40, show_atx=4, show_aty=4)
                e = F.add(npyscreen.TitleText, name="Search for:")
                e.entry_widget.add_handlers({curses.ascii.CR: lambda k: F.exit_editing()})
                F.edit()
                self.update_screen()
                self.search_str = e.value
                addr = self.cur_addr()
            else:
                addr = self.next_addr()

            try:
                engine.render_from(TextSearchModel(self.search_str, self), addr, 10000000)
            except FoundException as res:
                self.goto_addr(res.args[0], from_addr=self.cur_addr())
            else:
                self.show_status("Not found: " + self.search_str)

        else:
            self.show_status("Unbound key: " + repr(key))
コード例 #55
0
 def show_help(self):
     self.h = help.help()
     self.h.show()
コード例 #56
0
ファイル: scratchabit.py プロジェクト: noscripter/ScratchABit
    def handle_key_unprotected(self, key):
        if key == editor.KEY_ENTER:
            line = self.get_cur_line()
            log.info("Enter pressed: %s" % line)
            op_no = self.cur_operand_no(line)
            self.show_status("Enter pressed: %s, %s" % (self.col, op_no))
            to_addr = None
            # No longer try to jump only to addresses in args, parse
            # textual representation below
            if False and isinstance(line, engine.DisasmObj):
                if op_no >= 0:
                    o = line[op_no]
                    to_addr = o.get_addr()
                if to_addr is None:
                    o = line.get_operand_addr()
                    if o:
                        to_addr = o.get_addr()
            if to_addr is None:
                pos = self.col - line.LEADER_SIZE - len(line.indent)
                word = utils.get_word_at_pos(line.cache, pos)
                if word:
                    if word[0].isdigit():
                        to_addr = int(word, 0)
                    else:
                        to_addr = self.model.AS.resolve_label(word)
                        if to_addr is None:
                            self.show_status("Unknown address: %s" % word)
                            return
            self.goto_addr(to_addr, from_addr=line.ea)
        elif key == editor.KEY_ESC:
            if self.addr_stack:
                self.show_status("Returning")
                self.goto_addr(self.addr_stack.pop())
        elif key == b"q":
            return editor.KEY_QUIT
        elif key == b"c":
            addr = self.cur_addr()
            self.show_status("Analyzing at %x" % addr)
            engine.add_entrypoint(addr, False)
            engine.analyze(self.analyze_status)
            self.update_model()
        elif key == b"d":
            addr = self.cur_addr()
            fl = self.model.AS.get_flags(addr)
            if fl not in (self.model.AS.DATA, self.model.AS.UNK):
                self.show_status("Undefine first")
                return
            if fl == self.model.AS.UNK:
                self.model.AS.set_flags(addr, 1, self.model.AS.DATA, self.model.AS.DATA_CONT)
            else:
                sz = self.model.AS.get_unit_size(addr)
                self.model.undefine_unit(addr)
                sz *= 2
                if sz > 4: sz = 1
                self.model.AS.set_flags(addr, sz, self.model.AS.DATA, self.model.AS.DATA_CONT)
            self.update_model()
        elif key == b"a":
            addr = self.cur_addr()
            fl = self.model.AS.get_flags(addr)
            if fl != self.model.AS.UNK:
                self.show_status("Undefine first")
                return
            sz = 0
            label = "s_"
            while True:
                b = self.model.AS.get_byte(addr)
                fl = self.model.AS.get_flags(addr)
                if not (0x20 <= b <= 0x7e or b in (0x0a, 0x0d)):
                    if b == 0:
                        sz += 1
                    break
                if fl != self.model.AS.UNK:
                    break
                c = chr(b)
                if c < '0' or c in string.punctuation:
                    c = '_'
                label += c
                addr += 1
                sz += 1
            if sz > 0:
                self.model.AS.set_flags(self.cur_addr(), sz, self.model.AS.STR, self.model.AS.DATA_CONT)
                self.model.AS.make_unique_label(self.cur_addr(), label)
                self.update_model()
        elif key == b"u":
            addr = self.cur_addr()
            self.model.undefine_unit(addr)
            self.update_model()
        elif key == b"o":
            addr = self.cur_addr()
            line = self.get_cur_line()
            o = line.get_operand_addr()
            if not o:
                self.show_status("Cannot convert operand to offset")
                return
            if o.type != idaapi.o_imm or not self.model.AS.is_valid_addr(o.get_addr()):
                self.show_status("Cannot convert operand to offset: #%s: %s" % (o.n, o.type))
                return

            if self.model.AS.get_arg_prop(addr, o.n, "type") == idaapi.o_mem:
                self.model.AS.set_arg_prop(addr, o.n, "type", idaapi.o_imm)
                self.model.AS.del_xref(addr, o.get_addr(), idaapi.dr_O)
            else:
                self.model.AS.make_arg_offset(addr, o.n, o.get_addr())
            self.update_model(True)
        elif key == b";":
            addr = self.cur_addr()
            comment = self.model.AS.get_comment(addr) or ""
            res = self.dialog_edit_line(line=comment, width=60)
            if res is not None:
                self.model.AS.set_comment(addr, res)
                self.update_model()
            else:
                self.update_screen()
        elif key == b"n":
            addr = self.cur_addr()
            label = self.model.AS.get_label(addr)
            def_label = self.model.AS.get_default_label(addr)
            s = label or def_label
            while True:
                res = self.dialog_edit_line(line=s)
                if not res:
                    break
                if res == def_label:
                    res = addr
                else:
                    if self.model.AS.label_exists(res):
                        s = res
                        self.show_status("Duplicate label")
                        continue
                self.model.AS.set_label(addr, res)
                if not label:
                    # If it's new label, we need to add it to model
                    self.update_model()
                    return
                break
            self.update_screen()
        elif key == b"g":
            d = Dialog(4, 4, title="Go to")
            d.add(1, 1, WLabel("Label/addr:"))
            entry = WAutoComplete(20, "", self.model.AS.get_label_list())
            entry.popup_h = 12
            entry.finish_dialog = ACTION_OK
            d.add(13, 1, entry)
            d.add(1, 2, WLabel("Press Down to auto-complete"))
            res = d.loop()
            self.update_screen()

            if res == ACTION_OK:
                value = entry.get_text()
                if '0' <= value[0] <= '9':
                    addr = int(value, 0)
                else:
                    addr = self.model.AS.resolve_label(value)
                self.goto_addr(addr, from_addr=self.cur_addr())

        elif key == editor.KEY_F1:
            help.help(self)
            self.update_screen()
        elif key == b"S":
            saveload.save_state(project_dir)
            self.show_status("Saved.")
        elif key == b"\x11":  # ^Q
            class IssueList(WListBox):
                def render_line(self, l):
                    return "%08x %s" % l
            d = Dialog(4, 4, title="Problems list")
            lw = IssueList(40, 16, self.model.AS.get_issues())
            lw.finish_dialog = ACTION_OK
            d.add(1, 1, lw)
            res = d.loop()
            self.update_screen()
            if res == ACTION_OK:
                val = lw.get_cur_line()
                if val:
                    self.goto_addr(val[0], from_addr=self.cur_addr())

        elif key == b"i":
            off, area = self.model.AS.addr2area(self.cur_addr())
            props = area[engine.PROPS]
            percent = 100 * off / (area[engine.END] - area[engine.START] + 1)
            func = self.model.AS.lookup_func(self.cur_addr())
            func = self.model.AS.get_label(func.start) if func else None
            self.show_status("Area: 0x%x %s (%s): %.1f%%, func: %s" % (
                area[engine.START], props.get("name", "noname"), props["access"], percent, func
            ))
        elif key == b"I":
            L = 5
            T = 2
            W = 66
            H = 20
            self.dialog_box(L, T, W, H)
            v = Viewer(L + 1, T + 1, W - 2, H - 2)
            lines = []
            for area in self.model.AS.get_areas():
                props = area[engine.PROPS]
                lines.append("%s (%08x-%08x):" % (props.get("name", "noname"), area[engine.START], area[engine.END]))
                flags = area[engine.FLAGS]
                l = ""
                for i in range(len(flags)):
                    if i % 64 == 0 and l:
                        lines.append(l)
                        l = ""
                    l += engine.flag2char(flags[i])
                if l:
                    lines.append(l)
            v.set_lines(lines)
            v.loop()
            self.update_screen()
        elif key == b"W":
            out_fname = "out.lst"
            with open(out_fname, "w") as f:
                engine.render_partial(TextSaveModel(f, self), 0, 0, 10000000)
            self.show_status("Disassembly listing written: " + out_fname)
        elif key == b"\x17":  # Ctrl+W
            outfile = self.write_func(self.cur_addr())
            if outfile:
                self.show_status("Wrote file: %s" % outfile)
        elif key in (b"/", b"?"):  # "/" and Shift+"/"
            class FoundException(Exception): pass
            class TextSearchModel:
                def __init__(self, substr, ctrl):
                    self.search = substr
                    self.ctrl = ctrl
                    self.cnt = 0
                def add_line(self, addr, line):
                    line = line.render()
                    if self.search in line:
                        raise FoundException(addr)
                    if self.cnt % 256 == 0:
                        self.ctrl.show_status("Searching: 0x%x" % addr)
                    self.cnt += 1
            if key == b"/":
                d = Dialog(4, 4, title="Text Search")
                d.add(1, 1, WLabel("Search for:"))
                entry = WTextEntry(20, self.search_str)
                entry.finish_dialog = ACTION_OK
                d.add(13, 1, entry)
                res = d.loop()
                self.update_screen()
                self.search_str = entry.get_text()
                if res != ACTION_OK or not self.search_str:
                    return
                addr = self.cur_addr()
            else:
                addr = self.next_addr()

            try:
                engine.render_from(TextSearchModel(self.search_str, self), addr, 10000000)
            except FoundException as res:
                self.goto_addr(res.args[0], from_addr=self.cur_addr())
            else:
                self.show_status("Not found: " + self.search_str)

        else:
            self.show_status("Unbound key: " + repr(key))