Esempio n. 1
0
def main(outsourcedLogger=None):

    if outsourcedLogger is None:
        logger = Log.Logger()
    else:
        logger = outsourcedLogger

    logger.printAndLog(const.MessageType.Summarize.value, "Gathering data...")
    twitterService = TwitterCrawler(logger)

    # Fetch tweets
    logger.printAndLog(const.MessageType.Header.value, "Collecting data from twitter...")
    twitterService.crawlTwitter()

    # Merge files
    operations = DataBaseOperationsService(logger)
    logger.printAndLog(const.MessageType.Header.value, "Merging new data with current database...")
    operations.merge()

    # Plot statistics
    statistics = DataBaseStatistics(logger)
    statistics.PublishDataBaseCompaniesGraph()
    statistics.PublishDataBaseCompaniesKeywordsGraph()

    # Done
    logger.printAndLog(const.MessageType.Summarize.value, "Gathering finished...")
Esempio n. 2
0
    def Run(self, vrouter, cni_params):
        '''
        main method for CNI plugin
        '''
        global logger
        logger = Logger.Logger('cni', cni_params.contrail_params.log_file,
                               cni_params.contrail_params.log_level)

        self.params = cni_params
        self.vrouter = vrouter
        ret = True
        code = 0
        if self.params.command.lower() == 'version':
            resp = self.Version()
        elif self.params.command.lower() == 'add':
            resp = self.add_cmd()
        elif self.params.command.lower() == 'delete':
            resp = self.delete_cmd()
        elif self.params.command.lower() == 'get':
            resp = self.get_cmd()
        elif self.params.command.lower() == 'poll':
            resp = self.poll_cmd()
        else:
            raise CniError(CNI_UNSUPPORTED_CMD,
                           'Invalid command ' + self.params.command)

        json_data = json.dumps(resp, indent=4)
        logger.debug('CNI output : ' + json_data)
        print json_data
        return
Esempio n. 3
0
    def Run(self, vrouter, cni_params):
        '''
        main method for CNI plugin
        '''
        global logger
        logger = Logger.Logger('cni', cni_params.contrail_params.log_file,
                               cni_params.contrail_params.log_level)

        self.params = cni_params
        self.vrouter = vrouter
        if self.params.command.lower() == CNI_CMD_VERSION:
            resp = self.Version()
        elif self.params.command.lower() == CNI_CMD_ADD:
            resp = self.add_cmd()
        elif (self.params.command.lower() == CNI_CMD_DELETE or
              self.params.command.lower() == CNI_CMD_DEL):
            resp = self.delete_cmd()
        elif self.params.command.lower() == CNI_CMD_GET:
            resp = self.get_cmd()
        elif self.params.command.lower() == CNI_CMD_POLL:
            resp = self.poll_cmd()
        else:
            raise CniError(CNI_UNSUPPORTED_CMD,
                           'Invalid command ' + self.params.command)

        json_data = json.dumps(resp, indent=4)
        logger.debug('CNI output : ' + json_data)
        print json_data
        return
Esempio n. 4
0
 def __init__(self, taskId, stratExecConfig):
     chanchero.tasks.MasterTask.__init__(self, taskId)
     # Everything that is defined here should be pickleable or reset in beforeToPickleString.
     self.__stratExecConfigKey = stratExecConfig.key()
     self.__paramsIt = build_params_iterator(stratExecConfig)
     self.__tooManyErrosChecked = False
     self.__logger = logger.Logger()
Esempio n. 5
0
 def __init__(self, driver):
     '''获取操作系统信息'''
     platform1 = platform.platform(
     )  # 获取操作系统名称及版本号,'Windows-7-6.1.7601-SP1'
     version = platform.version()  # 获取操作系统版本号,'6.1.7601'
     architecture = platform.architecture(
     )  # 获取操作系统的位数,('32bit', 'WindowsPE')
     machine = platform.machine()  # 计算机类型,'x86'
     node = platform.node()  # 计算机的网络名称,'hongjie-PC'
     processor = platform.processor(
     )  # 计算机处理器信息,'x86 Family 16 Model 6 Stepping 3, AuthenticAMD'
     uname = platform.uname(
     )  # 包含上面所有的信息汇总,uname_result(system='Windows', node='hongjie-PC',
     MASTER_HELPER.environment(platform=platform1,
                               version=version,
                               architecture=architecture,
                               machine=machine,
                               node=node,
                               processor=processor,
                               uname=uname)
     '''设置轮循时间及超时时间'''
     self.logger = logger.Logger().getLogger()
     self.driver = driver
     self.timeout = 10
     self.t = 0.5
