from __future__ import print_function, division, absolute_import

from numba import types, intrinsics
from numba.utils import PYVERSION
from numba.typing.templates import (AttributeTemplate, ConcreteTemplate,
                                    AbstractTemplate, builtin_global, builtin,
                                    builtin_attr, signature, bound_function)

builtin_global(range, types.range_type)
if PYVERSION < (3, 0):
    builtin_global(xrange, types.range_type)
builtin_global(len, types.len_type)
builtin_global(slice, types.slice_type)
builtin_global(abs, types.abs_type)
builtin_global(print, types.print_type)

@builtin
class Print(ConcreteTemplate):
    key = types.print_type
    intcases = [signature(types.none, ty) for ty in types.integer_domain]
    realcases = [signature(types.none, ty) for ty in types.real_domain]
    cases = intcases + realcases

@builtin
class PrintOthers(AbstractTemplate):
    key = types.print_type

    def accepted_types(self, ty):
        if ty in types.integer_domain or ty in types.real_domain:
            return True

        if isinstance(ty, types.CharSeq):
            return True

    def generic(self, args, kws):
        assert not kws, "kwargs to print is not supported."
        for a in args:
            if not self.accepted_types(a):
                raise TypeError("Type %s is not printable." % a)
        return signature(types.none, *args)

@builtin
class Abs(ConcreteTemplate):
    key = types.abs_type
    int_cases = [signature(ty, ty) for ty in types.signed_domain]
    real_cases = [signature(ty, ty) for ty in types.real_domain]
    complex_cases = [signature(ty.underlying_float, ty)
                     for ty in types.complex_domain]
    cases = int_cases + real_cases + complex_cases

@builtin
class Slice(ConcreteTemplate):
    key = types.slice_type
    cases = [
        signature(types.slice3_type),
        signature(types.slice3_type, types.none, types.none),
        signature(types.slice3_type, types.none, types.intp),
        signature(types.slice3_type, types.intp, types.none),
        signature(types.slice3_type, types.intp, types.intp),
        signature(types.slice3_type, types.intp, types.intp, types.intp),
    ]

@builtin
class Range(ConcreteTemplate):
    key = types.range_type
    cases = [
        signature(types.range_state32_type, types.int32),
        signature(types.range_state32_type, types.int32, types.int32),
        signature(types.range_state32_type, types.int32, types.int32,
                  types.int32),
        signature(types.range_state64_type, types.int64),
        signature(types.range_state64_type, types.int64, types.int64),
        signature(types.range_state64_type, types.int64, types.int64,
                  types.int64),
    ]

@builtin
class GetIter(AbstractTemplate):
    key = "getiter"

    def generic(self, args, kws):
        assert not kws
        [obj] = args
        if isinstance(obj, types.IterableType):
            return signature(obj.iterator_type, obj)

@builtin
class IterNext(AbstractTemplate):
    key = "iternext"

    def generic(self, args, kws):
        assert not kws
        [it] = args
        if isinstance(it, types.IteratorType):
            return signature(types.Pair(it.yield_type, types.boolean), it)

@builtin
class PairFirst(AbstractTemplate):
    """
    Given a heterogenous pair, return the first element.
    """
    key = "pair_first"

    def generic(self, args, kws):
        assert not kws
        [pair] = args
        if isinstance(pair, types.Pair):
            return signature(pair.first_type, pair)

@builtin
class PairSecond(AbstractTemplate):
    """
    Given a heterogenous pair, return the second element.
    """
    key = "pair_second"

    def generic(self, args, kws):
        assert not kws
        [pair] = args
        if isinstance(pair, types.Pair):
            return signature(pair.second_type, pair)

class BinOp(ConcreteTemplate):
    cases = [signature(max(types.intp, op), op, op)
             for op in sorted(types.signed_domain)]
    cases += [signature(max(types.uintp, op), op, op)
              for op in sorted(types.unsigned_domain)]
    cases += [signature(op, op, op) for op in sorted(types.real_domain)]
    cases += [signature(op, op, op) for op in sorted(types.complex_domain)]

@builtin
class BinOpAdd(BinOp):
    key = "+"

@builtin
class BinOpSub(BinOp):
    key = "-"

@builtin
class BinOpMul(BinOp):
    key = "*"

@builtin
class BinOpDiv(BinOp):
    key = "/?"

@builtin
class BinOpMod(ConcreteTemplate):
    key = "%"
    cases = [signature(op, op, op)
             for op in sorted(types.signed_domain)]
    cases += [signature(op, op, op)
              for op in sorted(types.unsigned_domain)]
    cases += [signature(op, op, op) for op in sorted(types.real_domain)]

@builtin
class BinOpTrueDiv(ConcreteTemplate):
    key = "/"
    cases = [signature(types.float64, op, op)
             for op in sorted(types.signed_domain)]
    cases += [signature(types.float64, op, op)
              for op in sorted(types.unsigned_domain)]
    cases += [signature(op, op, op) for op in sorted(types.real_domain)]
    cases += [signature(op, op, op) for op in sorted(types.complex_domain)]

@builtin
class BinOpFloorDiv(ConcreteTemplate):
    key = "//"
    cases = [signature(op, op, op)
             for op in sorted(types.signed_domain)]
    cases += [signature(op, op, op)
              for op in sorted(types.unsigned_domain)]
    cases += [signature(op, op, op) for op in sorted(types.real_domain)]

@builtin
class BinOpPower(ConcreteTemplate):
    key = "**"
    cases = [signature(types.intp, types.intp, types.intp)]
    cases += [signature(types.float64, types.float64, op)
             for op in sorted(types.signed_domain)]
    cases += [signature(types.float64, types.float64, op)
             for op in sorted(types.unsigned_domain)]
    cases += [signature(op, op, op)
             for op in sorted(types.real_domain)]
    cases += [signature(op, op, op)
             for op in sorted(types.complex_domain)]

class PowerBuiltin(BinOpPower):
    key = pow
    # TODO add 3 operand version

builtin_global(pow, types.Function(PowerBuiltin))

class BitwiseShiftOperation(ConcreteTemplate):
    cases = [signature(op, op, types.uint32)
             for op in sorted(types.signed_domain)]
    cases += [signature(op, op, types.uint32)
              for op in sorted(types.unsigned_domain)]

@builtin
class BitwiseLeftShift(BitwiseShiftOperation):
    key = "<<"

@builtin
class BitwiseRightShift(BitwiseShiftOperation):
    key = ">>"

class BitwiseLogicOperation(BinOp):
    cases = [signature(max(types.intp, op), op, op)
             for op in sorted(types.signed_domain)]
    cases += [signature(max(types.uintp, op), op, op)
              for op in sorted(types.unsigned_domain)]

@builtin
class BitwiseAnd(BitwiseLogicOperation):
    key = "&"

@builtin
class BitwiseOr(BitwiseLogicOperation):
    key = "|"

@builtin
class BitwiseXor(BitwiseLogicOperation):
    key = "^"

@builtin
class BitwiseInvert(ConcreteTemplate):
    key = "~"

    cases = [signature(types.int8, types.boolean)]
    cases += [signature(op, op) for op in sorted(types.signed_domain)]
    cases += [signature(op, op) for op in sorted(types.unsigned_domain)]

class UnaryOp(ConcreteTemplate):
    cases = [signature(op, op) for op in sorted(types.signed_domain)]
    cases += [signature(op, op) for op in sorted(types.unsigned_domain)]
    cases += [signature(op, op) for op in sorted(types.real_domain)]
    cases += [signature(op, op) for op in sorted(types.complex_domain)]

@builtin
class UnaryNot(UnaryOp):
    key = "not"
    cases = [signature(types.boolean, types.boolean)]
    cases += [signature(types.boolean, op) for op in sorted(types.signed_domain)]
    cases += [signature(types.boolean, op) for op in sorted(types.unsigned_domain)]
    cases += [signature(types.boolean, op) for op in sorted(types.real_domain)]
    cases += [signature(types.boolean, op) for op in sorted(types.complex_domain)]

@builtin
class UnaryNegate(UnaryOp):
    key = "-"
    cases = [signature(max(types.intp, op), op)
             for op in sorted(types.signed_domain)]
    cases += [signature(max(types.uintp, op), op)
              for op in sorted(types.unsigned_domain)]
    cases += [signature(op, op) for op in sorted(types.real_domain)]
    cases += [signature(op, op) for op in sorted(types.complex_domain)]

@builtin
class UnaryPositive(UnaryOp):
    key = "+"
    cases = UnaryNegate.cases

class OrderedCmpOp(ConcreteTemplate):
    cases = [signature(types.boolean, types.boolean, types.boolean)]
    cases += [signature(types.boolean, op, op) for op in sorted(types.signed_domain)]
    cases += [signature(types.boolean, op, op) for op in sorted(types.unsigned_domain)]
    cases += [signature(types.boolean, op, op) for op in sorted(types.real_domain)]

class UnorderedCmpOp(ConcreteTemplate):
    cases = OrderedCmpOp.cases + [
        signature(types.boolean, op, op) for op in sorted(types.complex_domain)]

@builtin
class CmpOpLt(OrderedCmpOp):
    key = '<'

@builtin
class CmpOpLe(OrderedCmpOp):
    key = '<='

@builtin
class CmpOpGt(OrderedCmpOp):
    key = '>'

@builtin
class CmpOpGe(OrderedCmpOp):
    key = '>='

@builtin
class CmpOpEq(UnorderedCmpOp):
    key = '=='

@builtin
class CmpOpNe(UnorderedCmpOp):
    key = '!='

class CmpOpIdentity(AbstractTemplate):
    def generic(self, args, kws):
        [lhs, rhs] = args
        return signature(types.boolean, lhs, rhs)

@builtin
class CmpOpIs(CmpOpIdentity):
    key = 'is'

@builtin
class CmpOpIsNot(CmpOpIdentity):
    key = 'is not'

def normalize_index(index):
    if isinstance(index, types.UniTuple):
        if index.dtype in types.integer_domain:
            idxtype = types.intp if index.dtype.signed else types.uintp
            return types.UniTuple(idxtype, len(index))
        elif index.dtype == types.slice3_type:
            return index

    elif isinstance(index, types.Tuple):
        for ty in index:
            if (ty not in types.integer_domain and ty != types.slice3_type):
                raise TypeError('Type %s of index %s is unsupported for indexing'
                                 % (ty, index))
        return index

    elif index == types.slice3_type:
        return types.slice3_type

    elif isinstance(index, types.Integer):
        return types.intp if index.signed else types.uintp

@builtin
class GetItemUniTuple(AbstractTemplate):
    key = "getitem"

    def generic(self, args, kws):
        tup, idx = args
        if isinstance(tup, types.UniTuple):
            return signature(tup.dtype, tup, normalize_index(idx))

@builtin
class GetItemArray(AbstractTemplate):
    key = "getitem"

    def generic(self, args, kws):
        assert not kws
        [ary, idx] = args
        if not isinstance(ary, types.Array):
            return

        idx = normalize_index(idx)
        if idx is None:
            return

        if idx == types.slice3_type: #(types.slice2_type, types.slice3_type):
            res = ary.copy(layout='A')
        elif isinstance(idx, (types.UniTuple, types.Tuple)):
            if ary.ndim > len(idx):
                return
            elif ary.ndim < len(idx):
                return
            elif any(i == types.slice3_type for i in idx):
                ndim = ary.ndim
                for i in idx:
                    if i != types.slice3_type:
                        ndim -= 1
                res = ary.copy(ndim=ndim, layout='A')
            else:
                res = ary.dtype
        elif isinstance(idx, types.Integer):
            if ary.ndim != 1:
                return
            res = ary.dtype

        else:
            raise Exception("unreachable: index type of %s" % idx)

        return signature(res, ary, idx)

