Exemplo n.º 1
0
def new_line(used_space):
    con_width, con_height = console.getTerminalSize()
    s = str()
    for space in range(0, con_width - used_space):
        s += " "

    return s
Exemplo n.º 2
0
def title(text, s='='):
    """ Pretty print for titles """
    X, Y = console.getTerminalSize()
    msg = spacer(s) + '\n'
    msg += f'\033[1m{center(text)}\033[0m\n'
    msg += spacer(s)
    return msg
Exemplo n.º 3
0
	def render(self):
		os.system("clear")
		(width, height) = console.getTerminalSize()

		self.info.render()
		self.info.render_dialogue()

		horiz_buffer = " " * int((width - self.width) / 2)


		# draws everything in the map array, and everything in the entity_icons array
		for i in range(self.height):
			sys.stdout.write(horiz_buffer)
			for j in range(self.width):
				try:
					if self.entity_icons[i][j][-1] == " ":
						sys.stdout.write(self.map[i][j])

					elif self.entity_icons[i][j][-1] != " ":
						# always uses the last item in the list for rendering
						try:
							sys.stdout.write(self.entity_icons[i][j][-1])
						except IndexError:
							pass
				except IndexError:
					sys.stdout.write(".")

			if i == self.height - 1:
				print("    " + str(self.time))

			sys.stdout.write("\n")
Exemplo n.º 4
0
	def render(self):
		(self.screenwidth, height) = console.getTerminalSize()
		self.msg = self.player.name + " the " + self.player.title + " |  Strength: " + str(self.player.health) + "   Defense: " + str(self.player.armor) + "   Level: " + str(self.player.level) + "  |"
		self.width = len(self.msg)
		horiz_buffer = " " * ((self.screenwidth - self.width) / 2)
		
		print(horiz_buffer + (" " * len(self.player.name + " the  " + self.player.title)) + "-" * (len(self.msg) - len(self.player.name + " the  " + self.player.title)))

		print(horiz_buffer + self.msg)

		print(horiz_buffer + (" " * len(self.player.name + " the  " + self.player.title)) + "-" * (len(self.msg) - len(self.player.name + " the  " + self.player.title)))

		health_percent = self.player.health*1.0 / self.player.maxhealth
		print(health_percent)
		if health_percent*100 >= 75:
			print(horiz_buffer + "Health: " + color.GREEN + "=" * int(((self.width) - 8) * health_percent) + color.END)
		elif health_percent*100 < 75 and health_percent*100 >= 25:
			print(horiz_buffer + "Health: " + color.YELLOW + "=" * int(((self.width) - 8) * health_percent) + color.END)
		elif health_percent*100 < 25:
			print(horiz_buffer + "Health: " + color.RED + "=" * int(((self.width) - 8) * health_percent) + color.END)

		hunger_percent = self.player.hunger*1.0 / self.player.maxhunger
		# print(horiz_buffer + "  Food: " + "=" * int(((width/2) + 2) * hunger_percent))

		if hunger_percent*100 >= 75:
			print(horiz_buffer + "  Food: " + color.GREEN + "=" * int(((self.width) - 8) * hunger_percent) + color.END)
		elif hunger_percent*100 < 75 and hunger_percent*100 >= 25:
			print(horiz_buffer + "  Food: " + color.YELLOW + "=" * int(((self.width) - 8) * hunger_percent) + color.END)
		elif hunger_percent*100 < 25:
			print(horiz_buffer + "  Food: " + color.RED + "=" * int(((self.width) - 8) * hunger_percent) + color.END)
Exemplo n.º 5
0
def parseOsmTAGRelation() :
    networkId = '3921495'
    url = "http://overpass-api.de/api/interpreter?data=relation%28"+networkId+"%29%3Brel%28r%29%3Bout%20body%3B%0A"
    s = localPageCache.getPage(url)

    # Parsing the Overpass API result of TAG relation 3300434
    soup = BeautifulSoup(s)
    lineRelations = soup.findAll("relation")

    # Progress bar is a cool feature.
    (termWidth, height) = console.getTerminalSize()
    #total = len(lineRelations)
    #index = 0

    lines = list()

    for aLine in lineRelations :  # 48 elements
        # index = index+1
        # percentage = index / total
        # sys.stdout.write("\r")
        # for i in range(int(termWidth*percentage)):
        #     sys.stdout.write("-")
        #     sys.stdout.flush()
        myLine = OsmLine(aLine)  # each objects parse the data related to its line
        lines.append(myLine)

    jsonOutput = json.dumps(lines, indent=4, sort_keys=True, cls=OsmLineEncoder)

    if verbose:
        print(jsonOutput)

    return jsonOutput
Exemplo n.º 6
0
def initInterface():
    #init curses and draw interface.
    global stdscr
    global width
    global height
    (width, height) = console.getTerminalSize()
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.start_color()
    curses.cbreak()
    stdscr.clear()
    stdscr.border(0)
    stringLogo = """
 _ _                           _           _   
(_) | ___ __   _____      __   | |__   ___ | |_ 
| | |/ / '_ \ / _ \ \ /\ / /   | '_ \ / _ \| __|
| |   <| | | | (_) \ V  V /    | |_) | (_) | |_ 
|_|_|\_\_| |_|\___/ \_/\_/     |_.__/ \___/ \__|
                                              
"""    
    stdscr.addstr(1,width/2,stringLogo,curses.A_BLINK)
    #stdscr.addstr(2,(width/2)-5,'The All Knowing Bot',curses.A_DIM)
    stdscr.addstr(8,(width/2)-10,"Tejeshwar Sangam ([email protected])")
    stdscr.refresh()
Exemplo n.º 7
0
def title(text):
    """ Pretty print for titles """
    X, Y = console.getTerminalSize()
    msg = '=' * X + '\n'
    msg += '\033[1m' + center(text) + '\033[0m' + '\n'
    msg += '=' * X
    return msg
Exemplo n.º 8
0
def voice(text):
    """ Pretty print for titles """
    w, _ = console.getTerminalSize()
    msg = f"\x1B[3m{text}\x1B[23m"
    while len(msg) < w + 8:  #XXX +8??? wtf?!
        msg = ' ' + msg
    return msg
