def __init__(self, ip, port, cwd, debug=False):
        self.ip = ip
        self.port = port
        self.cwd = cwd
        self.debug = debug
        Configuration.global_parameters = self.__dict__
        self.app = Flask(
            'WSGI-Flask Server on port: {port}'.format(port=self.port),
            template_folder='{}/vue_web_code/dist'.format(self.cwd),
            static_folder='{}/vue_web_code/dist'.format(self.cwd))
        self.http_server = None

        # Setup database and trigger Database.__enter__()
        self.database = Database()
        with self.database:
            pass

        # Start the API documentation services
        try:
            yaml.warnings({'YAMLLoadWarning': False})
        except Exception as error:
            print(error)
        Swagger(self.app, template=template)

        threading.Thread(target=self.run).start()
Example #2
0
def main():
    # Define the barer token we are going to use to authenticate.
    # See here to create the token:
    # https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/
    aToken = ""

    # disable warnings
    #urllib3.disable_warnings()
    yaml.warnings({'YAMLLoadWarning': False})

    # Create a configuration object
    # aConfiguration = client.Configuration()
    aConfiguration = config.load_kube_config()

    # Specify the endpoint of your Kube cluster
    # aConfiguration.host = "https://172.26.138.146:6443"
    # aConfiguration.host = str(apiserver)
    # aConfiguration.api_key = {"Authorization": "Bearer " + str(aToken)}

    # Create a ApiClient with our config
    aApiClient = client.ApiClient(aConfiguration)

    # Do calls
    v1 = client.CoreV1Api(aApiClient)
    print("Listing services:")
    ret = v1.list_namespaced_service("kube-system")
    for i in ret.items:
        #print("pods: %s"%i)
        print("%s\t%s\t%s\t%s" % (i.metadata.name, i.spec.type,
                                  i.spec.cluster_ip, i.spec.external_i_ps))
Example #3
0
def cli():
    """
    Entrypoint for Zelt.
    """

    # Disable deprecation warning coming from Kubernetes client's YAML loading.
    # See https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation
    yaml.warnings({"YAMLLoadWarning": False})

    config = _load_config(docopt(__doc__, version=_version()))

    logging.basicConfig(level=config.logging)

    if config.from_har:
        config = config._replace(locustfile=zelt.invoke_transformer(
            paths=config.har_files, plugin_names=config.transformer_plugins))
        _deploy(config)

    if config.from_locustfile:
        _deploy(config)

    if config.rescale:
        _rescale(config)

    if config.delete:
        _delete(config)
Example #4
0
def read_yaml_file(filename):
    """
    从本地读入yaml文件
    """
    fix_yaml_loader()
    yaml.warnings({'YAMLLoadWarning': False})
    return yaml.load(read_file(filename, "utf-8"))
Example #5
0
def index():

    #Disabling the warning
    yaml.warnings({'YAMLLoadWarning': False})
    website_data = yaml.load(open('_config.yaml'))

    return render_template('index.html', data=website_data)
Example #6
0
def import_yaml(path):
    yaml.warnings({'YAMLLoadWarning': False})
    with open(path, 'r') as ymlfile:
        cfg = yaml.load(ymlfile)
    # for section in cfg:
    #     print(section)
    return cfg
Example #7
0
def predict(model, image):
    """Predict a label for input image"""
    # Suppress Keras deprecation warnings
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    yaml.warnings({'YAMLLoadWarning': False})
    tf.logging.set_verbosity(tf.logging.ERROR)

    # Load network and labels
    click.echo(click.style('Loading CapsNet...', fg='green'))
    model, labels = CapsNet.load(model)

    # Load the image (default slice for LFW)
    click.echo(click.style('Loading image...', fg='green'))
    images = _load_imgs([image],
                        slice_=(slice(70, 195), slice(78, 172)),
                        color=True,
                        resize=0.5)
    images = np.array([downsample(i, (32, 32)) for i in images]) / 255

    click.echo(click.style('Predicting...', fg='green'))
    prediction = model.predict(images)[0]

    # Print a table with predictions
    click.echo(click.style('Guessed likelihood per label:', fg='green'))

    click.echo(click.style(f'{"Label":20}{"Probability":10}', fg='blue'))
    best = np.argmax(prediction)
    for idx, (l, p) in enumerate(zip(labels, prediction)):
        msg = f'{l:20}{p:>10.2%}'
        if idx == best:
            click.echo(click.style(f'{msg} <-- Best match', fg='green'))
        else:
            click.echo(msg)