@builtin
class SetItemArray(AbstractTemplate):
    key = "setitem"

    def generic(self, args, kws):
        assert not kws
        ary, idx, val = args
        if isinstance(ary, types.Array):
            if ary.const:
                raise TypeError("Constant array")
            return signature(types.none, ary, normalize_index(idx), ary.dtype)

@builtin
class LenArray(AbstractTemplate):
    key = types.len_type

    def generic(self, args, kws):
        assert not kws
        (ary,) = args
        if isinstance(ary, types.Array):
            return signature(types.intp, ary)

#-------------------------------------------------------------------------------

@builtin_attr
class ArrayAttribute(AttributeTemplate):
    key = types.Array

    def resolve_shape(self, ary):
        return types.UniTuple(types.intp, ary.ndim)

    def resolve_strides(self, ary):
        return types.UniTuple(types.intp, ary.ndim)

    def resolve_ndim(self, ary):
        return types.intp

    # def resolve_flatten(self, ary):
    #     return types.Method(Array_flatten, ary)

    def resolve_size(self, ary):
        return types.intp

    def resolve_flat(self, ary):
        return types.NumpyFlatType(ary)

    def generic_resolve(self, ary, attr):
        if isinstance(ary.dtype, types.Record):
            if attr in ary.dtype.fields:
                return types.Array(ary.dtype.typeof(attr), ndim=ary.ndim,
                                   layout='A')

def generic_homog(self, args, kws):
    assert not args
    assert not kws
    return signature(self.this.dtype, recvr=self.this)

def generic_expand(self, args, kws):
    if isinstance(self.this.dtype, types.Integer):
        # Expand to a machine int, not larger (like Numpy)
        if self.this.dtype.signed:
            return signature(max(types.intp, self.this.dtype), recvr=self.this)
        else:
            return signature(max(types.uintp, self.this.dtype), recvr=self.this)
    return signature(self.this.dtype, recvr=self.this)

def generic_hetero_real(self, args, kws):
    assert not args
    assert not kws
    if self.this.dtype in types.integer_domain:
        return signature(types.float64, recvr=self.this)
    return signature(self.this.dtype, recvr=self.this)

def generic_index(self, args, kws):
    assert not args
    assert not kws
    return signature(types.intp, recvr=self.this)

def install_array_method(name, generic):
    my_attr = {"key": "array." + name, "generic": generic}
    temp_class = type("Array_" + name, (AbstractTemplate,), my_attr)

    def array_attribute_attachment(self, ary):
        return types.BoundFunction(temp_class, ary)

    setattr(ArrayAttribute, "resolve_" + name, array_attribute_attachment)

# Functions that return the same type as the array
for fname in ["min", "max"]:
    install_array_method(fname, generic_homog)

# Functions that return a machine-width type, to avoid overflows
for fname in ["sum", "prod"]:
    install_array_method(fname, generic_expand)

# Functions that require integer arrays get promoted to float64 return
for fName in ["mean", "var", "std"]:
    install_array_method(fName, generic_hetero_real)

# Functions that return an index (intp)
install_array_method("argmin", generic_index)
install_array_method("argmax", generic_index)

@builtin
class CmpOpEqArray(AbstractTemplate):
    key = '=='

    def generic(self, args, kws):
        assert not kws
        [va, vb] = args
        if isinstance(va, types.Array) and va == vb:
            return signature(va.copy(dtype=types.boolean), va, vb)

#-------------------------------------------------------------------------------
class ComplexAttribute(AttributeTemplate):

    def resolve_real(self, ty):
        return self.innertype

    def resolve_imag(self, ty):
        return self.innertype

    @bound_function("complex.conjugate")
    def resolve_conjugate(self, ty, args, kws):
        assert not args
        assert not kws
        return signature(ty)

def register_complex_attributes(ty):
    @builtin_attr
    class ConcreteComplexAttribute(ComplexAttribute):
        key = ty
        try:
            innertype = ty.underlying_float
        except AttributeError:
            innertype = ty

for ty in types.number_domain:
    register_complex_attributes(ty)

#-------------------------------------------------------------------------------

@builtin_attr
class NumbaTypesModuleAttribute(AttributeTemplate):
    key = types.Module(types)

    def resolve_int8(self, mod):
        return types.Function(ToInt8)

    def resolve_int16(self, mod):
        return types.Function(ToInt16)

    def resolve_int32(self, mod):
        return types.Function(ToInt32)

    def resolve_int64(self, mod):
        return types.Function(ToInt64)

    def resolve_uint8(self, mod):
        return types.Function(ToUint8)

    def resolve_uint16(self, mod):
        return types.Function(ToUint16)

    def resolve_uint32(self, mod):
        return types.Function(ToUint32)

    def resolve_uint64(self, mod):
        return types.Function(ToUint64)

    def resolve_float32(self, mod):
        return types.Function(ToFloat32)

    def resolve_float64(self, mod):
        return types.Function(ToFloat64)

    def resolve_complex64(self, mod):
        return types.Function(ToComplex64)

    def resolve_complex128(self, mod):
        return types.Function(ToComplex128)

class Caster(AbstractTemplate):
    def generic(self, args, kws):
        assert not kws
        [a] = args
        if a in types.number_domain:
            return signature(self.key, a)

class ToInt8(Caster):
    key = types.int8

class ToInt16(Caster):
    key = types.int16

class ToInt32(Caster):
    key = types.int32

class ToInt64(Caster):
    key = types.int64

class ToUint8(Caster):
    key = types.uint8

class ToUint16(Caster):
    key = types.uint16

class ToUint32(Caster):
    key = types.uint32

class ToUint64(Caster):
    key = types.uint64

class ToFloat32(Caster):
    key = types.float32

class ToFloat64(Caster):
    key = types.float64

class ToComplex64(Caster):
    key = types.complex64

class ToComplex128(Caster):
    key = types.complex128

builtin_global(types, types.Module(types))
builtin_global(types.int8, types.Function(ToInt8))
builtin_global(types.int16, types.Function(ToInt16))
builtin_global(types.int32, types.Function(ToInt32))
builtin_global(types.int64, types.Function(ToInt64))
builtin_global(types.uint8, types.Function(ToUint8))
builtin_global(types.uint16, types.Function(ToUint16))
builtin_global(types.uint32, types.Function(ToUint32))
builtin_global(types.uint64, types.Function(ToUint64))
builtin_global(types.float32, types.Function(ToFloat32))
builtin_global(types.float64, types.Function(ToFloat64))
builtin_global(types.complex64, types.Function(ToComplex64))
builtin_global(types.complex128, types.Function(ToComplex128))

#------------------------------------------------------------------------------

class Max(AbstractTemplate):
    key = max

    def generic(self, args, kws):
        assert not kws

        # max(a, b, ...)
        if len(args) < 2:
            return
        for a in args:
            if a not in types.number_domain:
                return

        retty = self.context.unify_types(*args)
        return signature(retty, *args)

class Min(AbstractTemplate):
    key = min

    def generic(self, args, kws):
        assert not kws

        # min(a, b, ...)
        if len(args) < 2:
            return
        for a in args:
            if a not in types.number_domain:
                return

        retty = self.context.unify_types(*args)
        return signature(retty, *args)

class Round(ConcreteTemplate):
    key = round
    cases = [
        signature(types.float32, types.float32),
        signature(types.float64, types.float64),
    ]

builtin_global(max, types.Function(Max))
builtin_global(min, types.Function(Min))
builtin_global(round, types.Function(Round))

#------------------------------------------------------------------------------

class Bool(AbstractTemplate):
    key = bool

    def generic(self, args, kws):
        assert not kws

        [arg] = args

        if arg not in types.number_domain:
            raise TypeError("bool() only support for numbers")

        return signature(types.boolean, arg)

class Int(AbstractTemplate):
    key = int

    def generic(self, args, kws):
        assert not kws

        [arg] = args

        if arg not in types.number_domain:
            raise TypeError("int() only support for numbers")

        if arg in types.complex_domain:
            raise TypeError("int() does not support complex")

        if arg in types.integer_domain:
            return signature(arg, arg)

        if arg in types.real_domain:
            return signature(types.intp, arg)

class Float(AbstractTemplate):
    key = float

    def generic(self, args, kws):
        assert not kws

        [arg] = args

        if arg not in types.number_domain:
            raise TypeError("float() only support for numbers")

        if arg in types.complex_domain:
            raise TypeError("float() does not support complex")

        if arg in types.integer_domain:
            return signature(types.float64, arg)

        elif arg in types.real_domain:
            return signature(arg, arg)

class Complex(AbstractTemplate):
    key = complex

    def generic(self, args, kws):
        assert not kws

        if len(args) == 1:
            [arg] = args
            if arg not in types.number_domain:
                raise TypeError("complex() only support for numbers")
            if arg == types.float32:
                return signature(types.complex64, arg)
            else:
                return signature(types.complex128, arg)

        elif len(args) == 2:
            [real, imag] = args
            if (real not in types.number_domain or
                imag not in types.number_domain):
                raise TypeError("complex() only support for numbers")
            if real == imag == types.float32:
                return signature(types.complex64, real, imag)
            else:
                return signature(types.complex128, real, imag)

builtin_global(bool, types.Function(Bool))
builtin_global(int, types.Function(Int))
builtin_global(float, types.Function(Float))
builtin_global(complex, types.Function(Complex))

#------------------------------------------------------------------------------

@builtin
class Enumerate(AbstractTemplate):
    key = enumerate

    def generic(self, args, kws):
        assert not kws
        it = args[0]
        if len(args) > 1 and not args[1] in types.integer_domain:
            raise TypeError("Only integers supported as start value in "
                            "enumerate")
        elif len(args) > 2:
            #let python raise its own error
            enumerate(*args)

        if isinstance(it, types.IterableType):
            enumerate_type = types.EnumerateType(it)
            return signature(enumerate_type, *args)

builtin_global(enumerate, types.Function(Enumerate))

@builtin
class Zip(AbstractTemplate):
    key = zip

    def generic(self, args, kws):
        assert not kws
        if all(isinstance(it, types.IterableType) for it in args):
            zip_type = types.ZipType(args)
            return signature(zip_type, *args)

builtin_global(zip, types.Function(Zip))

@builtin
class Intrinsic_array_ravel(AbstractTemplate):
    key = intrinsics.array_ravel

    def generic(self, args, kws):
        assert not kws
        [arr] = args
        if arr.layout in 'CF' and arr.ndim >= 1:
            return signature(arr.copy(ndim=1), arr)

builtin_global(intrinsics.array_ravel, types.Function(Intrinsic_array_ravel))


import datetime
import time

from selenium.common.exceptions import NoSuchElementException, InvalidElementStateException
from selenium.webdriver.common.by import By

from DataBase.data import (add_new_profile, get_column,
                           check_ok, subscribe_ok,
                           wait_list_unsub, get_to_unsubscribe,
                           delete_subscript)
from global_set import settings
from global_set.global_set import get_browser
from delay_time import daley_press

browser = get_browser()

class ObjectMixin:
    @staticmethod
    def get_xpath_object(path_html):
        """
        Принимает путь XPath элемента HTML
        Возвращает объект(ссылку)
        :param path_html:
        """
        button_or_form = browser.find_element(By.XPATH, path_html)

        if button_or_form:
            return button_or_form

        else:
            return 'Ошибка Xpath'