Esempio n. 6
0
 def __init__(self, taskId, stratExecConfigKey, paramsIt, chunkSize):
     chanchero.tasks.WorkerTask.__init__(self, taskId)
     # Everything that is defined here should be pickleable or reset in beforeToPickleString.
     self.__stratExecConfigKey = stratExecConfigKey
     self.__paramsIt = paramsIt
     self.__chunkSize = chunkSize
     self.__logger = logger.Logger()
Esempio n. 7
0
 def __init__(self, ip, port, timeout, retries, directory, log_file,
              log_level):
     self.ip = ip
     self.port = port
     self.poll_timeout = timeout
     self.poll_retries = retries
     self.directory = directory
     global logger
     logger = Logger.Logger('vrouter', log_file, log_level)
     return
def main():
    params = Params.Params()
    args = parse_args()
    input_json = read_config_file(args.file)

    # Read logging parameters first and then create logger
    params.get_loggin_params(input_json)
    global logger
    logger = Logger.Logger('opencontrail', params.contrail_params.log_file,
                           params.contrail_params.log_level)

    try:
        # Set command from argument if specified
        if args.command is not None:
            os.environ['CNI_COMMAND'] = args.command
        # Set UUID from argument. If valid-uuid is found, it will overwritten
        # later. Useful in case of UT where valid uuid for pod cannot be found
        if args.uuid is not None:
            params.k8s_params.set_pod_uuid(args.uuid)

        # Set PID from argument. If valid pid is found, it will overwritten
        # later. Useful in case of UT where valid pid for pod cannot be found
        if args.pid is not None:
            params.k8s_params.set_pod_pid(args.pid)

        # Update parameters from environement and input-string
        params.get_params(input_json)
    except Params.ParamsError as params_err:
        params_err.log()
        Cni.ErrorExit(logger, params_err.code, params_err.msg)

    # Log params for debugging
    params.log()
    try:
        contrail_params = params.contrail_params
        vrouter = VRouter.VRouter(contrail_params.vrouter_ip,
                                  contrail_params.vrouter_port,
                                  contrail_params.poll_timeout,
                                  contrail_params.poll_retries,
                                  contrail_params.directory,
                                  contrail_params.log_file,
                                  contrail_params.log_level)
        cni = Cni.Cni(vrouter, params)
        # Run CNI
        cni.Run(vrouter, params)
    except Cni.CniError as cni_err:
        cni_err.log()
        Cni.ErrorExit(logger, cni_err.code, cni_err.msg)
        sys.exit(cni_err.code)
    except VRouter.VRouterError as vr_err:
        vr_err.log()
        Cni.ErrorExit(logger, vr_err.code, vr_err.msg)
        sys.exit(cni_err.code)
    return
Esempio n. 9
0
 def __init__(self, args=None):
     self.args = args
     self.logger = logger.Logger(args)
     self.q = Queue()
     self.vnc = vnc_kubernetes.VncKubernetes(args=self.args,
         logger=self.logger, q=self.q)
     self.namespace = namespace_monitor.NamespaceMonitor(args=self.args,
         logger=self.logger, q=self.q)
     self.pod = pod_monitor.PodMonitor(args=self.args,
         logger=self.logger, q=self.q)
     self.service = service_monitor.ServiceMonitor(args=self.args,
         logger=self.logger, q=self.q)
     self.network_policy = network_policy_monitor.NetworkPolicyMonitor(
         args=self.args, logger=self.logger, q=self.q)
