def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--folder',
                        '-f',
                        nargs='?',
                        help='Folder containing the json files')
    parser.add_argument('--version',
                        '-v',
                        '-V',
                        action='store_true',
                        help='View version of program')
    args = parser.parse_args()
    config_from_args = args.__dict__
    fil = config_from_args.pop('folder')
    ver = config_from_args.pop('version')
    if ver is not None and ver is True:
        logger.info('Version: ' + __version__)
    elif fil is not None and os.path.isdir(fil):
        folder = fil
        f = []
        f = glob.glob(folder + "/*.json")
        if f.__len__() == 0:
            logger.error(fil + ' doesn`t contain any json files')
        else:
            json_to_dataset(f)
    elif fil is not None and os.path.isdir(fil) is False:
        logger.fatal(fil + ' is not a folder')
    else:
        print(os.system('python2.7 ~/Development/json_to_dataset.py -h'))
示例#2
0
 def openErrorMessage(self, msg):
     logger.fatal(msg)
     msgBox = QMessageBox()
     msgBox.setIcon(QMessageBox.Critical)
     msgBox.setText(msg)
     msgBox.setWindowTitle("Error")
     msgBox.exec_()
示例#3
0
 def get_prefix(self):
     try:
         token = self.config['prefix']
         return token
     except KeyError:
         logger.fatal("Could not find command prefix")
         exit(1)
示例#4
0
 def get_token(self):
     try:
         token = self.config['token']
         return token
     except KeyError:
         logger.fatal("Could not find discord token")
         exit(1)
示例#5
0
def test_fatal(capsys, input, input2, expected_output, desc):
    logger.fatal(input, input2)
    sys.stderr.write(logger.log_stream.getvalue())
    captured = capsys.readouterr()
    logger.log_stream.truncate(0)
    logger.log_stream.seek(0)
    assert re.match(
        r"\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} " + re.escape(expected_output),
        captured.err), desc
示例#6
0
    def shootImage_fullResolution(self, mode="Color"):
        """Shoot single image with maximal camera resolution
        :return np.ndarray: image """
        self.setCaptureSettings(mode, "full")
        if self.cap.grab():
            _, fullImage = self.cap.retrieve(0)
        else:
            logger.fatal("Can't grab camera image")
            logger.fatal("Using test image instead")
            fullImage = cv2.imread(constants.TEST_IMAGE_NAME)

        fullImage = cv2.cvtColor(fullImage, cv2.COLOR_RGB2BGR)

        return fullImage
示例#7
0
def loadSettings():
    """Parse resources/settings.json to constants.settings."""
    path = os.path.join(str(Path(__file__).parent.absolute()),
                        "../resources/settings.json")
    if os.path.isfile(path):
        with open(path) as file:
            try:
                constants.settings = json.load(file)
            except json.decoder.JSONDecodeError as e:
                logger.fatal("settings.json could not be parsed")
                constants.settings = {}
                raise e
    else:
        constants.settings = {}
        raise IOError("Settings file not found in resources/settings.json")
示例#8
0
    def send_keys(self, keys):
        self.__web_element_wait__()
        # Remove from validation
        for _ in range(5):
            self.clear()
            if not self.get_attribute('value'):
                break
            else:
                logger.warning('Not possible to clean ')
                time.sleep(.001)
        else:
            logger.fatal('Fatal Error: %r' % self.value)

        logger.debug('Value %r' % self.value)
        super().send_keys(keys)
示例#9
0
        def wrapper(*args, **kwargs):
            for attempt in range(2, -1, -1):
                try:
                    close_popups(instance.driver)
                    self.method(instance, *args, **kwargs)
                    break

                except Exception as e:
                    # return instance
                    instance.status = 'restart'
                    logger.warning('Browser error %s' % instance.node_info, exc_info=e)
                    if instance.node_connect_retry_count:
                        instance.node_connect_retry_count -= 1
                        instance.restart_session()

            else:
                logger.fatal('Fatal error %s' % instance)
                raise SeleniumBrowserNotStarting()
示例#10
0
 def grab_images(queue):
     self.setCaptureSettings(mode, "low")
     while self.capture:
         if self.cap.grab():
             _, image = self.cap.retrieve(0)
             if image is not None and queue.qsize() < 2:
                 image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                 image = cv2.resize(image,
                                    constants.DISPLAY_RESOLUTION[::-1],
                                    interpolation=cv2.INTER_CUBIC)
                 queue.put(image)
             else:
                 time.sleep(constants.DISP_MSEC / 1000.0)
         else:
             logger.fatal("Can't grab camera image")
             logger.fatal("Using test image instead")
             image = cv2.imread(constants.TEST_IMAGE_NAME)
             image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
             image = cv2.resize(image,
                                constants.DISPLAY_RESOLUTION[::-1],
                                interpolation=cv2.INTER_CUBIC)
             queue.put(image)
             break
示例#11
0
#!/usr/bin/env python3
# This is the TGbot part of this bot.
# This file only defines a pyrogram Bot client, and a simple function which sends a text to bot_master.


from pyrogram import Client
from config import bot_name, bot_token, bot_master
from logger import logger


bot = Client(
	session_name=bot_name,
	bot_token=bot_token
)

def sendmaster(text: str) -> None:
	bot.send_message(
		chat_id=bot_master,
		text=text
		)

if __name__ == "__main__":
    logger.fatal('Please run ./run.py instead.\n')
    exit(1)
 def wrapped(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except Exception as ex:
         logger.fatal('{0}. {1}'.format(func.__name__, ex))
示例#13
0
            token = self.config['prefix']
            return token
        except KeyError:
            logger.fatal("Could not find command prefix")
            exit(1)


def start_check():

    if not os.path.exists("./data"):
        os.mkdir("./data")

    if not os.path.exists("./data/config.json"):
        with open("./data/config.json", "w") as f:
            f.write("{}")
            f.close()


start_check()
config = Config()
client = commands.Bot(command_prefix=config.get_prefix())
start_check()
for file in os.listdir("./cogs"):
    if file.endswith(".py"):
        client.load_extension("cogs.{}".format(file[:-3]))
        logger.info("Successfully loaded {} cog".format(file[:-3]))
try:
    client.run(config.get_token())
except discord.errors.LoginFailure:
    logger.fatal("Failed to login to discord!")
示例#14
0
    def __init__(self):
        settings = dict(debug=False,
                        cookie_secret="asdasfsdjf#8899",
                        template_path=os.path.join(os.path.dirname(__file__),
                                                   "templates"),
                        static_path=os.path.join(os.path.dirname(__file__),
                                                 "static"),
                        xsrf_cookies=False)
        mongo = MongoClient(config.get('mongodb', 'host'),
                            config.getint("mongodb", "port"))
        self.db = mongo.xinrui
        super(App, self).__init__(handlers, **settings)


try:
    options, args = getopt(sys.argv[1:], "port:", ["port="])
except GetoptError, e:
    logger.fatal(e)

port = 8080
for option in options:
    if option[0] == "--port":
        port = int(option[1])
        break

http_server = HTTPServer(App(), xheaders=True)
http_server.bind(port)
http_server.start(1)
logger.info("http server start on port %s..." % port)
IOLoop.instance().start()