class LoginUser(ObjectMixin):
    def log_in(self):
        """
        Функция авторизации
        :param:
        :return:    1 if crash
                    0 if success connect
        """
        form_login = '//*[@id="loginForm"]/div/div[1]/div/label/input'
        form_pass = '//*[@id="loginForm"]/div/div[2]/div/label/input'
        button_login = '//*[@id="loginForm"]/div/div[3]'

        next_page_url = 'https://www.instagram.com/accounts/onetap/?next=%2F'

        count_auth = 1
        time.sleep(2)

        while browser.current_url != next_page_url:
            print('Попытка авторизации: ', count_auth)
            count_auth += 1
            try:
                time.sleep(settings.wait_open_new_page)

                self.get_xpath_object(form_login).clear()
                self.get_xpath_object(form_pass).clear()

                time.sleep(2)

                self.get_xpath_object(form_login).send_keys(settings.user_name)
                self.get_xpath_object(form_pass).send_keys(settings.user_pass)
                self.get_xpath_object(button_login).click()

                time.sleep(settings.wait_open_new_page)

            except NoSuchElementException:
                pass

        print('Авторизация прошла успешно!')
        return 0

class Scrolling(ObjectMixin):
    def __scroll(self):
        """
        Функция пролистывания списка подписчиков
        :return:
        """

        block_to_scroll = browser.find_element(By.CLASS_NAME, 'isgrP')
        script = "arguments[0].scrollTop = arguments[0].scrollHeight"

        end_scroll = True
        try:
            time.sleep(2)

            browser.execute_script(script, block_to_scroll)
            return 0

        except NoSuchElementException:
            if not end_scroll:
                return 1
            else:
                time.sleep(5)
                self.__scroll()
            return 0.5

    def wait_scroll(self, number_to_scroll, button):
        """
        Нажимаем на кнопку подписчиков и листаем на установленное количесво раз
        :return:
        """
        try:
            time.sleep(2)
            self.get_xpath_object(button).click()
            time.sleep(2)

            number_scroll_local = 0
            count = 0
            time_wait = 0
            end = True
            while end:
                number_scroll_local += 1
                count += int(self.__scroll())

                if time_wait == 10:
                    time.sleep(3)

                if count == 3 or number_scroll_local == number_to_scroll:
                    break

                time_wait += 1
        except:
            return 0

class UserInfo(ObjectMixin):
    def __init__(self, url_user):
        self.url_user = url_user

    def get_info_user(self):
        """
        Функция возвращает информацию со страницы профиля
        :return data_return = [posts_user, name_user, num_followers[0], number_sub, number_posts]
                            [Список постов, ник, кол-во подписчиков, кол-во подписок, кол-во постов]
        """

        browser.get(self.url_user)
        time.sleep(4)
        try:
            block_name = '//*[@id="react-root"]/section/main/div/header/section/div[1]/h2'
            block_followers = '//*[@id="react-root"]/section/main/div/header/section/ul/li[2]/a/span'

            name_user = self.get_xpath_object(block_name).text
            no_filter_followers = self.get_xpath_object(block_followers).text

            # Проверка на наличя слова тыс в кол-во подписчиков
            num_followers = []
            if 'т' in no_filter_followers:
                num_followers.append(no_filter_followers[0:3] + '000')

            elif ' ' in no_filter_followers:
                x = no_filter_followers.split()
                res = x[0] + x[1]
                num_followers.append(res)

            else:
                num_followers.append(no_filter_followers)

            try:
                number_sub = self.get_xpath_object('//*[@id="react-root"]/section/main/'
                                                   'div/header/section/ul/li[3]/span/span').text
            except:
                number_sub = self.get_xpath_object('//*[@id="react-root"]/section/main/'
                                                   'div/header/section/ul/li[3]/a/span').text
            try:
                number_posts = self.get_xpath_object('//*[@id="react-root"]/section/main/'
                                                     'div/header/section/ul/li[1]/span/span').text
            except:
                number_posts = self.get_xpath_object('//*[@id="react-root"]/section/main/'
                                                     'div/header/section/ul/li[2]/a/span').text

            # Фильтрация кол-во подписок
            if ' ' in number_sub:
                number = number_sub.split()
                number_subscript = number[0] + number[1]
            else:
                number_subscript = number_sub

            posts_user = self.__get_user_posts()
            data_return = {'posts_user': str(posts_user),
                           'name_user': str(name_user),
                           'num_followers': str(num_followers[0]),
                           'number_subscript': str(number_subscript),
                           'number_posts': str(number_posts),
                           'url_user': str(self.url_user)}

            return data_return
        except:
            return 404

    @staticmethod
    def __get_user_posts():
        # Получение списка постов(ссылки)
        links = browser.find_elements(By.CLASS_NAME, 'v1Nh3.kIKUG._bz0w')
        posts_user = []
        for el in links:
            post = el.find_element(By.TAG_NAME, 'a').get_attribute('href')
            posts_user.append(post)
        return posts_user

    def __get_followers_links(self):
        """
        Получение списка ссылок на подписчиков пользователя
        :return: all_followers
        """

        # Находим поле с подписчиками
        followers = browser.find_elements(By.CSS_SELECTOR, 'body>div.RnEpo.Yx5HN>div>div>div.isgrP>ul>div>li')

        all_followers = []
        for follower in followers:
            post = follower.find_element(By.TAG_NAME, 'a').get_attribute('href')
            all_followers.append(post)
        self.get_xpath_object('/html/body/div[6]/div/div/div[1]/div/div[2]/button').click()
        return str(all_followers)

    def __get_subscript_links(self):
        """
        Получение списка ссылок на подписки пользователя
        :return: all_sub
        """
        try:
            number_sub = self.get_xpath_object('//*[@id="react-root"]/section/main/div/header/'
                                               'section/ul/li[3]/span/span').text

        except:
            number_sub = self.get_xpath_object('//*[@id="react-root"]/section/main/div/header/'
                                               'section/ul/li[3]/a/span').text

        if number_sub != '0':
            # Находим поле с подписками
            subscript = browser.find_elements(By.CSS_SELECTOR, 'body>div.RnEpo.Yx5HN>div>div>div.isgrP>ul>div')

            all_subscript = []
            for sub in subscript:
                post = sub.find_element(By.TAG_NAME, 'a').get_attribute('href')
                all_subscript.append(post)

            self.get_xpath_object('/html/body/div[6]/div/div/div[1]/div/div[2]/button').click()

            return str(all_subscript)
        else:
            pass

    def get_dict_profile(self):
        scroll = Scrolling()
        xpath_follower_window = '//*[@id="react-root"]/section/main/div/header/section/ul/li[2]/a'
        xpath_subscript_window = '//*[@id="react-root"]/section/main/div/header/section/ul/li[3]/a'

        try:
            profile_info = self.get_info_user()

            scroll.wait_scroll(settings.number_scroll_followers, xpath_follower_window)
            all_followers_user = self.__get_followers_links()

            scroll.wait_scroll(settings.number_scroll_subscripts, xpath_subscript_window)
            all_subscripts_user = self.__get_subscript_links()

            # Чистка 1 000 от пробела (подписчики)
            if profile_info == 404:
                return 404
            clear_number = profile_info['number_posts']
            if ' ' in clear_number:
                clear_number = profile_info['number_posts'].split()
                clear_number = int(clear_number[0] + clear_number[1])

            data = {'user_name': profile_info['name_user'],
                    'user_link': profile_info['url_user'],
                    'user_sub': all_subscripts_user,
                    'user_followers': all_followers_user,
                    'user_posts': profile_info['posts_user'],
                    'number_sub': profile_info['number_subscript'],
                    'number_followers': profile_info['num_followers'],
                    'number_posts': clear_number,
                    }

            return data
        except InvalidElementStateException:
            return 404

class NewSubscript(ObjectMixin):
    """
    Удаление/Подписка на пользователей
    """

    def new_subscript(self):
        """
        Подписка на пользователей
        :return:
        """
        data = get_column(name_column='user_link', sub_max=1_000, follower_max=1_000)
        for user_link in data:
            print(user_link)

            try:
                browser.get(user_link[1])
                self.__subscript_button()
                subscribe_ok(user_link[0])
                today = datetime.date.today()
                tomorrow = today + datetime.timedelta(days=1)
                data = {'name_user': user_link[1],
                        'date_sub': datetime.date.today(),
                        'date_unsub': tomorrow}

                wait_list_unsub(data)
                daley_press('ожидание после подписки')
            except:
                pass

    def __subscript_button(self):
        try:
            button_subscript = '//*[@id="react-root"]/section/main' \
                               '/div/header/section/div[1]/div[1]/div/div/div/span/span[1]/button'
            self.get_xpath_object(button_subscript).click()
        except NoSuchElementException:
            pass

    @staticmethod
    def delete_sub():
        response_db = get_to_unsubscribe()
        time.sleep(2)

        # link = ['id', 'url-профиля']
        for link in response_db:
            link = list(link)
            print(link)
            try:
                browser.get(link[1])
                time.sleep(settings.wait_open_new_page)

                button_unsubscribe = '_5f5mN.-fzfL._6VtSN.yZn4P'
                browser.find_element(By.CLASS_NAME, button_unsubscribe).click()
                time.sleep(1)

                button_unsubscribe_ok = 'aOOlW.-Cab_'
                browser.find_element(By.CLASS_NAME, button_unsubscribe_ok).click()

                delete_subscript(link[0])
                wait_list_unsub('Ожидание после отписки')

            except:
                print(link[0], 'не удалось')

class InitProgram:
    list_check_profile = []
    list_links = get_column()

    def __init__(self):
        self.login = LoginUser()
        self.login.log_in()
        self.sub = NewSubscript()

    def check_profiles(self):
        for link in self.list_links:
            for profile in link[1]:
                try:
                    profile_user = UserInfo(profile)
                    profile_user = profile_user.get_dict_profile()
                except:
                    profile_user = 404

                if profile_user == 404:
                    pass
                else:
                    add_new_profile(profile_user)
            self.list_check_profile.append(link[0])
            check_ok(link[0])

    def new_subs(self):
        self.sub.new_subscript()

init = InitProgram()
init.sub.new_subscript()
time.sleep(500)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 14:33:59 2019

@author: SpaceMeerkat