def main():
    """自动合并发布分支,创建分支标记。"""
    global log
    log = logger.Logger().getlog()
    isexit = "t"
    while isexit == "t":
        # 选择哪种操作
        process = input("请选择哪种处理(1--合并发布分支,2--创建tag):")

        if process not in ("1", "2"):
            process = input("请选择(1--合并发布分支,2--创建tag):")

        if process not in ("1", "2"):
            log.error("抱歉您的选择不在选项中,无法处理,谢谢。")
            return

        # 判断能否启动git
        cnt = call("git --version")
        if cnt.returncode != 0:
            log.error("此电脑不能运行git,请安装git,并加入坏境变量path中。")
            return

        # 项目路径
        projectpath = input("请输入项目路径(例:F:/git-source/team/api):")

        if os.path.exists(projectpath):
            # 跳转到目录下
            os.chdir(projectpath)
            path = os.getcwd()
            loginfo = "已经跳转到目录: %s" % (path)
            log.info(loginfo)

        # 项目名
        projectname = input("请输入项目名(例:school.igrow.cn):")

        # 发布分支
        releasebranch = input("请输入发布分支:")

        if process == "1":
            mergebranch(projectname, releasebranch)
            loginfo = ">>>>>项目(%s)合并分支处理完毕。" % (projectname)
            log.info(loginfo)
        elif process == "2":
            version = input("请输入项目版本:")
            createtag(projectname, releasebranch, version)
            loginfo = ">>>>>项目(%s)创建tag处理完毕。" % (projectname)
            log.info(loginfo)

        isexit = input("您要继续处理其他项目吗?(t--继续,q--退出):")
Esempio n. 11
0
def main():
    logger = Logger.Logger()

    logger.printAndLog(
        const.MessageType.Summarize,
        "Welcome to our project: \"Stock prediction by twitter\" :)")
    logger.printAndLog(const.MessageType.printLog, "")

    tweetsCrawler = input(const.MAIN_HEADER +
                          "Do you want to run the twitter crawler? \n"
                          "Twitter crawler uses twitter's REST API "
                          "to fetch new tweets.\n"
                          "Type <yes/no>: " + const.MAIN_ENDC)

    if tweetsCrawler == "yes":
        tc.main(logger)
    else:
        logger.printAndLog(const.MessageType.Summarize,
                           "TweetsCrawler not ran")

    runPreProcessing = input(
        const.MAIN_HEADER + "Do you want to run the Preprocessor? \n"
        "Preprocessor uses fetched databases to build and analyze "
        "stocks database prior the learning stage. \n"
        "Type <yes/no>: " + const.MAIN_ENDC)
    if runPreProcessing == "yes":
        init.main(logger)
    else:
        logger.printAndLog(const.MessageType.Summarize, "Preprocessor not ran")

    runMachineLearning = input(const.MAIN_HEADER +
                               "Do you want to run the machine learner? \n"
                               "description \n"
                               "Type <yes/no>: " + const.MAIN_ENDC)

    if runMachineLearning == "yes":
        learner.main(logger)
    else:
        logger.printAndLog(const.MessageType.Summarize,
                           "MachineLearner not ran")
Esempio n. 12
0
    def getNextWorker(self):
        # Check if we need to abort executions.
        # We're doing this only once per MasterTask execution to avoid calling the db too much.
        if not self.__tooManyErrosChecked:
            self.__tooManyErrosChecked = True
            stratExecConfig = persistence.StratExecConfig.getByKey(
                self.__stratExecConfigKey)
            if stratExecConfig.status == persistence.StratExecConfig.Status.CANCELED_TOO_MANY_ERRORS:
                logger.Logger().error(
                    "Dropping execution of '%s' due to too many errors" %
                    (stratExecConfig.className))
                return None

        chunkSize = 1000  # Max executions per task.
        ret = None
        if not self.isFinished():
            # Clone self.__paramsIt before building WorkerTask because we'll modify it immediately.
            paramsIt = copy.deepcopy(self.__paramsIt)
            ret = WorkerTask(1, self.__stratExecConfigKey, paramsIt, chunkSize)

            # Advance parameters iterator for the next worker.
            for i in xrange(chunkSize):
                self.__paramsIt.moveNext()
        return ret
Esempio n. 13
0
    def __init__(self,
                 driver_name=None,
                 driver_path=None,
                 timeout=10,
                 headless=False):
        driver = None
        if driver_path is None:
            driver_path = os.path.join(BASE_PATH, 'utils', 'chromedriver.exe')
        if driver_name is None:
            driver_name = "chrome"
        if driver_name == "chrome":
            options = webdriver.ChromeOptions()
            if headless:
                options.add_argument('--headless')
            driver = webdriver.Chrome(executable_path=driver_path,
                                      options=options)
        elif driver_name == 'firefox':
            options = webdriver.FirefoxOptions()
            if headless:
                options.add_argument('--headless')
            driver = webdriver.Firefox(executable_path=driver_path,
                                       options=options)
        elif driver_name == 'ie':
            driver = webdriver.Ie()
        elif driver_path == 'edge':
            driver = webdriver.Edge()

        if driver is None:
            raise NameError(
                "Not found {} browser, You can enter 'ie', 'firefox','edge', 'chrome'."
                .format(driver_name))
        else:
            self.driver = driver
            self.timeout = timeout
            self.wait = WebDriverWait(self.driver, self.timeout)
            self.logger = logger.Logger().get_logger()