Exemplo n.º 9
0
def spider(SpiderGlobalVariable):
    if SpiderGlobalVariable.spider_use_gevent:
        import gevent
    while True:
        if SpiderGlobalVariable.spider_urlnode_queue.qsize() > 0:
            _,node = SpiderGlobalVariable.spider_urlnode_queue.get()
            html = fetch(node.url, SpiderGlobalVariable.spider_model, SpiderGlobalVariable.fetch_time_interval, SpiderGlobalVariable.random_agent)
            if len(html) < 10:
                pass
            html_node = HtmlNode(node.url, html, timestamp(), node.depth)
            SpiderGlobalVariable.htmlnode_queue.put(html_node)
            SpiderGlobalVariable.total_count += 1

            if SpiderGlobalVariable.print_all:
                msg = "[Url] %s  Depth: %s  Found: %s Remaining: %s  Html: %s"% (node.url, str(node.depth), str(SpiderGlobalVariable.total_count), str(SpiderGlobalVariable.spider_urlnode_queue.qsize()), str(len(html)))
                spider_logger.info(msg)

            else:
                msg = "[Url] %s  Depth: %s  Found: %s Remaining: %s  Html: %s" % (node.url, str(node.depth), str(SpiderGlobalVariable.total_count), str(SpiderGlobalVariable.spider_urlnode_queue.qsize()), str(len(html)))
                console_width = getTerminalSize()[0] - 0
                if len(msg) - console_width > 0:
                    msg = msg[:console_width]
                    sys.stdout.write('\r' + msg)
                    sys.stdout.flush()
                else:
                    sys.stdout.write('\r' + msg + ' ' * (console_width - len(msg)))
                    sys.stdout.flush()
            if SpiderGlobalVariable.spider_use_gevent:
                gevent.sleep(0)
        else:
            if SpiderGlobalVariable.spider_use_gevent:
                gevent.sleep(0)
            else:
                time.sleep(5)
    SpiderGlobalVariable.exit_flag_count += 1
Exemplo n.º 10
0
def center(string):
    """ Center text in the console width """
    X, Y = console.getTerminalSize()
    rest = X - len(string)
    if rest > 0:
        padd = rest // 2
        return ' ' * padd + string
    else:
        return string
Exemplo n.º 11
0
	def display_title(self):
		(width, height) = console.getTerminalSize()
		vert_buffer = "\n" * int((height)/2 - 8)
		print(vert_buffer)
		buffer = " " * int((width - len("_ _ _ ____ _    ____ ____ _  _ ____    ___ ____    _  _ _  _ _    _       ___  ____ ____ ____ ____ _  _")) / 2)


		print(color.RED + color.BOLD + buffer + "_ _ _ ____ _    ____ ____ _  _ ____    ___ ____    _  _ _  _ _    _       ___  ____ ____ ____ ____ _  _")
		print(buffer + "| | | |___ |    |    |  | |\/| |___     |  |  |    |__| |  | |    |       |__] |__/ |___ |__| |    |__|")
		print(buffer + "|_|_| |___ |___ |___ |__| |  | |___     |  |__|    |  | |__| |___ |___    |__] |  \ |___ |  | |___ |  |" + color.END)
		print("\n")
Exemplo n.º 12
0
	def display_settings(self):
		for setting in self.settings:
			(width, height) = console.getTerminalSize()

			buffer = " " * int((width - len(setting)) / 2)
			if setting == self.selected_setting:
				print(color.BLUE + color.BOLD + buffer[:len(buffer)-3:] + ">> " + setting + " <<" + color.END)
			else:
				print(color.YELLOW + buffer + setting + color.END)

			print("")
Exemplo n.º 13
0
	def display_options(self):
		for option in self.options:
			(width, height) = console.getTerminalSize()

			buffer = " " * int((width - len(option)) / 2)
			if option == self.selected_option:

				print(color.BLUE + color.BOLD + buffer[:len(buffer)-3:] + ">> " + option + " <<" + color.END)
			else:
				print(color.YELLOW + buffer + option + color.END)

			print("")
Exemplo n.º 14
0
def justifyRL(str1, str2, w=0):
    """
     Align string 1 and 2 to the left and right respectively.
     If no width is given, use the width of the console
   """
    if str2 == '': return str1
    if w == 0: X, Y = console.getTerminalSize()
    else: X = w
    total = str1 + str2
    while len(total) < X:
        str1 = str1 + ' '
        total = str1 + str2
    return total
Exemplo n.º 15
0
def init():
    global size, width, height, padding, boundaries, passSize

    # Get containing terminal window and set it to maximised
    pid = os.getpid()
    win = _get_window_by_child_pid(pid)
    gdk_window_settings(win, maximized=True)
    time.sleep(0.1)
    available_size = (width, height) = console.getTerminalSize()

    try:
        # Check for screen resolution
        h = gdk.screen_height()

        # Select a set of sizes depending on the screen resolution
        if h > 1024:
            chosen_size = config.game_sizes_big[parser.args.board]
        elif h <= 1024 and h > 720:
            chosen_size = config.game_sizes_medium[parser.args.board]
        else:
            chosen_size = config.game_sizes_small[parser.args.board]
        passSize = parser.args.board
    except Exception:
        from kano.logging import logger
        logger.error("Can't find board size: {}".format(parser.args.board))
        __main__.exit()

    # Calculate width
    if chosen_size[0] > available_size[0] / 2:
        width = (available_size[0] / 2) - 3
    else:
        width = chosen_size[0]
    # Calculate height
    if chosen_size[1] > available_size[1]:
        height = available_size[1]
    else:
        height = chosen_size[1]

    size = (width, height)

    padding_x = int(math.floor(available_size[0] - width) / 4)
    padding_y = int(math.floor(available_size[1] - height) / 2)

    padding = (padding_y, padding_x, padding_y, padding_x)

    boundaries = {
        "bottom": int(math.floor(height / 2)),
        "left": int(math.floor(-width / 2)),
        "right": int(math.floor(width / 2)),
        "top": int(math.floor(-height / 2)),
    }
Exemplo n.º 16
0
def breakline(text, W=0):
    """
    Introduce breaklines when printing to avoid splitting words
   """
    if W == 0: W, Y = console.getTerminalSize()
    final_text = ''
    current_sentence = ''
    for w in text.split():
        if len(current_sentence + w) >= W:
            final_text += current_sentence + '\n'
            current_sentence = ''
        else:
            current_sentence += w + ' '
    return final_text
Exemplo n.º 17
0
def paragraph(text, W=0):
    """
    Introduce breaklines when printing to avoid splitting words
   """
    #XXX BUUUUGGG!!!! it cuts the paragraph for some reason
    if W == 0: W, Y = console.getTerminalSize()
    final_text = ''
    current_sentence = ''
    for w in text.split():
        if len(current_sentence + w) >= W:
            final_text += current_sentence + '\n'
            current_sentence = ''
        else:
            current_sentence += w + ' '
    return final_text
Exemplo n.º 18
0
def init():
    global size, width, height, padding, boundaries, chosen_theme, resolution

    # Get containing terminal window and set it to maximised
    pid = os.getpid()
    win = _get_window_by_child_pid(pid)
    gdk_window_settings(win, maximized=True)
    time.sleep(0.1)
    available_size = (width, height) = console.getTerminalSize()

     # Check for screen resolution
    resolution = gdk.screen_height()

    # Select a set of sizes depending on the screen resolution
    if resolution > 768:
        chosen_size = (20, 15)
    else:
        chosen_size = (10, 5)

    # Calculate width
    if chosen_size[0] > available_size[0] / 2:
        width = available_size[0] / 2
    else:
        width = chosen_size[0]
    # Calculate height
    if chosen_size[1] > available_size[1]:
        height = available_size[1]
    else:
        height = chosen_size[1]

    size = (width, height)

    padding_x = int(math.floor(available_size[0] - width) / 4)
    padding_y = int(math.floor(available_size[1] - height) / 2)

    padding = (padding_y, padding_x, padding_y, padding_x)

    boundaries = {
        "bottom": int(math.floor(height / 2)),
        "left": int(math.floor(-width / 2)),
        "right": int(math.floor(width / 2)),
        "top": int(math.floor(-height / 2)),
    }
Exemplo n.º 19
0
def get_terminal_width():
    ""
    ncol = None

    try:
        ncol = os.get_terminal_size(0)[0]
    except Exception:
        try:
            import fcntl, termios, struct
            data = struct.pack( 'HHHH', 0, 0, 0, 0 )
            data = fcntl.ioctl( 0, termios.TIOCGWINSZ, data )
            h, w, hp, wp = struct.unpack( 'HHHH', data )
            ncol = w
        except Exception:
            try:
                import console
                ncol = console.getTerminalSize()[0]
            except Exception:
                pass

    return ncol
Exemplo n.º 20
0
def init():
    global size, width, height, padding, boundaries, chosen_theme

    available_size = (width, height) = console.getTerminalSize()

    chosen_size = config.game_sizes[parser.options.size]

    if parser.options.fullscreen:
        width = available_size[0] / 2 - 2
        height = available_size[1]
    else:
        if chosen_size[0] > available_size[0] / 2:
            width = available_size[0] / 2
        else:
            width = chosen_size[0]

        if chosen_size[1] > available_size[1]:
            height = available_size[1]
        else:
            height = chosen_size[1]

    size = (width, height)

    padding_x = int(math.floor(available_size[0] - width) / 4)
    padding_y = int(math.floor(available_size[1] - height) / 2)

    padding = (padding_y, padding_x, padding_y, padding_x)

    boundaries = {
        "bottom": int(math.floor(height / 2)),
        "left": int(math.floor(-width / 2)),
        "right": int(math.floor(width / 2)),
        "top": int(math.floor(-height / 2)),
    }

    chosen_theme = themes.game_themes[parser.options.theme]
    
Exemplo n.º 21
0
def init():
    global size, width, height, padding, boundaries, chosen_theme

    available_size = (width, height) = console.getTerminalSize()

    chosen_size = config.game_sizes[parser.options.size]

    if parser.options.fullscreen:
        width = available_size[0] / 2 - 2
        height = available_size[1]
    else:
        if chosen_size[0] > available_size[0] / 2:
            width = available_size[0] / 2
        else:
            width = chosen_size[0]

        if chosen_size[1] > available_size[1]:
            height = available_size[1]
        else:
            height = chosen_size[1]

    size = (width, height)

    padding_x = int(math.floor(available_size[0] - width) / 4)
    padding_y = int(math.floor(available_size[1] - height) / 2)

    padding = (padding_y, padding_x, padding_y, padding_x)

    boundaries = {
        "bottom": int(math.floor(height / 2)),
        "left": int(math.floor(-width / 2)),
        "right": int(math.floor(width / 2)),
        "top": int(math.floor(-height / 2)),
    }

    chosen_theme = themes.game_themes[parser.options.theme]
Exemplo n.º 22
0
def parseOsmTAGRelation():
    networkId = '3921495'
    url = "http://overpass-api.de/api/interpreter?data=relation%28" + networkId + "%29%3Brel%28r%29%3Bout%20body%3B%0A"
    s = localPageCache.getPage(url)

    # Parsing the Overpass API result of TAG relation 3300434
    soup = BeautifulSoup(s)
    lineRelations = soup.findAll("relation")

    # Progress bar is a cool feature.
    (termWidth, height) = console.getTerminalSize()
    #total = len(lineRelations)
    #index = 0

    lines = list()

    for aLine in lineRelations:  # 48 elements
        # index = index+1
        # percentage = index / total
        # sys.stdout.write("\r")
        # for i in range(int(termWidth*percentage)):
        #     sys.stdout.write("-")
        #     sys.stdout.flush()
        myLine = OsmLine(
            aLine)  # each objects parse the data related to its line
        lines.append(myLine)

    jsonOutput = json.dumps(lines,
                            indent=4,
                            sort_keys=True,
                            cls=OsmLineEncoder)

    if verbose:
        print(jsonOutput)

    return jsonOutput
Exemplo n.º 23
0
def get_terminal_width():
    """
    Get number of chars that can fit into current terminal
    """
    import console
    return console.getTerminalSize()[0]
Exemplo n.º 24
0
version='alpha'

import argparse
import numpy as np
import re
from collections import *
import datetime
import sys
import tempfile
import console
import fea
import fea.abaqus
import fea.lsdyna

terminal_width,_ = console.getTerminalSize()

# argument parsing definitions

parser = argparse.ArgumentParser(prog='abaqus2dyna',
                                 description='Translate Abaqus to LS-DYNA')
parser.add_argument('input',
                    metavar='INPUT',
                    help='Abaqus keyword file (limit one)',
                    nargs=1,
                    type=argparse.FileType('r'))
parser.add_argument('-o', '--output',
                    dest='output',
                    metavar='OUTPUT',
                    help='LS-DYNA keyword file output location',
                    type=argparse.FileType('w'))
Exemplo n.º 25
0
import time
import datetime
import platform
import tarfile
from urllib.parse import urlparse
import console

VERSION = '1.0'
DEFAULT_FTP_BASE_URL = 'ftp://builderust.dev.ath/tachyon/'
DEFAULT_DIST_FILE = {
    'Linux': 'tachyon-linux.tar.gz',
    'Windows': 'tachyon-windows.tar.gz',
    'Darwin': 'tachyon-macos.tar.gz'
}[platform.system()]
CONFIG_FILE = 'config.json'
CONSOLE_WIDTH, _ = console.getTerminalSize()

g_args = None