Example #8
0
    def getRandomComment(self):
        with open('data_config.yml', 'r') as f:
            yaml.warnings({'YAMLLoadWarning': False})
            config = yaml.load(f)

            index = random.randint(0, len(config['comments']) - 1)
            return config['comments'][index]
Example #9
0
 def get_data(self):
     # 通过yamlparam参数获取yaml文件对应的value
     with open(config_path, 'rb') as f:
         cont = f.read()                             # 获取yaml文件中的所有信息
     warnings({'YAMLLoadWarning': False})            # 禁用加载器warnings报警
     cf = load(cont)                                 # 将bytes格式转成dict格式
     data = cf.get(self.yamlparam)                   # 获取key为self.yamlparam的value
     return data
Example #10
0
def yml_data_with_filename_key(file_name, key):
    with open("./data/" + file_name + ".yaml", "r", encoding='utf-8') as f:
        yaml.warnings({'YAMLLoadWarning': False})
        data = yaml.load(f)[key]
        case_data_list = []
        for case_data in data.values():
            case_data_list.append(case_data)
        return case_data_list
Example #11
0
def config_yaml():
    curpath = os.path.dirname(os.path.realpath(__file__))
    yamlpath = os.path.join(curpath, 'config.yaml')
    f = open(yamlpath, 'r', encoding='utf-8')
    cfg = f.read()
    # 解决安全警告配置形成字典
    d = yaml.load(cfg, Loader=yaml.FullLoader)
    yaml.warnings({'YAMLLoadWarning': False})
    return d
Example #12
0
    def read_data(self):
        '''
		加载yaml数据
		'''
        # file_path = base_path + '/Config/userconfig.yaml'
        with open(file_path) as fr:
            data = yaml.load(fr)
            yaml.warnings({'YAMLLoadWarning': False})
        return data
Example #13
0
 def get_data(self):
     try:
         open(self.file_path, encoding='utf-8')
     except:
         print('读取配置文件异常')
     data = yaml.load(open(self.file_path, encoding='utf-8'),
                      Loader=yaml.FullLoader)
     yaml.warnings({'YAMLLoadWarning': False})
     return data
Example #14
0
def read_yaml_data(yaml_file):
    yaml.warnings({'YAMLLoadWarning': False})

    file_data = None
    with open(yaml_file, 'r', encoding="utf-8") as file:
        file_data = file.read()

    data = yaml.load(file_data)
    return data
Example #15
0
 def readm():
     print(">>读取多个文件")
     yaml.warnings({'YANMLLoadWarning': False})
     f = open('../file/yaml/ymlm.yaml', 'r', encoding='utf-8')  # 打开yaml文件
     cfg = f.read()
     d = yaml.load_all(
         cfg)  # 将数据转换成python字典形式输出,存在多个文件时,用load_all, 单个的时候load就可以
     for data in d:
         print(data)
     f.close()
Example #16
0
 def read_yaml(self, path):
     """
     获取yaml文件中的数据
     :param path: yaml文件地址
     :return:
     """
     with open(path, 'rb') as y:
         cont = y.read()  # 获取yaml文件中的所有信息
     yaml.warnings({'YAMLLoadWarning': False})  # 禁用加载器warnings报警
     return yaml.load(cont)  # 将bytes格式转成dict格式
Example #17
0
 def get_data(self, key=None):
     with open(self.path, 'rb') as y:
         cont = y.read()  # 获取yaml文件中的所有信息
     yaml.warnings({'YAMLLoadWarning': False})  # 禁用加载器warnings报警
     cf = yaml.load(cont)  # 将bytes格式转成dict格式
     y.close()  # 关闭文件
     if key is None:
         return cf  # 返回所有数据
     else:
         return cf.get(key)  # 获取键为param的值