Esempio n. 14
0
class WorkerTask(chanchero.tasks.WorkerTask):
    def __init__(self, taskId, stratExecConfigKey, paramsIt, chunkSize):
        chanchero.tasks.WorkerTask.__init__(self, taskId)
        # Everything that is defined here should be pickleable or reset in beforeToPickleString.
        self.__stratExecConfigKey = stratExecConfigKey
        self.__paramsIt = paramsIt
        self.__chunkSize = chunkSize

    def run(self):
        global strategyExecutor

        taskTimer = timer.Timer()
        stratExecConfig = persistence.StratExecConfig.getByKey(
            self.__stratExecConfigKey)
        # logger.Logger().info("WorkerTask for '%s' starting from %s" % (stratExecConfig.className, str(self.__paramsIt.getCurrent())))

        maxTaskRunTime = 9 * 60  # Stop the task after 9 minutes to avoid getting interrupted after 10 minutes.
        bestResult = 0.0
        bestResultParams = []
        errors = 0
        executions = 0
        maxStratTime = 0

        while self.__chunkSize > 0:
            stratExecTimer = timer.Timer()
            try:
                paramValues = self.__paramsIt.getCurrent()
                # logger.Logger().info("WorkerTask running '%s' with parameters: %s" % (stratExecConfig.className, paramValues))

                # If there are no more parameters, just stop.
                if paramValues is None:
                    break

                result = strategyExecutor.runStrategy(stratExecConfig,
                                                      paramValues)
                if result > bestResult:
                    bestResult = result
                    bestResultParams = paramValues
            except Exception, e:
                errors += 1
                strategyExecutor.getLogger().error(
                    "Error executing strategy '%s' with parameters %s: %s" %
                    (stratExecConfig.className, paramValues, e))
                strategyExecutor.getLogger().error(traceback.format_exc())

            maxStratTime = max(maxStratTime, stratExecTimer.secondsElapsed())
            executions += 1
            self.__chunkSize -= 1
            self.__paramsIt.moveNext()

            # Stop executing if we'll ran out of time with the next execution.
            if self.__chunkSize > 0 and taskTimer.secondsElapsed(
            ) + maxStratTime > maxTaskRunTime:
                break

        # Save the (potentially partial) results.
        ResultTask(1, self.__stratExecConfigKey, bestResult, bestResultParams,
                   executions, errors).queue()

        # Reschedule ourselves if there is work left to do.
        if self.__chunkSize > 0 and self.__paramsIt.getCurrent() is not None:
            logger.Logger().info(
                "Rescheduling WorkerTask for '%s'. %d executions completed. Continuing from %s."
                % (stratExecConfig.className, executions,
                   self.__paramsIt.getCurrent()))
            self.queue()
        else:
            logger.Logger().info(
                "WorkerTask for '%s' finished after %d minutes. %d executions completed. Max strat runtime %d seconds."
                % (stratExecConfig.className, taskTimer.minutesElapsed(),
                   executions, maxStratTime))
Esempio n. 15
0
 def __init__(self):
     self.logger = logger.Logger().getLogger()
from config import settings, U3_settings
from config.config import global_config
import uiautomator2 as u2
from pywinauto import application
# from openpyxl import xw.Book
import xlwings as xw

# 启动切口工具
subprocess.getstatusoutput(" ".join(["start", settings.Qualcomm_SwitchCom_file]))

# 获取项目名称
project_name = os.path.basename(__file__).split('.')[0]
# 创建log对象
log_name = '.'.join(['_'.join([project_name, time.strftime('%Y%m%d%H%M%S', time.localtime())]), "log"])
log_file = os.path.join(BASEDIR, "logs", log_name)
log = logger.Logger(screen_output=True, log_level='logging.INFO', log_file=log_file).create_logger()

@allure.feature("FOTA")
class Test_Fota:
    def setup_class(self):
        log.info("-" * 20 + "Start Test_Fota" + "-" * 20)
        # 测试截图、视频的保存路径;如果不存在此路径,就创建此路径
        self.test_record_path = '/'.join([BASEDIR, 'TestRecord', project_name, "Test_Fota"])
        if not os.path.exists(self.test_record_path):
            os.makedirs(self.test_record_path)

        # 初始化信息
        self.serialno = global_config.getRaw("S1_S13", "serialno")
        self.source_version = global_config.getRaw("S1_S13", "source_version")
        self.target_version = global_config.getRaw("S1_S13", "target_version")
        self.s1 = models.Glocalme(device_id=self.serialno, log_project=log)