def main():
    parser = argparse.ArgumentParser(
        description='Tachyon updater. Version {}'.format(VERSION),
        add_help=True)
    parser.add_argument('-u',
                        '--ftp-base_url',
                        help='ftp base URL',
                        default=DEFAULT_FTP_BASE_URL)
    parser.add_argument('-f',
                        '--file-name',
                        help='distribution file name',
Exemplo n.º 26
0
def spacer(s='=', w=0):
    if w == 0: w, _ = console.getTerminalSize()
    return s * w
Exemplo n.º 27
0
def main():
    # init app config
    global app
    app['conf'] = ConfigParser.SafeConfigParser()
    app['path'] = {}
    app['path']['app'] = os.path.dirname(os.path.realpath(__file__)) + os.sep

    # add import path
    sys.path.append(app['path']['app'] + 'lib')
    sys.path.append(app['path']['app'] + 'plugin')
    sys.path.append(app['path']['app'] + 'service')

    # add conf path
    import platformDep
    path = os.path.join(platformDep.getNmcontrolDir(), 'conf') + os.sep
    for argv in sys.argv:
        if argv.startswith("--confdir=") or argv.startswith("--main.confdir="):
            path = argv.split("=")[1]
            path = os.path.realpath(path) + os.sep
    app['path']['conf'] = path

    import common
    common.app = app

    import console
    (cWidth, cHeight) = console.getTerminalSize()
    fmt = optparse.IndentedHelpFormatter(indent_increment=4,
                                         max_help_position=40,
                                         width=cWidth - 3,
                                         short_first=1)
    app['parser'] = optparse.OptionParser(formatter=fmt,
                                          description='nmcontrol %s' %
                                          __version__)

    # debug mode
    app['debug'] = False
    for s in ['--debug=1', '--main.debug=1']:
        while s in sys.argv:
            app['debug'] = True
            sys.argv.remove(
                s
            )  # do not disturb client mode option parsing with debug option

    # parse command line options
    (options, app['args']) = app['parser'].parse_args()

    # determine client mode
    app['client'] = False
    if len(app['args']) > 0 and app['args'][0] != 'start':
        app['client'] = True

    # set up output and log
    if app['client']:
        common.logToFile = False
    log = common.get_logger(__name__, clear=True)
    if not app['client']:
        log.info("#######################################################")
    log.debug("DEBUG MODE")

    # init modules
    import re

    # init vars and main plugin
    app['services'] = {}
    app['plugins'] = {}
    import pluginMain
    app['plugins']['main'] = pluginMain.pluginMain('plugin')

    # init service & plugins
    for modType in ['service', 'plugin']:
        modules = os.listdir(os.path.join(app['path']['app'], modType))
        if modType == 'plugin': modules.remove('pluginMain.py')
        for module in modules:
            if re.match("^" + modType + ".*.py$", module):
                module = re.sub(r'\.py$', '', module)
                modulename = re.sub(r'^' + modType, '', module).lower()
                try:
                    log.debug("launching", modType, module)
                    importedModule = __import__(module)
                    importedClass = getattr(importedModule, module)
                    app[modType +
                        's'][importedClass.name] = importedClass(modType)
                    importedClass.app = app
                except Exception as e:
                    log.exception("Exception when loading " + modType, module,
                                  ":", e)

    # structure command line options to suit modules
    # Note: There should not be plugins and services with the same name
    for option, value in vars(options).items():
        if value is not None:
            tmp = option.split('.')
            if len(tmp) == 1:
                app['plugins']['main'].conf[tmp[0]] = value
            else:
                module = tmp[0]
                tmp.remove(module)
                if module in app['plugins']:
                    app['plugins'][module].conf['.'.join(tmp)] = value
                if module in app['services']:
                    app['services'][module].conf['.'.join(tmp)] = value

    ###### Act as client : send rpc request ######
    if app['client']:
        error, data = app['plugins']['rpc'].pSend(app['args'][:])
        if error is True or data['error'] is True:
            print "ERROR:", data
        else:
            if data['result']['reply'] in [None, True]:
                print 'ok'
            else:
                print data['result']['reply']
            if data['result']['prints']:
                log.debug("LOG:", data['result']['prints'])
        if app['args'][0] != 'restart':
            return

    # daemon mode
    if os.name == "nt":  # MS Windows
        log.info("Daemon mode not possible on MS Windows.")
    elif int(app['plugins']['main'].conf['daemon']) == 1:
        log.info("Entering background mode")
        import daemonize
        retCode = daemonize.createDaemon()

    ###### Act as server : start plugins ######
    plugins_started = []
    for plugin in app['plugins']:
        if int(app['plugins'][plugin].conf['start']) == 1 and plugin not in [
                'rpc', 'main'
        ]:
            # exit immediatly when main is stopped, unless in debug mode
            app['plugins'][plugin].daemon = True
            if app['plugins'][plugin].running is False:
                app['plugins'][plugin].start()
                plugins_started.append(app['plugins'][plugin].name)
    log.info("Plugins started :", ', '.join(plugins_started))

    for plugin in app['plugins']:
        if app['plugins'][plugin].__dict__.has_key(
                "criticalStartException"
        ) and app['plugins'][plugin].criticalStartException:
            raise Exception(app['plugins'][plugin].criticalStartException)

    #services_started = []
    #for service in app['services']:
    #    if app['services'][service].running:
    #        services_started.append(app['services'][service].name)
    #print "Services started :", ', '.join(services_started)

    # stay there to catch CTRL + C and not exit when in daemon mode
    try:
        app['plugins']['main'].start2()
    except (KeyboardInterrupt, SystemExit):
        log.info('\n! Received keyboard interrupt, quitting threads.\n')

    # stop main program
    app['plugins']['main'].stop()
Exemplo n.º 28
0
 def __init__(self):
     (self.monitor_width, self.monitor_height) = console.getTerminalSize()
     self.twrapper = textwrap.TextWrapper(width=self.monitor_width, replace_whitespace=False, drop_whitespace=False)
     self.priority_tpl = u'%10s'
     self.done_tpl = u'%3s%%'
     self.status_tpl = u'%12s'
Exemplo n.º 29
0
def printTasks(board_id, board_name):
    query = "SELECT task_ids FROM boards WHERE board_id = {0}".format(board_id)
    cursor.execute(query)
    taskList = []
    for task in cursor:
        taskList.append(task)
        # print taskList

    tasks = []
    if str(taskList[0]) != "(u'',)":
        for task in str(taskList[0]).split(","):
            # print task
            if task != "'" and task != ")":
                # print task.strip('()').replace("u'","")
                query2 = "SELECT task_description,task_state FROM tasks WHERE task_id = {0}".format(
                    task.strip("()").replace("u'", "")
                )
                cursor.execute(query2)
                for i in cursor:
                    # print i
                    tasks.append(i)

                # print tasks

    bl = 0
    ip = 0
    done = 0
    blList = []
    ipList = []
    doneList = []
    i = 0
    (width, height) = console.getTerminalSize()
    for task in tasks:
        for char in task[0]:
            if i == width / 3 - 4:
                task[0] = insert(task[0], "\n", i)
        i += 1
        if task[1] == "0":
            bl += 1
            appender = "{0}".format(i) + ":" + task[0]
            # appender = '{0}'.format(i)+ ' '+task[0]
            update_query = "UPDATE tasks SET task_description= '{0}' WHERE task_description='{1}'".format(
                appender, task[0]
            )
            cursor.execute(update_query)
            conn.commit()

            blList.append(appender)
        if task[1] == "1":
            update_query = "UPDATE tasks SET task_description= '{0}' WHERE task_description='{1}'".format(
                appender, task[0]
            )
            cursor.execute(update_query)
            conn.commit()
            ip += 1
            ipList.append(task[0])
        if task[1] == "2":
            done += 1
            update_query = "UPDATE tasks SET task_description= '{0}' WHERE task_description='{1}'".format(
                appender, task[0]
            )
            cursor.execute(update_query)
            conn.commit()
            doneList.append(task[0])

    backLogWithSpacing = "Backlog" + " " * (width / 3 - 4 - len("Backlog"))
    inProgressWithSpacing = "In Progress" + " " * (width / 3 - 4 - len("In Progress"))
    doneWithSpacing = "Done" + " " * (width / 3 - 4 - len("Done"))
    allTasks = [[backLogWithSpacing, inProgressWithSpacing, doneWithSpacing]]
    # print bl
    # print ip
    # print done
    for i in range(0, max(bl, ip, done)):
        currentList = []
        if i < bl:
            currentList.append(blList[i])
        else:
            currentList.append("")
        if i < ip:
            currentList.append[ipList[i]]
        else:
            currentList.append("")
        if i < done:
            currentList.append(doneList[i])
        else:
            currentList.append("")
        allTasks.append(currentList)

    table = DoubleTable(allTasks, board_name)
    table.inner_row_border = True
    print(table.table)
Exemplo n.º 30
0
def main():
    # init app config
    global app
    app['conf'] = ConfigParser.SafeConfigParser()
    app['path'] = {}
    app['path']['app'] = os.path.dirname(os.path.realpath(__file__)) + os.sep
    app['path']['conf'] = app['path']['app'] + os.sep + 'conf' + os.sep

    # add import path
    sys.path.append(app['path']['app'] + 'lib')
    sys.path.append(app['path']['app'] + 'plugin')
    sys.path.append(app['path']['app'] + 'service')

    import common
    common.app = app

    import console
    (cWidth, cHeight) = console.getTerminalSize()
    fmt = optparse.IndentedHelpFormatter(indent_increment=4,
                                         max_help_position=40,
                                         width=cWidth - 3,
                                         short_first=1)
    app['parser'] = optparse.OptionParser(formatter=fmt,
                                          description='nmcontrol %s' %
                                          __version__)
    app['debug'] = False

    # debug mode
    for argv in sys.argv:
        if argv in ['--debug=1', '--main.debug=1']:
            app['debug'] = True

    # init modules
    import re
    import dircache

    # init vars and main plugin
    app['services'] = {}
    app['plugins'] = {}
    import pluginMain
    app['plugins']['main'] = pluginMain.pluginMain('plugin')

    # init service & plugins
    for modType in ['service', 'plugin']:
        modules = dircache.listdir(modType)
        if modType == 'plugin': modules.remove('pluginMain.py')
        for module in modules:
            if re.match("^" + modType + ".*.py$", module):
                module = re.sub(r'\.py$', '', module)
                modulename = re.sub(r'^' + modType, '', module).lower()
                try:
                    importedModule = __import__(module)
                    importedClass = getattr(importedModule, module)
                    app[modType +
                        's'][importedClass.name] = importedClass(modType)
                    importedClass.app = app
                except Exception as e:
                    print "Exception when loading " + modType, module, ":", e

    # parse command line options
    (options, app['args']) = app['parser'].parse_args()
    if app['debug']: print "Cmdline args:", app['args']
    if app['debug']: print "Cmdline options:", options
    for option, value in vars(options).items():
        if value is not None:
            tmp = option.split('.')
            if len(tmp) == 1:
                app['plugins']['main'].conf[tmp[0]] = value
            else:
                module = tmp[0]
                tmp.remove(module)
                if module in app['plugins']:
                    app['plugins'][module].conf['.'.join(tmp)] = value
                elif module in app['services']:
                    app['services'][module].conf['.'.join(tmp)] = value

    ###### Act as client : send rpc request ######
    if len(app['args']) > 0 and app['args'][0] != 'start':
        error, data = app['plugins']['rpc'].pSend(app['args'][:])
        if error is True or data['error'] is True:
            print "ERROR:", data
        else:
            if data['result']['reply'] in [None, True]:
                print 'ok'
            else:
                print data['result']['reply']
            if app['debug'] and data['result']['prints']:
                print "LOG:", data['result']['prints']
        if app['args'][0] != 'restart':
            return

    # daemon mode
    if int(app['plugins']['main'].conf['daemon']) == 1:
        print "Entering background mode"
        import daemonize
        retCode = daemonize.createDaemon()

    ###### Act as server : start plugins ######
    plugins_started = []
    for plugin in app['plugins']:
        if int(app['plugins'][plugin].conf['start']) == 1 and plugin not in [
                'rpc', 'main'
        ]:
            # exit immediatly when main is stopped, unless in debug mode
            app['plugins'][plugin].daemon = True
            if app['plugins'][plugin].running is False:
                app['plugins'][plugin].start()
                plugins_started.append(app['plugins'][plugin].name)
    print "Plugins started :", ', '.join(plugins_started)

    #services_started = []
    #for service in app['services']:
    #	if app['services'][service].running:
    #		services_started.append(app['services'][service].name)
    #print "Services started :", ', '.join(services_started)

    # stay there to catch CTRL + C and not exit when in daemon mode
    try:
        app['plugins']['main'].start2()
    except (KeyboardInterrupt, SystemExit):
        print '\n! Received keyboard interrupt, quitting threads.\n'

    # stop main program
    app['plugins']['main'].stop()
Exemplo n.º 31
0
# -*- coding: utf-8 -*-
'''
Discover all instances of unittest.TestCase in this directory.
'''
# Import python libs
import sys
import os
import logging
import optparse
import resource
import tempfile

# Import salt libs
try:
    import console
    width, height = console.getTerminalSize()
    PNUM = width
except:
    PNUM = 70
import saltunittest
from integration import TestDaemon

try:
    import xmlrunner
except ImportError:
    xmlrunner = None

TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__)))