A script for testing the trained CAE with synthetic moment maps
"""

# =============================================================================
# Import relevant packages
# =============================================================================

import matplotlib.pyplot as plt
import multiprocessing as mp
import numpy as np
import torch
from tqdm import tqdm
import sys
sys.path.append("../utils/")

from model_int import CAE
from functions import return_cube, synthetic_plotter
from rcparams import rcparams
rcparams()

# =============================================================================
# Setup paths
# =============================================================================

model_path = '/path/to/saves/models/'
image_path = '/path/to/image/save/directory/'

# =============================================================================
# Setup the model
# =============================================================================

def apply_dropout(m):
    if type(m) == torch.nn.Dropout:
        m.train(True)

model = CAE()
model.load_state_dict(torch.load(model_path))
model = model.cpu()
model.train(False)
model.apply(apply_dropout)
print("Model cast to CPU")

# =============================================================================
# Open the testing data
# =============================================================================

index = np.array([100])
num_cores = 14
pool = mp.Pool(num_cores,maxtasksperchild=100)
results = list(pool.imap(return_cube,index))
pool.close()

batch = np.array([r[0] for r in results])
target = np.array([r[1:] for r in results])

batch = torch.tensor(batch).to(torch.float)
batch[batch!=batch]=0
target = torch.tensor(target).to(torch.float)

pos = target[:,0]
ah = target[:,-2]

mom0s, mom1s = batch[:,0,:,:].unsqueeze(1), batch[:,1,:,:].unsqueeze(1)

print("Test data created")

# =============================================================================
# Begin the testing procedure
# =============================================================================

predictions = []
errors = []
temp_pred = []
for _ in tqdm(range(1000)): #10000
    prediction1 = model.test_encode(mom0s,mom1s,pos)
    prediction1 = prediction1.detach().numpy()
    temp_pred.append(prediction1)
temp_pred = np.vstack(temp_pred)
mean_pred = np.mean(temp_pred,0)
predictions.append(mean_pred)
errors.append(np.sum(np.abs(temp_pred-mean_pred[None,:]),0)/len(temp_pred))

errors = np.vstack(errors)

fig, axs = plt.subplots(1, 4, figsize=(30,7.5))

axs[0].hist(np.rad2deg(temp_pred[:,1]),bins=50,density=True,color='b')
axs[0].set_xlim(10,90)
axs[1].hist(temp_pred[:,2],bins=50,density=True,color='b')
axs[1].set_xlim(0.1,0.35)
axs[2].hist(temp_pred[:,4],bins=50,density=True,color='b')
axs[2].set_xlim(50,500)
axs[3].hist(temp_pred[:,3],bins=50,density=True,color='b')
axs[3].set_xlim(0.01,0.8)

axs[0].set(ylabel= 'Probability density')
axs[0].set(xlabel= r'i $(^{\circ})$')
axs[1].set(xlabel= r'$a_{I}$')
axs[2].set(xlabel= r'$V_{max} \, sin(i) \, (km\,s^{-1})$')
axs[3].set(xlabel= r'$V_{scale}$')

plt.tight_layout()
plt.savefig(image_path + 'param_dists.png')

# =============================================================================
# Put the medians back into the network to get "out" images
# =============================================================================

predictions = torch.tensor(mean_pred).to(torch.float).unsqueeze(0).unsqueeze(0).unsqueeze(0)

batch_size = predictions.shape[0]

### Create the auxiliary arrays
l = torch.arange(0 - 63/2., (63/2.)+1)
yyy, xxx, zzz = torch.meshgrid(l,l,l)

xxx, yyy, zzz = xxx.repeat(batch_size,1,1,1), yyy.repeat(batch_size,1,1,1), zzz.repeat(batch_size,1,1,1)
xxx = xxx.to(torch.float)
yyy = yyy.to(torch.float)
zzz = zzz.to(torch.float)

BRIGHTNESS, VELOCITY, vmax = CAE(xxx,yyy,zzz).test_images(mom0s, mom1s, predictions[:,:,:,0],
                                                          predictions[:,:,:,1], predictions[:,:,:,2],
                                                          predictions[:,:,:,3], predictions[:,:,:,4],
                                                          predictions[:,:,:,0]*0 + 1, shape=64)

predictions = predictions.squeeze(0).squeeze(0).numpy()
mom0s, mom1s = mom0s.squeeze(1).numpy(), mom1s.squeeze(1).numpy()
BRIGHTNESS, VELOCITY = BRIGHTNESS.squeeze(1).numpy(), VELOCITY.squeeze(1).numpy()

synthetic_plotter(np.array([32]), mom0s, mom1s, BRIGHTNESS,VELOCITY,predictions,errors,0,image_path+'synthetic.pdf')

# =============================================================================
# End of script
# =============================================================================


import random
import logging
import os
import importlib.util
from pathlib import Path
from contextlib import ExitStack

import numpy as np
import boto3
from botocore.exceptions import ClientError

from ..utils.factory import get_monitor, get_model
from ..utils.aws import s3_fetch_data
from ..utils.misc import set_framework_seed

logging.basicConfig(level=logging.INFO)

def main() -> None:
    s3_path = Path(os.environ['S3_PATH'])
    bucket_name = os.environ['BUCKETNAME']
    blueprint_path = Path('home', 'dl-benchmarking', 'bp.py')

    s3 = boto3.resource('s3')
    bucket = s3.Bucket(bucket_name)
    bucket.download_file(str(s3_path / 'bp.py'), str(blueprint_path))

    spec = importlib.util.spec_from_file_location('bp', blueprint_path)
    bp = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(bp)

    logging.info(f'{bp.framework}_{bp.job_name}_{bp.instance_type}')

    random.seed(bp.python_seed)
    np.random.seed(bp.numpy_seed)
    set_framework_seed(bp.framework, bp.framework_seed)

    train_data = s3_fetch_data(bp.bucket_name,
                               Path(bp.train_data_path)).reshape(*bp.reshape_input_data)
    train_label = s3_fetch_data(bp.bucket_name,
                                Path(bp.train_label_path))

    try:
        test_data = s3_fetch_data(bp.bucket_name,
                                  Path(bp.test_data_path)).reshape(*bp.reshape_input_data)
        test_label = s3_fetch_data(bp.bucket_name,
                                   Path(bp.test_label_path))
    except (TypeError, ClientError):
        test_data = None
        test_label = None

    try:
        params = s3_fetch_data(bucket_name, Path(bp.model_params_path))
    except (TypeError, ClientError):
        params = None

    if bp.framework in ['pytorch', 'mxnet']: # Use NCHW format for image data in pytorch and mxnet
        if len(train_data.shape) > 3:
            train_data = train_data.swapaxes(-3, -1)
            if isinstance(test_data, np.ndarray):
                test_data = test_data.swapaxes(-3, -1)

    model = get_model(bp.architecture, bp.framework, params)

    if bp.mode == 'training':
        with ExitStack() as stack:
            for monitor in bp.monitors:
                stack.enter_context(get_monitor(monitor, s3_path, bp.bucket_name, aws=True))
            model.training(train_data,
                           train_label,
                           test_data,
                           test_label,
                           bp.loss_function,
                           bp.optimizer,
                           bp.optimizer_mode,
                           bp.epochs,
                           bp.learning_rate,
                           s3_path,
                           bp.batch_size,
                           bp.train_seq_length,
                           bp.test_seq_length,
                           bp.state_sizes,
                           bp.truncated_backprop_length,
                           bp.bucket_name,
                           aws=True)

    elif bp.mode == 'inference':
        with ExitStack() as stack:
            for monitor in bp.monitors:
                stack.enter_context(get_monitor(monitor, s3_path, bp.bucket_name, aws=True))
            model.inference(train_data,
                            bp.batch_size,
                            s3_path,
                            bp.mode,
                            bp.optimizer_mode,
                            bp.state_sizes,
                            bp.bucket_name,
                            aws=True)

if __name__ == "__main__":
    main()


from fastapi import FastAPI, WebSocket, Request
import uvicorn
import json
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory='templates')

@app.get("/")
async def root(request: Request):
    return templates.TemplateResponse('index.html', {'request': request})

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    id = 1
    while True:
        data_1 = await websocket.receive_json()
        data_2 = {}
        data_2[id] = data_1['id']
        data_2 = json.dumps(data_2)
        await websocket.send_json(data_2)

if __name__ == '__main__':
    uvicorn.run('main:app', port=8000, host='127.0.0.1', reload=True)


#!/usr/bin/env python
import numpy as np
import random
import cv2

def do_full_homo(p, q):
    mat = np.zeros((len(p) * 3, 9))
    for i in range(len(p)):
        mat[i * 2][0] = p[i][0]
        mat[i * 2][1] = p[i][1]
        mat[i * 2][2] = 1

        mat[i * 2][3] = 0
        mat[i * 2][4] = 0
        mat[i * 2][5] = 0

        mat[i * 2][6] = -p[i][0] * q[i][0]
        mat[i * 2][7] = -p[i][1] * q[i][0]
        mat[i * 2][8] = -q[i][0]

        mat[(i * 2) + 1][0] = 0
        mat[(i * 2) + 1][1] = 0
        mat[(i * 2) + 1][2] = 0

        mat[(i * 2) + 1][3] = p[i][0]
        mat[(i * 2) + 1][4] = p[i][1]
        mat[(i * 2) + 1][5] = 1

        mat[(i * 2) + 1][6] = -p[i][0] * q[i][1]
        mat[(i * 2) + 1][7] = -p[i][1] * q[i][1]
        mat[(i * 2) + 1][8] = -q[i][1]
    _, _, v = np.linalg.svd(mat)
    h = v[-1].reshape(3, 3)
    h /= v[-1][-1]
    return h

def ransac(points_left, points_right, desc_left, desc_right):
    n = 10000
    best_points = 0
    best_homo = None

    max_len = min(len(points_left), len(points_right))

    bf = cv2.BFMatcher()
    matches = bf.match(desc_left, desc_right)
    mp1 = [points_left[m.queryIdx].pt for m in matches]
    mp2 = [points_right[m.trainIdx].pt for m in matches]
    #print(mp1, mp2)

    for _ in range(n):
        l = [random.randint(0, max_len - 1) for _ in range(4)]
        p = np.array([mp1[i] for i in l])
        q = np.array([mp2[i] for i in l])

        #potential_homo = do_full_homo(p, q)
        potential_homo, _ = cv2.findHomography(p, q)
        if np.array_equal(potential_homo, None):
            continue
        points_transformed = [potential_homo @ (point[0], point[1], 1) for point in mp1]
        good_points = 0
        for i in range(len(mp1)):
            p_i = points_transformed[i][:2]
            q_i = mp2[i]
            #print(mp1[i], p_i, q_i)
            diff = np.linalg.norm(p_i - q_i)
            #if diff < 100:
                #print(diff)
            if diff < 10:
                good_points += 1
            if best_points < good_points:
                best_points = good_points
                best_homo = potential_homo
    #print(best_points, "out of", len(points_left))
    return best_homo

    """
    for _ in range(n):
        l = [random.randint(0, max_len - 1) for _ in range(4)]
        p = [points_left[i].pt for i in l]
        q = [points_right[i].pt for i in l]

        potential_homo = do_full_homo(p, q)
        points_transformed = [potential_homo @ (point.pt[0], point.pt[1], 1) for point in points_left]
        good_points = 0
        for i in range(max_len):
            p_i = points_transformed[i][:2]
            q_i = points_right[i].pt
            diff = np.linalg.norm(p_i - q_i)
            #total_diff += diff
            if diff < 50:
                good_points += 1
        if best_points < good_points:
            best_points = good_points
            best_homo = potential_homo
    print(best_points, "out of", len(points_left))
    return best_homo
    """

path_left = './to_detect_2_1.jpg'
path_right = './to_detect_2_2.jpg'

img_left = cv2.imread(path_left)
img_right = cv2.imread(path_right)

sift = cv2.SIFT_create()
points_left, desc_left = sift.detectAndCompute(img_left, None)
points_right, desc_right = sift.detectAndCompute(img_right, None)

homo = ransac(points_left, points_right, desc_left, desc_right)

#max_len = min(len(points_left), len(points_right))
#pts_src = np.array([np.float32(k.pt) for k in points_left], np.float32).reshape(-1, 2)[:max_len]
#pts_dst = np.array([np.float32(k.pt) for k in points_right], np.float32).reshape(-1, 2)[:max_len]
#other_homo, _ = cv2.findHomography(pts_src, pts_dst)

warped = cv2.warpPerspective(img_right, np.linalg.inv(homo), (img_right.shape[1] * 2, img_right.shape[0]))
warped[:img_left.shape[0], :img_left.shape[1]] = img_left
cv2.imwrite("stitched.jpg", warped)


import requests
from bs4 import BeautifulSoup
import tweepy # Library Used For twitter

auth = tweepy.OAuthHandler('NZIjCl060lClQIcGIvQZY7Er5','FFafAZfS4PuCIBajvzmTQLU2jW140DeQsDBxhnWneEUk82TvOQ') # this is one of the tokens and secret keys to initialize the API

auth.set_access_token('905298941830418432-kqrO4GcUWlSUt3M50mnVYadYrPuemAD','rztBW3cTEcudo3wK5lGDxzjjTarHRwJa5YCrcAMvA8nxn') # this is one of the tokens and secret keys to initialize the API

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

URL = 'https://www.google.com/search?q=weather+in+mumbai&rlz=1C1CHBF_enIN868IN868&oq=weather+&aqs=chrome.0.69i59j69i57j69i60l3.1072j0j7&sourceid=chrome&ie=UTF-8'
headers = {"User_Agent" : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'}

page = requests.get(URL, headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')

temp = soup.find(id= "wob_tm").get_text() # this accesses the website where the data is, and finds the correct ID for the current temperature

login= api.me()
api.update_status(temp) # this tweets out the temperature in Mumbai at any given time


import setuptools

from tensorcircuit import __version__, __author__
from tensorcircuit.utils import is_m1mac

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

install_requires = ["numpy", "scipy", "tensornetwork", "networkx"]

if not is_m1mac():
    install_requires.append("tensorflow")
    # avoid the embarassing macos M1 chip case, where the package is called tensorflow-macos

setuptools.setup(
    name="tensorcircuit",
    version=__version__,
    author=__author__,
    author_email="shixinzhang@tencent.com",
    description="Quantum circuits on top of tensor network",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/tencent-quantum-lab/tensorcircuit",
    packages=setuptools.find_packages(),
    include_package_data=True,
    install_requires=install_requires,
    tests_require=[
        "pytest",
        "pytest-lazy-fixture",
        "pytest-cov",
        "pytest-benchmark",
        "pytest-xdist",
    ],
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
    ],
)


import cv2

img = cv2.imread("images.jpeg")

gaussian = cv2.GaussianBlur(img,(15,15),0)#  (yapıcalak gorsel, çekirdek boyutu ,sigma)  genel blurlama yapıyor.

median = cv2.medianBlur(img,5) # gürültüyü gidermede kullanılır.

bila = cv2.bilateralFilter(img,20,120,75) #kenar koruyarak blurlama performansı gaustan iyidr. kenarları korur. gaus her şeyi blurlar.

blur = cv2.blur(img,(5,5))

cv2.imshow("blur",blur)
cv2.imshow("bila",bila)
cv2.imshow("median",median)
cv2.imshow("gassuian",gaussian)
cv2.imshow("image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()


#!/usr/bin/python
from sh import grep, avahi_resolve_address, wget
import os, sys, re, sh

OUI_FILE = '/usr/share/arp-scan/ieee-oui.txt'

stdout = sys.stdout.write

oui_url = 'https://raw.githubusercontent.com/royhills/arp-scan/master/ieee-oui.txt'

mac_regex = re.compile('(?:[0-9a-fA-F]:?){12}')
ipv4_like_regex = re.compile(r'[0-9]+(?:\.[0-9]+){3}')
valid_ip_octets = lambda ip: all([0<=int(p)<256 for p in ip.split('.')])

def check_oui_file_and_prompt(oui_file):
    tmp_oui_file = '/tmp/ieee-oui.txt'
    home_oui_file = os.path.expanduser('~') + 'ieee-oui.txt'
    paths = [oui_file, tmp_oui_file, home_oui_file]
    for filepath in paths:
        if os.path.exists(filepath):
            return filepath
    stdout('\nCould not find any of {}. Execute this command to download:\n\t{}\n'
           ''.format(paths, 'wget {} -O ~/ieee-oui.txt'.format(oui_url)))
    return None

def extract_first_ip(text):
    dot_matches = re.findall(ipv4_like_regex, text)
    ips = [x for x in dot_matches if valid_ip_octets(x)]
    return ips[0] if ips else None

def sh_host(ip):
    call = sh.host(ip, _ok_code=[0,1])
    if call.exit_code != 0:
        return None
    else:
        host = str(call).split(' pointer ')[1:]
        return host[0] if host else None

def extract_first_mac(text):
    macs = re.findall(mac_regex, text)
    return macs[0] if macs else None

def get_vendor(mac):
    if not mac:
        return None
    grepped = grep(
        mac.upper().replace(':','')[:6],
        OUI_FILE,
        _ok_code=[0,1]
    )
    return str(grepped)[7:] or '<unknown vendor>'

def dict_to_string(d):
    return '{{{}}}'.format(
        ', '.join(
            ["{}: {}".format(k, v) for k, v in d.iteritems()]
        )
    )

def process_stdin():
    lines = sys.stdin.readlines()
    ips = map(extract_first_ip, lines)
    macs = map(extract_first_mac, lines)
    _avahi_call = [(ip, avahi_resolve_address(ip, _iter=True)) for ip in ips if ip]
    avahi = {k:str(v) for (k,v) in _avahi_call}
    for line in lines:
        ip = extract_first_ip(line)
        mac = extract_first_mac(line)
        half_sep = '\t' if '\t' in line else ' '*4
        sep = half_sep * 2
        extra = ''
        if mac:
            extra += sep + get_vendor(mac)
        if ip:
            avahi_host = avahi[ip].split('\t')[1] if avahi.get(ip, False) else ''
            extra += sep + (sh_host(ip) or avahi_host or '<unknown host>')
        if extra:
            sys.stdout.write((line + half_sep + extra).replace('\n', '') + '\n')
        else:
            sys.stdout.write(line)

help_text = ''\
"""
IP&MAC address lookup script
============================
This script will find the the first IP and MAC address in lines
from stdin, and append MAC-vendor and IP hostname to the lines if
found.