Esempio n. 17
0
# coding=utf-8
# pylint: disable=C0103
'''
批量下载入口函数
Licensed to MIT
'''

import Queue
import qphoto
from worker import Worker
import common
from common import logger

qq = 10000
print '正在登陆...'
logger = logger.Logger()
qz = qphoto.QzonePhoto(logger)
qz.login(10000, 'Password')
print '登录完成!'
common.set_queue(Queue.Queue())
common.set_main_thread_pending(False)
worker_count = 2
worker_list = []
while worker_count > 0:
    worker = Worker(logger)
    worker.setDaemon(False)
    worker.start()
    worker_count -= 1
    worker_list.append(worker)
qz.savephotos(qq)
logger.info(u'主线程已经将所有任务放到队列中')
Esempio n. 18
0
 def __init__(self):
     self.logger = logger.Logger().print_log()
Esempio n. 19
0
    def do_startup(self):
        Gtk.Application.do_startup(self)

        import gtkexcepthook
        gtkexcepthook.init()

        try:
            import nbxmpp
        except ImportError:
            print('Gajim needs python-nbxmpp to run. Quitting…')
            sys.exit(1)

        from distutils.version import LooseVersion as V
        if V(nbxmpp.__version__) < V(MIN_NBXMPP_VER):
            print('Gajim needs python-nbxmpp >= %s to run. '
                  'Quitting…' % MIN_NBXMPP_VER)
            sys.exit(1)

        # Create and initialize Application Paths & Databases
        from common import configpaths
        configpaths.gajimpaths.init(self.config_path, self.profile,
                                    self.profile_separation)

        if hasattr(sys, 'frozen'):
            self.frozen_logging(configpaths.gajimpaths.config_root)

        from common import gajim
        from common import check_paths
        from common import exceptions
        from common import logger
        from common import caps_cache
        try:
            gajim.logger = logger.Logger()
            caps_cache.initialize(gajim.logger)
            check_paths.check_and_possibly_create_paths()
        except exceptions.DatabaseMalformed:
            dlg = Gtk.MessageDialog(
                None,
                Gtk.DialogFlags.DESTROY_WITH_PARENT | Gtk.DialogFlags.MODAL,
                Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _('Database Error'))
            dlg.format_secondary_text(
                _('The database file (%s) cannot be read. Try to repair it '
                  '(see http://trac.gajim.org/wiki/DatabaseBackup) or remove it '
                  '(all history will be lost).') % gajim.gajimpaths['LOG_DB'])
            dlg.run()
            dlg.destroy()
            sys.exit()

        if os.name == 'nt':
            import gettext
            # needed for docutils
            sys.path.append('.')
            APP = 'gajim'
            DIR = '../po'
            lang, enc = locale.getdefaultlocale()
            os.environ['LANG'] = lang
            gettext.bindtextdomain(APP, DIR)
            gettext.textdomain(APP)
            gettext.install(APP, DIR)

        # This is for Windows translation which is currently not
        # working on GTK 3.18.9
        #    locale.setlocale(locale.LC_ALL, '')
        #    import ctypes
        #    import ctypes.util
        #    libintl_path = ctypes.util.find_library('intl')
        #    if libintl_path == None:
        #        local_intl = os.path.join('gtk', 'bin', 'intl.dll')
        #        if os.path.exists(local_intl):
        #            libintl_path = local_intl
        #    if libintl_path == None:
        #        raise ImportError('intl.dll library not found')
        #    libintl = ctypes.cdll.LoadLibrary(libintl_path)
        #    libintl.bindtextdomain(APP, DIR)
        #    libintl.bind_textdomain_codeset(APP, 'UTF-8')
        #    plugins_locale_dir = os.path.join(common.configpaths.gajimpaths[
        #       'PLUGINS_USER'], 'locale').encode(locale.getpreferredencoding())
        #    libintl.bindtextdomain('gajim_plugins', plugins_locale_dir)
        #    libintl.bind_textdomain_codeset('gajim_plugins', 'UTF-8')

        if Gtk.Widget.get_default_direction() == Gtk.TextDirection.RTL:
            i18n.direction_mark = '\u200F'

        from ctypes import CDLL
        from ctypes.util import find_library
        import platform

        sysname = platform.system()
        if sysname in ('Linux', 'FreeBSD', 'OpenBSD', 'NetBSD'):
            libc = CDLL(find_library('c'))

            # The constant defined in <linux/prctl.h> which is used to set the name
            # of the process.
            PR_SET_NAME = 15

            if sysname == 'Linux':
                libc.prctl(PR_SET_NAME, 'gajim')
            elif sysname in ('FreeBSD', 'OpenBSD', 'NetBSD'):
                libc.setproctitle('gajim')

        # Seed the OpenSSL pseudo random number generator from file and initialize
        if PYOPENSSL_PRNG_PRESENT:
            self.rng_seed = gajim.gajimpaths['RNG_SEED']
            # Seed from file
            try:
                OpenSSL.rand.load_file(self.rng_seed)
            except TypeError:
                OpenSSL.rand.load_file(self.rng_seed.encode('utf-8'))
            crypto.add_entropy_sources_OpenSSL()
            try:
                OpenSSL.rand.write_file(self.rng_seed)
            except TypeError:
                OpenSSL.rand.write_file(self.rng_seed.encode('utf-8'))

        def sigint_cb(num, stack):
            print('SIGINT/SIGTERM received')
            self.quit()

        # ^C exits the application normally
        signal.signal(signal.SIGINT, sigint_cb)
        signal.signal(signal.SIGTERM, sigint_cb)

        print("Encodings: d:{}, fs:{}, p:{}".format(
            sys.getdefaultencoding(), sys.getfilesystemencoding(),
            locale.getpreferredencoding()))

        # Set Application Menu
        gajim.app = self
        path = os.path.join(configpaths.get('GUI'), 'application_menu.ui')
        builder = Gtk.Builder()
        builder.set_translation_domain(i18n.APP)
        builder.add_from_file(path)
        self.set_menubar(builder.get_object("menubar"))
        self.set_app_menu(builder.get_object("appmenu"))