Example #18
0
def console_logger(
    level="WARNING"
):
    """
    *Setup and return a console logger*

    **Key Arguments:**
        - ``level`` -- the level of logging required

    **Return:**
        - ``logger`` -- the console logger

    **Usage:**
        .. code-block:: python 

            from fundamentals import logs
            log = logs.console_logger(
                level="DEBUG"
            )
            log.debug("Testing console logger")
    """
    ################ > IMPORTS ################
    ## STANDARD LIB ##

    import logging
    import logging.config
    ## THIRD PARTY ##
    import yaml
    try:
        yaml.warnings({'YAMLLoadWarning': False})
    except:
        pass
    ## LOCAL APPLICATION ##

    # SETUP LOGGING
    loggerConfig = """
  version: 1
  formatters:
      console_style:
          format: '* %(asctime)s - %(levelname)s: %(pathname)s:%(funcName)s:%(lineno)d > %(message)s'
          datefmt: '%H:%M:%S'
  handlers:
      console:
          class: logging.StreamHandler
          level: """ + level + """
          formatter: console_style
          stream: ext://sys.stdout
  root:
      level: """ + level + """
      handlers: [console]"""

    logging.config.dictConfig(yaml.load(loggerConfig))
    logger = logging.getLogger(__name__)

    return logger
Example #19
0
 def __init__(self):  #初始化,并读取配置文件
     self.cookies = {}
     self.data = DataSet()  #初始值为对象
     self.my_requests = ""
     self.token = ""
     yamlPath = "../base/config.yaml"
     yaml.load(yamlPath, Loader=yaml.BaseLoader)
     yaml.warnings({'YAMLLoadWarning': False})
     f = open(yamlPath, 'r')
     temp = yaml.load(f.read())
     self.uri = temp['st3']['uri']
Example #20
0
 def template(cls, path, data, sub=None):
     yaml.warnings({'YAMLLoadWarning': False})
     with open(path, 'r') as f:
         if sub is None:
             return yaml.load(Template(f.read()).substitute(data))
         else:
             # return yaml.load(Template(f.read()).substitute(data))[sub]
             return yaml.load(
                 Template(
                     yaml.dump(yaml.load(
                         f, Loader=yaml.FullLoader)[sub])).substitute(data))
Example #21
0
def apkinfo(apkname):
    yaml.warnings({'YAMLLoadWarning': False})
    curpath = os.path.realpath(__file__)
    dir1 = os.path.dirname(curpath)
    yamlpath = os.path.join(dir1, apkname)
    print('APK配置信息:', yamlpath)
    f = open(yamlpath, 'r', encoding='utf-8')
    file = f.read()
    info = yaml.load(file)
    for i in info:
        return (i['info']['appPackage'], i['info']['startActivity'])
Example #22
0
def console_logger(level="WARNING"):
    """
    *Setup and return a console logger*

    **Key Arguments:**
        - ``level`` -- the level of logging required

    **Return:**
        - ``logger`` -- the console logger

    **Usage:**
        .. code-block:: python 

            from fundamentals import logs
            log = logs.console_logger(
                level="DEBUG"
            )
            log.debug("Testing console logger")
    """
    ################ > IMPORTS ################
    ## STANDARD LIB ##

    import logging
    import logging.config
    ## THIRD PARTY ##
    import yaml
    try:
        yaml.warnings({'YAMLLoadWarning': False})
    except:
        pass
    ## LOCAL APPLICATION ##

    # SETUP LOGGING
    loggerConfig = """
  version: 1
  formatters:
      console_style:
          format: '* %(asctime)s - %(levelname)s: %(pathname)s:%(funcName)s:%(lineno)d > %(message)s'
          datefmt: '%H:%M:%S'
  handlers:
      console:
          class: logging.StreamHandler
          level: """ + level + """
          formatter: console_style
          stream: ext://sys.stdout
  root:
      level: """ + level + """
      handlers: [console]"""

    logging.config.dictConfig(yaml.load(loggerConfig))
    logger = logging.getLogger(__name__)

    return logger
Example #23
0
 def __init__(self, project_name):
     self.driver = ''
     self.loc = ''
     self.project_name = project_name
     yamlPath = "user.yaml"
     yaml.load(yamlPath, Loader=yaml.BaseLoader)
     yaml.warnings({'YAMLLoadWarning': False})
     f = open(yamlPath, 'r')
     temp = yaml.load(f.read())
     self.url = temp[project_name]['url']
     self.username = temp[project_name]['username']
     self.password = temp[project_name]['password']
Example #24
0
def loadfile(file: str, safe=True) -> dict:
    """
    Load yaml file.
    """
    if safe:
        with open(file, 'r') as f:
            return yaml.safe_load(f.read())
    else:
        with open(file, 'r') as f:
            if hasattr(pyyaml, 'warnings'):
                pyyaml.warnings({'YAMLLoadWarning': False})
            return yaml.load(f.read())
