import os

from metalift.analysis_new import VariableTracker, analyze
from metalift.ir import *

import typing
from typing import Callable, Union, Protocol

from metalift.synthesis_common import SynthesisFailed, VerificationFailed

def observeEquivalence(
    inputState: Expr, synthState: Expr, queryParams: typing.List[Var]
) -> Expr:
    return Call("equivalence", Bool(), inputState, synthState, *queryParams)

def opsListInvariant(
    fnNameBase: str, synthState: Expr, synthStateType: Type, opType: Type
) -> Expr:
    return And(
        Eq(
            Call(
                "apply_state_transitions",
                synthStateType,
                TupleGet(synthState, IntLit(len(synthStateType.args) - 1)),
                Var(
                    f"{fnNameBase}_next_state",
                    FnT(synthStateType, synthStateType, *opType.args),
                ),
                Var(
                    f"{fnNameBase}_init_state",
                    FnT(synthStateType),
                ),
            ),
            synthState,
        ),
        Call(
            "ops_in_order",
            Bool(),
            TupleGet(synthState, IntLit(len(synthStateType.args) - 1)),
        ),
    )

def supportedCommand(synthState: Expr, args: typing.Any) -> Expr:
    return Call("supportedCommand", Bool(), synthState, *args)

def unpackOp(op: Expr) -> typing.List[Expr]:
    if op.type.name == "Tuple":
        return [TupleGet(op, IntLit(i)) for i in range(len(op.type.args))]
    else:
        return [op]

def opListAdditionalFns(
    synthStateType: Type,
    opType: Type,
    initState: Callable[[], Expr],
    inOrder: Callable[[typing.Any, typing.Any], Expr],
    opPrecondition: Callable[[typing.Any], Expr],
) -> typing.List[Union[FnDecl, FnDeclNonRecursive, Axiom]]:
    def list_length(l: Expr) -> Expr:
        return Call("list_length", Int(), l)

    def list_get(l: Expr, i: Expr) -> Expr:
        return Call("list_get", opType, l, i)

    def list_tail(l: Expr, i: Expr) -> Expr:
        return Call("list_tail", ListT(opType), l, i)

    data = Var("data", ListT(opType))
    next_state_fn = Var(
        "next_state_fn",
        FnT(
            synthStateType,
            synthStateType,
            *(opType.args if opType.name == "Tuple" else [opType]),
        ),
    )

    init_state_fn = Var("init_state_fn", FnT(synthStateType))

    reduce_fn = FnDecl(
        "apply_state_transitions",
        synthStateType,
        Ite(
            Eq(list_length(data), IntLit(0)),
            CallValue(init_state_fn),
            CallValue(
                next_state_fn,
                Call(
                    "apply_state_transitions",
                    synthStateType,
                    list_tail(data, IntLit(1)),
                    next_state_fn,
                    init_state_fn,
                ),
                *(
                    [
                        # TODO(shadaj): unnecessary cast
                        typing.cast(
                            Expr, TupleGet(list_get(data, IntLit(0)), IntLit(i))
                        )
                        for i in range(len(opType.args))
                    ]
                    if opType.name == "Tuple"
                    else [list_get(data, IntLit(0))]
                ),
            ),
        ),
        data,
        next_state_fn,
        init_state_fn,
    )

    next_op = Var("next_op", opType)
    ops_in_order_helper = FnDecl(
        "ops_in_order_helper",
        Bool(),
        And(
            opPrecondition(unpackOp(next_op)),
            Ite(
                Eq(list_length(data), IntLit(0)),
                BoolLit(True),
                And(
                    inOrder(unpackOp(list_get(data, IntLit(0))), unpackOp(next_op)),
                    Call(
                        "ops_in_order_helper",
                        Bool(),
                        list_get(data, IntLit(0)),
                        list_tail(data, IntLit(1)),
                    ),
                ),
            ),
        ),
        next_op,
        data,
    )

    ops_in_order = FnDecl(
        "ops_in_order",
        Bool(),
        Ite(
            Eq(list_length(data), IntLit(0)),
            BoolLit(True),
            Call(
                "ops_in_order_helper",
                Bool(),
                list_get(data, IntLit(0)),
                list_tail(data, IntLit(1)),
            ),
        ),
        data,
    )

    return [reduce_fn, ops_in_order_helper, ops_in_order]

class SynthesizeFun(Protocol):
    def __call__(
        self,
        basename: str,
        targetLang: typing.List[Union[FnDecl, FnDeclNonRecursive, Axiom]],
        vars: typing.Set[Var],
        invAndPs: typing.List[Synth],
        preds: Union[str, typing.List[Expr]],
        vc: Expr,
        loopAndPsInfo: typing.List[Expr],
        cvcPath: str = "cvc5",
        uid: int = 0,
        noVerify: bool = False,
        unboundedInts: bool = False,
        optimize_vc_equality: bool = False,
        listBound: int = 2,
        log: bool = True,
    ) -> typing.List[FnDecl]:
        ...