Esempio n. 20
0
 def __init__(self, driver):
     self.logger = logger.Logger()
     self.driver = driver
     self.timeout = 10
     self.t = 0.5
Esempio n. 21
0
import xlrd
import os
from common import logger
from common.config_manager import ConfigManager

log = logger.Logger('ReadExl').get_log()


class ReadExl(object):
    """
    读取excle中的数据,默认从第二行开始读取,以字典格式输入,提供接口使用
    """
    def __init__(self, ex_name, sheet=0):
        """
        初始化excle,传入服务名称查询到excle_name和case_data
        """
        # 获取在配置文件中管理的文件名称,然后拿到文件的存储路径
        case_dir, case_data = ConfigManager.get_ex_name(ex_name).split(',')
        path = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                            'project_data', case_dir, case_data)
        log.info('准备读取的测试数据为%s' % path)
        self.data = xlrd.open_workbook(path, encoding_override='utf-8')
        # 默认选取第一张sheet
        self.table = self.data.sheet_by_index(sheet)
        # 获取第一行的值作为key
        self.keys = self.table.row_values(0)
        # 获取总行数
        self.rowNumber = self.table.nrows
        # 获取总列数
        self.colNumber = self.table.ncols
Esempio n. 22
0
    def do_activate(self):
        # If a second instance starts do_activate() is called
        # We bringt the Roster window to the front, GTK exits afterwards.
        if self.interface:
            self.interface.roster.window.present()
            return

        Gtk.Application.do_activate(self)

        import gtkexcepthook
        gtkexcepthook.init()

        # Create and initialize Application Paths & Databases
        import common.configpaths
        common.configpaths.gajimpaths.init(self.config_path, self.profile,
                                           self.profile_separation)
        from common import gajim
        from common import check_paths
        from common import exceptions
        from common import logger
        from common import caps_cache
        try:
            gajim.logger = logger.Logger()
            caps_cache.initialize(gajim.logger)
            check_paths.check_and_possibly_create_paths()
        except exceptions.DatabaseMalformed:
            dlg = Gtk.MessageDialog(
                None,
                Gtk.DialogFlags.DESTROY_WITH_PARENT | Gtk.DialogFlags.MODAL,
                Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _('Database Error'))
            dlg.format_secondary_text(
                _('The database file (%s) cannot be read. Try to repair it '
                  '(see http://trac.gajim.org/wiki/DatabaseBackup) or remove it '
                  '(all history will be lost).') % gajim.gajimpaths['LOG_DB'])
            dlg.run()
            dlg.destroy()
            sys.exit()

        if os.name == 'nt':
            import gettext
            # needed for docutils
            sys.path.append('.')
            APP = 'gajim'
            DIR = '../po'
            lang, enc = locale.getdefaultlocale()
            os.environ['LANG'] = lang
            gettext.bindtextdomain(APP, DIR)
            gettext.textdomain(APP)
            gettext.install(APP, DIR)

        # This is for Windows translation which is currently not
        # working on GTK 3.18.9
        #    locale.setlocale(locale.LC_ALL, '')
        #    import ctypes
        #    import ctypes.util
        #    libintl_path = ctypes.util.find_library('intl')
        #    if libintl_path == None:
        #        local_intl = os.path.join('gtk', 'bin', 'intl.dll')
        #        if os.path.exists(local_intl):
        #            libintl_path = local_intl
        #    if libintl_path == None:
        #        raise ImportError('intl.dll library not found')
        #    libintl = ctypes.cdll.LoadLibrary(libintl_path)
        #    libintl.bindtextdomain(APP, DIR)
        #    libintl.bind_textdomain_codeset(APP, 'UTF-8')
        #    plugins_locale_dir = os.path.join(common.configpaths.gajimpaths[
        #       'PLUGINS_USER'], 'locale').encode(locale.getpreferredencoding())
        #    libintl.bindtextdomain('gajim_plugins', plugins_locale_dir)
        #    libintl.bind_textdomain_codeset('gajim_plugins', 'UTF-8')

        if Gtk.Widget.get_default_direction() == Gtk.TextDirection.RTL:
            i18n.direction_mark = '\u200F'

        from ctypes import CDLL
        from ctypes.util import find_library
        import platform

        sysname = platform.system()
        if sysname in ('Linux', 'FreeBSD', 'OpenBSD', 'NetBSD'):
            libc = CDLL(find_library('c'))

            # The constant defined in <linux/prctl.h> which is used to set the name
            # of the process.
            PR_SET_NAME = 15

            if sysname == 'Linux':
                libc.prctl(PR_SET_NAME, 'gajim')
            elif sysname in ('FreeBSD', 'OpenBSD', 'NetBSD'):
                libc.setproctitle('gajim')

        # Seed the OpenSSL pseudo random number generator from file and initialize
        if PYOPENSSL_PRNG_PRESENT:
            self.rng_seed = gajim.gajimpaths['RNG_SEED']
            # Seed from file
            try:
                OpenSSL.rand.load_file(self.rng_seed)
            except TypeError:
                OpenSSL.rand.load_file(self.rng_seed.encode('utf-8'))
            crypto.add_entropy_sources_OpenSSL()
            try:
                OpenSSL.rand.write_file(self.rng_seed)
            except TypeError:
                OpenSSL.rand.write_file(self.rng_seed.encode('utf-8'))

        def sigint_cb(num, stack):
            print('SIGINT/SIGTERM received')
            self.quit()

        # ^C exits the application normally
        signal.signal(signal.SIGINT, sigint_cb)
        signal.signal(signal.SIGTERM, sigint_cb)

        log.info("Encodings: d:%s, fs:%s, p:%s", sys.getdefaultencoding(),
                 sys.getfilesystemencoding(), locale.getpreferredencoding())

        from gui_interface import Interface
        self.interface = Interface()
        self.interface.run(self)