Usage:
------
File:
    cat my_ip_and_mac_addresses.txt | ./ipmac_lookup.py

Local subnet:
    sudo arp-scan 192.168.1.0/24 | ./ipmac_lookup.py

Local ip address:
    arp 192.168.1.1 | ./ipmac_lookup.py
 Output:
    Address          HWtype  HWaddress           Flags Mask  Iface
    192.168.1.1    ether   38:2c:4b:aa:bb:cc   C           eth0    ASUSTek COMPUTER INC.   somehostname.local

The script currently processes all stdin at once, because executing
`avahi-resolve-address` on a bunch of IP addresses is a lot faster than
potentially timing out on one IP address after another.

TODO: Rewrite in order to choose if we want to process stdin one line at a
      time, which would make it possible to use the script as a filter-step
      in a tail -f command, for example.

A prerequisite is a ieee-oui.txt file for performing the MAC <--> vendor
lookup.
The official IEEE link is dead slow. A faster mirror can be found at:
https://raw.githubusercontent.com/royhills/arp-scan/master/ieee-oui.txt
"""

if __name__ == '__main__':
    if os.isatty(0):
        stdout(help_text + '\n')
    else:
        OUI_FILE = check_oui_file_and_prompt(OUI_FILE)
        process_stdin()


from screenplay_selenium.actions import navigate_to, find_element, enter_text, value_of
from os import path
from selenium.webdriver.common.by import By
from .user_fixture import user  # noqa: F401

test_page = 'file://' + path.join(path.dirname(__file__), 'elements.html')

def test_accessing_the_value_of_a_stored_element(user):
    returned_value = user.attempts_to(
        navigate_to(test_page),
        find_element((By.ID, 'fourth_text')).and_store_as('textbox'),
        value_of().stored_element('textbox')
    )

    assert returned_value == 'fourth textbox'

def test_stripping_the_whitespace_of_the_accessed_value(user):
    locator = (By.ID, 'third_text')

    returned_value = user.attempts_to(
        navigate_to(test_page),
        enter_text('  text  ').into_element(locator),
        find_element(locator).and_store_as('textbox'),
        value_of().stored_element('textbox').stripped_of_whitespace()
    )

    assert returned_value == 'text'


from pyramid.view import view_config
from .security import logged
import psutil

# - Check process on system
def processIsRun(process_name):
    for proc in psutil.process_iter():
        try:
            if process_name in proc.name().lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False

# - default page
@view_config (
    route_name = 'service',
    renderer = 'nodirectory:templates/services.jinja2',
)

def service(request):

    # Verify if there is a session
    logged(request, request.session)

    return {
        'title': 'Service',
        'autor': 'ConexInfra',
        'project': 'NoDirectory',
        }

# - List service status
@view_config (
    route_name = 'servicelist',
    renderer = 'json'
)

def servicelist(request):

    # Verify if there is a session
    logged(request, request.session)

    service = []
    state = []

    if processIsRun('smbd'):
        service.append('samba')
        state.append('running')
    else:
        service.append('samba')
        state.append('stopped')

    if processIsRun('slapd'):
        service.append('openldap')
        state.append('running')
    else:
        service.append('openldap')
        state.append('stopped')

    dict_to_return = []
    for i in range(0, len(service)):
        dict_to_return.append([service[i], state[i]])

    return {'services': dict_to_return}


#!/usr/bin/python
# -*- coding:utf-8 -*-
import datetime
import traceback

from actions.applet import find_member_by_open_id
from actions.applet.utils import do_diamond_reward
from db import SOURCE_MEMBER_DIAMOND_DAILY_SHARE_TIMES_LIMIT, SOURCE_MEMBER_DIAMOND_DAILY_SHARE, \
    SOURCE_MEMBER_DIAMOND_DICT
from db.model_utils import get_cache_share_times, set_cache_share_times
from db.models import GameDiamondReward
from logger import log_utils
from web import decorators, WechatAppletHandler

logger = log_utils.get_logging('a_miniapp')

class MiniappShareAwardViewHandler(WechatAppletHandler):
    """ 分享好友奖励会员钻石"""

    @decorators.render_json
    @decorators.wechat_applet_authenticated
    async def post(self):
        r_dict = {'code': 0}
        open_id = self.get_i_argument('open_id', None)
        try:
            if open_id:
                member = await find_member_by_open_id(open_id)
                if member:
                    award_title = ''
                    award_diamonds = ''
                    share_times = await GameDiamondReward.find_one(
                        filtered={'source': SOURCE_MEMBER_DIAMOND_DAILY_SHARE_TIMES_LIMIT})
                    value = get_cache_share_times(member.cid)
                    if value < share_times.quantity:
                        end_datetime = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999)
                        current_datetime = datetime.datetime.now()
                        timeout = (end_datetime - current_datetime).seconds
                        # 分享奖励
                        _, m_diamond = await do_diamond_reward(member, SOURCE_MEMBER_DIAMOND_DAILY_SHARE)
                        # 设置更新已奖励次数
                        set_cache_share_times(member.cid, timeout)
                        if member.diamond is None:
                            member.diamond = m_diamond
                        else:
                            member.diamond = member.diamond + m_diamond
                        await member.save()
                        award_title = SOURCE_MEMBER_DIAMOND_DICT.get(SOURCE_MEMBER_DIAMOND_DAILY_SHARE)
                        award_diamonds = m_diamond
                    # 用户的钻石
                    r_dict['diamonds_num'] = member.diamond
                    r_dict['award_title'] = award_title
                    r_dict['award_diamonds'] = award_diamonds
                    r_dict['code'] = 1000
                else:
                    r_dict['code'] = 1002
            else:
                r_dict['code'] = 1001
        except Exception:
            logger.error(traceback.format_exc())

        return r_dict


"""
2019 Day 14
https://adventofcode.com/2019/day/14
"""

from functools import partial
from math import ceil, floor
from typing import Callable, Dict, List, Set, Tuple
import aocd  # type: ignore

MaterialQty = Tuple[str, int]
Recipes = Dict[str, Tuple[int, Set[MaterialQty]]]

def read_ingredient(ingredient: str) -> MaterialQty:
    parts = ingredient.split(" ")
    return parts[1], int(parts[0])

def read_recipe_side(side: str) -> List[MaterialQty]:
    return [read_ingredient(ing) for ing in side.split(", ")]

def read_recipe_line(line: str) -> Tuple[List[MaterialQty], List[MaterialQty]]:
    sides = [read_recipe_side(side) for side in line.split(" => ")]
    return sides[0], sides[1]

def read_recipes(text: str) -> Recipes:
    return {
        right[0][0]: (right[0][1], set(left))
        for left, right in [read_recipe_line(line) for line in text.split("\n")]
    }

def resolve_need(
    element: str, inventory: Dict[str, int], recipes: Recipes
) -> Dict[str, int]:
    reacted = dict(inventory)
    need = -inventory[element]

    if need > 0 and element in recipes:
        qty, ingredients = recipes[element]
        repetitions = ceil(need / qty)
        reacted[element] = reacted.get(element, 0) + (repetitions * qty)
        for (ing_element, ing_qty) in ingredients:
            reacted[ing_element] = reacted.get(ing_element, 0) - (repetitions * ing_qty)

    return reacted

def ore_required(recipes: Recipes, fuel: int = 1) -> int:
    inventory = {"FUEL": -fuel}
    needs = ["FUEL"]
    while len(needs) > 0:
        inventory = resolve_need(needs[0], inventory, recipes)
        needs = [
            element
            for element, qty in inventory.items()
            if element != "ORE" and qty < 0
        ]
    return -inventory["ORE"]

def binary_search(
    func: Callable[[int], int], target: int, lower: int, upper: int
) -> int:
    while lower <= upper:
        mid = floor((lower + upper) / 2)
        attempt = func(mid)
        if attempt < target:
            lower = mid + 1
        elif attempt > target:
            upper = mid - 1
        else:
            return mid
    return upper

def exponential_search(func: Callable[[int], int], target: int) -> int:
    bound = 1
    while func(bound) < target:
        bound *= 2
    return binary_search(func, target, bound // 2, bound + 1)

def fuel_from_trillion_ore(recipes: Recipes) -> int:
    return exponential_search(partial(ore_required, recipes), 1_000_000_000_000)

def test_part1() -> None:
    """
    Examples for Part 1.
    """
    text = "\n".join(
        (
            "10 ORE => 10 A",
            "1 ORE => 1 B",
            "7 A, 1 B => 1 C",
            "7 A, 1 C => 1 D",
            "7 A, 1 D => 1 E",
            "7 A, 1 E => 1 FUEL",
        )
    )
    eg1 = {
        "A": (10, {("ORE", 10)}),
        "B": (1, {("ORE", 1)}),
        "C": (1, {("A", 7), ("B", 1)}),
        "D": (1, {("A", 7), ("C", 1)}),
        "E": (1, {("A", 7), ("D", 1)}),
        "FUEL": (1, {("A", 7), ("E", 1)}),
    }
    assert read_recipes(text) == eg1
    assert ore_required(eg1) == 31
    eg2 = {
        "A": (2, {("ORE", 9)}),
        "B": (3, {("ORE", 8)}),
        "C": (5, {("ORE", 7)}),
        "AB": (1, {("A", 3), ("B", 4)}),
        "BC": (1, {("B", 5), ("C", 7)}),
        "CA": (1, {("C", 4), ("A", 1)}),
        "FUEL": (1, {("AB", 2), ("BC", 3), ("CA", 4)}),
    }
    assert ore_required(eg2) == 165
    eg3 = {
        "STKFG": (1, {("VPVL", 2), ("FWMGM", 7), ("CXFTF", 2), ("MNCFX", 11)}),
        "VPVL": (8, {("NVRVD", 17), ("JNWZP", 3)}),
        "FUEL": (
            1,
            {
                ("STKFG", 53),
                ("MNCFX", 6),
                ("VJHF", 46),
                ("HVMC", 81),
                ("CXFTF", 68),
                ("GNMV", 25),
            },
        ),
        "FWMGM": (5, {("VJHF", 22), ("MNCFX", 37)}),
        "NVRVD": (4, {("ORE", 139)}),
        "JNWZP": (7, {("ORE", 144)}),
        "HVMC": (
            3,
            {("MNCFX", 5), ("RFSQX", 7), ("FWMGM", 2), ("VPVL", 2), ("CXFTF", 19)},
        ),
        "GNMV": (6, {("VJHF", 5), ("MNCFX", 7), ("VPVL", 9), ("CXFTF", 37)}),
        "MNCFX": (6, {("ORE", 145)}),
        "CXFTF": (8, {("NVRVD", 1)}),
        "RFSQX": (4, {("VJHF", 1), ("MNCFX", 6)}),
        "VJHF": (6, {("ORE", 176)}),
    }
    assert ore_required(eg3) == 180697

def test_part2() -> None:
    """
    Examples for Part 2.
    """
    eg3 = {
        "STKFG": (1, {("VPVL", 2), ("FWMGM", 7), ("CXFTF", 2), ("MNCFX", 11)}),
        "VPVL": (8, {("NVRVD", 17), ("JNWZP", 3)}),
        "FUEL": (
            1,
            {
                ("STKFG", 53),
                ("MNCFX", 6),
                ("VJHF", 46),
                ("HVMC", 81),
                ("CXFTF", 68),
                ("GNMV", 25),
            },
        ),
        "FWMGM": (5, {("VJHF", 22), ("MNCFX", 37)}),
        "NVRVD": (4, {("ORE", 139)}),
        "JNWZP": (7, {("ORE", 144)}),
        "HVMC": (
            3,
            {("MNCFX", 5), ("RFSQX", 7), ("FWMGM", 2), ("VPVL", 2), ("CXFTF", 19)},
        ),
        "GNMV": (6, {("VJHF", 5), ("MNCFX", 7), ("VPVL", 9), ("CXFTF", 37)}),
        "MNCFX": (6, {("ORE", 145)}),
        "CXFTF": (8, {("NVRVD", 1)}),
        "RFSQX": (4, {("VJHF", 1), ("MNCFX", 6)}),
        "VJHF": (6, {("ORE", 176)}),
    }
    assert fuel_from_trillion_ore(eg3) == 5586022

def main() -> None:
    """
    Calculate and output the solutions based on the real puzzle input.
    """
    data = aocd.get_data(year=2019, day=14)
    recipes = read_recipes(data)

    print(f"Part 1: {ore_required(recipes)}")
    print(f"Part 2: {fuel_from_trillion_ore(recipes)}")

if __name__ == "__main__":
    main()


import os
import sys
import asyncio
import signal
from binance import AsyncClient, BinanceSocketManager
from dotenv import load_dotenv
load_dotenv()

symbol = sys.argv[1]
entry_price = float(sys.argv[2])
entry_order_id = sys.argv[3]
stop_order_id = sys.argv[4]
qty = float(sys.argv[5])

stop_loss_margin = 0.995 # 0.5% stop loss margin
take_profit_margin = 1.0085 # 0.85% take profit margin

take_profit_bid = entry_price * take_profit_margin
stop_loss_bid = entry_price * stop_loss_margin

async def main():
    client = await AsyncClient.create(api_key=os.getenv("API_KEY_PROD"), api_secret=os.getenv("SECRET_KEY_PROD"))
    bm = BinanceSocketManager(client)
    # start any sockets here, i.e a trade socket
    ts = bm.trade_socket(symbol=symbol)
    # then start receiving messages
    async with ts as tscm:
        while True:
            res = await tscm.recv()
            print(res)
            if float(res["p"]) >= take_profit_bid:
                print("Take profit")
                await client.cancel_order(symbol=symbol, orderId=stop_order_id)
                await client.create_order(symbol=symbol, side="SELL", type="MARKET", quantity=qty)
                break
            if float(res["p"]) <= stop_loss_bid:
                print("Stop loss")
                break

    await client.close_connection()
    os.kill(os.getppid(), signal.SIGTERM)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


#!/usr/bin/env python3
# @Time    : 2020-02-14
# @Author  : caicai
# @File    : request.py
import requests
import urllib3

urllib3.disable_warnings()

from myscan.lib.core.data import cmd_line_options, logger
from myscan.lib.core.common import getredis, gethostportfromurl
from myscan.lib.core.block_info import block_info
from time import sleep
from random import uniform
from myscan.pocs.search import searchmsg
from myscan.config import scan_set
import copy
from myscan.lib.core.const import key_unquote

def request(**kwargs_sour):
    return do_req(None, **kwargs_sour)

def request_session(session, **kwargs_sour):
    return do_req(session, **kwargs_sour)

def do_req(session, **kwargs_sour):
    kwargs = copy.deepcopy(kwargs_sour)
    if kwargs.get("quote", None) is not None:
        if isinstance(kwargs.get("quote"), bool):
            if not kwargs.get("quote"):
                kwargs["url"] = key_unquote + kwargs.get("url", "")
        else:
            logger.warning("requests quote args need bool")
            return
        del kwargs["quote"]
    # print("start:",kwargs)
    if not kwargs.get("verify", None):
        kwargs["verify"] = False
    if not kwargs.get("timeout", None):
        kwargs["timeout"] = 12
    if not kwargs.get("headers", None):
        kwargs["headers"] = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0"}
    elif not kwargs.get("headers").get("User-Agent", None):
        kwargs["headers"]["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0"

    if cmd_line_options.proxy:
        kwargs["proxies"] = cmd_line_options.proxy
    if cmd_line_options.timeout:
        kwargs["timeout"] = cmd_line_options.timeout
    # print("end:",kwargs)
    if kwargs.get('data', None):
        if isinstance(kwargs.get("data"), str):
            kwargs["data"] = kwargs["data"].encode("utf-8", "ignore")
    r = None
    h, p = gethostportfromurl(kwargs.get("url"))
    block = block_info(h, p)
    if block.is_block():
        return None
    # retry
    for x in range(cmd_line_options.retry + 1):
        try:
            if session is None:
                r = requests.request(**kwargs)
            else:
                r = session.request(**kwargs)
            break
        except requests.exceptions.ConnectTimeout:
            pass
            # logger.debug("request connect timeout :{}".format(kwargs["url"]))
        except requests.exceptions.ReadTimeout:
            pass
            # logger.debug("request read timeout :{}".format(kwargs["url"]))
        except Exception as ex:
            # print(kwargs)
            logger.debug("Request error url:{} error:{}".format(kwargs["url"], ex))
        sleep(uniform(0, 0.2))
    red = getredis()
    red.hincrby("count_all", "request", amount=1)
    if r != None:
        block.push_result_status(0)
        if scan_set.get("search_open", False):
            s = searchmsg(r)
            s.verify()
            # s.saveresult()
    else:
        block.push_result_status(1)
        red.hincrby("count_all", "request_fail", amount=1)
    return r


from flask import Flask, render_template, request, redirect, session, flash

app = Flask(__name__)
app.secret_key = 'maicondouglasfilipiaki'

class Jogo:
    def __init__(self, nome, categoria, console):
        self.nome = nome
        self.categoria = categoria
        self.console = console

jogo1 = Jogo('Super Mario', 'Acao', 'SNES')
jogo2 = Jogo('Pokemon', 'RPG', 'GAMEBOY')
jogo3 = Jogo('Mortal Kombat', 'Luta', 'SNES')
lista = [jogo1, jogo2, jogo3]

@app.route('/')
def index():
    return render_template('lista.html', titulo='Jogos', jogos=lista)

@app.route('/novo')
def novo():
    if 'usuario_logado' not in session or session['usuario_logado'] == None:
        flash('Faca o login para entrar')
        return redirect('/login?proxima=novo')
    return render_template('novo.html', titulo='Novo Jogo')

@app.route('/criar', methods=['POST',])
def criar():
    nome = request.form['nome']
    categoria = request.form['categoria']
    console = request.form['console']
    jogo = Jogo(nome, categoria, console)
    lista.append(jogo)
    return redirect('/')

@app.route('/login', methods=['GET',])
def login():
    proxima = request.args.get('proxima')
    return render_template('login.html', titulo="Login", proxima=proxima)

@app.route('/autenticar', methods=['POST',])
def autenticar():
    if 'mestrar' == request.form['senha']:
        session['usuario_logado'] = request.form['usuario']
        flash(request.form['usuario'] + ' logou com sucesso!')
        return redirect('/{}'.format(request.form['proxima']))
    else:
        flash('Tente novamente')
        return redirect('/login')

@app.route('/logout')
def logout():
    session['usuario_logado'] = None
    flash('Nenhum usuario logado')
    return redirect('/')

app.run(debug=True)


# std
import logging
from typing import Optional
from datetime import datetime

# project
from . import FinishedSignageConditionChecker
from src.notifier import Event, EventService, EventType, EventPriority
from src.chia_log.parsers.finished_signage_point_parser import FinishedSignagePointMessage
from src.chia_log.handlers.util.calculate_skipped_signage_points import calculate_skipped_signage_points

class NonSkippedSignagePoints(FinishedSignageConditionChecker):
    """Check that the full node did not skip any signage points.
    If there are signage points missing, this could indicate connection
    issues which prevent the farmer from participating in all challenges.
    """

    def __init__(self):
        logging.debug("Enabled check for finished signage points.")
        self._last_signage_point_timestamp: datetime = datetime.fromtimestamp(0)
        self._last_signage_point: int = 0

    def check(self, obj: FinishedSignagePointMessage) -> Optional[Event]:
        if self._last_signage_point == 0:
            self._last_signage_point_timestamp = obj.timestamp
            self._last_signage_point = obj.signage_point
            return None

        event = None
        valid, skipped = calculate_skipped_signage_points(
            self._last_signage_point_timestamp, self._last_signage_point, obj.timestamp, obj.signage_point
        )

        if not valid:
            return None

        # To reduce notification spam, only send notifications for skips larger than 1
        if skipped == 1:
            logging.info(
                f"Detected {skipped} skipped signage point."
                "This is expected to happen occasionally and not a reason for concern."
            )
        elif skipped >= 2:
            message = f"Experiencing networking issues? Skipped {skipped} signage points!"
            logging.warning(message)
            event = Event(
                type=EventType.USER,
                priority=EventPriority.NORMAL,
                service=EventService.FULL_NODE,
                message=message,
            )

        self._last_signage_point_timestamp = obj.timestamp
        self._last_signage_point = obj.signage_point
        return event


# -*- coding:UTF-8  -*-
"""
获取指定账号的全部重复库存内个人资料背景和表情
https://store.steampowered.com/
@author: hikaru
email: hikaru870806@hotmail.com
如有问题或建议请联系
"""
from common import output, crawler
from game.steam import steamCommon

CHECK_EXTRA_CARD = True  # 是否检测额外的交换卡（徽章等级大于5，并且还有卡牌）
CHECK_DUPLICATE_BACKGROUND = True  # 是否检测重复的个人背景图
CHECK_DUPLICATE_EMOTICON = False  # 是否检测重复的表情

# 获取当前account正在收集的徽章进度
def main(account_id):
    try:
        inventory_item_list = steamCommon.get_account_inventory(account_id)
    except crawler.CrawlerException as e:
        output.print_msg("库存解析失败，原因：%s" % e.message)
        raise
    badges_list = {}
    if CHECK_EXTRA_CARD:
        # 获取徽章等级
        try:
            badges_list = steamCommon.get_account_badges(account_id)
        except crawler.CrawlerException as e:
            output.print_msg("获取徽章等级失败，原因：%s" % e.message)
            raise
    for item_id, item_info in inventory_item_list.items():
        if item_info["type"] == steamCommon.INVENTORY_ITEM_TYPE_PROFILE_BACKGROUND:
            if CHECK_DUPLICATE_BACKGROUND and item_info["count"] > 1:
                output.print_msg(item_info)
        elif item_info["type"] == steamCommon.INVENTORY_ITEM_TYPE_EMOTICON:
            if CHECK_DUPLICATE_EMOTICON and item_info["count"] > 1:
                output.print_msg(item_info)
        elif item_info["type"] == steamCommon.INVENTORY_ITEM_TYPE_TRADE_CARD:
            if CHECK_EXTRA_CARD:
                # 闪卡，跳过
                if item_info['name'].find("(Foil)") >= 0:
                    continue
                if item_info["game_id"] in badges_list:
                    badge_level = badges_list[item_info["game_id"]]
                else:
                    badge_level = 0
                # 如果剩余卡牌数量 + 当前徽章等级 > 5
                if item_info["count"] + badge_level > steamCommon.MAX_BADGE_LEVEL:
                    output.print_msg(item_info)

if __name__ == "__main__":
    main(steamCommon.get_account_id_from_file())


import time
import utils

from autotest_lib.client.common_lib import error
from autotest_lib.client.cros.enterprise import enterprise_policy_base
from telemetry.core.exceptions import EvaluateException

class policy_DefaultJavaScriptSetting(
        enterprise_policy_base.EnterprisePolicyTest):
    """
    Tests the DefaultJavaScriptSetting policy in Chrome OS.

    If the DefaultJavaScriptSetting policy is set to Allow, going to the
    local test page should display YES. If the policy is set to Do Not Allow
    going to the local test page should display NO.

    """
    version = 1

    def initialize(self, **kwargs):
        """Initialize this test."""
        super(policy_DefaultJavaScriptSetting, self).initialize(**kwargs)
        self.TEST_FILE = 'js_test.html'
        self.TEST_URL = '%s/%s' % (self.WEB_HOST, self.TEST_FILE)
        self.POLICY_NAME = 'DefaultJavaScriptSetting'
        self.POLICIES = {}
        self.TEST_CASES = {
            'Allow': 1,
            'Do Not Allow': 2}
        self.start_webserver()

    def _can_execute_javascript(self):
        """
        Determine whether JavaScript is allowed to run on the given page.

        @param tab: browser tab containing JavaScript to run.

        Note: This test does not use self.navigate_to_url(), because it can
        not depend on methods that evaluate or execute JavaScript.

        """
        tab = self.cr.browser.tabs.New()
        tab.Activate()
        tab.Navigate(self.TEST_URL)
        time.sleep(1)

        utils.poll_for_condition(
            lambda: tab.url == self.TEST_URL,
            exception=error.TestError('Test page is not ready.'))

        try:
            utils.poll_for_condition(
                lambda: tab.EvaluateJavaScript('jsAllowed', timeout=2),
                exception=error.TestError('Test page is not ready.'))
            return True
        except (EvaluateException, utils.TimeoutError):
            return False

    def run_once(self, case):
        """
        Setup and run the test configured for the specified test case.

        @param case: Name of the test case to run.

        """
        case_value = self.TEST_CASES[case]
        self.POLICIES[self.POLICY_NAME] = case_value
        self.setup_case(user_policies=self.POLICIES)

        if case == 'Allow':
            if not self._can_execute_javascript():
                raise error.TestFail('JavaScript disabled, should be enabled.')
        else:
            if self._can_execute_javascript():
                raise error.TestFail('JavaScript enabled, should be disabled.')


from .composer import Composer
from .mangalib_parser import MangaLibBook, load_chapter
from .status import StatusMessage

from uuid import uuid4 as random_token
import asyncio
from io import BytesIO

from dtelbot.inline_keyboard import markup, button
from telethon import TelegramClient
from telethon.sessions.string import StringSession

class MangaParser:
    def __init__(self, bot, telethon_params):
        self.composer = Composer()
        self.bot = bot
        self.telethon_session = telethon_params[0]
        self.telethon_api_id = telethon_params[1]
        self.telethon_api_hash = telethon_params[2]
        self.bot_name = None
        self.callback_timesleep = 2
        self.per_page = 10
        self.files = {}
        self.nav_codes = lambda c: 10**(len(c)-1) if c[0] == '>' else -10**(len(c)-1) if c[0] == '<' else  0

    async def set_bot_name(self):
        result = await (self.bot.getme().send())
        self.bot_name = '@' + result['result']['username']

    def navbar(self, count, nav_text, buttons=[]):
        if count > 10:
            buttons = [button('<', callback_data='{} <'.format(nav_text))] + buttons + [button('>', callback_data='{} >'.format(nav_text))]
        if count > 100:
            buttons = [button('<<', callback_data='{} <<'.format(nav_text))] + buttons + [button('>>', callback_data='{} >>'.format(nav_text))]
        if count > 1000:
            buttons = [button('<<<', callback_data='{} <<<'.format(nav_text))] + buttons + [button('>>>', callback_data='{} >>>'.format(nav_text))]
        return buttons

    def main_menu(self, source, id):
        return [
                [button('Volumes', callback_data='vls {} {} 0 -'.format(source, id))],
                [button('Download', callback_data='d {} {}'.format(source, id))]
            ]

    async def load_mangalib_book(self, session, id, new=False):
        from_session = session.get('mangalib')
        if from_session is None:
            from_session = {}
            session['mangalib'] = from_session
        book = from_session.get(id) if not new else None
        if not book:
            book = await MangaLibBook(id).load()
            if book:
                from_session[id] = book
        return book if book.loaded else None

    async def send_manga(self, chat_id, source, id, thumbnail, name, other_name, lang, description, chapters, volumes):
        await self.bot.photo(thumbnail, chat_id=chat_id, caption='{}\n{}[{}]\n{}\nVolumes: {}\nChapters: {}'.format(name, other_name, lang, description, len(volumes), len(chapters)),
             parse_mode='HTML', reply_markup=markup(self.main_menu(source, id))).send()

    async def send_mangalib(self, chat_id, id, session):
        book = await self.load_mangalib_book(session, id, True)
        if book:
            info = await book.info
            await self.send_manga(chat_id, 'mangalib', id, book.thumbnail, info['name'], info['rus_name'], book.lang, info['summary'].replace('
', ''), book.chapters, book.volumes)

    async def load_all_chapters(self, message, book, filename):
        msg = StatusMessage(self.bot, message, 'Loading...')
        chapter_count = len(book.chapters)
        await msg.next('Loading {} chapters...'.format(chapter_count))
        async def status_chapters(num):
            await msg.next('Chapters loaded: {}/{}'.format(chapter_count - num, chapter_count))
        pictures = await book.load_chapters(status_chapters)
        pic_count = len(pictures)
        await msg.next('Loading {} pictures...'.format(pic_count))
        async def status_pictures(num):
            await msg.next('Pictures loaded: {}/{}'.format(num, pic_count))
        callback_pic = Clock(status_pictures, self.callback_timesleep)
        filename = '{}_{}_{}'.format(msg.chat_id, msg.message_id, filename)
        await asyncio.gather(self.composer.pics2pdf(pictures, filename, callback_pic.set_args), callback_pic.start(lambda n: n < pic_count - 1))
        async def status_uploading(num, all_):
            await msg.next('Uploading: {} %'.format(int(num/all_*100)))
        await self.send_via_telethon(filename, msg.chat_id, status_uploading)
        await msg.next('Uploaded!!!')

    async def back_to_main(self, source, id, chat_id, message_id):
        await self.bot.editreplymarkup(chat_id=chat_id, message_id=message_id, reply_markup=markup(self.main_menu(source, id))).send()

    async def load_all_chapters_from_mangalib(self, message, id, session):
        book = await self.load_mangalib_book(session, id)
        if book:
            await self.load_all_chapters(message, book, id + '.pdf')

    async def send_via_telethon(self, file, chat_id, progress_callback):
        callback = Clock(progress_callback, self.callback_timesleep)
        token = str(random_token())
        async def send_file(telethon):
            self.set_file_to_send(token, chat_id)
            if not self.bot_name:
                await self.set_bot_name()
            await telethon.send_file(self.bot_name, file, caption=token, progress_callback=callback.set_args)
            callback.stop()
        async with TelegramClient(StringSession(self.telethon_session), self.telethon_api_id, self.telethon_api_hash) as telethon:
            await asyncio.gather(send_file(telethon), callback.start())

    def set_file_to_send(self, token, chat_id):
        self.files[token] = {'chat_id': chat_id}

    def get_file_to_send(self, token):
        return self.files.get(token)

    async def send_file_by_token(self, file_id, token):
        unfile = self.get_file_to_send(token)
        if unfile:
            await self.bot.document(file_id, unfile['chat_id']).send()

    async def content_list(self, chat_id, message_id, id, page, source, volumes, turn=None):
        lines_count = 0
        lines = []
        for vol in volumes:
            lines.append(vol)
            if vol.choosen:
                lines.extend(vol.chapters)
                lines_count += (2 + len(vol.chapters))
            else:
                lines_count += 1
        if turn:
            pages = lines_count // self.per_page + 1
            vector = self.nav_codes(turn)
            start_page = pages + page + vector if page + vector < 0 else page + vector if page + vector < pages else page + vector - pages
        else:
            start_page = page
        start = start_page * self.per_page
        end = None if start + self.per_page > lines_count else start + self.per_page
        buttons_lines = []
        for line in lines[start:end]:
            if line.type == 'chapter':
                buttons_lines.append([button('{} {}: {}'.format('✅' if line.choosen else '📑', line.id, line.title), callback_data='c{} {} {} {}'.format(0 if line.choosen else 1, source, id, line.id))])
            elif line.type == 'volume':
                buttons_lines.append([button('📁 Volume {}'.format(line.id), callback_data='v{} {} {} {}'.format(0 if line.choosen else 1, source, id, line.id))])
                if line.choosen:
                    buttons_lines.append([button('Choose all'.format(line.id), callback_data='c_all {} {} {}'.format(source, id, line.id))])
        buttons = [[button('< To main', callback_data='main mangalib {}'.format(id))]] + buttons_lines + [self.navbar(lines_count, 'vls mangalib {} {}'.format(id, start_page), [button(start_page + 1, callback_data='page {} {}'.format(start_page, self.per_page))])]
        await self.bot.editreplymarkup(chat_id=chat_id, message_id=message_id, reply_markup=markup(buttons)).send()

    async def volumes_mangalib(self, chat_id, message_id, id, page, turn, session):
        book = await self.load_mangalib_book(session, id)
        if book:
            await self.content_list(chat_id, message_id, id, page, 'mangalib', book.volumes_list, turn)

    #async def set_volume_choose(chat, i)

class Clock:
    def __init__(self, async_callback, delta):
        self.callback = async_callback
        self.delta = delta
        self.args = None
        self.is_running = True

    def set_args(self, *args):
        self.args = args

    async def start(self, while_=None):
        while self.is_running and not (while_ and self.args and not while_(*self.args)):
            if self.args:
                await self.callback(*self.args)
            await asyncio.sleep(self.delta)

    def stop(self):
        self.is_running = False


import eikon as ek
import asyncio as asyncio
from IPython.display import display
import pandas as pd
import twitter

print("Python will now attempt to submit tweets to twitter...")

print("Connecting to Twitter API")
#Twitter API https://github.com/bear/python-twitter
api = twitter.Api(consumer_key='HIDDEN',
                      consumer_secret='HIDDEN',
                      access_token_key='HIDDEN',
                      access_token_secret='HIDDEN')

print("Connecting to Refinitiv API")
ek.set_app_key('HIDDEN')

streaming_prices = ek.StreamingPrices(
    instruments = ['BTC=', '.SPX', 'SPY', 'VXX', 'TLT.O', 'GLD', 'SLV', 'BBY'],
    fields   = ['CF_LAST', 'CF_BID','CF_ASK','OPEN_PRC', 'CF_HIGH','CF_LOW', 'CF_CLOSE', 'TR.TSVWAP', 'OPINT_1', 'OPINTNC']
)

streaming_prices.open()

df = streaming_prices.get_snapshot(
    instruments = ['BTC=', '.SPX', 'SPY', 'VXX', 'BBY'],
    fields   = ['CF_LAST','OPINTNC','OPINT_1']
)

status = api.PostUpdate("{0}".format(df))

print("Tweets submitted successfully!")

streaming_prices.close()


import RPi.GPIO as GPIO
import time
from configparser import ConfigParser
from helpers import init_all_loggers, get_main_bot_logger

logger = get_main_bot_logger()

def toggle_relay(relay_pin, duration):
    GPIO.output(relay_pin, GPIO.HIGH)
    time.sleep(duration)
    GPIO.output(relay_pin, GPIO.LOW)
    logger.info(f"Relay {relay_pin} activated")

def main(config):
    config_settings = config['SETTINGS']
    config_gpio = config['GPIO']
    init_all_loggers(log_level=config_settings.get("LOG_LEVEL"))

    TRIG = int(config_gpio.get("ULTRASONIC_TRIG"))
    ECHO = int(config_gpio.get("ULTRASONIC_ECHO"))
    RELAY = int(config_gpio.get("RELAY"))
    DURATION = int(config_settings.get("RELAY_DURATION"))

    logger.info(f"Starting up main....")
    try:
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)

        max_time = 0.04
        while True:
            GPIO.setup(TRIG,GPIO.OUT)
            GPIO.setup(ECHO,GPIO.IN)
            GPIO.setup(RELAY, GPIO.OUT)

            GPIO.output(TRIG,False)
            time.sleep(0.01)
            GPIO.output(TRIG,True)
            time.sleep(0.00001)
            GPIO.output(TRIG,False)

            pulse_start = time.time()
            timeout = pulse_start + max_time
            while GPIO.input(ECHO) == 0 and pulse_start < timeout:
                pulse_start = time.time()

            pulse_end = time.time()
            timeout = pulse_end + max_time
            while GPIO.input(ECHO) == 1 and pulse_end < timeout:
                pulse_end = time.time()

            pulse_duration = pulse_end - pulse_start
            distance = pulse_duration * 17000
            distance = round(distance, 2)

            if distance < 20:
                toggle_relay(relay_pin=RELAY, duration=DURATION)

    except Exception as e:
        logger.info(f"__Exception:Main__: {e}")
        GPIO.cleanup()

if __name__ == "__main__":
    config = ConfigParser()
    config.read("config.ini")

    main(config)


from django.urls import path
from . import views

app_name = 'subjects'

urlpatterns = [
    path("subjects/", views.subjects, name="subjects"),
    path("subjects/<int:pk>/", views.subject_detail, name="subject_detail"),
    path("subjects/add/", views.add, name="add"),

]


"""Creator information."""
from typing import Optional

class Creator:
    """Creator in ModelHistory and other COMBINE formats."""

    def __init__(
        self,
        familyName: str,
        givenName: str,
        email: str,
        organization: str,
        site: Optional[str] = None,
        orcid: Optional[str] = None,
    ):
        """Initialize Creator."""
        self.familyName = familyName
        self.givenName = givenName
        self.email = email
        self.organization = organization
        self.site = site
        self.orcid = orcid

    def __str__(self) -> str:
        """Get string representation."""
        return f"{self.familyName} {self.givenName} ({self.email}, {self.organization}, {self.site}, {self.orcid})"

    def __hash__(self) -> int:
        """Get hash."""
        return hash(str(self))

    def __eq__(self, other: object) -> bool:
        """Check for equality."""
        if not isinstance(other, Creator):
            return NotImplemented

        return (
            self.familyName == other.familyName
            and self.givenName == other.givenName
            and self.email == other.email
            and self.organization == other.organization
            and self.site == other.site
            and self.orcid == other.orcid
        )


from gmshparser.mesh_format_parser import MeshFormatParser
from gmshparser.mesh import Mesh
import io

def test_mesh_format_parser():
    parser = MeshFormatParser()
    mesh = Mesh()
    data = io.StringIO("4.1 0 8")
    parser.parse(mesh, data)
    assert mesh.get_version() == 4.1
    assert mesh.get_ascii() is True
    assert mesh.get_precision() == 8


from django.urls import path
from . import views

app_name = 'posts'  # обьявил namespace

urlpatterns = [
    path(
        '',
        views.index,
        name='index'
    ),
    path(
        'group/<slug:slug>/',
        views.group_posts,
        name='group_posts'
    ),
    #  Профайл пользователя
    path(
        'profile/<str:username>/',
        views.profile,
        name='profile'
    ),
    #  Просмотр записи
    path(
        'posts/<int:post_id>/',
        views.post_detail,
        name='post_detail'
    ),
    #  Создание записи
    path(
        'create/',
        views.post_create,
        name='post_create'
    ),
    path(
        'posts/<post_id>/edit/',
        views.post_edit,
        name='post_edit'
    ),
    # добавление комментария
    path(
        'posts/<int:post_id>/comment/',
        views.add_comment,
        name='add_comment'
    ),
    # посты на которые подписан авторизованный клиент
    path(
        'follow/',
        views.follow_index,
        name='follow_index'
    ),
    # подписка на пользователя
    path(
        'profile/<str:username>/follow/',
        views.profile_follow,
        name='profile_follow'
    ),
    # отписка от пользователя
    path(
        'profile/<str:username>/unfollow/',
        views.profile_unfollow,
        name='profile_unfollow'
    ),
]


import os
import cv2
import torch
import torchvision
from torchvision import transforms, datasets
import torch.nn as nn
import time
from torchvision import models
import numpy as np
from torch.utils.data.sampler import WeightedRandomSampler
from skimage import io, transform

torch.cuda.set_device(0)

class TransferModel(nn.Module):
    def __init__(self,
                base_model : str = 'resnet50',
                pretrain : bool = True,
                n_class : int = 4):
        super(TransferModel, self).__init__()
        self.base_model = base_model
        self.pretrain = pretrain
        self.n_class = n_class
        if self.base_model == 'resnet50':
            self.model = torchvision.models.resnet50(pretrained=True)
            n_features = self.model.fc.in_features
            fc = torch.nn.Linear(n_features, n_class)
            self.model.fc = fc
        else:
            # Use other models you like, such as vgg or alexnet
            pass
        self.model.fc.weight.data.normal_(0, 0.005)
        self.model.fc.bias.data.fill_(0.1)

    def forward(self, x):
        return self.model(x)

    def predict(self, x):
        return self.forward(x)

class Rescale(object):
    def __init__(self, output_size):
        assert isinstance(output_size, (int, tuple))
        self.output_size = output_size

    def __call__(self, image):
        h, w = image.shape[:2]
        if isinstance(self.output_size, int):
            if h > w:
                new_h, new_w = self.output_size * h / w, self.output_size
            else:
                new_h, new_w = self.output_size, self.output_size * w / h
        else:
            new_h, new_w = self.output_size

        new_h, new_w = int(new_h), int(new_w)

        img = transform.resize(image, (new_h, new_w), mode='constant')

        return img

def get_video_details(video_array, model):
    # video_array(frame_num, w, h, channel)
    crop = Rescale((224, 224))
    to_tensor = transforms.ToTensor()
    norm = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                std=[0.229, 0.224, 0.225])
    print(video_array.shape)
    preprocess_array = None
    results = None
    batch_size = 10
    batch_num = int(video_array.shape[0]/batch_size)
    for i, frame in enumerate(video_array):
        crop_image = crop(frame)
        tensor_image = to_tensor(crop_image).cuda()
        # print(tensor_image.shape)
        norm_image = norm(tensor_image)
        norm_image = norm_image.float()
        norm_image = norm_image.unsqueeze(0)
        if(preprocess_array == None):
            # print("new!")
            preprocess_array = norm_image
        else:
            # print("append!")
            preprocess_array = torch.cat([preprocess_array, norm_image], dim=0)
    print(preprocess_array.shape)

    for i in range(batch_num):
        if(results==None):
            results = model(preprocess_array[i*batch_size:(i+1)*batch_size])
        else:
            result_now = model(preprocess_array[i*batch_size:(i+1)*batch_size])
            results = torch.cat([results,result_now],axis = 0)

    if(results==None):
        results = model(preprocess_array[batch_num*batch_size:])
    elif(video_array.shape[0]-batch_size*batch_num >0):
        # print(preprocess_array[batch_num*batch_size:].shape)
        result_now = model(preprocess_array[batch_num*batch_size:])
        results = torch.cat([results,result_now],axis = 0)

    return results

def get_image_details(np_image,model):
    # image_array(w,h,channel)

    crop = Rescale((224, 224))
    to_tensor = transforms.ToTensor()
    norm = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                std=[0.229, 0.224, 0.225])

    crop_image = crop(np_image)
    tensor_image = to_tensor(crop_image).cuda()
    # print(tensor_image.shape)
    norm_image = norm(tensor_image)
    norm_image = norm_image.float()
    norm_image = norm_image.unsqueeze(0)

    result = model(norm_image)

    return result