def synthesize_crdt(
    filename: str,
    fnNameBase: str,
    loopsFile: str,
    cvcPath: str,
    synthStateType: Type,
    initState: Callable[[], Expr],
    grammarStateInvariant: Callable[[Expr, int, int], Expr],
    grammarSupportedCommand: Callable[[Expr, typing.Any, int, int], Expr],
    inOrder: Callable[[typing.Any, typing.Any], Expr],
    opPrecondition: Callable[[typing.Any], Expr],
    grammar: Callable[[Expr, typing.List[Var], int], Expr],
    grammarQuery: Callable[[str, typing.List[Var], Type, int], Synth],
    grammarEquivalence: Callable[[Expr, Expr, typing.List[Var], int], Expr],
    targetLang: Callable[[], typing.List[Union[FnDecl, FnDeclNonRecursive, Axiom]]],
    synthesize: SynthesizeFun,
    stateTypeHint: typing.Optional[Type] = None,
    opArgTypeHint: typing.Optional[typing.List[Type]] = None,
    queryArgTypeHint: typing.Optional[typing.List[Type]] = None,
    queryRetTypeHint: typing.Optional[Type] = None,
    uid: int = 0,
    unboundedInts: bool = True,
    useOpList: bool = False,
    listBound: int = 1,
    baseDepth: int = 2,
    invariantBoost: int = 0,
    log: bool = True,
    skipSynth: bool = False,
) -> typing.List[FnDecl]:
    basename = os.path.splitext(os.path.basename(filename))[0]

    tracker = VariableTracker()

    state_transition_analysis = analyze(
        filename,
        fnNameBase + "_next_state",
        loopsFile,
    )

    query_analysis = analyze(
        filename,
        fnNameBase + "_response",
        loopsFile,
    )

    origSynthStateType = synthStateType

    op_arg_types = (
        [v.type for v in state_transition_analysis.arguments[1:]]
        if opArgTypeHint is None
        else opArgTypeHint
    )
    opType = TupleT(*op_arg_types) if len(op_arg_types) > 1 else op_arg_types[1]

    if useOpList:
        synthStateType = TupleT(*synthStateType.args, ListT(opType))

    queryParameterTypes = (
        [v.type for v in query_analysis.arguments[1:]]
        if queryArgTypeHint is None
        else queryArgTypeHint
    )

    def supportedCommandWithList(synthState: Expr, args: typing.Any) -> Expr:
        return And(
            opPrecondition(args),
            Ite(
                Eq(
                    Call(
                        "list_length",
                        Int(),
                        TupleGet(synthState, IntLit(len(synthStateType.args) - 1)),
                    ),
                    IntLit(0),
                ),
                BoolLit(True),
                inOrder(
                    unpackOp(
                        Call(
                            "list_get",
                            opType,
                            TupleGet(synthState, IntLit(len(synthStateType.args) - 1)),
                            IntLit(0),
                        )
                    ),
                    args,
                ),
            ),
        )

    seq_start_state = tracker.variable(
        "seq_start_state", state_transition_analysis.arguments[0].type
    )
    synth_start_state = tracker.variable("synth_start_state", synthStateType)
    equivalence_query_vars = [
        tracker.variable(
            f"start_state_query_var_{i}", query_analysis.arguments[i + 1].type
        )
        for i in range(len(query_analysis.arguments) - 1)
    ]

    synth_after_op = tracker.variable("synth_after_op", synthStateType)

    first_op_group = tracker.group("first_op")
    first_op_args = [
        first_op_group.variable(v.name(), t)
        for v, t in zip(state_transition_analysis.arguments[1:], op_arg_types)
    ]

    second_op_group = tracker.group("second_op")
    second_op_args = [
        second_op_group.variable(v.name(), t)
        for v, t in zip(state_transition_analysis.arguments[1:], op_arg_types)
    ]

    vcStateTransition = state_transition_analysis.call(seq_start_state, *first_op_args)(
        tracker,
        lambda seq_after_op: Implies(
            And(
                observeEquivalence(
                    seq_start_state, synth_start_state, equivalence_query_vars
                ),
                *(
                    [
                        opsListInvariant(
                            fnNameBase, synth_start_state, synthStateType, opType
                        ),
                        supportedCommandWithList(synth_start_state, first_op_args),
                    ]
                    if useOpList
                    else [
                        opPrecondition(first_op_args),
                        supportedCommand(synth_start_state, first_op_args),
                    ]
                ),
                Eq(
                    synth_after_op,
                    Call(
                        f"{fnNameBase}_next_state",
                        synthStateType,
                        synth_start_state,
                        *first_op_args,
                    ),
                ),
            ),
            query_analysis.call(seq_start_state, *equivalence_query_vars)(
                tracker,
                lambda seqQueryResult: Implies(
                    Eq(
                        seqQueryResult,
                        Call(
                            f"{fnNameBase}_response",
                            seqQueryResult.type,
                            synth_start_state,
                            *equivalence_query_vars,
                        ),
                    ),
                    And(
                        observeEquivalence(
                            seq_after_op, synth_after_op, equivalence_query_vars
                        ),
                        query_analysis.call(seq_after_op, *equivalence_query_vars)(
                            tracker,
                            lambda seqQueryResult: Eq(
                                seqQueryResult,
                                Call(
                                    f"{fnNameBase}_response",
                                    seqQueryResult.type,
                                    synth_after_op,
                                    *equivalence_query_vars,
                                ),
                            ),
                        ),
                        *(
                            [
                                Implies(
                                    And(
                                        inOrder(first_op_args, second_op_args),
                                        opPrecondition(second_op_args),
                                    ),
                                    supportedCommand(synth_after_op, second_op_args),
                                )
                            ]
                            if not useOpList
                            else []
                        ),
                    ),
                ),
            ),
        ),
    )

    # define synthesis problem for state transition
    cur_state_param = Var("cur_state", synthStateType)

    op_arg_vars = [
        Var(v.name(), t)
        for v, t in zip(state_transition_analysis.arguments[1:], op_arg_types)
    ]

    stateTransitionSynthNode = grammar(
        cur_state_param,
        op_arg_vars,
        baseDepth,
    )

    invAndPsStateTransition = (
        [
            Synth(
                fnNameBase + "_next_state",
                Tuple(
                    # the grammar directly produces the tupled next state, unpack to tack on the op-list
                    *stateTransitionSynthNode.args,
                    Call(
                        "list_prepend",
                        ListT(opType),
                        Tuple(*op_arg_vars) if len(op_arg_vars) > 1 else op_arg_vars[0],
                        TupleGet(
                            cur_state_param,
                            IntLit(len(synthStateType.args) - 1),
                        ),
                    ),
                ),
                cur_state_param,
                *op_arg_vars,
            )
        ]
        if useOpList
        else [
            Synth(
                fnNameBase + "_next_state",
                stateTransitionSynthNode,
                cur_state_param,
                *op_arg_vars,
            )
        ]
    )
    # end state transition (in order)

    # begin query
    invAndPsQuery = [
        grammarQuery(
            query_analysis.name,
            [Var(query_analysis.arguments[0].name(), synthStateType)]
            + (
                [
                    Var(query_analysis.arguments[i + 1].name(), queryArgTypeHint[i])
                    for i in range(len(queryArgTypeHint))
                ]
                if queryArgTypeHint
                else query_analysis.arguments[1:]
            ),
            query_analysis.return_type
            if queryRetTypeHint is None
            else queryRetTypeHint,
            baseDepth,
        )
    ]
    # end query

    # begin init state
    initState_analysis = analyze(
        filename,
        fnNameBase + "_init_state",
        loopsFile,
    )

    synthInitState = tracker.variable("synth_init_state", synthStateType)

    init_op_arg_vars = []
    for i, typ in enumerate(op_arg_types):
        init_op_arg_vars.append(tracker.variable(f"init_op_arg_{i}", typ))

    queryParamVars = [
        tracker.variable(
            f"init_state_equivalence_query_param_{i}",
            query_analysis.arguments[i + 1].type,
        )
        for i in range(len(query_analysis.arguments) - 1)
    ]

    vcInitState = initState_analysis.call()(
        tracker,
        lambda seqInitialState: Implies(
            Eq(synthInitState, Call(f"{fnNameBase}_init_state", synthStateType)),
            And(
                observeEquivalence(seqInitialState, synthInitState, queryParamVars),
                query_analysis.call(seqInitialState, *queryParamVars)(
                    tracker,
                    lambda seqQueryResult: Eq(
                        seqQueryResult,
                        Call(
                            f"{fnNameBase}_response",
                            seqQueryResult.type,
                            synthInitState,
                            *queryParamVars,
                        ),
                    ),
                ),
                BoolLit(True)
                if useOpList
                else Implies(
                    opPrecondition(init_op_arg_vars),
                    supportedCommand(synthInitState, init_op_arg_vars),
                ),
            ),
        ),
    )

    initStateSynthNode = initState()
    invAndPsInitState = [
        Synth(
            fnNameBase + "_init_state",
            Tuple(
                *initStateSynthNode.args,
                Call("list_empty", ListT(opType)),
            )
            if useOpList
            else Tuple(
                *initStateSynthNode.args,
            ),
        )
    ]
    # end init state

    # begin equivalence
    inputStateForEquivalence = Var(
        "inputState",
        state_transition_analysis.arguments[0].type
        if stateTypeHint is None
        else stateTypeHint,
    )
    synthStateForEquivalence = Var("synthState", synthStateType)

    equivalenceQueryParams = [
        Var(f"equivalence_query_param_{i}", queryParameterTypes[i])
        for i in range(len(queryParameterTypes))
    ]

    invAndPsEquivalence = [
        Synth(
            "equivalence",
            And(
                grammarEquivalence(
                    inputStateForEquivalence,
                    synthStateForEquivalence,
                    equivalenceQueryParams,
                    baseDepth,
                ),
                *(
                    [
                        grammarStateInvariant(
                            synthStateForEquivalence, baseDepth, invariantBoost
                        )
                    ]
                    if not useOpList
                    else []
                ),
            ),
            inputStateForEquivalence,
            synthStateForEquivalence,
            *equivalenceQueryParams,
        )
    ]

    synthStateForSupported = Var(f"supported_synthState", synthStateType)
    argList = [
        Var(
            f"supported_arg_{i}",
            op_arg_types[i],
        )
        for i in range(len(op_arg_types))
    ]
    invAndPsSupported = (
        [
            Synth(
                "supportedCommand",
                grammarSupportedCommand(
                    synthStateForSupported, argList, baseDepth, invariantBoost
                ),
                synthStateForSupported,
                *argList,
            )
        ]
        if not useOpList
        else []
    )
    # end equivalence

    if log:
        print("====== synthesis")

    combinedVCVars = set(tracker.all())

    combinedInvAndPs = (
        invAndPsStateTransition
        + invAndPsQuery
        + invAndPsInitState
        + invAndPsEquivalence
        + invAndPsSupported
    )

    combinedVC = And(vcStateTransition, vcInitState)

    lang = targetLang()
    if useOpList:
        lang = lang + opListAdditionalFns(
            synthStateType, opType, initState, inOrder, opPrecondition
        )

    if skipSynth:
        return  # type: ignore

    try:
        out = synthesize(
            basename,
            lang,
            combinedVCVars,
            combinedInvAndPs,
            [],
            combinedVC,
            [*combinedInvAndPs],
            cvcPath,
            uid=uid,
            unboundedInts=unboundedInts,
            noVerify=useOpList,
            listBound=listBound,
            log=log,
        )
    except VerificationFailed:
        # direct synthesis mode
        print(
            f"#{uid}: CVC5 failed to verify synthesized design, increasing Rosette data structure bounds to",
            listBound + 1,
        )
        return synthesize_crdt(
            filename,
            fnNameBase,
            loopsFile,
            cvcPath,
            origSynthStateType,
            initState,
            grammarStateInvariant,
            grammarSupportedCommand,
            inOrder,
            opPrecondition,
            grammar,
            grammarQuery,
            grammarEquivalence,
            targetLang,
            synthesize,
            stateTypeHint=stateTypeHint,
            opArgTypeHint=opArgTypeHint,
            queryArgTypeHint=queryArgTypeHint,
            queryRetTypeHint=queryRetTypeHint,
            uid=uid,
            unboundedInts=unboundedInts,
            useOpList=useOpList,
            listBound=listBound + 1,
            baseDepth=baseDepth,
            invariantBoost=invariantBoost,
            log=log,
        )

    if useOpList:
        print(
            f"#{uid}: Synthesizing invariants for unbounded verification (Rosette structure/history bound: {listBound})"
        )
        equivalence_fn = [x for x in out if x.args[0] == "equivalence"][0]
        state_transition_fn = [
            x for x in out if x.args[0] == f"{fnNameBase}_next_state"
        ][0]
        query_fn = [x for x in out if x.args[0] == f"{fnNameBase}_response"][0]
        init_state_fn = [x for x in out if x.args[0] == f"{fnNameBase}_init_state"][0]

        equivalence_fn.args[3] = Var(
            equivalence_fn.args[3].args[0],
            TupleT(*equivalence_fn.args[3].type.args[:-1]),
        )

        equivalence_fn.args[1] = equivalence_fn.args[1].rewrite(
            {equivalence_fn.args[3].args[0]: equivalence_fn.args[3]}
        )

        state_transition_fn.args[2] = Var(
            state_transition_fn.args[2].args[0],
            TupleT(*state_transition_fn.args[2].type.args[:-1]),
        )

        # drop the op-list
        state_transition_fn.args[1] = Tuple(
            *[
                e.rewrite(
                    {state_transition_fn.args[2].args[0]: state_transition_fn.args[2]}
                )
                for e in state_transition_fn.args[1].args[:-1]
            ]
        )

        query_fn.args[2] = Var(
            query_fn.args[2].args[0], TupleT(*query_fn.args[2].type.args[:-1])
        )

        query_fn.args[1] = query_fn.args[1].rewrite(
            {query_fn.args[2].args[0]: query_fn.args[2]}
        )

        init_state_fn.args[1] = Tuple(*init_state_fn.args[1].args[:-1])

        try:
            # attempt to synthesize the invariants
            return synthesize_crdt(
                filename,
                fnNameBase,
                loopsFile,
                cvcPath,
                origSynthStateType,
                lambda: init_state_fn.args[1],  # type: ignore
                grammarStateInvariant,
                grammarSupportedCommand,
                inOrder,
                opPrecondition,
                lambda inState, args, _baseDepth: typing.cast(
                    Expr, state_transition_fn.args[1]
                ).rewrite(
                    {
                        cur_state_param.name(): inState,
                        **{orig.name(): new for orig, new in zip(op_arg_vars, args)},
                    }
                ),
                lambda _name, _args, _retT, _baseDepth: Synth(
                    query_fn.args[0], query_fn.args[1], *query_fn.args[2:]
                ),
                lambda a, b, _baseDepth, _invariantBoost: equivalence_fn.args[1],  # type: ignore
                targetLang,
                synthesize,
                stateTypeHint=stateTypeHint,
                opArgTypeHint=opArgTypeHint,
                queryArgTypeHint=queryArgTypeHint,
                queryRetTypeHint=queryRetTypeHint,
                uid=uid,
                unboundedInts=unboundedInts,
                useOpList=False,
                listBound=listBound,
                baseDepth=baseDepth,
                invariantBoost=invariantBoost,
                log=log,
            )
        except SynthesisFailed:
            try:
                # try to re-verify with a larger bound
                print(
                    f"#{uid}: re-verifying with history bound {listBound + 1} and attempting to re-synthesize invariants with deeper grammar"
                )
                return synthesize_crdt(
                    filename,
                    fnNameBase,
                    loopsFile,
                    cvcPath,
                    origSynthStateType,
                    lambda: init_state_fn.args[1],  # type: ignore
                    grammarStateInvariant,
                    grammarSupportedCommand,
                    inOrder,
                    opPrecondition,
                    lambda inState, args, _baseDepth: typing.cast(
                        Expr, state_transition_fn.args[1]
                    ).rewrite(
                        {
                            cur_state_param.name(): inState,
                            **{
                                orig.name(): new for orig, new in zip(op_arg_vars, args)
                            },
                        }
                    ),
                    lambda _name, args, _retT, _baseDepth: Synth(
                        query_fn.args[0], query_fn.args[1], *args
                    ),
                    lambda a, b, c, _baseDepth: equivalence_fn.args[1],  # type: ignore
                    targetLang,
                    synthesize,
                    stateTypeHint=stateTypeHint,
                    opArgTypeHint=opArgTypeHint,
                    queryArgTypeHint=queryArgTypeHint,
                    queryRetTypeHint=queryRetTypeHint,
                    uid=uid,
                    unboundedInts=unboundedInts,
                    useOpList=useOpList,
                    listBound=listBound + 1,
                    baseDepth=baseDepth,
                    invariantBoost=invariantBoost + 1,
                    log=log,
                )
            except SynthesisFailed:
                print(
                    f"#{uid}: could not synthesize invariants, re-synthesizing entire design with history bound {listBound + 1}"
                )
                return synthesize_crdt(
                    filename,
                    fnNameBase,
                    loopsFile,
                    cvcPath,
                    origSynthStateType,
                    initState,
                    grammarStateInvariant,
                    grammarSupportedCommand,
                    inOrder,
                    opPrecondition,
                    grammar,
                    grammarQuery,
                    grammarEquivalence,
                    targetLang,
                    synthesize,
                    stateTypeHint=stateTypeHint,
                    opArgTypeHint=opArgTypeHint,
                    queryArgTypeHint=queryArgTypeHint,
                    queryRetTypeHint=queryRetTypeHint,
                    uid=uid,
                    unboundedInts=unboundedInts,
                    useOpList=useOpList,
                    listBound=listBound + 1,
                    baseDepth=baseDepth,
                    invariantBoost=invariantBoost,
                    log=log,
                )
    else:
        return out


# -*- coding: utf-8 -*-
from pandas import DataFrame
from selenium import webdriver

browser = webdriver.Chrome()

def toPage(page):
	browser.get("http://219.135.157.143:2002/gzwz/gdyj/sjwz/yp/sjwzYpScqyList.faces")
	input = browser.find_element_by_css_selector('.dr-table-footer .commonTextInput01')
	# input.click()
	input.clear()
	input.send_keys(page)
	browser.find_element_by_css_selector('.dr-table-footer input[type="submit"]').click()
	return browser

def totalElement():
	atags = browser.find_elements_by_css_selector('.dr-table>tbody td a')
	return len(atags)

def openElement(current):
	# actions = ActionChains(browser)
	atags = browser.find_elements_by_css_selector('.dr-table>tbody td a')
	count = len(atags)
	curInfo = atags[current]
	curInfo.click()

def getCompanyInfo(companies=[]):
	# label=browser.find_element_by_css_selector('#sjwzYpScqyForm:qymc')
	trs = browser.find_elements_by_css_selector('#tb_sjwzBjpPzss_table tr')
	info = {}
	for tr in trs[:-1]:
		try:
			key = tr.find_element_by_css_selector('.rich-table-sixrow6').text
			value = tr.find_element_by_css_selector('.rich-table-fiverow6').text
			info[key] = value
		except Exception as e:
			print('发生异常')
			print(e)
	print(info)
	companies.append(info)
	return info

def getTotalPage():
	return 58

companies = []
try:
	for i in range(1, getTotalPage() + 1):
		toPage(i)
		total = totalElement()
		for x in range(total):
			openElement(x)
			getCompanyInfo(companies)
			browser.back()

	print(companies)
	df = DataFrame(companies)
	df.to_excel('D:\\pypy\\pythonresult\\食品药品\\食品药品相关公司.xlsx', index=False)
except RuntimeError as e:
	print(e)
finally:
	browser.close()

爬虫文件/爬取药企数据信息.py


import sys
import pandas as pd

def merge_csv(files):
    df_list = []
    for file in files:
        df = pd.read_csv(file)
        df_list.append(df)
    result = pd.concat(df_list)
    result.to_csv('result.csv', index=False)

if __name__ == '__main__':
    files = sys.argv[1:]
    merge_csv(files)


import pandas as pd
import pymc as pm
import numpy as np
import arviz as az
import matplotlib.pyplot as plt

#1
data = pd.read_csv("C:\\Users\\Daniel\\Desktop\\PMP-2023\\Lab9\\Admission.csv")
x1 = data['GRE'].values.astype(int)
x2 = data['GPA'].values.astype(float)
admission = data['Admission'].values.astype(int)

with pm.Model() as logistic_model:
    beta0 = pm.Normal('beta0', mu=0, sd=10)
    beta1 = pm.Normal('beta1', mu=0, sd=10)
    beta2 = pm.Normal('beta2', mu=0, sd=10)

    pi = pm.Deterministic('pi', pm.math.sigmoid(beta0 + beta1*x1 + beta2*x2))

    admission_obs = pm.Bernoulli('admission_obs', p=pi, observed=admission)

with logistic_model:
    trace = pm.sample(2000, tune=1000)

pm.summary(trace)

#2
gre_values = np.linspace(data['GRE'].min(), data['GRE'].max(), 100)
gpa_values = np.linspace(data['GPA'].min(), data['GPA'].max(), 100)
x_grid = np.meshgrid(gre_values, gpa_values)
p_grid = pm.math.sigmoid(np.mean(trace['beta0']) + np.mean(trace['beta1']) * x_grid[0] + np.mean(trace['beta2']) * x_grid[1])
decision_boundary = np.mean(p_grid > 0.5)

hdi = az.hdi(trace['p'], hdi_prob=0.94)
print(f"Granita de decizie: {decision_boundary}")

p_grid_values = p_grid.eval()
decision_boundary_grid = p_grid_values > 0.5
hdi_grid = az.hdi(p_grid_values, hdi_prob=0.94)
plt.scatter(data['GRE'], data['GPA'], c=[f'C{x}' for x in data['Admission']])
plt.contour(x_grid[0], x_grid[1], decision_boundary_grid, levels=[0.5], colors='k')
plt.contourf(x_grid[0], x_grid[1], hdi_grid, levels=[hdi_grid.min(), 0.5, hdi_grid.max()], colors=['b', 'r', 'b'], alpha=0.5)
plt.xlabel('GRE')
plt.ylabel('GPA')
plt.legend(['Decision boundary', '94% HDI'])
plt.show()

#3
student1 = np.array([[550, 3.5]])
p_student1 = pm.math.sigmoid(np.mean(trace['beta0']) + np.mean(trace['beta1']) * student1[0, 0] + np.mean(trace['beta2']) * student1[0, 1]).eval()
hdi_student1 = az.hdi(p_student1, hdi_prob=0.9)
print(f"90% HDI for a student with GRE=550 and GPA=3.5: {hdi_student1[0]}, {hdi_student1[1]}")

#4
student2 = np.array([[500, 3.2]])
p_student2 = pm.math.sigmoid(np.mean(trace['beta0']) + np.mean(trace['beta1']) * student2[0, 0] + np.mean(trace['beta2']) * student2[0, 1]).eval()
hdi_student2 = az.hdi(p_student2, hdi_prob=0.9)
print(f"90% HDI for a student with GRE=500 and GPA=3.2: {hdi_student2[0]}, {hdi_student2[1]}")


from django.core.exceptions import ObjectDoesNotExist

from rest_framework.permissions import BasePermission

from consultant.models import Consultant

from .models import Circle
from .conf import settings

class CanViewCircle(BasePermission):

    def has_permission(self, request, view):
        can_view = False
        circle_name = view.kwargs.get('name')
        try:
            circle = Circle.objects.get(
                name__iexact=circle_name)
            can_view = circle.is_user_in_followers(request.user)
        except Circle.DoesNotExist:
            if circle_name == settings.CIRCLES_PROJECT_QUESTION_CIRCLE_NAME:
                can_view = request.user in Consultant.objects.filter_consulting_enabled().users()
            else:
                raise ObjectDoesNotExist

        return can_view or request.user.is_superuser


#!/usr/bin/env python
from setuptools import setup
import dyndns

with open("README.md", "r") as fh:
    long_description = fh.read()

test_deps = [
    'unittest2 >= 1.1.0',
]

setup(
    name = 'domain-connect-dyndns',
    version=dyndns.__version__,
    description = 'Python client library for Dynamic DNS using Domain Connect',
    license = 'MIT',
    long_description=long_description,
    long_description_content_type="text/markdown",
    author = 'Andreea Dima',
    author_email = 'andreea.dima@1and1.ro',
    url="https://github.com/Domain-Connect/DomainConnectDDNS-Python",
    classifiers = [
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 2',
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent"
    ],
    packages = [
        'dyndns',
    ],
    install_requires = [
        'validators >= 0.12.6',
        'requests >= 2.21.0',
        'dnspython >= 1.15.0',
        'domain-connect >= 0.0.9',
        'ipaddress >= 1.0.23;python_version<"3.3"',
    ],
    entry_points = {
        'console_scripts': ['domain-connect-dyndns=dyndns.command_line:main'],
    },
    tests_require=test_deps,
    extras_require={
        'test': test_deps,
    },
)


import heapq
import json
import math
import os
import pickle
from os import listdir
from os.path import isfile

import numpy as np
import pkg_resources
import scipy
from gensim.models import FastText
from scipy import spatial

from aminer.precision.evaluate.evaluate_better import extract_fos_set, extract_lang_and_fos_set
from aminer.recall.query_es import get_abstract_by_pids, get_references_by_pid
from aminer.precision.metrics import recall, precision

root_directory = pkg_resources.resource_filename("aminer", "support")
model_directory = os.path.join(root_directory, "models")

vec = pickle.load(open(os.path.join(model_directory, 'vec.model'), 'rb'))
fasttext = FastText.load(os.path.join(model_directory, 'fasttext', 'fasttext.model'))
word_to_idx = list(vec.get_feature_names())

def compute_abstract_embedding(abstract, is_query=False):
    tfidf_vec = vec.transform([abstract])
    tfidf_vec = scipy.sparse.coo_matrix(tfidf_vec)
    word_count = 0
    sum_embedding = np.zeros(50)
    for _, word_index, word_tfidf in zip(tfidf_vec.row, tfidf_vec.col, tfidf_vec.data):
        word = word_to_idx[word_index]
        if word in fasttext.wv.vocab:
            word_count += 1
            if not is_query:
                sum_embedding += word_tfidf * fasttext.wv[word]
            else:
                sum_embedding += fasttext.wv[word]

    if word_count == 0:
        return [0] * 50

    return (sum_embedding / word_count).tolist()

def get_all_embeddings(current_embedding, files, fos):
    for file in files:
        print("Checking file: ", file)
        with open(file, 'r') as f:
            embeddings = json.load(f)
            f.close()

        for pid, emb in embeddings.items():
            target_lang, target_fos = extract_lang_and_fos_set(pid)
            if not target_fos.isdisjoint(fos):
                if target_lang == 'en' or target_lang == 'Not inputted':
                    cosine_similarity = 1 - spatial.distance.cosine(current_embedding, emb)
                    if not math.isnan(cosine_similarity):
                        yield (pid, cosine_similarity)

def recommend(ids, k=100):
    ids_to_abstract = get_abstract_by_pids(ids)

    recommendations = {}

    for target_id, abstract in ids_to_abstract.items():
        print("Finding recommendations for: ", target_id)
        fos = extract_fos_set(target_id)
        embeddings_directory = os.path.join(root_directory, "output_embeddings2")

        current_embedding = compute_abstract_embedding(abstract, is_query=True)

        files = [os.path.join(embeddings_directory, f) for f in listdir(embeddings_directory) if isfile(os.path.join(embeddings_directory, f))]

        all_embeddings = get_all_embeddings(current_embedding, files, fos)
        recommendations[target_id] = heapq.nlargest(k, all_embeddings, key=lambda e: e[1])

    return recommendations

if __name__ == '__main__':
    file = os.path.join(root_directory, 'sample_id.txt')
    ids = [line.rstrip('\n') for line in open(file)]

    recommendations = recommend(ids, 100000)

    outfile = os.path.join(root_directory, 'recommendations.json')

    with open(outfile, 'w') as f:
        json.dump(recommendations, f)

    for pid, recs in recommendations.items():
        pred_reference_list = [e[0] for e in recs]
        true_reference_list = get_references_by_pid(pid)

        print(precision(pred_reference_list, true_reference_list))
        print(recall(pred_reference_list, true_reference_list))


import pygame
import sys
from pygame.locals import *
import math
from random import randint
import background
import time

class vec2d(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

indigo = (121, 134, 203)
sun_red = (191, 54, 12)
radius_red = (230, 74, 25)
sea = (13, 71, 161)
lightblue1 = (3, 155, 229)
lightblue2 = (41, 182, 246)
blue = (2, 119, 189)
darkblue = (129, 212, 250)
white = (255, 255, 255)
orange = (255, 152, 0)
amber = (255, 111, 0)
earth = (0, 77, 64)
day_sky = (128,222,234)
dark_sky = (0,96,100)
moon = (255,241,118)

def draw(display, display_width, display_height):
    millis_weight = 10
    mod_range = 1000
    mod_weight = millis_weight*mod_range
    mod_middle = mod_weight/2
    millis = int(round(time.time() * 1000))
    display.fill((255, 255, 255))
    if millis%mod_weight > mod_middle:
        draw_day(display, display_width, display_height)
    elif millis%mod_weight< mod_middle:
        draw_dark(display, display_width, display_height)

    draw_sky(display, display_width, display_height)
    draw_wave(display, display_width, display_height)

    if millis%mod_weight > mod_middle:
        draw_sun(display, display_width, display_height)
    elif millis%mod_weight< mod_middle:
        draw_moon(display)

def draw_sun(display, display_width, display_height):
    sun_center = (200, 100)
    radius_number = 10 + randint(0, 10)
    radius_length = 40 + randint(0, 10)
    sub_radius_angle = 360 / radius_number
    sun_radius = 50 + randint(0, 10)
    sun_radius_gap = 10 + randint(0, 10)
    for radius_index in range(0, radius_number):
        angle = math.radians((radius_index - 1) * sub_radius_angle)
        X = sun_center[0]
        Y = sun_center[1]
        radius_start = radius_length + sun_radius_gap + randint(0, 40)
        radius_end = sun_radius + radius_length + \
            sun_radius_gap + randint(0, 40)
        point1 = (math.floor(X - (math.cos(angle) * (radius_start))),
                  math.floor(Y - (math.sin(angle) * (radius_start))))
        point2 = (math.floor(X - (math.cos(angle) * (radius_end))),
                  math.floor(Y - (math.sin(angle) * (radius_end))))
        pygame.draw.lines(
            display, radius_red, True, [point1, point2], 10)

    pygame.draw.circle(display, sun_red, sun_center, radius_length, 0)

def draw_cloud(display, display_width, display_height):
    pygame.draw.arc(display, indigo, (600, 150, 100, 80),
                    math.radians(0), math.radians(randint(10, 300)), 4)

def draw_wave(display, display_width, display_height):
    sea_tick = 20
    rim_tick = 20
    start_point = 600
    sea_start = start_point
    wave_start = start_point
    max_wave = 10
    min_wave = 10
    max_amp = 50
    wave_gap = 25
    wave_gang = randint(min_wave, max_wave)

    for wave in range(0, wave_gang, 2):
        vary_base = randint(30, 50)
        amp = randint(vary_base, max_amp)
        wave_start -= wave_gap
        random_sea = randint(0, 3)
        for xaxis in range(0, display_width, 15):
            if wave == 0 or wave == wave_gang - 1:
                pygame.draw.circle(display, sea, (xaxis, (wave_start) + math.floor(
                    (amp) * math.sin(math.radians(xaxis)))), rim_tick, 0)
            elif wave == 0 or wave == wave_gang - 1:
                pygame.draw.circle(display, sea, (xaxis, (wave_start) + math.floor(
                    (amp) * math.sin(math.radians(xaxis)))), rim_tick, 0)
            else:
                if random_sea == 0:
                    pygame.draw.circle(display, blue, (xaxis, (wave_start) + math.floor(
                        (amp) * math.sin(math.radians(xaxis)))), sea_tick, 0)
                elif random_sea == 1:
                    pygame.draw.circle(display, lightblue1, (xaxis, (
                        wave_start) + math.floor((amp) * math.sin(math.radians(xaxis)))), sea_tick, 0)
                elif random_sea == 2:
                    pygame.draw.circle(display, lightblue2, (xaxis, (
                        wave_start) + math.floor((amp) * math.sin(math.radians(xaxis)))), sea_tick, 0)
                elif random_sea == 3:
                    pygame.draw.circle(display, darkblue, (xaxis, (wave_start) + math.floor(
                        (amp) * math.sin(math.radians(xaxis)))), sea_tick, 0)

def draw_sky(display, display_width, display_height):
    start_point = 500
    end_point = 800
    gap = math.floor((end_point - start_point) / 20)
    amp = 1
    for sand in range(0, 4):
        amp = 10
        start = sand * 30
        for xaxis in range(0, display_width, randint(5, 20)):
            if randint(0, 1) == 0:
                if sand % 2 == 0:
                    pygame.draw.circle(
                        display, orange, (xaxis, (start) + math.floor((amp) * math.sin(math.radians(xaxis)))), 10, 0)
                else:
                    pygame.draw.circle(
                        display, amber, (xaxis, (start) + math.floor((amp) * math.sin(math.radians(xaxis)))), 10, 0)
            else:
                if sand % 2 == 0:
                    pygame.draw.circle(
                        display, sea, (xaxis, (start) + math.floor((amp) * math.sin(math.radians(xaxis)))), 10, 0)
                else:
                    pygame.draw.circle(
                        display, blue, (xaxis, (start) + math.floor((amp) * math.sin(math.radians(xaxis)))), 10, 0)

def draw_day(display, display_width, display_height):
    pygame.draw.rect(
        display, day_sky, (0, 0, display_width, display_height), 0)

def draw_dark(display, display_width, display_height):
    pygame.draw.rect(
        display, dark_sky, (0, 0, display_width, display_height), 0)

def draw_moon(display):
    width = 30
    height = 200
    moon_head = [300, 100]
    moon_tail = [moon_head[0], moon_head[1] + height]
    body_top = [moon_head[0]-(width+80), moon_head[1]+20]
    body_low = [moon_head[0]-(width+80), moon_tail[1]-20]

    for fillMoon in range(0, width):
        control_points = [vec2d(moon_head[0], moon_head[1]), vec2d(body_top[0]+fillMoon, body_top[
            1]), vec2d(body_low[0]+fillMoon, body_low[1]), vec2d(moon_tail[0], moon_tail[1])]

        # Draw bezier curve
        b_points = compute_bezier_points([(x.x, x.y) for x in control_points])
        pygame.draw.lines(display, moon, False, b_points, 2)

def compute_bezier_points(vertices, numPoints=None):
    if numPoints is None:
        numPoints = 30
    if numPoints < 2 or len(vertices) != 4:
        return None

    result = []

    b0x = vertices[0][0]
    b0y = vertices[0][1]
    b1x = vertices[1][0]
    b1y = vertices[1][1]
    b2x = vertices[2][0]
    b2y = vertices[2][1]
    b3x = vertices[3][0]
    b3y = vertices[3][1]

    # Compute polynomial coefficients from Bezier points
    ax = -b0x + 3 * b1x + -3 * b2x + b3x
    ay = -b0y + 3 * b1y + -3 * b2y + b3y

    bx = 3 * b0x + -6 * b1x + 3 * b2x
    by = 3 * b0y + -6 * b1y + 3 * b2y

    cx = -3 * b0x + 3 * b1x
    cy = -3 * b0y + 3 * b1y

    dx = b0x
    dy = b0y

    # Set up the number of steps and step size
    numSteps = numPoints - 1  # arbitrary choice
    h = 1.0 / numSteps  # compute our step size

    # Compute forward differences from Bezier points and "h"
    pointX = dx
    pointY = dy

    firstFDX = ax * (h * h * h) + bx * (h * h) + cx * h
    firstFDY = ay * (h * h * h) + by * (h * h) + cy * h

    secondFDX = 6 * ax * (h * h * h) + 2 * bx * (h * h)
    secondFDY = 6 * ay * (h * h * h) + 2 * by * (h * h)

    thirdFDX = 6 * ax * (h * h * h)
    thirdFDY = 6 * ay * (h * h * h)

    # Compute points at each step
    result.append((int(pointX), int(pointY)))

    for i in range(numSteps):
        pointX += firstFDX
        pointY += firstFDY

        firstFDX += secondFDX
        firstFDY += secondFDY

        secondFDX += thirdFDX
        secondFDY += thirdFDY

        result.append((int(pointX), int(pointY)))

    return result


class Solution:
    def isValid(self, s: str) -> bool:
        stack = list()
        lens = len(s)
        for i in range(lens):
            if len(stack) == 0:
                stack.append(s[i])
            else:
                if (s[i] == ')' and stack[-1] == '(') or (s[i] == '}' and stack[-1] == '{') or \
                        (s[i] == ']' and stack[-1] == '['):
                    stack.pop()
                else:
                    stack.append(s[i])

        return len(stack) == 0

if __name__ == "__main__":
    s = "()[]{}"
    res = Solution().isValid(s)
    print(res)


# Necessary imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import random
r = lambda x: random.randint(0,x)

# build a rectangle in axes coords
left, width = .1, .8
bottom, height = .1, .8
right = left + width
top = bottom + height

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])

# axes coordinates are 0,0 is bottom left and 1,1 is upper right
frame = patches.Rectangle((left, bottom), width, height,
    fill=False, transform=ax.transAxes, clip_on=False
    )

ax.add_patch(frame)

def drawBox(text, box_left, box_width, row = 0, box_height = 0.1):

	if row == 0:
		color = '#8844FF'
	else:
		red = int(255*box_width/width)
		green = r(255)
		blue =  max(0, min(255, 255-row*50 + r(50)))

		color = '#%02X%02X%02X' % (red, green, blue)

	p = patches.Rectangle((box_left, top - box_height*(1+row)), box_width, box_height,
    facecolor=color, transform=ax.transAxes, clip_on=False, linewidth=1,edgecolor='#000000'
    )

	ax.add_patch(p)

	if box_width > 0.05:
		ax.text(box_left*0.5 + box_width*0.5 + left, top - box_height/2 - box_height*row, text,
		        horizontalalignment='center', verticalalignment='center',
		        fontsize=10, transform=ax.transAxes, wrap=True)

infilename  = "lofar_bootes_ps_timing_timestep500.txt"
infile = open(infilename,"r")
bleft1 = left
bleft2 = left
toptime = 1
for line in infile:
	if ':' not in line: continue
	toks = line.split(':')
	time = toks[-1].strip().split(' ')[0]
	name = toks[0]

	print(line)
	if line[:6] == 'Total:':
		drawBox("{0}: {1}s".format(name,time), left, width, row = 0)
		toptime = float(time)
		continue
	if line[0] != ' ':
		drawBox("{0}: {1}s".format(name,time), bleft1, width*float(time)/toptime, row = 1)
		bleft1 += width*float(time)/toptime
	if line[:2] == '  ' and line[2] != ' ':
		drawBox("{0}: {1}s".format(name,time), bleft2, width*float(time)/toptime, row = 2)
		bleft2 += width*float(time)/toptime

'''
ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5*(bottom+top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5*(bottom+top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        fontsize=20,
        transform=ax.transAxes)

ax.text(right, 0.5*(bottom+top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)
'''

ax.set_axis_off()
plt.show()


import time
from qode.util import output, indent

# operators, SCF and CCSD modules
from qode                               import fermion_field
from qode.many_body.nested_operator     import operator, space_traits, BakerCampbellHausdorff
from qode.many_body                     import CCSD

# Hamiltonian
from hamiltonian import hamiltonian, inv_fock

def main(h_mat, V_mat, F_mat, E_nuclear_repul, occ_orbs, vrt_orbs, textlog, resources):
	out = output(log=textlog)

	out.log("Partioning fluctuations (excitations, flat, deexcitations) ...")
	fluctuations = fermion_field.OV_partitioning(occ_orbs,vrt_orbs)

	out.log("Building normal-ordered H ...")
	H = hamiltonian(E_nuclear_repul, h_mat, V_mat, fluctuations)

	out.log("Getting orbital energy preconditioner ...")
	invF = inv_fock(F_mat, fluctuations)

	out.log("Initializing T ...")
	T = operator(fluctuations)		# Initialized to zero

	BCH = BakerCampbellHausdorff(fluctuations, resources)
	out.log("Baker-Campbell-Hausdorff module initialized.")

	out.log("Perform coupled-cluster iterations.")
	t_ccsd_start = time.time()
	E = CCSD(H, T, invF, BCH, space_traits, out.log.sublog())
	t_ccsd_end = time.time()

	out.log("CCSD Energy =", E, 'Hartree')
	out.log("CCSD TIME {}".format(t_ccsd_end - t_ccsd_start))

	return out(energy=E)


import requests
import csv

def startGame():
    # Loop through 3 questions, get answer, compare answer with question and keep score
    print("Let's start {} ".format(username))
    score = 0
    for eachResult in getResults:
        oneStatement = eachResult["question"]
        correctAnswer = eachResult["correct_answer"].lower()
        oneStatement = oneStatement.replace('"', '"')
        print(oneStatement)
        answer = input("Is this statement true or false?").lower()

        while answer != "true" and answer != "false" and answer != "t" and answer != "f":
            print("That is not an acceptable answer, please try again")
            answer = input("Is this statement true or false?").lower()

        if correctAnswer == answer or correctAnswer[0] == answer[0]:
            print("You scored one point")
            score += 1

        else:
            print("Sorry your answer is incorrect, now you know for next time")

    print("Your score this time is {} and your score has been added to the scoreboard".format(score))

    # Save player and score to CSV
    results = [{"player": username, "score": score}]

    with open('scoreboard.csv', 'a') as scoreboard:
        spreadsheet = csv.DictWriter(scoreboard, fieldnames=["player", "score"])
        spreadsheet.writerows(results)

# Get data from API
getData = requests.get("https://opentdb.com/api.php?amount=3&category=18&difficulty=easy&type=boolean")
convertData = getData.json()
getResults = convertData["results"]

# Display welcome message
print("Welcome to Trivia")

# Ask for name, display welcome message, then slice the name for the scoreboard
name = input("What is your first name?")
username = name[0:3].lower()
startGame()

#Gives the option to play again
playAgain = input("Do you want to play again?").lower()
while playAgain == "yes" or playAgain == "y":
    startGame()
    playAgain = input("Do you want to play again?")

print("Thanks for playing")


import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import*
import random
from pygame import mixer

pygame.init()
textfont = pygame.font.SysFont("monospace",50)
class display:

    def __init__(self, width, height, window):
        self.width = width
        self.height = height
        self.window = window

    def update(self):
        pygame.display.flip()
        pygame.time.wait(10)

    def clear(self):
        glClearColor(0,0,0.1,1)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

screen = display(800, 400, pygame.display.set_mode((800, 400), DOUBLEBUF|OPENGL))
pygame.display.set_caption('Space Shooter 1v1')

#BGMUSIC########

index = 0
rages = True
bgmusiclist = ['bgmusic.mp3','low.mp3']
pygame.mixer.music.load(bgmusiclist[index])
mixer.music.play(-100)

bullet2_sound = mixer.Sound('blaster2.mp3')###
collide_sound = mixer.Sound('coolide.mp3')###
player_hitsound = mixer.Sound('playerhit.mp3')####
player_hitsound.set_volume(0.5)
bullet1_sound = mixer.Sound('blaster1.mp3')###
alarm = mixer.Sound('alarm.mp3')#####
end = mixer.Sound('end.mp3')#####

#BGMUSIC########

def rage_true():
        global index
        index = 1
        pygame.mixer.music.load(bgmusiclist[index])
        pygame.mixer.music.play(-100)
def rage_false():
        global index
        index = 0
        pygame.mixer.music.load(bgmusiclist[index])
        pygame.mixer.music.play(-100)

class player_one:
    def __init__(self, vertices, edges):
        self.vertices = vertices
        self.edges = edges
        self.pos = [-13,0,0]
        self.int = 0.02

    def move(self):
        self.k_press = pygame.key.get_pressed()
        if self.k_press[pygame.K_w]:
            if self.pos[1] < 6:
                self.pos[1] += self.int

        if self.k_press[pygame.K_s]:
            if self.pos[1] > -6:
                self.pos[1] -= self.int

        #if self.k_press[pygame.K_d]:
            #if self.pos[0] < -1.2:
          #      self.pos[0] += self.int

     #   if self.k_press[pygame.K_a]:
      #      if self.pos[0] > -13.8:
         #       self.pos[0] -= self.int

    def draw(self):
        glPushMatrix()
        glTranslatef(*self.pos)
        r = random.uniform(0,1)
        g = random.uniform(0,1)
        b = random.uniform(0,1)
        if one_health.int <= 5:
                glColor3f(r,g,b)
        #RAGEEEEEEE
        if one_health.int <= 5:
                if finish == False:
                        glColor3f(r,g,b)
                        self.int = 0.3
                        bullet_one.int = 0.8
                        rage = True

        else:
                glColor3f(1,1,1)

        glBegin(GL_LINES)
        glVertex2f(0,0)
        glVertex2f(0,1)

        glVertex2f(0,1)
        glVertex2f(1,0.0)

        glVertex2f(1,0)
        glVertex2f(0,-1.0)

        glVertex2f(0,-1.0)
        glVertex2f(0,0.0)
        glEnd()
        glPopMatrix()

    def draw_line(self):
        if finish == True:
                glColor3f(0,0,0)
        elif title == True:
                glColor3f(0,0,0)
        else:
                glColor3f(1,1,1)
        glPushMatrix()

        glBegin(GL_LINES)
        glVertex2f(0,8)
        glVertex2f(0,-8)
        glEnd()

        #player 1 bar
        glBegin(GL_LINES)
        glColor3f(1,1,1)
        glVertex2f(-13.62,5.3)
        glVertex2f(-3.05,5.3)

        glVertex2f(-3.05,5.3)
        glVertex2f(-3.05,6.67)

        glVertex2f(-3.05,6.67)
        glVertex2f(-13.62,6.67)

        glVertex2f(-13.62,6.67)
        glVertex2f(-13.62,5.3)
        glEnd()
        #player 2 bar
        glBegin(GL_LINES)
        glColor3f(1,1,1)
        glVertex2f(13.62,5.3)
        glVertex2f(3.05,5.3)

        glVertex2f(3.05,5.3)
        glVertex2f(3.05,6.67)

        glVertex2f(3.05,6.67)
        glVertex2f(13.62,6.67)

        glVertex2f(13.62,6.67)
        glVertex2f(13.62,5.3)
        glEnd()
        glPopMatrix()

    def random_stars(self):
        for i in range(10):
                glEnable(GL_POINT_SMOOTH)
                sizerandom = random.uniform(0.5,2.5)
                glPointSize(sizerandom)
                clockobject = pygame.time.Clock()
                starsX = random.uniform(-15.6,15.2)
                starsY = random.uniform(-15.2,12.4)
                rr = random.randint(0,1)
                gg = random.randint(0,1)
                bb = random.randint(0,1)
                glBegin(GL_POINTS)
                glColor3f(rr,gg,bb)
                glVertex3d(starsX,starsY,0)
                glEnd()