Esempio n. 23
0
 def get_loggin_params(self, json_input):
     self.contrail_params.get_loggin_params(json_input.get('contrail'))
     global logger
     logger = Logger.Logger('params', self.contrail_params.log_file,
                            self.contrail_params.log_level)
Esempio n. 24
0
 def _create_directories(self):
     """Create necessary sub-directories."""
     self._checkpoint_dir = os.path.join(self._base_dir, 'checkpoints')
     self._logger = logger.Logger(os.path.join(self._base_dir, 'logs'))
import json
import requests
import hashlib
from common import logger
from common.constants import Constants
from common.config_manager import ConfigManager

log = logger.Logger('RequestManager').get_log()


class RequestManager(object):
    """请求的实现类"""
    @staticmethod
    def send_requests(**kwargs):
        url = ConfigManager.get_service(Constants.HOST.TEST)
        # todo 关于接口签名认证的方法可以做进一步处理如:直接去数据库查询等。
        headers = {
            'User-Agent': ConfigManager.get_basic(Constants.UserAgent.CHROME)
        }  # 请求头默认带浏览器chrome 可配置
        headers = headers if kwargs.get('HEADERS') is None else dict(
            headers, **kwargs.get('HEADERS'))  # 和传入的请求头合并
        # method = 'post' if kwargs.get('请求类型') is '' else kwargs.get('METHOD')
        method = 'post'
        allow_redirects = True if kwargs.get(
            'allow_redirects') is None else kwargs.get(
                'allow_redirects')  # 是否重定向
        timeout = 500 if kwargs.get('time_out') is None else kwargs.get(
            'time_out')  # 超时时间的设置
        data = dict()
        format_data = kwargs.get('data')
        if isinstance(format_data, str):