try:
Exemplo n.º 32
0
def section(string, w=0):
    if w == 0: w, _ = console.getTerminalSize()
    txt = f'== {string} '
    while len(txt) < w:
        txt += '='
    return txt
Exemplo n.º 33
0
# Constants
COLUMNS = ("name","exec","description","icon") # The possible colums (ie fields) that can be outputted (these are keys for <item-dict>'s)


# An exception class for errors encountered that are probably due to the user
class HumanError(Exception):
	pass


# The main attraction
if __name__ == '__main__':


	# Get the terminal dimensions
	(terminalWidth, terminalHeight) = console.getTerminalSize()


	## The argument parser

	# Initialise the argument parser
	argParser = ArgumentParser(
		description="A command-line application launcher",
		add_help=False
		)

	# The help option - I want it to be capitalised and end with a full-stop
	argParser.add_argument(
		"-h",
		"--help",
		action="help",
Exemplo n.º 34
0
import oauth2 as oauth
import urllib
import json
import sys
import console

twitter_api = 'https://api.twitter.com/1/'
consumer_key = ''
consumer_key_secret = ''
access_token = ''
access_token_secret = ''

consumer = oauth.Consumer(key=consumer_key, secret=consumer_key_secret)
token = oauth.Token(key=access_token, secret=access_token_secret)
client = oauth.Client(consumer, token)
size = console.getTerminalSize()
width = size[0] - (15+1)

def home_timeline():
    url = twitter_api + "statuses/home_timeline.json?count=100"
    content = client.request(url, "GET")
    tweets = list(json.loads(content[1]))
    print_tweets(tweets)

def mentions():
    url = twitter_api + "statuses/mentions.json"
    content = client.request(url, "GET")
    tweets = list(json.loads(content[1]))
    print_tweets(tweets)

def search(query):
Exemplo n.º 35
0
try:
    get_char = unichr
except NameError:
    get_char = chr


#HAN = get_char(0x4DFF)
HAN = get_char(0x7121)  # nothing


"""
BOARDWIDTH = 100
BOARDHEIGHT = 48
"""
import console
(BOARDWIDTH, BOARDHEIGHT) = console.getTerminalSize()

EAST_ASIAN_BOARDWIDTH = BOARDWIDTH / 2

# delta is the width of populations
DELTA1 = 10

CHAR_INCLUDE_RANGE = [
        ( 0x0021, 0x0021 ),
        ( 0x0023, 0x0026 ),
        ( 0x0028, 0x007E ),
        ( 0x00A1, 0x00AC ),
        ( 0x00AE, 0x00FF ),
        ( 0x0100, 0x017F ),
        ( 0x0180, 0x024F ),
        ( 0x2C60, 0x2C7F ),
Exemplo n.º 36
0
def main():
    # init app config
    global app
    app['conf'] = ConfigParser.SafeConfigParser()
    app['path'] = {}
    app['path']['app'] = os.path.dirname(os.path.realpath(__file__)) + os.sep

    # add import path
    sys.path.append(app['path']['app'] + 'lib')
    sys.path.append(app['path']['app'] + 'plugin')
    sys.path.append(app['path']['app'] + 'service')

    # add conf path
    import platformDep
    path = os.path.join(platformDep.getNmcontrolDir(), 'conf') + os.sep
    for argv in sys.argv:
        if argv.startswith("--confdir=") or argv.startswith("--main.confdir="):
            path = argv.split("=")[1]
            path = os.path.realpath(path) + os.sep
    app['path']['conf'] = path

    import common
    common.app = app

    import console
    (cWidth, cHeight) = console.getTerminalSize()
    fmt=optparse.IndentedHelpFormatter(indent_increment=4, max_help_position=40, width=cWidth-3, short_first=1 )
    app['parser'] = optparse.OptionParser(formatter=fmt,description='nmcontrol %s' % __version__)

    # debug mode
    app['debug'] = False
    for s in ['--debug=1', '--main.debug=1']:
        while s in sys.argv:
            app['debug'] = True
            sys.argv.remove(s)  # do not disturb client mode option parsing with debug option

    # parse command line options
    (options, app['args']) = app['parser'].parse_args()

    # determine client mode
    app['client'] = False
    if len(app['args']) > 0 and app['args'][0] != 'start':
        app['client'] = True

    # set up output and log
    if app['client']:
        common.logToFile = False
    log = common.get_logger(__name__, clear=True)
    if not app['client']:
        log.info("#######################################################")
    log.debug("DEBUG MODE")

    # init modules
    import re

    # init vars and main plugin
    app['services'] = {}
    app['plugins'] = {}
    import pluginMain
    app['plugins']['main'] = pluginMain.pluginMain('plugin')

    # init service & plugins
    for modType in ['service', 'plugin']:
        modules = os.listdir(os.path.join(app['path']['app'], modType))
        if modType == 'plugin': modules.remove('pluginMain.py')
        for module in modules:
            if re.match("^"+modType+".*.py$", module):
                module = re.sub(r'\.py$', '', module)
                modulename = re.sub(r'^'+modType, '', module).lower()
                try:
                    log.debug("launching", modType, module)
                    importedModule = __import__(module)
                    importedClass = getattr(importedModule, module)
                    app[modType+'s'][importedClass.name] = importedClass(modType)
                    importedClass.app = app
                except Exception as e:
                    log.exception("Exception when loading " + modType, module, ":", e)

    # structure command line options to suit modules
    # Note: There should not be plugins and services with the same name
    for option, value in vars(options).items():
        if value is not None:
            tmp = option.split('.')
            if len(tmp) == 1:
                app['plugins']['main'].conf[tmp[0]] = value
            else:
                module = tmp[0]
                tmp.remove(module)
                if module in app['plugins']:
                    app['plugins'][module].conf['.'.join(tmp)] = value
                if module in app['services']:
                    app['services'][module].conf['.'.join(tmp)] = value

    ###### Act as client : send rpc request ######
    if app['client']:
        error, data = app['plugins']['rpc'].pSend(app['args'][:])
        if error is True or data['error'] is True:
            print "ERROR:", data
        else:
            if data['result']['reply'] in [None, True]:
                print 'ok'
            else:
                print data['result']['reply']
            if data['result']['prints']:
                log.debug("LOG:", data['result']['prints'])
        if app['args'][0] != 'restart':
            return

    # daemon mode
    if os.name == "nt":  # MS Windows
        log.info("Daemon mode not possible on MS Windows.")
    elif int(app['plugins']['main'].conf['daemon']) == 1:
        log.info("Entering background mode")
        import daemonize
        retCode = daemonize.createDaemon()

    ###### Act as server : start plugins ######
    plugins_started = []
    for plugin in app['plugins']:
        if int(app['plugins'][plugin].conf['start']) == 1 and plugin not in ['rpc','main']:
            # exit immediatly when main is stopped, unless in debug mode
            app['plugins'][plugin].daemon=True
            if app['plugins'][plugin].running is False:
                app['plugins'][plugin].start()
                plugins_started.append(app['plugins'][plugin].name)
    log.info("Plugins started :", ', '.join(plugins_started))

    for plugin in app['plugins']:
        if app['plugins'][plugin].__dict__.has_key("criticalStartException") and app['plugins'][plugin].criticalStartException:
            raise Exception(app['plugins'][plugin].criticalStartException)

    #services_started = []
    #for service in app['services']:
    #    if app['services'][service].running:
    #        services_started.append(app['services'][service].name)
    #print "Services started :", ', '.join(services_started)

    # stay there to catch CTRL + C and not exit when in daemon mode
    try:
        app['plugins']['main'].start2()
    except (KeyboardInterrupt, SystemExit):
        log.info('\n! Received keyboard interrupt, quitting threads.\n')

    # stop main program
    app['plugins']['main'].stop()
Exemplo n.º 37
0
#  YMMMa. 8M     M8 MM.         
# L.   I8 YA.   ,A9  Mb.     , 
# M9mmmP;  .Ybmd9.    ..bmmmd.
# -------------------------------------------------------------------------------------------------------------------------- #
import os, sys, subprocess, time
import traceback, re, readline, math
from scapy.all import *
from contextlib import closing
from datetime import datetime, timedelta
import json, pcapy, sqlite3, struct, traceback
import urllib2, ssl
from math import floor
from fractions import Fraction
# --------------------------------------------------------------------------------------- #
import console
(width, height) = console.getTerminalSize()

termwidth = width 
fillchar = '*'

def print_text_center(text, ch='=', length=width):

    if text is None:
        return ch * length
    elif len(text) + 2 + len(ch)*2 > length:
        # Not enough space for even one line char (plus space) around text.
        return text
    else:
        remain = length - (len(text) + 16)
        prefix_len = remain / 2
        suffix_len = remain - prefix_len
Exemplo n.º 38
0
def main():
    # init app config
    global app
    app['conf'] = ConfigParser.SafeConfigParser()
    app['path'] = {}
    app['path']['app'] = os.path.dirname(os.path.realpath(__file__)) + os.sep

    # add import path
    sys.path.append(app['path']['app'] + 'lib')
    sys.path.append(app['path']['app'] + 'plugin')
    sys.path.append(app['path']['app'] + 'service')

    # add conf path
    import platformDep
    app['path']['conf'] = os.path.join(platformDep.getNmcontrolDir(),
                                       'conf') + os.sep

    import common
    common.app = app

    import console
    (cWidth, cHeight) = console.getTerminalSize()
    fmt=optparse.IndentedHelpFormatter(indent_increment=4, max_help_position=40, width=cWidth-3, short_first=1 )
    app['parser'] = optparse.OptionParser(formatter=fmt,description='nmcontrol %s' % __version__)
    app['debug'] = False

    # debug mode
    for argv in sys.argv:
        if argv in ['--debug=1','--main.debug=1']:
            app['debug'] = True

    # init modules
    import re
    import dircache

    # init vars and main plugin
    app['services'] = {}
    app['plugins'] = {}
    import pluginMain
    app['plugins']['main'] = pluginMain.pluginMain('plugin')

    # init service & plugins
    for modType in ['service', 'plugin']:
        modules = dircache.listdir(modType)
        if modType == 'plugin': modules.remove('pluginMain.py')
        for module in modules:
            if re.match("^"+modType+".*.py$", module):
                module = re.sub(r'\.py$', '', module)
                modulename = re.sub(r'^'+modType, '', module).lower()
                try:
                    importedModule = __import__(module)
                    importedClass = getattr(importedModule, module)
                    app[modType+'s'][importedClass.name] = importedClass(modType)
                    importedClass.app = app
                except Exception as e:
                    print "Exception when loading "+modType, module, ":", e

    # parse command line options
    (options, app['args']) = app['parser'].parse_args()
    if app['debug']: print "Cmdline args:", app['args']
    if app['debug']: print "Cmdline options:", options
    for option, value in vars(options).items():
        if value is not None:
            tmp = option.split('.')
            if len(tmp) == 1:
                app['plugins']['main'].conf[tmp[0]] = value
            else:
                module = tmp[0]
                tmp.remove(module)
                if module in app['plugins']:
                    app['plugins'][module].conf['.'.join(tmp)] = value
                elif module in app['services']:
                    app['services'][module].conf['.'.join(tmp)] = value

    ###### Act as client : send rpc request ######
    if len(app['args']) > 0 and app['args'][0] != 'start':
        error, data = app['plugins']['rpc'].pSend(app['args'][:])
        if error is True or data['error'] is True:
            print "ERROR:", data
        else:
            if data['result']['reply'] in [None, True]:
                print 'ok'
            else:
                print data['result']['reply']
            if app['debug'] and data['result']['prints']: print "LOG:", data['result']['prints']
        if app['args'][0] != 'restart':
            return

    # daemon mode
    if os.name == "nt":  # MS Windows
        print "Daemon mode not possible on MS Windows."
    elif int(app['plugins']['main'].conf['daemon']) == 1:
        print "Entering background mode"
        import daemonize
        retCode = daemonize.createDaemon()

    ###### Act as server : start plugins ######
    plugins_started = []
    for plugin in app['plugins']:
        if int(app['plugins'][plugin].conf['start']) == 1 and plugin not in ['rpc','main']:
            # exit immediatly when main is stopped, unless in debug mode
            app['plugins'][plugin].daemon=True
            if app['plugins'][plugin].running is False:
                app['plugins'][plugin].start()
                plugins_started.append(app['plugins'][plugin].name)
    print "Plugins started :", ', '.join(plugins_started)

    #services_started = []
    #for service in app['services']:
    #    if app['services'][service].running:
    #        services_started.append(app['services'][service].name)
    #print "Services started :", ', '.join(services_started)

    # stay there to catch CTRL + C and not exit when in daemon mode
    try:
        app['plugins']['main'].start2()
    except (KeyboardInterrupt, SystemExit):
        print '\n! Received keyboard interrupt, quitting threads.\n'

    # stop main program
    app['plugins']['main'].stop()
Exemplo n.º 39
0
def associateOppositeStations(linesDict):

    resultList = list()

    for aLine in linesDict:

        if "MbtId" not in aLine:
            continue

        aLineDict = dict()

        lineName = aLine["name"]
        lineId = aLine["MbtId"]

        if "OsmId" in aLine:
            aLineDict["osmId"] = aLine["OsmId"]

        aLineDict["mbtId"] = lineId
        aLineDict["name"] = lineName
        aLineDict["sens1"] = list()
        aLineDict["sens2"] = list()

        if not "sens1" in aLine:
            print(aLine)

        for osmStationId in aLine["sens1"]:
            aDict = dict()
            aDict["name"] = ots.stationName(osmStationId)
            aDict["osmId"] = osmStationId
            aDict["mbtId"] = mbt.stationIdForLine(aDict["name"], lineId, 1)
            aDict["terminus"] = osmStationId in aLine["terminus1"]

            # If there is no mobitrans id for this station on the line with sens1, not adding it
            # /!\ Data should probably be changed on OSM to match with the one from Mobitrans
            if aDict["mbtId"] is None:
                continue

            aLineDict["sens1"].append(aDict)

        for osmStationId in aLine["sens2"]:
            aDict = dict()
            aDict["name"] = ots.stationName(osmStationId)
            aDict["osmId"] = osmStationId
            aDict["mbtId"] = mbt.stationIdForLine(aDict["name"], lineId, 2)
            aDict["terminus"] = osmStationId in aLine["terminus2"]

            # If there is no mobitrans id for this station on the line with sens2, not adding it
            # /!\ Data should probably be changed on OSM to match with the one from Mobitrans
            if aDict["mbtId"] is None:
                continue

            aLineDict["sens2"].append(aDict)
        resultList.append(aLineDict)

    if verbose:
        (termWidth, height) = console.getTerminalSize()
        pprint.pprint(resultList, width=termWidth)

    #  jsonData = json.dumps(resultList, indent=2, sort_keys=True)
    exportToXml(resultList)

    return resultList
Exemplo n.º 40
0
 def handle(*args):
     w.erase()
     w.refresh()
     WIDTH, HEIGHT = console.getTerminalSize()
Exemplo n.º 41
0
 def handle(*args):
     w.erase()
     w.refresh()
     WIDTH, HEIGHT = console.getTerminalSize()
Exemplo n.º 42
0
def mergingData() :
    if not os.path.isfile('osmDirections.json'):
        print("Recreating OSM relations file")
        OSMjson = osmAPI.parseOsmTAGRelation()
        text_file = open("osmDirections.json", "w")
        text_file.write(OSMjson)
        text_file.close()

    print("Loading OSM relations file")
    file = open("osmDirections.json", "r")
    s = file.read()
    linesDict = json.loads(s)


    (termWidth, height) = console.getTerminalSize()
    total = len(linesDict)
    index=0
    print ("Merging the data...")
    for osmLine in linesDict:
        if not verbose:
        # Progressbar stuff
            index = index+1
            percentage = index/total
            sys.stdout.write("\r")
            for i in range(int(termWidth*percentage)):
                sys.stdout.write("-")
                sys.stdout.flush()

        # Assign directions retrived from from OSM to the direction in Mobitrans

        # Testing if the line is available on Mobitrans
        MbtLineId = mbt.idForLine(osmLine["name"])
        if MbtLineId:
            sens = matchingSens(osmLine)
            osmLine["MbtId"] = MbtLineId
            if sens == 1:
                osmLine["sens1"] = osmLine["sensA"]
                osmLine["sens2"] = osmLine["sensB"]
                osmLine["terminus1"] = osmLine["terminusA"]
                osmLine["terminus2"] = osmLine["terminusB"]
                osmLine.pop("sensA", None)
                osmLine.pop("sensB", None)
                osmLine.pop("terminusA", None)
                osmLine.pop("terminusB", None)
            elif sens == 2:
                osmLine["sens2"] = osmLine["sensA"]
                osmLine["sens1"] = osmLine["sensB"]
                osmLine["terminus2"] = osmLine["terminusA"]
                osmLine["terminus1"] = osmLine["terminusB"]
                osmLine.pop("sensA", None)
                osmLine.pop("sensB", None)
                osmLine.pop("terminusA", None)
                osmLine.pop("terminusB", None)
            else:
                osmLine.pop("MbtId", None)
                osmLine.pop("sensA", None)
                osmLine.pop("sensB", None)

        #In case the line ain't present on Mobitrans
        else:
            print(osmLine["name"])
            osmLine.pop("sensA", None)
            osmLine.pop("sensB", None)

    if verbose:
        pprint.pprint(linesDict)

    jsonData = json.dumps(linesDict, indent=4, sort_keys=True)
    text_file = open("MergedData.json", "w")
    text_file.write(jsonData)
    text_file.close()
    return linesDict
Exemplo n.º 43
0
def printTasks(board_id,board_name):
	query = "SELECT task_ids FROM boards WHERE board_id = {0}".format(board_id)
	cursor.execute(query)
	taskList = []
	for task in cursor:
		taskList.append(task)
	print taskList

	tasks = []
	for task in taskList:
		query2 = "SELECT task_description,task_state FROM tasks WHERE task_id = {0}".format(task)
		currentTask = cursor.execute(query2)
		tasks.append(currentTask)

	print tasks

	bl = 0
	ip = 0
	done = 0
	blList = []
	ipList = []
	doneList = []
	i = 0
	(width, height) = console.getTerminalSize()
	for task in tasks:
		for char in task[0]:
			if i == width/3-4:
				task[0] = insert(task[0],'\n',i) 
	    	i+=1
		if task[1] == 0:
			bl += 1
			blList.append(task[0])
		if task[1] == 1:
			ip+= 1
			ipList.append(task[0])
		if task[1] == 2:
			done += 1
			doneList.append(task[0])
	backLogWithSpacing = "Backlog" + " " * (width/3-4-len("Backlog"))
	inProgressWithSpacing = "In Progress" + " " * (width/3-4-len("In Progress"))
	doneWithSpacing = "Done" + " " * (width/3-4-len("Done"))
	allTasks = [[backLogWithSpacing,inProgressWithSpacing,doneWithSpacing]]
	for i in range (0,max(bl,ip,done)):
		currentList = []
		if i < bl:
			currentList.append(blList[i])
		else:
			currentList.append('')
		if i < ip:
			currentList.append[ipList[i]]
		else:
			currentList.append('')
		if i < done:
			currentList.append(doneList[i])
		else:
			currentList.append('')
		allTasks.append(currentList)

	table = DoubleTable(allTasks, board_name)
	table.inner_row_border = True
	print(table.table)
Exemplo n.º 44
0
	def subsMake(self, line):
		# Go through all the prepared subs and try to apply them
		for key, sub in self.subs.items():
			m = sub.search(line)
			if m is not None and key in self.fmt:
				return self.fmt[key].format(m.groupdict())

		# If none applied just cut the line so it fits the terminal
		if len(line) > self.columns:
			ll = line[:self.columns-3]
			return ll + "..."
		else:
			return line.rstrip()

if __name__ == "__main__":
	formatter = Formatter()

	# Initialize the formatter
	filenames = [
		os.getenv('XDG_CONFIG_HOME') + '/fmake/config',
		os.environ['HOME'] + '/.fmakerc',
	]
	formatter.loadConfig(filenames)
	formatter.setColumns(console.getTerminalSize()[1])

	# Format everything we get on standard input and put it on standard output
	for line in stdin:
		stdout.write("%s\n" % formatter.subsMake(line))

Exemplo n.º 45
0
def get_terminal_width():
    """
    Get number of chars that can fit into current terminal
    """
    import console
    return console.getTerminalSize()[0]