def create_car_microservice_access_secret():
    core_v1 = client.CoreV1Api(client.api_client.ApiClient())

    name = car_microservice_secret_name()
    ## return context account_id here
    print("name for create_car_microservice_access_secret")
    print(name)

    data = ignore_404(
        lambda: core_v1.read_namespaced_secret(name, current_namespace()).data)
    print("show me current name space secret data for car microservice secret")
    print(data)
    if data:
        key, passwd = decode(data['key']), decode(data['passwd'])
        if validate_car_service_access(key, passwd):
            print("pass for validate")
            context().logger.info(
                'API Key for CAR service access is validated.')
            return
        else:
            print("failed for validate")
            context().logger.info(
                'API Key for CAR service access is not valid.')

    # key, passwd = generate_api_key()
    data = {CAR_SERVICE_API_KEY: key, CAR_SERVICE_API_PASSWORD: passwd}
    print("show me data for secret:")
    print(data)
    create_secret(name, data)
Example #2
0
 def wrapper(doc):
     doc_obj = getOpenedFileObject(doc)
     if doc_obj:
         context.context(doc_obj, modules[module])
         try:
             with run_lock:
                 #                    with Profile():
                 ret = func()
                 while not run_lock._value:
                     pass  #prevent interruption outside try block
                 return ret
         except KeyboardInterrupt:
             print("Macro '%s' interrupted" % func.__name__)
         except Exception as e:
             frame = sys.exc_info()[2].tb_next
             if not frame: frame = sys.exc_info()[2]
             print("Exception in macro '%s': %s[%s:%d] %s" %
                   (func.__name__, type(e).__name__, module,
                    frame.tb_lineno, e))
             showConsole()  #Show exception to user
         finally:
             try:
                 context.App.ScreenUpdating = True  #Turn back updating!
             except:
                 print("Failed to turn on screen updating!")
     else:
         print("Opened document '%s' not found" % doc)
def create_secret(name, data):
    core_v1 = client.CoreV1Api(client.api_client.ApiClient())
    ignore_404(
        lambda: core_v1.delete_namespaced_secret(name, current_namespace()))

    if not data:
        return

    context().logger.info('Creating secret %s for account %s' %
                          (name, context().account_id))
    encoded_data = {}
    for k, v in data.items():
        encoded_data[k] = encode(v)
    print("show me encoded data")
    print(encoded_data)

    metadata = {'name': name, 'namespace': current_namespace()}
    print("come here for create_secret ")
    # {'name': 'TNT_HMIYKXUFCW56WCEH2H9D38-cp4s-car-tan1-secrets', 'namespace': 'staging'}
    print(metadata)
    body = client.V1Secret(api_version='v1',
                           data=encoded_data,
                           kind='Secret',
                           metadata=metadata,
                           type='Opaque')
    handle_409(
        lambda: core_v1.create_namespaced_secret(current_namespace(), body))
def create():
    print("come to create")
    print(request.get_json())
    cronjob = context().persister.upsert(ConnectorConfig(request.get_json()))
    return Response(jsonpickle.encode(cronjob, unpicklable=False),
                    status=201,
                    mimetype='application/json')
Example #5
0
    def __init__(self, proxies={'http': 'http://127.0.0.1:8080',
        'https': 'http://127.0.0.1:8080'}):
        """
        Creates an instance of the ZAP api client.

        :Parameters:
           - `proxies`: dictionary of ZAP proxies to use.
           
        Note that all of the other classes in this directory are generated
        new ones will need to be manually added to this file
        """
        self.__proxies = proxies
        
        self.acsrf = acsrf(self)
        self.ajaxSpider = ajaxSpider(self)
        self.ascan = ascan(self)
        self.authentication = authentication(self)
        self.autoupdate = autoupdate(self)
        self.brk = brk(self)
        self.context = context(self)
        self.core = core(self)
        self.forcedUser = forcedUser(self)
        self.httpsessions = httpSessions(self)
        self.importLogFiles = importLogFiles(self)
        self.params = params(self)
        self.pnh = pnh(self)
        self.pscan = pscan(self)
        self.script = script(self)
        self.search = search(self)
        self.selenium = selenium(self)
        self.sessionManagement = sessionManagement(self)
        self.spider = spider(self)
        self.users = users(self)
Example #6
0
    def get_context_data(self, **kwargs):
        c = context(self.request)
        data = super(ArticleArchiveView, self).get_context_data(**kwargs)
        data.update({'enabled_tag': self.request.GET.get('tag')})
        c.update(**data)

        return c