Esempio n. 26
0
 def __init__(self):
     self.__logger = logger.Logger()
     self.__barCache = BarsCache(self.__logger)
Esempio n. 27
0
            if (os.environ['PYTHON_ENV'] == "debug"
                    and currentImagePath is not None):
                path = currentImagePath.replace(".jpg", "-lanes.jpg")
                cv2.imwrite(path, imageWithLane)
            if (self.type == "VID"):
                return cv2.cvtColor(imageWithLane, cv2.COLOR_BGR2RGB)
            return imageWithLane
        else:
            if (self.type == "VID"):
                return cv2.cvtColor(currentImage, cv2.COLOR_BGR2RGB)
            return currentImage


if __name__ == '__main__':
    # logging.basicConfig(filename='myapp.log', level=logging.INFO)
    log = logger.Logger(os.environ['PYTHON_ENV'])
    log.info("Process Start")

    if (os.environ['INPUT_TYPE'] == "video"):
        assetsFolder = os.environ['ASSETS_FOLDER']
        controller = Processor("VID")
        selector = 'project'
        videoPath = "%s/test_video/video.mp4" % (assetsFolder)
        clip = VideoFileClip(videoPath).fl_image(controller.processImage)
        clip.write_videofile(videoPath.replace("video.mp4", "result.mp4"),
                             audio=False)
    else:
        controller = Processor()
        assetsFolder = os.environ['ASSETS_FOLDER']
        testImageFolder = "%s/test_images" % (assetsFolder)
        fileList = os.listdir(testImageFolder)
Esempio n. 28
0
import pymysql
from common import logger
from common.config_manager import ConfigManager

log = logger.Logger('ConnectionMysql').get_log()


class ConnectionMysql(object):
    def __init__(self):
        config = ConfigManager.get_ini_obj()
        self.db = pymysql.connect(config.get('Mysql', 'server_host'),
                                  config.get('Mysql', 'username'),
                                  config.get('Mysql', 'password'),
                                  config.get('Mysql', 'database'),
                                  int(config.get('Mysql', 'port')),
                                  charset='utf8')
        self.cursor = self.db.cursor()

    def execute_db(self, sql):
        # 插入
        try:
            log.info('正在执行的sql语句为%s' % sql)
            # 执行sql
            self.cursor.execute(sql)
            self.db.commit()
        except Exception as e:
            # 发生错误时回滚
            log.error('文件:%s,\r\n行数: %s,\r\n错误内容: %s' %
                      (e.__traceback__.tb_frame.f_globals['__file__'],
                       e.__traceback__.tb_lineno, e))
            self.db.rollback()
Esempio n. 29
0
if Gtk.Widget.get_default_direction() == Gtk.TextDirection.RTL:
    i18n.direction_mark = '\u200F'
pritext = ''

from common import exceptions
try:
    from common import gajim
except exceptions.DatabaseMalformed:
    pritext = _('Database Error')
    sectext = _('The database file (%s) cannot be read. Try to repair it (see '
        'http://trac.gajim.org/wiki/DatabaseBackup) or remove it (all history '
        'will be lost).') % common.logger.LOG_DB_PATH
else:
    from common import logger
    gajim.logger = logger.Logger()
    from common import caps_cache
    caps_cache.initialize(gajim.logger)
    from common import dbus_support
    if dbus_support.supported:
        from music_track_listener import MusicTrackListener

    from ctypes import CDLL
    from ctypes.util import find_library
    import platform

    sysname = platform.system()
    if sysname in ('Linux', 'FreeBSD', 'OpenBSD', 'NetBSD'):
        libc = CDLL(find_library('c'))

        # The constant defined in <linux/prctl.h> which is used to set the name