class one_health:
    def __init__(selfh, vertices, edges):
        selfh.vertices = vertices
        selfh.edges = edges
        selfh.pos = [-13,6.5,0]
        selfh.int = 15

    def draw(selfh,size,health_num):

            glPushMatrix()
            glTranslatef(*selfh.pos)
            rg = random.uniform(0.5,1)
            rb = random.uniform(0.5,0.5)
            rr = random.uniform(0.5,1)

            if selfh.int >= 10:
                glColor3f(0,rg,rb)
            if selfh.int <= 9:
                glColor3f(rr,rg,0)
            if selfh.int <= 5:
                glColor3f(rr,0,rb)

            glBegin(GL_QUADS)
            for i in range(selfh.int):

                glVertex2f(0+size,0)
                glVertex2f(-0.5+size,0)

                glVertex2f(-0.5+size,0)
                glVertex2f(-0.5+size,-1)

                glVertex2f(-0.5+size,-1)
                glVertex2f(0+size,-1.0)

                glVertex2f(0+size,-1)
                glVertex2f(0+size,0)

                size += 0.7

            glEnd()
            glPopMatrix()

class two_health:
    def __init__(selfh, vertices, edges):
        selfh.vertices = vertices
        selfh.edges = edges
        selfh.pos = [13,5.5,0]
        selfh.int = 15

    def draw(selfh,size,health_num):

            glPushMatrix()
            glTranslatef(*selfh.pos)
            glRotatef(180,0,0,0)
            rg = random.uniform(0.5,1)
            rb = random.uniform(0.5,0.5)
            rr = random.uniform(0.5,1)

            if selfh.int >= 10:
                glColor3f(0,rg,rb)
            if selfh.int <= 9:
                glColor3f(rr,rg,0)
            if selfh.int <= 5:
                glColor3f(rr,0,rb)

            glBegin(GL_QUADS)
            for i in range(selfh.int):

                glVertex2f(0+size,0)
                glVertex2f(-0.5+size,0)

                glVertex2f(-0.5+size,0)
                glVertex2f(-0.5+size,-1)

                glVertex2f(-0.5+size,-1)
                glVertex2f(0+size,-1.0)

                glVertex2f(0+size,-1)
                glVertex2f(0+size,0)

                size += 0.7

            glEnd()
            glPopMatrix()

class player_two:
    def __init__(selfs, vertices, edges):
        selfs.vertices = vertices
        selfs.edges = edges
        selfs.pos = [13,0,0]
        selfs.int = 0.02

    def move(selfs):
        selfs.k_press = pygame.key.get_pressed()
        if selfs.k_press[pygame.K_UP]:
            if selfs.pos[1] < 6:
                selfs.pos[1] += selfs.int

        if selfs.k_press[pygame.K_DOWN]:
            if selfs.pos[1] > -6:
                selfs.pos[1] -= selfs.int
        #if selfs.k_press[pygame.K_RIGHT]:
        #    if selfs.pos[0] < 13.8:
         #       selfs.pos[0] += selfs.int

        #if selfs.k_press[pygame.K_LEFT]:
          #  if selfs.pos[0] > 1.2:
             #   selfs.pos[0] -= selfs.int

    def draw(selfs):
        glPushMatrix()
        glTranslatef(*selfs.pos)
        r = random.uniform(0,1)
        g = random.uniform(0,1)
        b = random.uniform(0,1)
        #RAGEEEEEEE
        if two_health.int <= 5:
                if finish == False:
                        glColor3f(r,g,b)
                        selfs.int = 0.3
                        bullet_two.int = 0.8

        else:
                glColor3f(1,1,1)

        glBegin(GL_LINES)
        glVertex2f(0,0)
        glVertex2f(0,-1)

        glVertex2f(0,-1)
        glVertex2f(-1,0.0)

        glVertex2f(-1,0)
        glVertex2f(0,1.0)

        glVertex2f(0,1.0)
        glVertex2f(0,0.0)
        glEnd()
        glPopMatrix()

class bullet_one:
    def __init__(selfr, vertices, edges):
        selfr.vertices = vertices
        selfr.edges = edges
        selfr.pos = [-12,0,0]
        selfr.int = 0.009

    def draw(selfr):
        glPushMatrix()
        glTranslatef(*selfr.pos)
        glPointSize(20)
        rg = random.uniform(0.5,1)
        rb = random.uniform(1,0.5)
        rr = random.uniform(0.5,0.5)
        glColor3f(0,rg,rb)
        glBegin(GL_POINTS)
        glVertex2d(0,0)
        glEnd()
        glPopMatrix()

    def shoot(selfr):
        global rages
        selfr.pos[0] += selfr.int

        #bulletsound condition
        if selfr.pos[0] <= player_one.pos[0] + 0.8:
            if finish == False:
                bullet1_sound.set_volume(0.3)
                bullet1_sound.play()####

        if selfr.pos[0] > 16:
            selfr.pos[0] = player_one.pos[0]
            selfr.pos[1] = player_one.pos[1]

        if selfr.pos[0] >= (player_two.pos[0] -0.5):
            if selfr.pos[0] <= (player_two.pos[0] + 0.5):
                if selfr.pos[1] < (player_two.pos[1]+1):
                    if selfr.pos[1] > (player_two.pos[1]-1):
                        if finish == False:
                            selfr.pos[0] = player_one.pos[0]
                            selfr.pos[1] = player_one.pos[1]
                            player_hitsound.play()
                            two_health.int -= 1
                            print("player 1 hit")
                            if two_health.int == 5:
                                alarm.play()#####
                                rages = True

                                if rages == True:
                                    rage_true()
                                    rages = False

                            if two_health.int == 0:
                                rage_false()
                                end.play()#####

        if selfr.pos[0] >= bullet_two.pos[0]:
            if selfr.pos[1] < (bullet_two.pos[1]+ 0.5):
                if selfr.pos[1] > (bullet_two.pos[1]- 0.5):
                    if finish == False:
                        selfr.pos[0] = player_one.pos[0]
                        selfr.pos[1] = player_one.pos[1]
                        bullet_two.pos[0] = player_two.pos[0]
                        bullet_two.pos[1] = player_two.pos[1]
                        collide_sound.set_volume(0.5)
                        collide_sound.play()

class bullet_two:
    def __init__(selft, vertices, edges):
        selft.vertices = vertices
        selft.edges = edges
        selft.pos = [12,0,0]
        selft.int = 0.009

    def draw(selft):
        glPushMatrix()
        glTranslatef(*selft.pos)
        glPointSize(20)
        rg = random.uniform(0.5,1)
        rb = random.uniform(0,1)
        rr = random.uniform(0.5,1)
        glColor3f(rr,0,rb)
        glBegin(GL_POINTS)
        glVertex2d(0,0)
        glEnd()
        glPopMatrix()

    def shoot(selft):
        global rages
        selft.pos[0] -= selft.int

        #bulletsound condition
        if selft.pos[0] >= player_two.pos[0] - 0.8:
            if finish == False:

                bullet2_sound.set_volume(0.2)###
                bullet2_sound.play()####

        if selft.pos[0] < -16:
            selft.pos[0] = player_two.pos[0]
            selft.pos[1] = player_two.pos[1]

        if selft.pos[0] <= (player_one.pos[0]+0.5):
            if selft.pos[0] >= (player_one.pos[0] - 0.5):
                if selft.pos[1] < (player_one.pos[1] + 1):
                    if selft.pos[1] > (player_one.pos[1] - 1):
                        if finish == False:
                            selft.pos[0] = player_two.pos[0]
                            selft.pos[1] = player_two.pos[1]
                            print("player 2 hit")
                            player_hitsound.play()
                            one_health.int -= 1
                            if one_health.int == 5:
                                alarm.play()#####
                                rages = True
                                if rages == True:
                                    rage_true()
                                    rages = False

                            if one_health.int == 0:
                                rage_false()

                                end.play()#####

        if one_health.int <= 0:
            selft.int = 0.01
            bullet_one.int = 0.01
            player_one.int = 0.01
            player_two.int = 0.01

        if two_health.int <= 0:
            selft.int = 0.01
            bullet_one.int = 0.01
            player_one.int = 0.01
            player_two.int = 0.01

class GameOver:
        def __init__(selfg, vertices, edges):
                selft.vertices = vertices
                selft.edges = edges
                selft.pos = [0,0,0]

        def drawText(x, y, text):
                r = random.uniform(150,255)
                g = random.uniform(150,255)
                b = random.uniform(150,255)
                textSurface = font.render(text, True, (255, r, g, 255)).convert_alpha()
                textData = pygame.image.tostring(textSurface, "RGBA", True)
                glWindowPos2d(x, y)
                glDrawPixels(textSurface.get_width(), textSurface.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, textData)

player_one = player_one(((1, -1)),((0, 0)))
player_two = player_two(((1, -1)),((0, 0)))
bullet_one = bullet_one(((1, -1)),((0, 0)))
bullet_two = bullet_two(((1, -1)),((0, 0)))
one_health = one_health(((1, -1)),((0, 0)))
two_health = two_health(((1, -1)),((0, 0)))

class main:

    def display_all():
        player_one.move()
        player_one.draw()
        one_health.draw(0,0)

        player_one.draw_line()
        player_one.random_stars()

        player_two.move()
        player_two.draw()
        two_health.draw(0,0)

        bullet_one.shoot()
        bullet_one.draw()

        bullet_two.shoot()
        bullet_two.draw()

glMatrixMode(GL_PROJECTION)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
gluPerspective(45, (screen.width/screen.height), 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
glTranslatef(0,0,-17)

game_over = False
finish = False
hideone = 1000
hidetwo = 1000
spacetext = 1000
hidetitle = 180
hidetitle2 = 120
title = True
coder = 0
hide1v1 = 260
rage = False

while not game_over:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            print('gameover')
            pygame.quit()

        if bullet_two.pos[0] <= bullet_one.pos[0]:
            if bullet_two.pos[1] < (bullet_one.pos[1] + 0.5):
                if bullet_two.pos[1] > (bullet_one.pos[1] - 0.5):
                   if finish == False:
                        bullet_two.pos[0] = player_two.pos[0]
                        bullet_two.pos[1] = player_two.pos[1]
                        bullet_one.pos[0] = player_one.pos[0]
                        bullet_one.pos[1] = player_one.pos[1]
                        collide_sound.play()
                        print('bullet collide')

        if one_health.int <=0:
            if two_health.int > one_health.int:
                print('PLAYER TWO WINS')
                hidetwo = 220
                spacetext = 150
                coder =0
                finish = True

        if two_health.int <=0:
            if one_health.int > two_health.int:
                print('PLAYER ONE WINS')
                hideone = 220
                spacetext = 150
                coder = 0
                finish = True

        if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                        if finish == True:
                                print(index)
                                if title == False:
                                    if index == 0:
                                        rage_false()
                                        print('restart')
                                        #player health
                                        one_health.int =15
                                        two_health.int = 15
                                        #reset movement speed and position p1
                                        player_one.int = 0.2
                                        player_one.pos[1] = 0
                                        player_one.pos[0] = -13
                                         #reset movement speed and position p2
                                        player_two.int = 0.2
                                        player_two.pos[1] = 0
                                        player_two.pos[0] = 13
                                        #bullet speed
                                        bullet_one.int = 0.5
                                        bullet_two.int = 0.5
                                        #bullet position reset Y
                                        bullet_one.pos[1] = 0
                                        bullet_two.pos[1] = 0
                                        #bullet position reset X
                                        bullet_one.pos[0] = -13
                                        bullet_two.pos[0] = 13

                                        hideone = 1000
                                        hidetwo = 1000
                                        spacetext = 1000
                                        coder =1000
                                        finish = False

                        if title == True:
                                print('Startgame')
                                #player health
                                one_health.int =15
                                two_health.int = 15
                                #reset movement speed and position p1
                                player_one.int = 0.2
                                player_one.pos[1] = 0
                                player_one.pos[0] = -13
                                #reset movement speed and position p2
                                player_two.int = 0.2
                                player_two.pos[1] = 0
                                player_two.pos[0] = 13
                                #bullet speed
                                bullet_one.int = 0.5
                                bullet_two.int = 0.5
                                #bullet position reset Y
                                bullet_one.pos[1] = 0
                                bullet_two.pos[1] = 0
                                #bullet position reset X
                                bullet_one.pos[0] = -13
                                bullet_two.pos[0] = 13

                                hideone = 1000
                                hidetwo = 1000
                                spacetext = 1000
                                hidetitle = 1000
                                hidetitle2 = 1000
                                hide1v1 = 1000
                                coder =1000

                                title = False

    screen.clear()
    main.display_all()
    font = pygame.font.SysFont('impact', 80)

    GameOver.drawText(120, hideone, "Player One Wins")
    GameOver.drawText(120, hidetwo, "Player Two Wins")
    font = pygame.font.SysFont('impact', 80)
    GameOver.drawText(351, hide1v1, "1v1")
    GameOver.drawText(140, hidetitle, "SPACE SHOOTER")
    font = pygame.font.SysFont('impact', 60)

    GameOver.drawText(225, hidetitle2, "SPACE to Start")
    GameOver.drawText(190, spacetext, "SPACE to Restart")
    font = pygame.font.SysFont('impact', 20)
    GameOver.drawText(0, coder, "Code by John Patrick Quintos - BT701")

    screen.update()


from flask import url_for
from flask_testing import TestCase
from requests_mock import mock
from app import app, db
from application.models import history

class TestBase(TestCase):
    def create_app(self):
        app.config.update(
            SQLALCHEMY_DATABASE_URI="sqlite:///test.db",
            SECRET_KEY = "dfs",
            WTF_CSRF_ENABLED = False
        )
        return app

    def setUp(self):
        db.create_all()
        test = history(rarity='Pink', gun = 'AWP', price = 9)
        db.session.add(test)
        db.session.commit()

    def tearDown(self):
        db.drop_all()

class TestResponse(TestBase):
    def test_index(self):
        with mock() as m:
            m.get('http://service_2:5002/get/rarity', json='Blue')
            m.get('http://service_3:5003/get/gun', json='Glock-18')
            m.post('http://service_4:5004/post/winnings', json=2)

            response = self.client.get(url_for('index'))

        self.assert200(response)
        self.assertIn('You rolled a Blue Glock-18 worth £2', response.data.decode())


import requests
from bs4 import BeautifulSoup
import re
import datetime as dt

class Scraper:

    def __init__(self, endpoint: str, name: str, location: str, distance: str, j_type: str):
        self.today = dt.datetime.today()
        # self.endpoint = "https://fr.indeed.com/jobs"  # Partie à inclure dans l'UI pour choix du pays
        self.endpoint = endpoint
        self.name = name
        self.location = location
        self.distance = distance
        self.j_type = j_type
        self.parameters = {
                "q": self.name,
                "l": self.location,
                "radius": self.distance,
                "jt": self.j_type,
        }
        self.response = requests.get(self.endpoint, self.parameters)
        self.response.raise_for_status()
        self.final_url = self.response.url
        self.soup = self.scrape_html(self.response.text)[0]
        self.global_content = self.scrape_html(self.response.text)[1]
        self.page_number = 1

    def get_record(self, content: BeautifulSoup, final_url: str):
        """"Permet d'obtenir les enregistrements au format texte pour les éléments suivants :
         Titre / Nom de l'entreprise / Lieu / Salaire / Lien de l'annonce / Résumé de l'annonce.
         Cette fonction doit être intégrée dans une boucle (for loop) pour pouvoir récupérer les
         éléments de toutes les balises <a> !"""
        job_title = content.h2.getText()
        if job_title.startswith("nouveau"):  # Indeed France
            job_title = job_title.replace("nouveau", "", 1)
        if job_title.startswith("neu"):  # Indeed Suisse
            job_title = job_title.replace("neu", "", 1)
        job_company = content.find("span", "companyName").getText()
        job_location = content.find("div", "companyLocation").getText()
        job_summary = content.find("div", "job-snippet").getText().strip().replace("\n", " ")

        try:
            job_salary = content.find("span", "salary-snippet").getText().replace("\xa0", "")
        except AttributeError:
            job_salary = "Absence de données"

        try:
            post_date = int(re.findall("\\d+", content.find("span", "date").getText())[0])
            if post_date < 30:
                post_date = (self.today - dt.timedelta(days=post_date)).strftime("%Y-%m-%d")
            else:
                post_date = "Posté il y a plus de 30 jours"
        except IndexError:
            post_date = self.today.strftime("%Y-%m-%d")

        try:
            job_url = final_url + "&advn=" + content.get("data-empn") + "&vjk=" + content.get("data-jk")
        except TypeError:
            job_url = final_url + "&vjk=" + content.get("data-jk")
        record = (job_title, job_company, job_location, job_salary, post_date, job_summary, job_url)
        return record

    @staticmethod
    def scrape_html(html_text: str):
        """"Permet de créer la soupe et de sélectionner les tags dans lesquels les données
        sont contenues. Cette fonction doit être rappelée pour chaque nouvelle page à scraper.
        Attention : Dans le cas d'une nouvelle page à scraper, il faut impérativement passer
        l'argument html_text avec les données de la nouvelle page. Il faut donc modifier les
        valeurs self : exemple :
        scraper = Scraper(job_name, job_location, job_distance, job_type)
        scraper.response = requests.get(next_page)
        scraper.response.raise_for_status()
        scraper.final_url = scraper.response.url
        scraper.soup = scraper.scrape_html(scraper.response.text)[0]
        global_content = scraper.scrape_html(scraper.response.text)[1]

        Cette fonction retourne un tuple avec en 0 la soupe et en 1 les éléments sélectionnés."""
        soup = BeautifulSoup(html_text, "html.parser")
        global_content = soup.select("a[data-jk]")
        return soup, global_content

    def get_next_page(self, soup: BeautifulSoup):
        """Fonction permettant d'obtenir la page suivante sur le site Indeed.
        Elle prend pour argument la soupe de la page en cours. Cette dernière
        est accessible de la façon suivante :
        scraper = Scraper(job_name, job_location, job_distance, job_type)
        next_page = scraper.get_next_page(scraper.soup)"""
        url_tag = soup.select(f'a[aria-label="{self.page_number}"]')
        tmp = self.final_url
        for tag in url_tag:
            self.final_url = (self.endpoint.replace("/jobs", "") + tag.get("href"))  # https://ch.indeed.com
        if self.final_url == tmp:
            print(f"Fin du scrapping. Nombre de pages scrapées : {self.page_number - 1}")
            return "Fin du scrapping"
        return self.final_url


from datetime import tzinfo, timedelta, datetime
import json
from io import StringIO
import re
import sys
import os
import jmespath

from optparse import OptionParser
parser = OptionParser()

# take input report: path, project: which project; summary: whether it's summary
parser.add_option("-r", "--report", action="store", type="string", dest="report")
parser.add_option("-p", "--project", action="store", type="string", dest="project")
parser.add_option("-s", "--summary", action="store_true", dest="summary", default=False)

(options, args) = parser.parse_args(sys.argv)

# project is a subdir under the report dir
report_path=os.path.join(options.report, options.project)

# check everything is there
if not os.path.exists(report_path):
   print ("\nReport path for project {} does not exist. Please check the inputs.\n".format(options.project))
   quit()

# init project summary
project={}
project["name"]=options.project
project["iam"]=0
project["sas"]=0
project["violations"]=0
project["warnings"]=0
project["kms"]=0
project["vpcs"]=0
project["subnets"]=0
project["fwr"]=0
project["roles"]=0
project["peers"]=0

# init violation summaries for item
c2d1={}
c2d1["violation"]=False
c1d12={}
c1d12["violation"]=False
c2d8={}
c2d8["violation"]=False
c2d8["offendings"]=[]
c4d3={}
c4d3["violation"]=False
c4d3["offendings"]=[]
c4d1={}
c4d2={}
c4d1["violation"]=False
c4d1["offendings"]=[]
c4d2["violation"]=False
c4d2["offendings"]=[]

# read in iam
f = open(os.path.join(report_path, 'project-iam'))
iam = json.loads(f.read())
f.close()

# check iam policies
iam["totalAuditConfig"]=0
iam["hasAllServices"]=False
if "auditConfigs" in iam:
    iam["totalAuditConfig"]=len(iam["auditConfigs"])
    allservice = jmespath.search("auditConfigs[?service == 'allServices']", iam)
    if len(allservice) > 0 and len(allservice[0])==3:
      iam["hasAllServices"]=True

# check iam violations
if iam["totalAuditConfig"]==0:
  c2d1["violation"]=True
  project["violations"] += 1
elif not iam["hasAllServices"]:
  c2d1["violation"]=True
  c2d1["message"]="No audit settings found for this project. Please set it explicitly"

if "bindings" in iam:
  project["roles"] = len(iam["bindings"])
  members=jmespath.search("bindings[].members[]", iam)
  members=list(set(members))
  project["iam"] = len(members)
  sas=jmespath.search("[?starts_with(@, `serviceAccount:`)]", members)
  project["sas"] = len(sas)
  owner= jmespath.search("bindings[?role==`roles/owner` && members[?starts_with(@,`serviceAccount:`)]]", iam)

# check owner role violations
  if len(owner)>0:
      c1d12["violation"]=True
      c1d12["offendings"]=[]
      for onrs in owner:
        for onr in onrs["members"]:
          if onr.startswith('serviceAccount:'):
             project["violations"] += 1
             c1d12["offendings"].append(onr)

# check kms violations
kmsfile=os.path.join(report_path,'project-kms')
if os.path.isfile(kmsfile):
  with open(kmsfile) as fp:
    kstart=True
    for line in fp:
      line = re.sub('[\n"]','',line)
      if kstart:
        project["kms"] += 1
        kms=line
        kstart=False
      else:
          if line=="null":
              c2d8["violation"]=True
              project["violations"] += 1
              c2d8["offendings"].append(kms)
          else:
              line = re.sub('s', '', line)
              period = int(line) / 24/ 60 /60
              if period > 90:
                    c2d8["violation"]=True
                    project["violations"] += 1
                    c2d8["offendings"].append(kms)
          kstart=True

# read in network information
nwpath=os.path.join(report_path,'project-network')
f=open(nwpath)
network = json.loads(f.read())
f.close()
subspath=os.path.join(report_path,'project-subnets')
f=open(subspath)
subnets = json.loads(f.read())
f.close()

# init network summaries
dt = datetime.now()
dtstr = dt.isoformat(' ')
project["vpcs"] = len(network)
project["subnets"] = len(subnets)

noflowflag= jmespath.search("[?!enableFlowLogs]", subnets)

# check vpc violation
c4d3["violation"] = len(noflowflag) > 0
project["violations"] += len(noflowflag)
for sbn in noflowflag:
   c4d3["offendings"].append({"name":sbn["name"], "vpc":sbn["network"], "region": sbn["region"]})

# read firewall information
fwrpath=os.path.join(report_path,'project-firewall-rules')
f=open(fwrpath)
firewallrs = json.loads(f.read())
f.close()

def arr_in_range (arr, num):
   """
   this is a utility for testing port range array contains port number
   """
   return any([in_range(s, num) for s in arr])

def in_range(rg, num):
   """
   this is a utility for testing port range contains port number
   """
   if rg.isdigit():
      return int(rg) == num
   sar = rg.split('-')
   if len(sar)!=2:
      return False
   if not sar[0].isdigit() or int(sar[0]) > num:
      return False
   if not sar[1].isdigit() or int(sar[1]) < num:
      return False
   return True

# check firewall violations
project["fwr"] = len(firewallrs)
for rule in firewallrs:
    if any([s.startswith('0.0.0.0') for s in rule["sourceRanges"]]):
        for ald in rule["allowed"]:
            if ald["IPProtocol"] == 'tcp' and arr_in_range(ald["ports"],22):
                c4d1["violation"]=True
                c4d1["offendings"].append(rule)
                project["violations"] += 1
            if ald["IPProtocol"] == 'tcp' and arr_in_range(ald["ports"],3389):
                c4d2["violation"]=True
                c4d2["offendings"].append(rule)
                project["violations"] += 1
            if ald["IPProtocol"] == 'ssh':
                c4d1["violation"]=True
                c4d1["offendings"].append(rule)
                project["violations"] += 1
            if ald["IPProtocol"] == 'rdp':
                c4d2["violation"]=True
                c4d2["offendings"].append(rule)
                project["violations"] += 1

# check peer violations
peers=jmespath.search("[?peerings]", network)
c4d5={}
c4d5["warning"]=len(peers) > 0
c4d5["offendings"]=[]

for pr in peers:
    project["warnings"] += len(pr["peerings"])
    project["peers"] += len(pr["peerings"])
    for p in pr["peerings"]:
      c4d5["offendings"].append({"vpc": pr["name"], "state": p["state"], "network":p["network"]})

def do_offending():
  """
  print out html of each benchmark
  """
  print ("""

SMX Benchmark	Level	VPC	Findings

""")
  if c1d12["violation"]:
      for v in c1d12["offendings"]:
          print ("""
 	{}	{}	{}	{}
""".format("SMX-1.12", "Alert", "ALL", "Service account {} has an owner role".format(v)))

  if c2d1["violation"]:
      print ("""
 	{}	{}	{}	{}
""".format("SMX-2.1",
        "Alert","ALL", "No log audit settings found for this project. Please set it explicitely globally using 'allServices'"))

  if c2d8["violation"]:
     for k in c2d8["offendings"]:
       vio = "Cryptographic key {} does not have a rotation schedule or schedule period is longer that 90 days.".format(k)
       print ("""
 	{}	{}	{}	{}
""".format("SMX-2.8", "Alert", "ALL", vio))

  if c4d1["violation"]:
     for k in c4d1["offendings"]:
         print ("""
 	{}	{}	{}	Wide open SSH:
{}
""".format("SMX-4.1", "Alert", os.path.basename(k["network"]), json.dumps(k)))

  if c4d2["violation"]:
      for k in c4d2["offendings"]:
          print ("""
 	{}	{}	{}	Wide open RDP:
{}
""".format("SMX-4.2", "Alert", os.path.basename(k["network"]), json.dumps(k)))

  if c4d3["violation"]:
      for k in c4d3["offendings"]:
          print ("""
 	{}	{}	{}	Subnet flow log need to be turn on for subnet '{}' in region '{}'.
""".format("SMX-4.3", "Alert", os.path.basename(k["vpc"]), k["name"], os.path.basename(k["region"])))

  if c4d5["warning"]:
      for k in c4d5["offendings"]:
          print ("""
 	{}	{}	{}	Network Contains {} peered VPCs. Peer network security need to be checked to ensure security.

""".format("SMX-4.5", "Warning", k["vpc"], json.dumps(k)))

def do_summary():
  """
  print out html summary
  """
  html="""

            Scan Summary For Project: {}
            IAM Principals: {}
			Service Accounts: {}
            Cypher Keys: {}, Peer VPC: {}

            VPCs: {}
            Subnets: {}
            Firewall Rules: {}

            Violations: {}
            Warnings: {}
            Report Date: {}

  """.format(project["name"], project["iam"],project["sas"],project["kms"], project["peers"], project["vpcs"],project["subnets"], project["fwr"], project["violations"], project["warnings"], dtstr)
  print(html)

# this is the main - print out everything
print ("
")
do_summary()
do_offending()
print ("

")


# Given a signed 32-bit integer x, return x with its digits reversed.
# If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1],
#then return 0.
#Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
from typing import List
class Solution:
    def reverse(self, x: int) -> int:
        # check if the integer is negative or positive
        sign = 1
        if x < 0:
            sign = -1
            x = abs(x)

        # reverse the integer
        rev = 0
        while x > 0:
            rev = rev * 10 + x % 10
            x = x // 10

        # check if the result is within the signed 32-bit integer range
        if rev > (2 ** 31 - 1):
            return 0

        # return the result with the appropriate sign
        return sign * rev
#This implementation first checks if the given integer is negative or positive,
#then reverses the digits of the integer by repeatedly taking the last digit of the integer and
# adding it to the result variable while removing the last digit from the integer.
# Finally, it checks if the result is within the signed 32-bit integer range and returns it
# with the appropriate sign.


from django.urls import path, include
from .views import *
from rest_framework.routers import DefaultRouter

r = DefaultRouter()

r.register('product', ProductAPI)

urlpatterns = [
    path('categories/', CategoryListCreateAPIView.as_view()),
    path('categories/<int:pk>/', CategoryDestroyAPIView.as_view()),
    path('tag/', TagListCreateAPIView.as_view()),
    path('tag/<int:pk>/', TagDestroyAPIView.as_view()),
    path('', include(r.urls)),
    path('export-excel/', ExcelExportView.as_view()),
]


# -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 15:57:07 2020

@author: STSC
"""

#replace space with '%20

def rep(word):
    space_count = 0
    word = word.strip()
    truelength = len(word)

    for i in range(truelength-1):

        if word[i] ==' ':

            space_count +=1
        index = truelength + space_count*2

    word = list(word)
    for f in range(truelength - 2, index - 2):
        word.append('0')

    for i in range(truelength-1,-1,-1):

        if word[i] ==' ':
            word[index-1] = "0"
            word[index-2] = "2"
            word[index-3] = "%"
            index -=3
        else:
            word[index-1] = word[i]
            index -=1
    return ''.join(word)

if __name__=='__main__':

    ans =rep("Mr John Smith ")
    print(ans)


# 导入操作系统库
import os
# 更改工作目录
os.chdir(r"D:\softwares\applied statistics\pythoncodelearning\chap3\sourcecode")
# 导入基础计算库
import numpy as np
# 导入绘图库
import matplotlib.pyplot as plt
# 导入支持向量机模型
from sklearn.svm import SVR
# 导入绘图库中的字体管理包
from matplotlib import font_manager
# 实现中文字符正常显示
font = font_manager.FontProperties(fname=r"C:\Windows\Fonts\SimKai.ttf")
# 使用seaborn风格绘图
plt.style.use("seaborn-v0_8")
# 生成样本
X = np.sort(5 * np.random.rand(40, 1), axis=0)
y = np.sin(X).ravel()
# 添加噪声
y[::5] += 3 * (0.5 - np.random.rand(8))
# rbf核函数的SVR
svr_rbf = SVR(kernel="rbf", C=100, gamma=0.1, epsilon=0.1)
# 线性核函数的SVR
svr_lin = SVR(kernel="linear", C=100, gamma="auto")
# 多项式核函数的SVR
svr_poly = SVR(kernel="poly", C=100, gamma="auto", degree=3, epsilon=0.1, coef0=1)
lw = 2
# 构造迭代对象列表
svrs = [svr_rbf, svr_lin, svr_poly]
kernel_label = ["RBF", "Linear", "Polynomial"]
model_color = ["m", "c", "g"]
# 开始绘图
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10), sharey=True)
for ix, svr in enumerate(svrs):
    axes[ix].plot(
        X,
        svr.fit(X, y).predict(X),
        color=model_color[ix],
        lw=lw,
        label="{} model".format(kernel_label[ix]),
    )
    axes[ix].scatter(
        X[svr.support_],
        y[svr.support_],
        facecolor="none",
        edgecolor=model_color[ix],
        s=50,
        label="{} support vectors".format(kernel_label[ix]),
    )
    axes[ix].scatter(
        X[np.setdiff1d(np.arange(len(X)), svr.support_)],
        y[np.setdiff1d(np.arange(len(X)), svr.support_)],
        facecolor="none",
        edgecolor="k",
        s=50,
        label="other training data",
    )
    axes[ix].legend(
        loc="upper center",
        bbox_to_anchor=(0.5, 1.1),
        ncol=1,
        fancybox=True,
        shadow=True,
    )

fig.text(0.5, 0.04, "data", ha="center", va="center")
fig.text(0.06, 0.5, "target", ha="center", va="center", rotation="vertical")
fig.suptitle("Support Vector Regression", fontsize=14)
plt.show()
fig.savefig("../codeimage/code5.pdf")