Example #7
0
    def get_context_data(self, **kwargs):
        c = context(self.request)
        data = super(GenericTagListView, self).get_context_data(**kwargs)

        data.update({'by_more': True})
        c.update(**data)
        return c
Example #8
0
    def __init__(self, proxies={'http': 'http://127.0.0.1:8080',
        'https': 'http://127.0.0.1:8080'}):
        """
        Creates an instance of the ZAP api client.

        :Parameters:
           - `proxies`: dictionary of ZAP proxies to use.
           
        Note that all of the other classes in this directory are generated
        new ones will need to be manually added to this file
        """
        self.__proxies = proxies
        
        self.acsrf = acsrf(self)
        self.ajaxSpider = ajaxSpider(self)
        self.ascan = ascan(self)
        self.authentication = authentication(self)
        self.autoupdate = autoupdate(self)
        self.brk = brk(self)
        self.context = context(self)
        self.core = core(self)
        self.forcedUser = forcedUser(self)
        self.httpsessions = httpSessions(self)
        self.importLogFiles = importLogFiles(self)
        self.params = params(self)
        self.pnh = pnh(self)
        self.pscan = pscan(self)
        self.script = script(self)
        self.search = search(self)
        self.selenium = selenium(self)
        self.sessionManagement = sessionManagement(self)
        self.spider = spider(self)
        self.users = users(self)
Example #9
0
    def get_context_data(self, **kwargs):
        c = context(self.request)
        data = super(GenericTagListView, self).get_context_data(**kwargs)

        data.update({'by_more': True})
        c.update(**data)
        return c
Example #10
0
def tests():
    c = context()

    print bool(c)
    print c.__getstate__()
    c.array = [ 1, 2, 3 ]
    c.attr = "Hel"
    print c.attr
    c.attr += "lo"
    print c.__getstate__()

    c = context.start_new()
    print c.__getstate__()
    c._dontstore = "never_store"
    print c.__getstate__()
    c.ensure("array", [1]).array += [2]
    c.ensure("array", [1]).array += [3]
    print c.__getstate__()
    del c.array
    print c.__getstate__()
    c.__setstate__({ "attr": ["a", 1]})
    print c.__getstate__()
    c.__setstate__({ "ensure": "Don't do this!"})
    try: print c.ensure("apple", "pear")
    except TypeError: print "Don't do this!"

    c.clear()
    print c.__getstate__()
Example #11
0
    def get_context_data(self, **kwargs):
        c = context(self.request)
        data = super(SearchView, self).get_context_data(**kwargs)
        data.update({'object_list': self.get_queryset()})

        c.update(**data)

        return c
Example #12
0
def validate_car_service_access(key, passwd):
    if debug_mode():
        return True
    from secrets import encode
    encoded = encode('%s:%s' % (key, passwd))
    headers = {
        'Authorization': 'Basic %s' % encoded,
        'Content-Type': 'application/json'
    }
    url = 'https://%s%s/health' % (os.environ.get(APP_FQDN),
                                   os.environ.get(CAR_API_PATH))
    resp = requests.get(url, headers=headers)
    if resp.status_code != 200:
        context().logger.warning(
            'Status code when validating CAR service access: %d' %
            resp.status_code)
    return resp.status_code != 401
def update(cronJobName):
    json_data = request.get_json()
    if json_data.get('name') != cronJobName:
        raise ValueError('Cron Job name mismatch.')
    cronjob = context().persister.upsert(ConnectorConfig(json_data=json_data))
    return Response(jsonpickle.encode(cronjob, unpicklable=False),
                    status=200,
                    mimetype='application/json')
Example #14
0
    def get_context_data(self, **kwargs):
        c = context(self.request)
        data = super(SearchView, self).get_context_data(**kwargs)
        data.update({'object_list': self.get_queryset()})

        c.update(**data)

        return c
Example #15
0
    def get_context_data(self, **kwargs):
        c = context(self.request)
        data = super(ArticleArchiveView, self).get_context_data(**kwargs)
        data.update({
            'enabled_tag': self.request.GET.get('tag')
        })
        c.update(**data)

        return c
Example #16
0
    def get_context_data(self, **kwargs):
        c = context(self.request)
        data = super(ArticleDetailView, self).get_context_data(**kwargs)

        data.update({'by_more': True})
        c.update(**data)

        #c['object'].weight += 1
        #c['object'].save()

        return c
Example #17
0
    def get_context_data(self, **kwargs):
        c = context(self.request)
        data = super(ArticleDetailView, self).get_context_data(**kwargs)

        data.update({'by_more': True})
        c.update(**data)

        #c['object'].weight += 1
        #c['object'].save()

        return c
Example #18
0
    def wrapper(doc):
        doc_obj = getOpenedFileObject(doc)
        if doc_obj:
            context.context(doc_obj, modules[module])
            try:
                with run_lock:
#                    with Profile():
                    ret = func()
                    while not run_lock._value: pass #prevent interruption outside try block
                    return ret
            except KeyboardInterrupt:
                print("Macro '%s' interrupted"%func.__name__)
            except Exception as e:
                frame = sys.exc_info()[2].tb_next
                if not frame: frame = sys.exc_info()[2]
                print("Exception in macro '%s': %s[%s:%d] %s" %
                    (func.__name__, type(e).__name__, module, frame.tb_lineno, e))
                showConsole() #Show exception to user
            finally:
                try: context.App.ScreenUpdating = True #Turn back updating!
                except: print("Failed to turn on screen updating!")
        else: print("Opened document '%s' not found"%doc)
Example #19
0
    def __init__(self, proxies=None, apikey=None):
        """
        Creates an instance of the ZAP api client.

        :Parameters:
           - `proxies`: dictionary of ZAP proxies to use.

        Note that all of the other classes in this directory are generated
        new ones will need to be manually added to this file
        """
        self.__proxies = proxies or {
            'http': 'http://127.0.0.1:8080',
            'https': 'http://127.0.0.1:8080'
        }
        self.__apikey = apikey

        self.acsrf = acsrf(self)
        self.ajaxSpider = ajaxSpider(self)
        self.ascan = ascan(self)
        self.authentication = authentication(self)
        self.authorization = authorization(self)
        self.autoupdate = autoupdate(self)
        self.brk = brk(self)
        self.context = context(self)
        self.core = core(self)
        self.forcedUser = forcedUser(self)
        self.httpsessions = httpSessions(self)
        self.importLogFiles = importLogFiles(self)
        self.params = params(self)
        self.pnh = pnh(self)
        self.pscan = pscan(self)
        self.reveal = reveal(self)
        self.script = script(self)
        self.search = search(self)
        self.selenium = selenium(self)
        self.sessionManagement = sessionManagement(self)
        self.spider = spider(self)
        self.stats = stats(self)
        self.users = users(self)

        # not very nice, but prevents warnings when accessing the ZAP API via https
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
Example #20
0
    def __init__(self, proxies=None, apikey=None):
        """
        Creates an instance of the ZAP api client.

        :Parameters:
           - `proxies`: dictionary of ZAP proxies to use.

        Note that all of the other classes in this directory are generated
        new ones will need to be manually added to this file
        """
        self.__proxies = proxies or {
            'http': 'http://127.0.0.1:8080',
            'https': 'http://127.0.0.1:8080'
        }
        self.__apikey = apikey

        self.acsrf = acsrf(self)
        self.ajaxSpider = ajaxSpider(self)
        self.ascan = ascan(self)
        self.authentication = authentication(self)
        self.authorization = authorization(self)
        self.autoupdate = autoupdate(self)
        self.brk = brk(self)
        self.context = context(self)
        self.core = core(self)
        self.forcedUser = forcedUser(self)
        self.httpsessions = httpSessions(self)
        self.importLogFiles = importLogFiles(self)
        self.params = params(self)
        self.pnh = pnh(self)
        self.pscan = pscan(self)
        self.reveal = reveal(self)
        self.script = script(self)
        self.search = search(self)
        self.selenium = selenium(self)
        self.sessionManagement = sessionManagement(self)
        self.spider = spider(self)
        self.stats = stats(self)
        self.users = users(self)

        # not very nice, but prevents warnings when accessing the ZAP API via https
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
Example #21
0
    def __init__(self, proxies={'http': 'http://127.0.0.1:8080',
        'https': 'http://127.0.0.1:8080'}):
        """
        Creates an instance of the ZAP api client.

        :Parameters:
           - `proxies`: dictionary of ZAP proxies to use.
           
        Note that all of the other classes in this directory are generated
        new ones will need to be manually added to this file
        """
        self.__proxies = proxies
        
        self.acsrf = acsrf(self)
        self.ascan = ascan(self)
        self.auth = auth(self)
        self.autoupdate = autoupdate(self)
        self.context = context(self)
        self.core = core(self)
        self.params = params(self)
        self.pscan = pscan(self)
        self.search = search(self)
        self.spider = spider(self)
Example #22
0
special = [x[5:] for x in dir() if x.startswith ('test_')]

failed = []

# nobody wants to wait for a non-optimized tak20
optimize = ['t_vm']

succeeded = 0

for size, file in files:
    if file.endswith ('.scm'):
        base, ext = os.path.splitext (file)
        path = os.path.join ('tests', file)
        print 'compiling', path
        fail = file.startswith ('f')
        c = context.context()
        c.verbose = False
        c.typetype = True
        if base in optimize:
            c.optimize = True
        try:
            compile.compile_file (open (path, 'rb'), path, c)
        except:
            if not fail:
                #raise
                failed.append ((base, "compile failed"))
            else:
                succeeded += 1
        else:
            if fail:
                failed.append ((base, 'compile did not fail like expected'))
Example #23
0
special = [x[5:] for x in dir() if x.startswith('test_')]

failed = []

# nobody wants to wait for a non-optimized tak20
optimize = ['t_vm']

succeeded = 0

for size, file in files:
    if file.endswith('.scm'):
        base, ext = os.path.splitext(file)
        path = os.path.join('tests', file)
        print 'compiling', path
        fail = file.startswith('f')
        c = context.context()
        c.verbose = False
        c.typetype = True
        if base in optimize:
            c.optimize = True
        try:
            compile.compile_file(open(path, 'rb'), path, c)
        except:
            if not fail:
                #raise
                failed.append((base, "compile failed"))
            else:
                succeeded += 1
        else:
            if fail:
                failed.append((base, 'compile did not fail like expected'))
Example #24
0
def main(argv):
    ###---        main        ---###
    i_ok=False
    t_ok=False
    m_ok=False
    image_path=""
    textfile_path=""
    ocr_mode="t1"
    correction_mode="g"
    model_answer_path=""
    outfile_path=os.path.join( os.getcwd(),'report.txt')
    

    try:
        opts, args = getopt.getopt(argv, "hi:t:r:c:m:o:", ["image_path=", "textfile_path=", "outfile_path=", "model_answer_path="])
    except getopt.GetoptError:
        err()

    for opt, arg in opts:
        ####################################
        if opt == '-h':
            print("#-----------------------------------#")
            print("options")
            print("i | image_path         | selected  img path")
            print("t | textfile_path      | exam as text file")
            print("r | ocr_mode           | which ocr to use")
            print("c | correction_mode    | comaresion algorism")
            print("m | model_answer_path  | mentors answer as text file")
            print("o | outfile_path       | the report location")
            print("-------------------------------------")
            print("args")
            print("ocr_mode")
            print("g - google api")
            print("t - tessreact ocr")
            print("c - custom ocr")
            print()
            print("correction_mode")
            print("t1 - key words")
            print("t2 - context")
            print("#-----------------------------------#")
            print("usage")
            if system == "Windows":
                print("python xamcorrection.py -i <image_path> -m <model_answer_path> -o <outfile_path>")      
            else:
                print("python3 xamcorrection.py -i <image_path> -m <model_answer_path> -o <outfile_path>") 
            sys.exit()
        ####################################
        if opt in ['-i','--image_path']:
            image_path=arg
            i_ok=True
        ####################################
        if opt in ['-t','--textfile_path']:
            textfile_path=arg
            t_ok=True
        ####################################
        if opt in ['-r','--ocr_mode']:
            if arg in['g','t','c']:
                ocr_mode=arg
            else:
                err()
        ####################################
        if opt in ['-c','--correction_mode']:
            if arg in['t1','t2']:
                correction_mode=arg
            else:
                err()
        ####################################
        if opt in ['-m','--model_answer_path']:
            model_answer_path=arg
            m_ok=True
        ####################################
        if opt in ['-o','--outfile_path']:
            outfile_path=arg
        ####################################
    #start  
    if m_ok:    
        nlp=nltkToolKit()
        new =newToolKit(nlp)
        c=context(nlp,new)
        comp=compare()
    else:
        print("provide model answer please")

    if i_ok :
        os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'ServiceAccountToken.json'
        client = vision.ImageAnnotatorClient()

        with io.open(image_path, 'rb') as image_file:
            content = image_file.read()

        image = vision.types.Image(content=content)
        response = client.document_text_detection(image=image)

        docText = response.full_text_annotation.text
        #################################
        fixed=c.Context_sensitive_spellchecker(docText)
        report = open(outfile_path,"w")
        report.write( str(comp.compare(fixed,model_answer_path)))
        report.close()
    elif t_ok:
        pass
        '')

if settings.getSetting('movie_custom_directory') == "true":
    MOVIES_PATH = settings.getSetting('movie_directory')
else:
    MOVIES_PATH = os.path.join(
        xbmc.translatePath(
            'special://profile/addon_data/plugin.video.furklibraryx/movies'),
        '')

CACHE_PATH = os.path.join(
    xbmc.translatePath(
        'special://profile/addon_data/plugin.video.furklibraryx/traktcache'),
    '')
try:
    MYCONTEXT = context.context().getContext()
except:
    MYCONTEXT = 'video'

IMDB_WATCHLIST = "http://akas.imdb.com/user/" + settings.getSetting(
    "imdb_watchlist") + "/watchlist?"

from utils import searcher
from utils import common
from sites import trakt, traktlib
from sites import movielens
from sites import criticker
from sites import vcdq
from sites import imdb
from sites import torrentfreak
from sites import furklib
Example #26
0
def car_microservice_secret_name():
    return '%s-car-service-access-key' % context().account_id
print "[PLUGIN] '%s: version %s' initialized!" % (__plugin__, __version__)

if settings.getSetting('tv_show_custom_directory') == "true":
	TV_SHOWS_PATH = settings.getSetting('tv_show_directory')
else:
	TV_SHOWS_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.furklibraryx/tvshows'), '')

if settings.getSetting('movie_custom_directory') == "true":
	MOVIES_PATH = settings.getSetting('movie_directory')
else:
	MOVIES_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.furklibraryx/movies'), '')

CACHE_PATH= os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.furklibraryx/traktcache'), '')
try:
	MYCONTEXT = context.context().getContext()
except:
	MYCONTEXT = 'video'

IMDB_WATCHLIST = "http://akas.imdb.com/user/" + settings.getSetting("imdb_watchlist") + "/watchlist?"

from utils import searcher
from utils import common
from sites import trakt,traktlib
from sites import movielens
from sites import criticker
from sites import vcdq
from sites import imdb
from sites import torrentfreak
from sites import furklib
from sites import rotten
 def wrapper(*args, **kwargs):
     try:
         return fn(*args, **kwargs)
     except ApiException as e:
         context().logger.exception(e)
         context().logger.error(traceback.format_exc())
         return e.body, e.status
     except ValueError as e:
         context().logger.exception(e)
         context().logger.error(traceback.format_exc())
         return str(e.args), 400
     except AuthError as e:
         context().logger.exception(e)
         context().logger.error(traceback.format_exc())
         return e.error, 401
     except Exception as e:
         context().logger.exception(e)
         context().logger.error(traceback.format_exc())
         raise e
Example #29
0
def set_account_id(account_id=None):
    if not id or debug_mode():
        context().account_id = os.environ.get(CAR_TEST_ACCOUNT_ID).replace(
            '_', '-').lower()
    else:
        context().account_id = account_id
Example #30
0
    )
    parser.add_argument(
        "--mode",
        help="'trinomial' or 'pentanomial'",
        choices=["trinomial", "pentanomial"],
        default="pentanomial",
    )
    args = parser.parse_args()
    alpha = args.alpha
    beta = args.beta
    elo0 = args.elo0
    elo1 = args.elo1
    elo = args.elo
    draw_elo = args.draw_elo
    biases = args.biases
    c = context.context(draw_elo, biases)
    mode = args.mode

    print("elo0      : %.2f" % elo0)
    print("elo1      : %.2f" % elo1)
    print("elo       : %.2f" % elo)
    print("draw_elo  : %.2f" % draw_elo)
    print("biases    : %s" % biases)
    print("mode      : %s" % mode)

    alpha = 0.05
    beta = 0.05

    s = SPRT(alpha, beta, elo0, elo1, c, mode)
    (power, expected) = s.characteristics(elo)
def list():
    res = context().persister.list()
    return Response(jsonpickle.encode(res, unpicklable=False),
                    status=200,
                    mimetype='application/json')
def get(cronJobName):
    cronjob = context().persister.get(cronJobName)
    return Response(jsonpickle.encode(cronjob, unpicklable=False),
                    status=200,
                    mimetype='application/json')
def delete(cronJobName):
    context().persister.delete(cronJobName)
    return Response('Success', 200, {'Content-Type': 'text/plain'})
Example #34
0
 def __init__(self):
     self.cmdlines = []
     self.context = context()
Example #35
0
 def __init__(self):
     if running_in_cluster():
         config.load_incluster_config()
     else:
         config.load_kube_config(config_file=context().kube_config)
     self.k8s_client = client.api_client.ApiClient()
Example #36
0
"""