Example #25
0
    def read(self):
        # 由于官方提示load方法存在安全漏洞,所以读取文件时会报错。加上warning忽略,就不会显示警告
        yaml.warnings({'YAMLLoadWarning': False})

        # 打开文件
        f = open('config.yaml', 'r', encoding='utf-8')
        # 读取
        cfg = f.read()
        # 将数据转换成python字典行驶输出,存在多个文件时,用load_all,单个的时候load就可以
        d = yaml.load(cfg)
        print(d)
        print(d.get('user'))
        print(d.get('job')[0])
Example #26
0
    def readYaml(self):
        # 由于官方提示load方法存在安全漏洞,所以读取文件时会报错。加上warning忽略,就不会显示警告
        yaml.warnings({'YAMLLoadWarning': False})

        # 打开文件
        f = open('conf/mysql.yaml', 'r', encoding='utf-8')
        # 读取
        cfg = f.read()
        # 将数据转换成python字典行驶输出,存在多个文件时,用load_all,单个的时候load就可以
        d = yaml.load(cfg)
        print(d)
        print(d.get('seraphim'))
        print(d.get('seraphim').get('dev').get('database'))
Example #27
0
 def __init__(self):  #初始化连接,指定连接库
     yamlPath = "config.yaml"
     yaml.load(yamlPath, Loader=yaml.BaseLoader)
     yaml.warnings({'YAMLLoadWarning': False})
     f = open(yamlPath, 'r')
     data = yaml.load(f.read())['st3']
     self.pool = PooledDB(pymysql,
                          5,
                          host=data['db_host'],
                          user=data['db_user'],
                          passwd=data['db_pass'],
                          db=data['db'],
                          port=data['db_port'])
def main():
    path_str = getcwd()
    if 'Conf' in listdir(getcwd()):
        WriterFile()
    else:
        mkdir(path_str + 'Conf/')
        WriterFile()
    if len(listdir('Conf/')) == 1 and listdir('Conf/')[0] == 'Account.yml':
        configName = 'Conf/Account.yml'
        configFile = path.join(path.dirname(path.abspath(__file__)),
                               configName)
        warnings({'YAMLLoadWarning': False})
        config = load(open(configFile))
        print(dumps(config, indent=len(config.keys())))
Example #29
0
def read_case_data_to_yaml(file=None):
    yaml.warnings({'YAMLLoadWarning': False})
    if file:
        with open(file, encoding='utf-8') as f:
            x = yaml.load(f)
            case_data = x
            return case_data
    else:
        yaml_file_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'testcases.yaml')
        with open(yaml_file_path, encoding='utf-8') as f:
            x = yaml.load(f)
            case_data = x
            return case_data
Example #30
0
def read_data(index=None):
    '''
    :param index:
    :param param:
    :return:
    '''
    path = getcwd.get_cwd()  # 获取相对路径
    yaml_path = os.path.join(path, 'Params\Param\data.yml')  # 获取配置文件路径
    with open(yaml_path, 'rb') as y:
        cont = y.read()  # 获取data.yml所有信息
        yaml.warnings({'YAMLLoadWarning': False})
        cf = yaml.load(cont)
        y.close()
    return cf[index]['data']
Example #31
0
    def reads(file, keyp):
        print(">>读取单个文件")
        yaml.warnings({'YANMLLoadWarning': False})
        f = open(file, 'r', encoding='utf-8')  # 打开yaml文件
        cfg = f.read()
        d = yaml.load(cfg)
        # print(d)
        # print(type(d))

        for key in d:
            # print(key)
            if key in keyp:
                print(key + ':' + d[keyp])
        f.close()
Example #32
0
*A unit-testing kit to simplify my unit-tests*

:Author:
    David Young

:Date Created:
    April 16, 2014
"""
################# GLOBAL IMPORTS ####################
import sys
import os
import logging
import logging.config
import yaml
try:
    yaml.warnings({'YAMLLoadWarning': False})
except:
    pass


class utKit():

    """
    *Default setup for fundamentals style unit-testing workflow (all tests base on nose module)*

    **Key Arguments:**
        - ``moduleDirectory`` -- the directory to the unit-testing test file

    **Usage:**
        To use this kit within any of your unit-test modules add the following code before your test methods: