def compute_cost(A2, Y, parameters):
    """
    Computes the cross-entropy cost given in equation (13)

    Arguments:
    A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
    Y -- "true" labels vector of shape (1, number of examples)
    parameters -- python dictionary containing your parameters W1, b1, W2 and b2

    Returns:
    cost -- cross-entropy cost given equation (13)
    """
    import numpy as np

    m = Y.shape[1]  # number of example

    # Compute the cross-entropy cost
    # logprobs = None
    cost = -(1 / m) * (np.sum(np.dot(Y, np.log(A2).T) + np.dot(1 - Y, np.log(1 - A2).T)))

    cost = np.squeeze(cost)  # makes sure cost is the dimension we expect.
    # E.g., turns [[17]] into 17
    assert (isinstance(cost, float))

    return cost


import os
import unittest
import pandas as pd
from .variables import VARIABLES

class FileTests(unittest.TestCase):

    def test_output_file_existence(self):
        """
        Tests if the path on output_file_path value exists and if is a str
        """
        entry_value = VARIABLES["output_file_path"]
        expected_value = True
        self.assertEqual(type(entry_value), str)
        self.assertEqual(os.path.exists(entry_value), expected_value)

class StandaloneTests:

    @staticmethod
    def _is_able_to_parse() -> bool:
        """
        Verifies if data_file_path and test_file_path are able to parse through
        pd.read_csv
        @rtype: bool
        @return: a boolean representing parse viability
        """
        data_file_path = VARIABLES["data_file_path"]
        test_file_path = VARIABLES["test_file_path"]
        try:
            pd.read_csv(data_file_path,
                        sep=',',
                        header=None,
                        skiprows=VARIABLES["data_file_skip_row"], )
            pd.read_csv(test_file_path,
                        sep=',',
                        header=None,
                        skiprows=VARIABLES["test_file_skip_row"], )
            return True
        except pd.errors.ParserError:
            return False

    @staticmethod
    def _number_of_columns_is(expected_number_of_columns: int) -> bool:
        """
        Verifies if data_file_path and test_file_path has the expected number
        of columns
        @param expected_number_of_columns: an integer representing expected number
        of columns
        @type expected_number_of_columns: int
        @rtype: bool
        @return: a boolean representing the data_file_path and test_file_path
        expected number of columns conformity
        """
        data_file_path = VARIABLES["data_file_path"]
        test_file_path = VARIABLES["test_file_path"]
        data_file_dataframe = pd.read_csv(data_file_path,
                                          sep=',',
                                          header=None,
                                          skiprows=VARIABLES["data_file_skip_row"], )
        test_file_dataframe = pd.read_csv(test_file_path,
                                          sep=',',
                                          header=None,
                                          skiprows=VARIABLES["test_file_skip_row"], )
        data_n_of_columns = len(data_file_dataframe.columns)
        test_n_of_columns = len(test_file_dataframe.columns)
        return data_n_of_columns == expected_number_of_columns and test_n_of_columns == expected_number_of_columns

    @staticmethod
    def test_non_expected_values(string: str, column_number: int) -> bool:
        """
        Verifies if {string} is a non-expected value of the {column_number} of expected_values_and_types
        @type string: str
        @type column_number: int
        @rtype: bool
        @param string: a string representing the supposedly non-expected value
        @param column_number: a int representing the column index related to expected_values_and_types
        @return: a boolean representing the non-expectation
        """
        expected_values_and_types = VARIABLES["expected_values_and_types"]
        expected_values = expected_values_and_types[column_number]
        return string in expected_values

    @staticmethod
    def test_non_expected_types(string: str, column_number: int) -> bool:
        """
        Verifies if {string} is a non-expected type of the {column_number} of expected_values_and_types
        @type string: str
        @type column_number: int
        @rtype: bool
        @param string: a string representing the supposedly non-expected type
        @param column_number: a int representing the column index related to expected_values_and_types
        @return: a boolean representing the non-expectation
        """
        expected_values_and_types = VARIABLES["expected_values_and_types"]
        expected_type = expected_values_and_types[column_number]
        try:
            expected_type(string)
            return True
        except ValueError:
            return False

if __name__ == '__main__':
    unittest.main()


import os
import sys
import signal
import re
import shlex
import inspect
import platform as _platform
from copy import deepcopy
from hashlib import sha1
from importlib import import_module as importModule
from types import ModuleType

try:
    import threading
except ImportError as _pex:
    raise ImportError('Python must have threading support') from _pex

from waflib import Utils as wafutils
from waflib.ConfigSet import ConfigSet
from zm.pyutils import stringtype, maptype, struct, _unicode, _encode
from zm.error import ZenMakeError, ZenMakeProcessTimeoutExpired
from zm.buildconf.types import ConfNode

_joinpath = os.path.join

WINDOWS_RESERVED_FILENAMES = frozenset((
    'CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5',
    'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5',
    'LPT6', 'LPT7', 'LPT8', 'LPT9'
))

_USABLE_WHITESPACE = ' \t\n\r\v'

_RE_UNSAFE_FILENAME_CHARS = re.compile(r'[^-\w.]', re.UNICODE)
_RE_TOLIST = re.compile(r"""((?:[^\s"']|"[^"]*"|'[^']*')+)""", re.ASCII)
_RE_SUBST_VARS = re.compile(r"\${1,2}(\w+)|\${1,2}\{\s*(\w+)\s*\}", re.ASCII)
_RE_SUBST_BUILTINVARS = re.compile(r"\$\((\s*(\w+)\s*)\)", re.ASCII)
_RE_VERSION = re.compile(r"(\d+|[a-zA-Z]+)")

def platform():
    """
    Return current system platform. It is always 'windows' for MS Windows.
    """
    result = wafutils.unversioned_sys_platform()
    if result.startswith('win32'):
        result = 'windows' # pragma: no cover
    return result

PLATFORM = platform()

def hostOS():
    """
    Return current host operating system base name.
    It is 'windows' for MS Windows, MSYS2 and cygwin;
    'linux' for GNU/Linux; 'macos' for Mac OS, etc.
    """

    selector = {
        'cygwin' : 'windows',
        'msys'   : 'windows',
        'darwin' : 'macos',
    }

    return selector.get(PLATFORM, PLATFORM)

def getDefaultDestOS():
    """
    Return value of current platform suitable for Waf env.DEST_OS
    """

    return 'win32' if PLATFORM == 'windows' else PLATFORM

def getDestBinFormatByOS(destOS):
    """
    Return the binary format based on the platform name.
	Returns 'elf' if nothing is found.
    """

    if destOS == 'darwin':
        return 'mac-o'

    if destOS in ('win32', 'cygwin', 'uwin', 'msys', 'windows'):
        return 'pe'

    return 'elf'

def distroInfo():
    """
    Return dict of info from /etc/os-release or /usr/lib/os-release.
    Returns {} if failed
    """

    result = {}

    filePath = "/etc/os-release"
    if not os.path.isfile(filePath):
        filePath = "/usr/lib/os-release"
    if not os.path.isfile(filePath):
        return result

    import csv
    try:
        with open(filePath) as file:
            reader = csv.reader(file, delimiter = "=")
            result = { row[0]:row[1] for row in reader if row}
    except OSError:
        pass

    return result

def toPosixArchName(name):
    """
    Get 'standard' POSIX names for machine architecture type.
    It means that for 'amd64' it returns 'x86_64', etc.
    """

    name = name.lower()
    namesMap = {
        'x86_64' : 'x86_64',
        'amd64'  : 'x86_64',
        'i386'   : 'i386',
        'x86'    : 'i386',
    }

    return namesMap.get(name, name)

def unixLibDirPostfix():
    """
    Return postfix of lib dirs on UNIX
    """

    isdir = os.path.isdir

    # Debian, Ubuntu, etc
    isDebianLike = PLATFORM == 'linux' and os.path.isfile('/etc/debian_version')
    if isDebianLike:
        # at first try to detect without call dpkg-architecture
        pattern = '%s-linux-gnu'
        hostArch = _platform.machine().lower()

        params = [
            (('x86_64', 'amd64'), 'x86_64'),
            (('i386', 'i486', 'i586', 'i686'), 'i386'),
        ]
        for variants,  arch in params:
            dirname = pattern % arch
            if hostArch in variants and isdir('/usr/lib/' + dirname):
                return '/%s' % dirname

        try:
            result = runCmd(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
                            captureOutput = True)
            if result.exitcode == 0:
                return '/%s' % result.stdout.strip()
        except ZenMakeError:
            pass

    if PLATFORM in ('freebsd', 'irix'):
        return ''

    if os.sep == '/' and _platform.architecture()[0] == '64bit' and \
        isdir('/usr/lib64') and not os.path.exists('/usr/lib32'):

        return '64'

    return ''

def macosFrameworkHeadersDir(fwkroot, fwkname):
    """
    Return path to MacOS framework headers
    """

    return _joinpath(fwkroot, '%s.framework' % fwkname, 'Headers')

def macosFrameworkDynLibPath(fwkroot, fwkname):
    """
    Return path to MacOS framework dynamic library
    """

    return _joinpath(fwkroot, '%s.framework' % fwkname, fwkname)

class Version:
    """
    Class to compare application/package versions.
    Based on the algo to compare RPM package versions.
    """

    __slots__ = ('_strver', '_fields', '_hashval')

    def __init__(self, version):
        self._strver = version
        self._hashval = hash(version)

        fields = _RE_VERSION.findall(version)
        self._fields = [int(x) if x.isdigit() else x for x in fields]

    def __hash__(self):
        return self._hashval

    def __str__(self):
        return self._strver

    def __repr__(self):
        return '%s <%r>' % (self._strver, self._fields)

    def __eq__(self, other):
        return self._strver == other

    def __ne__(self, other):
        return not self == other

    def __gt__(self, other):
        return self._greaterThan(other)

    def __ge__(self, other):
        return self == other or self._greaterThan(other)

    def __lt__(self, other):
        return not (self == other or self._greaterThan(other))

    def __le__(self, other):
        return self == other or not self._greaterThan(other)

    def _greaterThan(self, other):

        # pylint: disable = protected-access

        if not isinstance(other, Version):
            if isinstance(other, stringtype):
                other = Version(other)
            else:
                return NotImplemented # pragma: no cover

        # optimization
        if self._strver == other._strver:
            return False

        for left, right in zip(self._fields, other._fields):

            # In the case of a mismatch where one field is numeric and
            # one is alphabetic, the numeric field is always
            # considered greater (newer).
            isLeftInt  = isinstance(left, int)
            if isLeftInt != isinstance(right, int):
                return isLeftInt

            if left != right:
                return left > right

        # In the case where one string runs out of fields,
        # the other is always considered greater (newer)
        return len(self._fields) > len(other._fields)

md5                = wafutils.md5
readFile           = wafutils.readf
hashOrdObj         = wafutils.h_list
hexOfStr           = wafutils.to_hex
Timer              = wafutils.Timer
subprocess         = wafutils.subprocess

def mayHaveSubstVar(strval):
    """
    Return True if the strval MAY have substitution variable.
    Return False if the strval has no substitution variable.
    """
    return '$' in strval

def substVars(strval, svarGetter, envVars = None, foundEnvVars = None):
    """
	Return string with $VAR/${VAR} replaced by the value of VAR taken by svarGetter
    """

    if not mayHaveSubstVar(strval): # optimization
        return strval

    if envVars is None:
        envVars = {}

    def replaceVar(match):
        foundName = match.group(1,2)
        foundName = [x for x in foundName if x][0]

        origName = match.group(0)
        foundVal = None
        useEnv = origName[:2] != '$$'
        if useEnv:
            foundVal = envVars.get(foundName)
            if foundEnvVars is not None:
                foundEnvVars.add(foundName)

        if foundVal is None:
            foundVal = svarGetter(foundName)

        if foundVal is None:
            # leave it for Waf if it doesn't start with $$
            foundVal = "${%s}" % foundName if useEnv else ""

        return foundVal

    return _RE_SUBST_VARS.sub(replaceVar, strval)

def substBuiltInVars(strval, svars, check = True, notHandled = None):
    """
	Return string with $(VAR) replaced by the value of VAR taken from a dict
    """

    if check and not mayHaveSubstVar(strval): # optimization
        return strval

    def replaceVar(match):
        foundName = match.group(1)

        if notHandled is not None:
            result = svars.get(foundName)
            if result is None:
                notHandled.add(foundName)
                return match.group(0)
            return result

        return svars.get(foundName, match.group(0))

    return _RE_SUBST_BUILTINVARS.sub(replaceVar, strval)

def substBuiltInVarsInParam(val, svars, splitListOfStrs = True, notHandled = None):
    """
    Return value with handled substitutions from a param of 'str',
    'list-of-strs' types or from a param of 'dict' with params of such types.
    """

    if not val:
        return val

    if isinstance(val, stringtype):
        return substBuiltInVars(val, svars, notHandled = notHandled)

    # This method should not allocate new memory for existing containers
    # in val if it can be avoided.

    extraArgs = {
        'svars': svars,
        'splitListOfStrs': splitListOfStrs,
        'notHandled': notHandled,
    }

    if isinstance(val, list):

        if not splitListOfStrs or any(not isinstance(x, stringtype) for x in val):
            result = [substBuiltInVarsInParam(x, **extraArgs) for x in val]
        else:
            # all items are strings
            result = []
            for item in val:
                if not mayHaveSubstVar(item):
                    result.append(item)
                    continue

                newVal = substBuiltInVars(item, svars, check = False,
                                            notHandled = notHandled)
                if not any(c in item for c in _USABLE_WHITESPACE):
                    result.extend(toList(newVal))
                else:
                    result.append(newVal)

        # use existing list and drop the new created one
        val[:] = result
        return val

    if isinstance(val, maptype):
        for k, v in val.items():
            val[k] = substBuiltInVarsInParam(v, **extraArgs)
        return val

    if isinstance(val, ConfNode):
        val.val = substBuiltInVarsInParam(val.val, **extraArgs)
        return val

    # buildconf should not use tuples for public elements
    assert not isinstance(val, tuple)
    return val

_HashAlgo = sha1

def setDefaultHashAlgo(algo):
    """
    Set default hash algo. Can be 'sha1' or 'md5'.
    """

    # pylint: disable = global-statement
    global _HashAlgo
    if algo == 'md5':
        _HashAlgo = wafutils.md5 = md5
    else:
        _HashAlgo = wafutils.md5 = sha1

def defaultHashAlgo():
    """
    Get default hash algo. Can be 'sha1' or 'md5'.
    """

    return _HashAlgo

# Since python 3.4 non-inheritable file handles are provided by default
if hasattr(os, 'O_NOINHERIT') and sys.hexversion < 0x3040000:
    def _hashFile(hashobj, path):
        # pylint: disable = no-member
        try:
            fd = os.open(path, os.O_BINARY | os.O_RDONLY | os.O_NOINHERIT)
        except OSError as pex:
            raise OSError('Cannot read from %r' % path) from pex

        with os.fdopen(fd, 'rb') as file:
            result = True
            while result:
                result = file.read(200000)
                hashobj.update(result)
        return hashobj
else:
    def _hashFile(hashobj, path):

        with open(path, 'rb') as file:
            result = True
            while result:
                result = file.read(200000)
                hashobj.update(result)
        return hashobj

def hashFile(path):
    """ Hash file by using sha1/md5 """
    _hash = _HashAlgo()
    return _hashFile(_hash, path).digest()

def hashFiles(paths):
    """
    Hash files from paths by using sha1/md5.
    Order of paths must be constant. Simple way to do it is to sort the path items.
    """

    # Old implementation (slower and less accurate):
    #_hash = 0
    #for path in paths:
    #    _hash = hashOrdObj((_hash, readFile(path, 'rb')))
    #return _hash

    _hash = _HashAlgo()
    for path in paths:
        _hashFile(_hash, path)
    return _hash.digest()

class BuildConfFunc(object):
    """
    Class to store a func from buildconf
    """

    __slots__ = ('func', 'name', '_filepath', '_startLN')

    def __init__(self, func):
        self.func = func
        self.name = func.__name__
        self._filepath = None
        self._startLN = None

    @property
    def filepath(self):
        """ Get file path where the function is """

        if self._filepath is None:
            func = self.func
            # the inspect.getabsfile exists but not documented
            filepath = inspect.getsourcefile(func) or inspect.getfile(func)
            if not os.path.isabs(filepath):
                filepath = os.path.abspath(filepath)
            self._filepath = filepath

        return self._filepath

    @property
    def startLN(self):
        """ Get line number in the file where the function is """

        if self._startLN is None:
            self._startLN = inspect.getsourcelines(self.func)[1]

        return self._startLN

    def __repr__(self):
        _repr = "%s:%s:%d" % (self.filepath, self.name, self.startLN)
        return _repr

if PLATFORM == 'windows':
    def lchown(path, user = -1, group = -1):
        """
        Change the owner/group of a path, raises an OSError if the
        ownership change fails.
        Do nothing on MS Windows.
        """

        # pylint: disable = unused-argument
        return
else:

    def lchown(path, user = -1, group = -1):
        """
        Change the owner/group of a path, raises an OSError if the
        ownership change fails.
        """

        import pwd
        import grp

        result = [user, group]
        for name, idx in (('user', 0), ('group', 1)):
            func = pwd.getpwnam if name == 'user' else grp.getgrnam

            if isinstance(result[idx], stringtype):
                try:
                    entry = func(result[idx])
                except KeyError as pex:
                    raise OSError('chown: unknown %s %r' % (name, user)) from pex
                if not entry: # just in case
                    raise OSError('chown: unknown %s %r' % (name, user)) from pex
                result[idx] = entry[2]

        return os.lchown(path, result[0], result[1])

wafutils.lchown = lchown

def normalizeForDefine(s):
    """
	Converts a string into an identifier suitable for C defines.
    """
    if s[0].isdigit():
        s = '_%s' % s
    return wafutils.quote_define_name(s)

def normalizeForFileName(s, spaceAsDash = False):
    """
    Convert a string into string suitable for file name
    """
    s = _unicode(s).strip()
    if spaceAsDash:
        s = s.replace(' ', '-')
    else:
        s = s.replace(' ', '_')
    s = _encode(_RE_UNSAFE_FILENAME_CHARS.sub('', s))
    if PLATFORM == 'windows' and s.upper() in WINDOWS_RESERVED_FILENAMES:
        s = '_%s' % s
    return s

def stripQuotes(val):
    """
    Strip quotes ' or " from the begin and the end of a string but do it only
    if they are the same on both sides.
    """

    if not val:
        return val

    if len(val) < 2:
        return val

    first = val[0]
    last = val[-1]
    if first == last and first in ("'", '"'):
        return val[1:-1]

    return val

def toListSimple(val):
    """
    Converts a string argument to a list by splitting it by spaces.
    Returns the object if not a string
    """
    if not isinstance(val, stringtype):
        return val
    return val.split()

def toList(val):
    """
    Converts a string argument to a list by splitting it by spaces.
    This version supports preserving quoted substrings with spaces but it works
    slower than toListSimple does.
    Returns the object if not a string
    """
    if not isinstance(val, stringtype):
        return val

    if not ('"' in val or "'" in val): # optimization
        return val.split()

    # shlex.split worked quite well but did it too slowly

    # Actually manual algorithm should be faster but python regexp engine uses
    # some C code and therefore it works faster.
    return [stripQuotes(x) for x in _RE_TOLIST.split(val)[1::2]]

def uniqueListWithOrder(lst):
    """
    Return new list with preserved the original order of the list.
    Each element in lst must be hashable.
    """

    # pylint: disable = simplifiable-condition

    used = set()
    return [x for x in lst if x not in used and (used.add(x) or True)]

def uniqueDictListWithOrder(lst):
    """
    Return new list with preserved the original order of the list.
    It works only with list of dicts.
    """

    used = set()
    result = []
    for elem in lst:
        key = frozenset(elem.items())
        if key in used:
            continue
        result.append(elem)
        used.add(key)

    return result

def envValToBool(rawVal):
    """
    Return env val as native bool value.
    Returns False if not recognized.
    """

    result = False
    if rawVal:
        try:
            # value from os.environ is a string but it may be a digit
            result = bool(int(rawVal))
        except ValueError:
            result = rawVal in ('true', 'True', 'yes')

    return result

def cmdHasShellSymbols(cmdline):
    """
    Return True if string 'cmdline' contains some specific shell symbols
    """
    return any(s in cmdline for s in ('<', '>', '&&', '||'))

def copyEnv(env):
    """
    Make shallow copy of ConfigSet object
    """

    newenv = ConfigSet()
    # copy only current table whithout parents
    newenv.table = env.table.copy()
    parent = getattr(env, 'parent', None)
    if parent is not None:
        newenv.parent = parent
    return newenv

def deepcopyEnv(env, filterKeys = None):
    """
    Make deep copy of ConfigSet object

    Function deepcopy doesn't work with ConfigSet and ConfigSet.detach
    doesn't make deepcopy for already detached objects.
    """

    # keys() returns all keys from current env and all parents
    keys = env.keys()
    if filterKeys is not None:
        keys = [ x for x in keys if filterKeys(x) ]

    newenv = ConfigSet()
    newenv.table = { k:deepcopy(env[k]) for k in keys }
    return newenv

def configSetToDict(configSet):
    """
    Convert Waf ConfigSet to python dict
    """
    result = configSet.get_merged_dict()
    result.pop('undo_stack', None)
    return result

def addRTLibPathsToOSEnv(paths, osenv):
    """
    Add runtime lib paths to OS environment depending on type of OS.
    Returns the osenv parameter.
    """

    def add(osenv, envname, vals):
        vals = os.pathsep.join(vals)
        paths = osenv.get(envname, '')
        if paths:
            paths = os.pathsep + paths
        osenv[envname] = vals + paths

    paths = toList(paths)
    if PLATFORM == 'windows':
        add(osenv, 'PATH', paths)
    else:
        add(osenv, 'LD_LIBRARY_PATH', paths)
        if PLATFORM == 'darwin':
            add(osenv, 'DYLD_LIBRARY_PATH', paths)

    return osenv

def mksymlink(src, dst, force = True):
    """
    Make symlink, force delete if destination exists already
    """
    if force and os.path.lexists(dst):
        os.unlink(dst)

    _mksymlink = getattr(os, "symlink", None)
    if callable(_mksymlink):
        _mksymlink(src, dst)
        return

    raise NotImplementedError

def printInWorkStatus(title = '', end = False):
    """
    Print 'in work' status like emerge does it.
    """

    statusSymbols = ('\\', '|', '/', '-',)

    try:
        printInWorkStatus.index += 1
        if printInWorkStatus.index >= len(statusSymbols):
            printInWorkStatus.index = 0
    except AttributeError:
        printInWorkStatus.index = 0

    symbols = '' if end else title + ' ' + statusSymbols[printInWorkStatus.index]
    sys.stdout.write("\r" + symbols)
    sys.stdout.flush()

def _loadPyModuleWithoutImport(name):

    # In this case we should compile python file manually
    # WARN: It has no support for all python module attributes.

    from zm.pypkg import PkgPath

    module = ModuleType(name)
    filename = name.replace('.', os.path.sep)

    # try to find module
    isPkg = False
    for path in sys.path:
        modulePath = _joinpath(path, filename)
        path = PkgPath(modulePath + '.py')
        if path.isfile():
            modulePath = path
            break
        path = PkgPath(_joinpath(modulePath, '__init__.py'))
        if path.isfile():
            modulePath = path
            isPkg = True
            break
    else:
        raise ImportError('File %r not found' % filename)

    try:
        code = modulePath.read()
    except EnvironmentError as pex:
        raise ZenMakeError('Could not read the file %r' % str(modulePath)) from pex

    module.__file__ = modulePath.path

    # pylint: disable = exec-used
    exec(compile(code, modulePath.path, 'exec'), module.__dict__)

    # From https://docs.python.org/3/reference/import.html:
    #
    # The module’s __package__ attribute should be set. Its value must be
    # a string, but it can be the same value as its __name__. If the attribute
    # is set to None or is missing, the import system will fill it in with
    # a more appropriate value. When the module is a package, its __package__
    # value should be set to its __name__. When the module is not a package,
    # __package__ should be set to the empty string for top-level modules, or
    # for submodules, to the parent package’s name.
    if isPkg:
        module.__package__ = name
    else:
        lastdotpos = name.rfind('.')
        module.__package__ = '' if lastdotpos < 0 else name[0:lastdotpos]
    return module

def loadPyModule(name, dirpath = None, withImport = True):
    """
    Load python module by name.
    Param 'dirpath' is optional param that is used to add/remove path into sys.path.
    Module is not imported (doesn't exist in sys.modules) if withImport is False.
    With withImport = False you should control where to store returned module object.
    """

    if withImport:
        loadModule = importModule
    else:
        loadModule = _loadPyModuleWithoutImport

    if dirpath:
        sys.path.insert(0, dirpath)
        try:
            module = loadModule(name)
        finally:
            sys.path.pop(0)
    else:
        module = loadModule(name)
    return module

class SafeCounter(object):
    """
    Thread safe counter
    """

    def __init__(self):
        self._value = 0
        self._lock = threading.Lock()

    def increment(self, val = 1):
        ''' Increment value with lock '''
        with self._lock:
            self._value += val
            return self._value

    @property
    def value(self):
        ''' Get value '''
        return self._value

    @value.setter
    def value(self, val):
        ''' Set value with lock '''
        with self._lock:
            self._value = val

ProcCmdResult = struct('ProcCmdResult', 'exitcode, stdout, stderr')

class ProcCmd(object):
    """
    Class to run external command in a subprocess
    """

    def __init__(self, cmdLine, shell = False, captureOutput = False,
                                        stdErrToOut = True, outCallback = None):

        """
        Parameter outCallback can be used to handle stdout/stderr line by line
        without waiting for a process to exit. Also if outCallback is not None
        then it means that captureOutput is True. If stdErrToOut is True it means
        that captureOutput is True as well.
        """

        self._origCmdLine = cmdLine

        cmdAsStr = isinstance(cmdLine, stringtype)
        if PLATFORM == 'windows':
            # On Windows, if args is a sequence, it will be converted to a
            # string in 'subprocess' module regardless of 'shell' value.
            # So on Windows cmdLine can be used as a string in any case.
            if not shell:
                shell = cmdHasShellSymbols(cmdLine)
        else:
            if shell and not cmdAsStr:
                cmdLine = ' '.join(cmdLine)
            elif not shell and cmdAsStr:
                shell = cmdHasShellSymbols(cmdLine)
                if not shell:
                    cmdLine = shlex.split(cmdLine)

        self._cmdLine = cmdLine
        self._outCallback = outCallback
        self._proc = None
        self._timeoutExpired = False
        self._popenArgs = {
            'shell' : shell,
            'stdout' : None,
            'stderr' : None,
            'universal_newlines' : True,
        }

        if captureOutput or outCallback is not None:
            self._popenArgs['stdout'] = subprocess.PIPE
            self._popenArgs['stderr'] = subprocess.PIPE

        if stdErrToOut:
            self._popenArgs['stdout'] = subprocess.PIPE
            self._popenArgs['stderr'] = subprocess.STDOUT

        # start_new_session was added in python 3.2
        # Use 'start_new_session' to change the process(forked) group id to itself
        # so os.killpg with proc.pid can be used.
        # This parameter does nothing on Windows.
        self._popenArgs['start_new_session'] = True

    def _communicate(self):

        callback = self._outCallback
        if callback is None:
            stdout, stderr = self._proc.communicate()
            return ProcCmdResult(self._proc.returncode, stdout, stderr)

        # It is simple and actually not optimal algo but it works for ZenMake needs
        proc = self._proc
        while True:
            noData = True
            if proc.stdout:
                line = proc.stdout.readline()
                if line:
                    noData = False
                    callback(line, err = False)
            if proc.stderr:
                line = proc.stderr.readline()
                if line:
                    noData = False
                    callback(line, err = True)
            if noData and proc.poll() is not None:
                break

        if proc.stdout:
            proc.stdout.close()
        if proc.stderr:
            proc.stderr.close()
        return ProcCmdResult(proc.returncode, None, None)

    def run(self, cwd = None, env = None, timeout = None):
        """
        Run command.
        Returns ProcCmdResult.
        """

        kwargs = self._popenArgs
        kwargs.update({
            'cwd' : cwd,
            'env' : env,
        })

        def killProc(proc):
            if kwargs.get('start_new_session') and hasattr(os, 'killpg'):
                # If 'shell' is true then killing of current process is killing of
                # executed shell but not childs.
                # Unix only.
                os.killpg(proc.pid, signal.SIGKILL)
            else:
                proc.kill()

        timer = None
        try:
            self._proc = subprocess.Popen(self._cmdLine, **kwargs)

            if timeout is not None:
                self._timeoutExpired = False

                def killProcTimeout(self):
                    killProc(self._proc)
                    self._timeoutExpired = True

                timer = threading.Timer(timeout, killProcTimeout, args = [self])
                # allow entire program to exit on unexpected exception like KeyboardInterrupt
                timer.daemon = True
                timer.start()

            result = self._communicate()

            if self._timeoutExpired:
                raise ZenMakeProcessTimeoutExpired(self._origCmdLine, timeout,
                                                    result.stdout, result.stderr)

        except (OSError, subprocess.SubprocessError) as ex:
            raise ZenMakeError(str(ex)) from ex
        except KeyboardInterrupt:
            if self._proc:
                killProc(self._proc)
            raise
        finally:
            if timer:
                timer.cancel()

            # release Popen object
            self._proc = None

        return result

def runCmd(cmdLine, cwd = None, env = None, shell = False, timeout = None,
            captureOutput = False, stdErrToOut = False, outCallback = None):
    """
    Run external command in a subprocess.
    Parameter outCallback can be used to handle stdout/stderr line by line
    without waiting for a process to exit. Also if outCallback is not None then
    it means that captureOutput is True. If stdErrToOut is True it means
    that captureOutput is True as well.
    Returns ProcCmdResult. If
    """

    # pylint: disable = too-many-arguments

    procCmd = ProcCmd(cmdLine, shell, captureOutput, stdErrToOut, outCallback)
    return procCmd.run(cwd, env, timeout)


import numpy as np
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split

#빙어와 도미가 합쳐진 데이터들
fish_length = [25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7,
31.0, 31.0, 31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5,
34.0, 34.0, 34.5, 35.0, 35.0, 35.0, 35.0, 36.0, 36.0, 37.0,
38.5, 38.5, 39.5, 41.0, 41.0, #여기 까지가 35개
9.8,10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0]

fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0,
475.0, 500.0, 500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0,
575.0, 685.0, 620.0, 680.0, 700.0, 725.0, 720.0, 714.0, 850.0, 1000.0,
920.0, 955.0, 925.0, 975.0, 950.0, #여기 까지가 35개
6.7, 7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]

#도미와 빙어 데이터를 합친다.
fish_data = [[l, w] for l, w in zip(fish_length, fish_weight)]
fish_target = [1]*35 + [0]*14 #도미 35마리 #빙어 14마리
# 훈련 데이터 입출력 35개
train_input = fish_data[:35]
train_target = fish_target[:35]
# 시험 데이터 입출력 35개
test_input = fish_data[35:]
test_target = fish_target[35:]

#주어진 데이터로 학습 시작
kn = KNeighborsClassifier()
KN = kn.fit(train_input, train_target)

#학습 결과 값 출력
print(kn.score(test_input,test_target))

#훈련데이터를 섞어주기위해기존 1차원 배열(List)을 다차원 배열(Array)로 바꿈
input_arr = np.array(fish_data)
target_arr = np.array(fish_target)

input(input_arr)

#데이터를 섞어줌

np.random.seed(42) #왜 42지?
index = np.arrange(49)
np.random.shuffle(index)

np.random.shuffle(index) #내가 볼려고 프린트한거
#index를 랜덤으로 생성하여 도미빙어가 구분되어있는 데이터를 섞어줌
train_input = input_arr[index[:35]]
train_target = target_arr[index[:35]]

test_input = input_arr[index[35:]]
test_target = target_arr[index[35:]]
#데이터를 나누고 확인하기 잘섞여있는지 그래프로 알 수 있음

plt.scatter(train_input[:,0], train_input[:,1])
plt.scatter(train_input[:,0], train_input[:,1])
plt.xlabel('length')
plt.xlabel('weight')
plt.show()

kn = kn.fit(train_input, train_target)
#훈련세트와 데이터세트의 유사성 나옴 1 에 가까울 수 록 유사함 but 항상 1이 나오진 않음
print(kn.score(test_input, test_target))

#넘파이로 데이터 준비 #Data_Size x [길이,무게] // Data_Size 행 x 2 열
fish_data = np.column_stack((fish_length, fish_weight))

fish_target = np.concatenate(np.ones(35),np.zeros(14))

train_input, test_input, train_target, test_target = train_test_split(
    fish_data,fish_target,stratify=fish_target, random_state=42) # shuffle seed = 42

#사이킷런으로 데이터를 나눈다.
kn.KNeighborsClassifier()
kn.fit(train_input,train_target)
print(kn.score(test_input,test_target))
#특이한 도미를 추가한다.
print(kn.predict([25,100]))

#[25,150]을 판단하는데 사용된 점들의 index와 그들간의 거리 distancs
distances, index = kn.kneighbors([[25,150]])

plt.scatter(train_input[:,0], train_input[:,1])
plt.scatter(25,150,marker="^")
plt.scatter(train_input[index,0],
train_input[index,1],marker ='D')
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

#기준을 맞춰준다.

plt.scatter(train_input[:,0], train_input[:,1])
plt.scatter(25,150,marker="^")
plt.scatter(train_input[index,0],
train_input[index,1],marker ='D')
plt.xlim((0,1000))
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

#표준점수로 변경
mean = np.mean(train_input,axis=0)
std = np.std(train_input, axis=0)

print(mean, std)

train_scaled = (train_input - mean) / std
#수상힌 도미 다시 표시하기
new = ([25,150] - mean) / std

plt.scatter(train_scaled[:0], train_scaled[:,1])
plt.scatter(new[0], new[1], marker = "^")
plt.xlabel("length")
plt.ylabel("weight")
plt.show()

#전처리 데이터에서 모델 훈련
kn.fit(train_scaled,train_target)
test_scaled = (test_input - mean) / std
kn.score(test_scaled, test_target)

print("새로운 생선" + kn.predict([new]))

distances, indexes = kn.kneighbors(new)
plt.scatter(train_scaled[:0], train_scaled[:,1])
plt.scatter(new[0], new[1], marker = "^")
plt.scatter(train_scaled[indexes,0],train_scaled[indexes,1],marker='D')
plt.xlabel("length")
plt.ylabel("weight")
plt.show()


# !/usr/bin/python3

import re

# I have added incorect formats just to point out that the regular expressions won't work if the format does not meet the requirement
ISBN_numbers =['ISBN 087-5-010-50987-5', 'ISBN 0-575-08082-9', 'ISPV -79sb-79h-%', 'ISBN 007-5-010-59587-9']
regex_ISBN = '^ISBN\s+?\d{3}\-\d{1}\-\d{3}\-\d{5}\-\d{1}$'

for x in ISBN_numbers:
    if re.findall(regex_ISBN, x):
        print(x, 'is a correct ISBN')
    else:
        print(x, 'is an incorrect ISBN')


def find(a):
    dic = {}
    for i, v in enumerate(a):
        dic[v] = dic[v][0] + 1 if v in dic else 1, i
    m = len(a) + 1
    pos = -1
    for i, v in enumerate(dic):
        if dic[v][0] == 1 and v < m:
            m = v
            pos = dic[v][1]
    return pos if pos == -1 else pos + 1

def main():
    t = int(input())

    for k in range(t):
        input()
        a = list(map(int, input().split()))

        print(find(a))

def test():
    print(find([2, 3, 2, 4, 2]))

main()


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dataset = pd.read_csv(f"combined/emg_fsr_data.csv",header=0)
emg_fsr_time = [x for x in range(len(dataset))]
ffls_data = dataset.iloc[:,21:]
# print(ffls_data.head())
# print(ffls_data.max())
# print(ffls_data.min())

def _normalize(data):
    return (data-data.min())/(data.max()-data.min())

def _standardize(array):
  mean = np.mean(array, axis=0)
  std = np.std(array, axis=0)
  array = (array - mean) / std
  return array

def press_locations(ffls_data,finger):
  ffls_data.columns=['Fing1','Fing2','Fing3','Fing4','Fing5','Fing6'] # Renaming Columns
  ffls_standardized = _standardize(ffls_data)
  ffls_normalized = _normalize(ffls_standardized)

  # Copying Key column to FFLS Data
  ffls_normalized['key']=dataset.iloc[:,0]
  # Reordering columns
  ffls_normalized=ffls_normalized[['key','Fing1','Fing2','Fing3','Fing4','Fing5','Fing6']]
  # Calculate Thresholds
  thresholds = [x-0.03 for x in ffls_normalized.mean()]

  indices=[]
  # https://stackoverflow.com/questions/21800169/python-pandas-get-index-of-rows-where-column-matches-certain-value
  # Find where Finger is pressed
  idx_list=np.where(ffls_normalized[f'Fing{finger}']<thresholds[finger])[0]
  for idx in idx_list:
    indices.append(idx)
  return indices

mov_avg_ffls = ffls_data.rolling(3).mean()
mov_avg_ffls.fillna(0.0,inplace=True)

# thresholds = [x-0.03 for x in ffls_normalized.mean()]
# plt.plot(emg_fsr_time,ffls_normalized)
# for i in range(6):
#     plt.subplot(3,2,i+1)
#     plt.axhline(y=thresholds[i], color='r', linestyle='-')
#     plt.plot(emg_fsr_time,ffls_normalized.iloc[:,i])
    # plt.hist(ffls_normalized.iloc[:,i],50)

plt.plot(emg_fsr_time,mov_avg_ffls)
colors=['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']
for i in range(1,7):
  for idx in press_locations(mov_avg_ffls,i):
    plt.axvline(x=idx,linestyle='-',color=colors[i])
plt.show()


# encoding=utf-8

from datetime import datetime as date
import traceback
import domutil
import storage
from BeautifulSoup import BeautifulSoup as Soup

def extract(pages):
    products = {}

    for page in pages:
        root = Soup(page)

        elem = root.find(name='table', attrs={'id':'rsTable'})
        if not elem:
            continue

        for tr in elem.findAll(name='tr'):
            tds = tr.findAll(name='td')
            if not tds or len(tds) == 0:
                continue

            company = tds[5].getText()
            fcc_id = tds[11].getText()
            lastupdate = extract_date(tds[13].getText())

            if fcc_id in products:
                entity = products[fcc_id]
                if entity.lastupdate < lastupdate:
                    entity.lastupdate = lastupdate
            else:
                entity = storage.create_instance(storage.FCCENTITY, \
                                                 company=company, \
                                                 fcc_id=fcc_id, \
                                                 lastupdate=lastupdate)

                products[fcc_id] = entity

    storage.db.put(products.values())

def extract_date(date_str):
    values = date_str.split('/')
    for ind in xrange(0, len(values)):
        values[ind] = int(values[ind])

    mon, day, year = values
    return date(year, mon, day)


from content_editor.models import Region, create_plugin_base
from django.db import models
from django.utils.translation import gettext_lazy as _
from feincms3.applications import ApplicationType, PageTypeMixin, TemplateType
from feincms3.mixins import LanguageMixin, MenuMixin
from feincms3.pages import AbstractPage
from feincms3.plugins import image, richtext

class Page(
    AbstractPage,
    PageTypeMixin,  # For adding the articles app to pages through the CMS.
    MenuMixin,  # We have a main and a footer navigation (meta).
    LanguageMixin,  # We're building a multilingual CMS. (Also,
    # feincms3.applications depends on LanguageMixin
    # currently.)
):
    TYPES = [
        TemplateType(
            key="standard",
            title=_("standard"),
            template_name="pages/standard.html",
            regions=(Region(key="main", title=_("Main")),),
        ),
        TemplateType(
            key="with-sidebar",
            title=_("with sidebar"),
            template_name="pages/with-sidebar.html",
            regions=(
                Region(key="main", title=_("Main")),
                Region(key="sidebar", title=_("Sidebar")),
            ),
        ),
        ApplicationType(
            key="publications",
            title=_("publications"),
            urlconf="app.articles.urls",
            regions=(Region(key="main", title=_("Main")),),
        ),
        ApplicationType(
            key="blog",
            title=_("blog"),
            urlconf="app.articles.urls",
            regions=(Region(key="main", title=_("Main")),),
        ),
    ]

    # MenuMixin
    MENUS = [
        ("main", _("main")),
        ("footer", _("footer")),
    ]

PagePlugin = create_plugin_base(Page)

class RichText(richtext.RichText, PagePlugin):
    pass

class Image(image.Image, PagePlugin):
    caption = models.CharField(
        _("caption"),
        max_length=200,
        blank=True,
    )


#https://www.youtube.com/watch?v=-RtVZsCvXAQ&list=PLS1QulWo1RIa7D1O6skqDQ-JZ1GGHKK-K&index=5&ab_channel=ProgrammingKnowledge

import cv2

cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')

#OR, fourcc = cv2.VideoWriter_fourcc(*'XVID')

out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

print(cap.isOpened())

while (cap.isOpened()):
    ret, frame = cap.read()

    if ret:

        print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

        out.write(frame)

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        cv2.imshow('frame', gray)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    else: break

cap.release()
out.release()
cv2.destroyAllWindows()


from django.db import models
from django.utils.timezone import now as timezone_now

# Create your models here.

class AREA_PROFESIONAL(models.Model):

    nombre_area = models.CharField(
        max_length = 100,
        primary_key = True
    )

class PROFESIONAL(models.Model):

    identificador_medico = models.IntegerField(
        null= False,
        default = -1,
        primary_key= True
    )
    nombre = models.CharField(
        null = False,
        default= '',
        max_length= 150
    )

    apellido1 = models.CharField(
        null = False,
        default='',
        max_length= 150
    )

    apellido2 = models.CharField(
        blank=True,
        default = '',
        max_length= 150
    )
    edad = models.IntegerField(
        null = False
    )

    area = models.ForeignKey(
       to = AREA_PROFESIONAL,
       null = False,
       on_delete = models.CASCADE
    )

    def __str__(self):
        return "Soy el profesional" + self.pk

class RECURSO(models.Model):

    nombre_recurso = models.CharField(
        null = False,
        max_length= 50
    )
    tipo = models.CharField(
        null = False,
        max_length= 50
    )

    def __str__(self):
        return "Soy el recurso" + self.pk

class ACTIVIDAD(models.Model):
    nombre_actividad = models.CharField(
        null = False,
        max_length = 50
    )
    tipo = models.ForeignKey(
        to=RECURSO,
        null=False,
        on_delete=models.CASCADE,
        verbose_name='tipo de recuerso profesional asociado a una actividad'
    )
    def __str(self):
        return "Soy la actividad" + self.pk

class PROCEDIMIENTOS(models.Model):
    nombre_procedimiento = models.CharField(
        null = False,
        max_length = 100
    )
class PACIENTE(models.Model):
    nombre = models.CharField(
        null=False,
        default='',
        max_length = 150
    )
    apellido1 = models.CharField(
        null=False,
        default = '',
        max_length = 150
    )
    apellido2 = models.CharField(
        blank=True,
        default= '',
        max_length=150
    )

    edad = models.IntegerField(
        null = False
    )
    fecha_inclusion = models.DateField(
        default=timezone_now
    )
    diagnostico = models.CharField(
        null = False,
        max_length= 150
    )
    procedimiento_paciente = models.ForeignKey(
        to = PROCEDIMIENTOS,
        null=False,
        on_delete=models.CASCADE,
        verbose_name='tipo de procedimiento asociado a un paciente'
    )
    actividad_paciente = models.ForeignKey(
        to = ACTIVIDAD,
        null=False,
        on_delete=models.CASCADE,
        verbose_name='Actividad asociada a un paciente'
    )
    profesional_paciente = models.ForeignKey(
        to = PROFESIONAL,
        null=False,
        on_delete=models.CASCADE,
        verbose_name='Profesional asociado a un paciente'
    )

    def __str__(self):
        return "Soy el paciente" + self.pk


#design of the appearance of the entire GUI itself
from PyQt4 import QtCore, QtGui, Qwt5
from PyQt4.Qwt5 import QwtPlot
import sys

try:
	_fromUtf8= QtCore.QString.fromUtf8
except AttributeError:
	def _fromUtf8(s):
		return s

try:
	_encoding= QtGui.QApplication.UnicodeUTF8
	def translate(context, text, disambig):
		return QtGui.QApplication.translate(context, text, disambig)
except AttributeError:
	def translate(context, text, disambig):
		return QtGui.QApplication.translate(context,text,disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(700, 500)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        #plotting of the EEG signal itself
        self.eegPlot = QwtPlot(self.centralwidget)
        self.eegPlot.setGeometry(QtCore.QRect(30, 20, 411, 411))
        self.eegPlot.setObjectName(_fromUtf8("EEG Plot"))

        #begin the acquisition of the signal and stop as well
        self.startEEG = QtGui.QPushButton(self.centralwidget)
        self.startEEG.setGeometry(QtCore.QRect(460, 370, 87, 27))
        self.startEEG.setObjectName(_fromUtf8("Start EEG"))
        self.stopEEG = QtGui.QPushButton(self.centralwidget)
        self.stopEEG.setGeometry(QtCore.QRect(580, 370, 87, 27))
        self.stopEEG.setObjectName(_fromUtf8("Stop EEG"))

        #create a menubar(?)

        menubar = QMainWindow.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 707, 24))
        self.menubar.setObjectName(_fromUtf8("MenuBar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("StatusBar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(translate("MainWindow", "MainWindow", None))
        self.startEEG.setText(translate("MainWindow", "Start", None))
        self.stopEEG.setText(translate("MainWindow", "Stop", None))


import logging
from contextlib import contextmanager
from os.path import exists
from sqlite3 import connect, Cursor

from constants import NUM_CAMERAS, NUM_BUTTONS, DB_FILE

LOG = logging.getLogger("db")

class Database:
    connection = None

    def __init__(self):
        if not exists(DB_FILE):
            LOG.info("Initialize sqlite database...")
            with self.cursor() as cur:
                cur.execute("CREATE TABLE positions ("
                            "cam INTEGER NOT NULL, "
                            "pos INTEGER NOT NULL, "
                            "name VARCHAR NOT NULL DEFAULT '', "
                            "btn_class VARCHAR NOT NULL DEFAULT 'btn-secondary', "
                            "focus INTEGER NOT NULL DEFAULT -1, "
                            "PRIMARY KEY (cam, pos))")
                for cam in range(NUM_CAMERAS):
                    for pos in range(NUM_BUTTONS):
                        cur.execute("INSERT INTO positions (cam, pos) VALUES (?, ?)", (cam, pos))
            LOG.info("Initialization complete")

    @contextmanager
    def dict_cursor(self) -> Cursor:
        connection = None
        try:
            connection = connect(DB_FILE)

            def dict_factory(cursor, row):
                return {c[0]: row[i] for i, c in enumerate(cursor.description)}

            connection.row_factory = dict_factory
            yield connection.cursor()
            connection.commit()
        finally:
            if connection is not None:
                connection.close()

    @contextmanager
    def cursor(self) -> Cursor:
        connection = None
        try:
            connection = connect(DB_FILE)
            yield connection.cursor()
            connection.commit()
        finally:
            if connection is not None:
                connection.close()

    def set_button(self, cam: int, pos: int, name: str, btn_class: str):
        with self.cursor() as cur:
            cur.execute("UPDATE positions SET name = ?, btn_class = ? WHERE cam = ? AND pos = ?",
                        (name, btn_class, cam, pos))

    def set_focus(self, cam: int, pos: int, focus: int):
        with self.cursor() as cur:
            cur.execute("UPDATE positions SET focus = ? WHERE cam = ? AND pos = ?", (focus, cam, pos))

    def get_focus(self, cam: int, pos: int) -> int:
        with self.cursor() as cur:
            cur.execute("SELECT focus FROM positions WHERE cam = ? AND pos = ?", (cam, pos))
            return cur.fetchone()[0]

    def get_data(self) -> list:
        with self.dict_cursor() as cur:
            return list(cur.execute("SELECT cam, pos, name, btn_class FROM positions ORDER BY cam, pos"))

    def clear_buttons(self):
        with self.cursor() as cur:
            cur.execute("UPDATE positions SET name = '', btn_class = 'btn-secondary'")


# numpy example
import numpy as np
import pandas as pd

# dictionary of lists
dict={
    "id":[1,4,np.nan,67],
    "age":[np.nan,56,43,np.nan],
    "Score":[678,56,np.nan,5]

}

# creating the dataframe
df =pd.DataFrame(dict)

print(df.isnull().sum())


#Method 1: Using regular method

class Solution(object):
    def remove_vowels(self,s):
        s=s.lower().replace("a","")
        s=s.lower().replace("e","")
        s=s.lower().replace("i","")
        s=s.lower().replace("o","")
        s=s.lower().replace("u","")
        return s
obj=Solution()
print(obj.remove_vowels('I am Python Programming Code'))

#Method 2: Using list comprehension method
def rem_vowels(string):
    vowels=['a','e','i','o','u']
    result=[letter for letter in string  if letter.lower() not in vowels]
    result=''.join(result)
    print(result)
string='I am Python Programming Code'
rem_vowels(string)

#Method 3: Using regular expression method
import re
def rem_vowels(string):
    return(re.sub("[aeiouAEIOU]","",string))
string="I am Python Programming Code"
print(rem_vowels(string))


n = 0
cont = 0
soma = 0
while n != 999:
    n = int(input('Digite um numero (999 para parar): '))
    if n != 999:
        cont += 1
        soma = soma + n
print(f'Foram digitados {cont} valores')
print(f'A soma dos numeros digitados: {soma}')


from random import randint
from random import random
from random import gauss
from math import exp
from math import log
import pygame
import sys

switch_time = 0
frames_per_sec = 60 # 1 (fps) = 1 (sec)
block_size = (50, 50)
bs_size = (20, 20)
road_width = 10
window_size = ((block_size[0] * 10 + road_width * 9), (block_size[1] * 10 + road_width * 9))
unit = 590 / 25
entropy = 10
starting_time_arr = []
holding_time_arr = []
p_min = 20
algo = ['Best Effort', 'Entropy', 'Threshold', 'My Algo']

speed = 0.02 * unit # km / sec
forward_prob = 1 / 2
uturn_prob = 1 / 16
left_prob = 7 / 32
right_prob = 7 / 32
transmission_power = 120 # dB
arrival_rate = 2 / 3600 # calls / sec
service_time = 3 * 60 # sec
freq_table = [i * 100 for i in range(1, 11)]
car_entering_rate = (1/12) * exp(-(1/12))

alice_blue = (240, 248, 255) # for bs
chartreuse1 = (127,255,0)
cadetblue1 = (152,245,255)
cyan2 = (0,238,238)
darkolivegreen1 = (202,255,112)
darkorchid = (153,50,204)
dodgerblue2 = (28,134,238)
firebrick2 = (238,44,44)
hotpink = (255,105,180)
lightsalmon3 = (205,129,98)
orangered1 = (255,69,0)
black = (0, 0, 0)
white = (255, 255, 255)

top_border_y = 0
left_border_x = 0
bottom_border_y = window_size[1]
right_border_x = block_size[0] * 10 + road_width * 9

color_arr = (chartreuse1, cadetblue1,cyan2, darkolivegreen1, darkorchid, dodgerblue2, firebrick2, hotpink, lightsalmon3, orangered1)
bs_arr = []
car_arr = []

clock = pygame.time.Clock()
pygame.init()
window = pygame.display.set_mode(window_size)

car_group = pygame.sprite.Group()
block_group = pygame.sprite.Group()
base_station_group = pygame.sprite.Group()
font = pygame.font.match_font('arial')

def calculate_arrival_rate():
    mu, sigma = 100, 5
    rand = round(gauss(mu, sigma))
    while rand <= 0:
        rand = round(gauss(mu, sigma))
    return rand

def calculate_service_time():
    mu, sigma = 5, 5
    return round(abs(60 * gauss(mu, sigma)))

def set_time_interval(calls_per_hour):
    i = 0
    while i < calls_per_hour:
        holding_time = calculate_service_time()
        starting_time = randint(0, 3600 - holding_time - 10)
        if len(starting_time_arr) == 0:
            starting_time_arr.append(starting_time)
        else:
            while starting_time == starting_time_arr[-1]:
                starting_time = randint(0, 3600 - holding_time - 10)
            starting_time_arr.append(starting_time)
        holding_time_arr.append(holding_time)
        i += 1
    starting_time_arr.sort()

def calculate_receiving_power(fc, dis):
    return transmission_power - (32.45 + 20 * (log(fc, 10)) + 20 * (log(dis, 10)))

def set_base_station_and_block():
    for i in range(10):
        for j in range(10):
            obj = block(i, j)
            block_group.add(obj)
            rand = randint(1, 10)
            if rand == 1:
                index = randint(0, 9)
                obj = base_station(i, j, index)
                bs_arr.append(obj)
                base_station_group.add(obj)

def best_effort_find_the_base_station(car):
    max_receiving_power = -(sys.maxsize)
    max_index = -1
    for i, bs in enumerate(bs_arr):
        dis = ((bs.rect.centerx - car.rect.centerx) ** 2 + (bs.rect.centery - car.rect.centery) ** 2) ** 0.5
        dis_in_km = dis / unit
        receiving_power = calculate_receiving_power(bs.freq, dis_in_km)
        if receiving_power > max_receiving_power:
            max_index = i
            max_receiving_power = receiving_power

    car.received_power = round(max_receiving_power, 2)
    car.connected_bs = max_index
    if car.connection:
        car.color = bs_arr[car.connected_bs].color

def entropy_find_the_base_station(car):
    max_receiving_power = -(sys.maxsize)
    max_index = -1
    for i, bs in enumerate(bs_arr):
        dis = ((bs.rect.centerx - car.rect.centerx) ** 2 + (bs.rect.centery - car.rect.centery) ** 2) ** 0.5
        dis_in_km = dis / unit
        receiving_power = calculate_receiving_power(bs.freq, dis_in_km)
        if receiving_power > max_receiving_power:
            max_index = i
            max_receiving_power = receiving_power

    # calculate current receiving power
    if car.connected_bs != -1:
        dis = ((bs_arr[car.connected_bs].rect.centerx - car.rect.centerx) ** 2 + (bs_arr[car.connected_bs].rect.centery - car.rect.centery) ** 2) ** 0.5
        dis_in_km = dis / unit
        car.received_power = calculate_receiving_power(bs_arr[car.connected_bs].freq, dis_in_km)
        car.received_power = round(car.received_power, 2)

    if (max_receiving_power - car.received_power) > entropy:
        # car.color = bs_arr[max_index].color
        car.received_power = round(max_receiving_power, 2)
        car.connected_bs = max_index

    if car.connection:
        car.color = bs_arr[car.connected_bs].color

def entropy_modified_find_the_base_station(car):
    max_receiving_power = -(sys.maxsize)
    max_index = -1
    shortest_index = -1
    shortest_dis_in_km = sys.maxsize

    for i, bs in enumerate(bs_arr):
        dis = ((bs.rect.centerx - car.rect.centerx) ** 2 + (bs.rect.centery - car.rect.centery) ** 2) ** 0.5
        dis_in_km = dis / unit
        receiving_power = calculate_receiving_power(bs.freq, dis_in_km)
        if receiving_power > max_receiving_power:
            max_index = i
            max_receiving_power = receiving_power
        if shortest_dis_in_km > dis_in_km:
            shortest_index = i
            shortest_dis_in_km = dis_in_km
            shortest_receiving_power = receiving_power
    # calculate current receiving power
    if car.connected_bs != -1:
        dis = ((bs_arr[car.connected_bs].rect.centerx - car.rect.centerx) ** 2 + (bs_arr[car.connected_bs].rect.centery - car.rect.centery) ** 2) ** 0.5
        dis_in_km = dis / unit
        car.received_power = calculate_receiving_power(bs_arr[car.connected_bs].freq, dis_in_km)
        car.received_power = round(car.received_power, 2)

    if (max_receiving_power - car.received_power) > entropy:
        if car.connected_bs == -1:
            # car.color = bs_arr[max_index].color
            car.received_power = round(max_receiving_power, 2)
            car.connected_bs = max_index
        else: # find the nearest base station
            # car.color = bs_arr[shortest_index].color
            car.received_power = round(shortest_receiving_power, 2)
            car.connected_bs = max_index

    if car.connection:
        car.color = bs_arr[car.connected_bs].color

def threshold_find_the_base_station(car):
    if car.connected_bs != -1:
        dis = ((bs_arr[car.connected_bs].rect.centerx - car.rect.centerx) ** 2 + (bs_arr[car.connected_bs].rect.centery - car.rect.centery) ** 2) ** 0.5
        dis_in_km = dis / unit
        car.received_power = calculate_receiving_power(bs_arr[car.connected_bs].freq, dis_in_km)
        car.received_power = round(car.received_power, 2)
        if car.received_power > p_min :
            if car.connection:
                car.color = bs_arr[car.connected_bs].color
            return

    max_receiving_power = -(sys.maxsize)
    max_index = -1
    for i, bs in enumerate(bs_arr):
        dis = ((bs.rect.centerx - car.rect.centerx) ** 2 + (bs.rect.centery - car.rect.centery) ** 2) ** 0.5
        dis_in_km = dis / unit
        receiving_power = calculate_receiving_power(bs.freq, dis_in_km)
        if receiving_power > max_receiving_power:
            max_index = i
            max_receiving_power = receiving_power

    car.received_power = round(max_receiving_power, 2)
    car.connected_bs = max_index
    if car.connection:
        car.color = bs_arr[car.connected_bs].color

def create_car(i, j, algorithm_select):
    if i == 0:
        x, y = block_size[0] * j + road_width * (j - 1), bottom_border_y
    elif i == 1:
        x, y = left_border_x, block_size[1] * j + road_width * (j - 1)
    elif i == 2:
        x, y = block_size[0] * j + road_width * (j - 1), top_border_y
    elif i == 3:
        x, y = right_border_x, block_size[1] * j + road_width * (j - 1)

    obj = car(x, y, i)
    if algorithm_select == 1:
        best_effort_find_the_base_station(obj)
    elif algorithm_select == 2:
        entropy_find_the_base_station(obj)
    elif algorithm_select == 3:
        threshold_find_the_base_station(obj)
    elif algorithm_select == 4:
        entropy_modified_find_the_base_station(obj)
    car_arr.append(obj)
    car_group.add(obj)

def if_needed_creating_car(algorithm_select):
    for i in range(4): # 4 dirs.
        for j in range(1, 10):
            rand = random() # rand a floating number between (0, 1)
            if rand <= car_entering_rate: # create cars
                create_car(i, j, algorithm_select)

class block(pygame.sprite.Sprite):
    def __init__(self, i, j):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface(block_size)
        self.image.fill(alice_blue)

        self.rect = self.image.get_rect()
        self.rect.x = (block_size[0] + road_width) * i
        self.rect.y = (block_size[1] + road_width) * j

    def update(self):
        return

class base_station(pygame.sprite.Sprite):
    def __init__(self, i, j, index):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface(bs_size)
        self.color = color_arr[index]
        self.image.fill(color_arr[index])
        self.freq = freq_table[index]

        self.rect = self.image.get_rect()
        self.rect.x = (block_size[0] + road_width) * i + ((block_size[0] - bs_size[0]) / 2)
        self.rect.y = (block_size[1] + road_width) * j + ((block_size[1] - bs_size[1]) / 2)

        p = randint(1, 4)
        if p == 1:
            self.rect.y = (block_size[1] + road_width) * j + ((block_size[1] - bs_size[1]) / 2) - (unit * 0.1)
        elif p == 2:
            self.rect.x = (block_size[0] + road_width) * i + ((block_size[0] - bs_size[0]) / 2) + (unit * 0.1)
        elif p == 3:
            self.rect.y = (block_size[1] + road_width) * j + ((block_size[1] - bs_size[1]) / 2) + (unit * 0.1)
        else:
            self.rect.x = (block_size[0] + road_width) * i + ((block_size[0] - bs_size[0]) / 2) - (unit * 0.1)

    def update(self):
        return

class car(pygame.sprite.Sprite):
    def __init__(self, x, y, dir):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((road_width,road_width))
        self.connected_bs = -1
        self.color = black
        self.image.fill(self.color)
        self.rect = self.image.get_rect()
        self.position_x = float(x)
        self.position_y = float(y)
        self.rect.x = x
        self.rect.y = y
        self.dir = dir
        self.received_power = -(sys.maxsize)
        self.connection = False
        self.remaining_time = 0

    def occur_intersection_check(self):
        x, y = self.rect.x, self.rect.y
        for i in range(9):
            for j in range(9):
                if x == (block_size[0] + (block_size[0] + road_width) * i) and y == (block_size[0] + (block_size[0] + road_width) * j):
                    return True
        return False

    def move_car(self):
        if self.dir == 0:
            self.position_y -= speed
        elif self.dir == 1:
            self.position_x += speed
        elif self.dir == 2:
            self.position_y += speed
        else:
            self.position_x -= speed

        self.rect.x = round(self.position_x)
        self.rect.y = round(self.position_y)

    def update(self):
        if self.connection:
            self.remaining_time -= 1
            if self.remaining_time == 0:
                self.connection = False
                self.color = black
        if self.occur_intersection_check():
            rand = randint(1, 32)
            if 17 <= rand and rand <= 18:
                self.dir += 2
            elif 19 <= rand and rand <= 25:
                self.dir += 1
            elif rand > 25:
                self.dir += 3
        self.dir %= 4
        self.move_car()
        self.image.fill(self.color)
        return

def check_if_any_car_needs_to_be_removed():
    for car in car_arr:
        rect = car.rect
        if rect.left > right_border_x or rect.right < left_border_x or rect.top > bottom_border_y or rect.bottom < top_border_y:
            car.kill()
            car_arr.remove(car)

def display_bs_carrier_freq():
    for bs in bs_arr:
        carrier_freq = str(bs.freq) + ' MHz'
        bs_font = pygame.font.Font(font, 12)
        text = bs_font.render(carrier_freq, True, black)
        rect = text.get_rect()
        rect.centerx = bs.rect.centerx
        rect.centery = bs.rect.centery
        window.blit(text, rect)

def calculate_switch_times_and_draw_line(time, algorithm_select):
    calling_car_index = -1
    if len(starting_time_arr) != 0 and (time in starting_time_arr):
        if len(car_arr):
            calling_car_index = randint(0, len(car_arr) - 1)
            while car_arr[calling_car_index].connection: # if the car is on call, find another car
                calling_car_index = randint(0, len(car_arr) - 1)
    for i, car in enumerate(car_arr):
        old_bs = car.connected_bs

        if algorithm_select == 1:
            best_effort_find_the_base_station(car)
        elif algorithm_select == 2:
            entropy_find_the_base_station(car)
        elif algorithm_select == 3:
            threshold_find_the_base_station(car)
        elif algorithm_select == 4:
            entropy_modified_find_the_base_station(car)

        if i == calling_car_index:
            calling_car_index = -1
            car.color = bs_arr[car.connected_bs].color
            car.connection = True
            car.remaining_time = holding_time_arr[0]
            del starting_time_arr[0]
            del holding_time_arr[0]

        if car.connection:
            received_power = str(car.received_power) + ' dB'
            pygame.draw.line(window , car.color, (bs_arr[car.connected_bs].rect.centerx, bs_arr[car.connected_bs].rect.centery), (car.rect.centerx, car.rect.centery), 1)
            car_font = pygame.font.Font(font, 14)
            text = car_font.render(received_power, True, car.color)
            rect = text.get_rect()
            rect.centerx = car.rect.x+10
            rect.centery = car.rect.y-10
            window.blit(text, rect)
            if car.connected_bs != old_bs:
                global switch_time
                switch_time += 1

def update(time, algorithm_select):
    check_if_any_car_needs_to_be_removed()
    display_bs_carrier_freq()
    calculate_switch_times_and_draw_line(time, algorithm_select)

def get_call_infos():
    calls_per_hour = calculate_arrival_rate()
    set_time_interval(calls_per_hour)
    return calls_per_hour

def Restart():
    global switch_time
    switch_time = 0
    for car in car_arr:
        car.kill()
    car_arr.clear()
    starting_time_arr.clear()
    holding_time_arr.clear()
    calls_per_hour = get_call_infos()
    return calls_per_hour

if __name__  == '__main__':
    algorithm_select = 1
    set_base_station_and_block()
    end_of_game = False
    time = 0
    calls_per_hour = get_call_infos()
    while True:
        clock.tick(frames_per_sec)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                end_of_game = True
            if event.type == pygame.KEYDOWN:
                if(event.key == pygame.K_1):
                    time = 0
                    calls_per_hour = Restart()
                    algorithm_select = 1
                elif(event.key == pygame.K_2):
                    time = 0
                    calls_per_hour = Restart()
                    algorithm_select = 2
                elif(event.key == pygame.K_3):
                    time = 0
                    calls_per_hour = Restart()
                    algorithm_select = 3
                elif(event.key == pygame.K_4):
                    time = 0
                    calls_per_hour = Restart()
                    algorithm_select = 4
                elif(event.key == pygame.K_5):
                    for ele in car_arr:
                        if ele.color == black:
                            ele.color = white
                elif(event.key == pygame.K_6):
                    for ele in car_arr:
                        if ele.color == white:
                            ele.color = black

        if_needed_creating_car(algorithm_select)

        window.fill(white)
        block_group.draw(window)
        base_station_group.draw(window)
        car_group.draw(window)

        block_group.update()
        base_station_group.update()
        car_group.update()
        update(time, algorithm_select)
        pygame.display.update()

        print("Switch times : {:d}, Car number : {:d}, Calls Per Hour : {:d}".format(switch_time, len(car_arr), calls_per_hour))
        print("Starting Time Array : ", starting_time_arr)
        print("Holding Time Array : ", holding_time_arr)
        print("{:d}".format(time))
        print("{}".format(algo[algorithm_select - 1]))
        if end_of_game:
            break
        time += 1
        if time == 3601:
            time = 0
            calls_per_hour = get_call_infos()
    pygame.quit()


from random import randint
import re

def roll_dice(argument):
    """Rolls dice based on a {x}d{y}+{z} pattern where the only necessary argument is at the very least a d{y}.
    This will return a message that can be sent.
    """
    result = [0, ""]
    detailed = "detailed" in argument
    firstcheck = re.search(r'[0-9]+d[0-9]+[+][0-9]+', argument)
    if firstcheck:
        outcomeList = "{"
        matchString = str(firstcheck.group())
        argsList = matchString.split('d')
        splitArg = argsList[1].split('+')
        diceAmount = int(argsList[0])
        diceEyes = int(splitArg[0])
        bonus = int(splitArg[1])
        outcome = 0
        for _ in range(1, diceAmount + 1):
            randomNumber = randint(1, diceEyes)
            if detailed:
                outcomeList += str(randomNumber) + " , "
            outcome += randomNumber

        outcome += bonus

        message = "Rolled " + str(diceAmount) + " d" + str(diceEyes) + " with a bonus of " + str(bonus) + " for a total count of: " + str(outcome)

        if detailed:
            message += " | Details on the rolls: " + outcomeList + " }"

        result[0] = outcome
        result[1] = message

    else:
        secondCheck = re.search(r'[0-9]+d[0-9]+', argument)
        if secondCheck:
            outcomeList = "{ "
            matchedString = str(secondCheck.group())
            argsList = matchedString.split('d')
            diceAmount = int(argsList[0])
            diceEyes = int(argsList[1])
            outcome = 0
            for _ in range(1, diceAmount + 1):
                randomNumber = randint(1, diceEyes)
                if detailed:
                    outcomeList += str(randomNumber) + " , "
                outcome += randomNumber

            message = "Rolled " + str(diceAmount) + " d" + str(diceEyes) + " for a total count of: " + str(outcome)
            if detailed:
                message += " | Details on the rolls: " + outcomeList + " }"

            result[0] = outcome
            result[1] = message

        else:
            tertiaryCheck = re.search(r'd[0-9]+', argument)
            if tertiaryCheck:
                matchedString = str(tertiaryCheck.group())
                argsList = matchedString.split('d')
                diceEyes = int(argsList[1])
                outcome = randint(1, diceEyes)
                message = "Rolled a d" + str(diceEyes) + " for: " + str(outcome)
                result[0] = outcome
                result[1] = message
            else:
                message = "That is not a valid die. Proper formatting is `>roll {x]d{y}+{z}`, `>roll {x]d{y}` or `>roll d{x}`"
                result[1] = message

    return result


inp = []
for i in open("input"):
    a = i.split()
    inp.append(a[0])

def most_common(inp, index):
    ans = [0,0]*len(inp[0])
    for i in inp:
        for j in range(len(i)):
            if i[j] == "0":
                ans[j*2] += 1
            else:
                ans[j*2+1] += 1
    if ans[index*2] > ans[(index*2)+1]:
        return "0"
    return "1"

def least_common(inp, index):
    ans = [0,0]*len(inp[0])
    for i in inp:
        for j in range(len(i)):
            if i[j] == "0":
                ans[j*2] += 1
            else:
                ans[j*2+1] += 1
    if ans[index*2] <= ans[(index*2)+1]:
        return "0"
    return "1"

def update_inp(inp, criteria):
    new_inp = []
    ele = 0
    remove = []
    for i in inp:
        for j in range(len(criteria)):
            if i[j] != criteria[j]:
                remove.append(ele)
                break
        ele += 1
    for i in range(len(inp)):
        if i not in remove:
            new_inp.append(inp[i])
    return new_inp

index = 0
criteria = ""
ox, lif = 0,0
for i in range(len(inp)):
    criteria += most_common(inp, i)
    inp = update_inp(inp, criteria)
    if len(inp) <= 1:
        print("Most common", int(inp[0], 2))
        ox = int(inp[0], 2)
        break

inp = []
for i in open("input"):
    a = i.split()
    inp.append(a[0])

index = 0
criteria = ""
for i in range(len(inp)):
    criteria += least_common(inp, i)
    inp = update_inp(inp, criteria)
    if len(inp) <= 1:
        print("Least common:", int(inp[0], 2))
        lif = int(inp[0], 2)
        break

print(ox * lif)


import decimal

from django.core.management.base import BaseCommand

from storeapp.models import Product

class Command(BaseCommand):
    help = 'Update the price of product by id'

    def add_arguments(self, parser):
        parser.add_argument('pk', type=int, help="Product's id")
        parser.add_argument('price', type=decimal.Decimal, help="Price of the product")

    def handle(self, *args, **kwargs):
        pk = kwargs.get('pk')
        price = kwargs.get('price')
        product = Product.objects.filter(pk=pk).first()
        if product:
            product.price = price
            product.save()
        self.stdout.write(f'{product}')


from pathlib import Path
from typing import List, Optional

import cli_ui as ui

from tsrc.executor import Outcome, Task
from tsrc.git import run_git, run_git_captured
from tsrc.repo import Remote, Repo

class RemoteSetter(Task[Repo]):
    """
    For each repository:

      * look for the remote configured in the manifest,
      * add any missing remote,
      * if a remote is found but with an incorrect URL, update its URL.

    """

    def __init__(self, workspace_path: Path) -> None:
        self.workspace_path = workspace_path

    def describe_item(self, item: Repo) -> str:
        return item.dest

    def describe_process_start(self, item: Repo) -> List[ui.Token]:
        return ["Configuring remotes", item.dest]

    def describe_process_end(self, item: Repo) -> List[ui.Token]:
        return [ui.green, "ok", ui.reset, item.dest]

    def process(self, index: int, count: int, repo: Repo) -> Outcome:
        # Note:
        #   When self.parallel is True we need to return a string describing
        #   all the changes, otherwise, we can just call cli_ui.info() directly
        summary_lines = []
        for remote in repo.remotes:
            existing_remote = self.get_remote(repo, remote.name)
            if existing_remote:
                if existing_remote.url != remote.url:
                    self.set_remote(repo, remote)
                    summary_lines.append(
                        f"{repo.dest}: remote '{remote.name}' set to '{remote.url}'"
                    )
            else:
                self.add_remote(repo, remote)
                summary_lines.append(
                    f"{repo.dest}: added remote '{remote.name}' with url: '{remote.url}'"
                )
        return Outcome.from_lines(summary_lines)

    def get_remote(self, repo: Repo, name: str) -> Optional[Remote]:
        full_path = self.workspace_path / repo.dest
        rc, url = run_git_captured(full_path, "remote", "get-url", name, check=False)
        if rc != 0:
            return None
        else:
            return Remote(name=name, url=url)

    def set_remote(self, repo: Repo, remote: Remote) -> None:
        full_path = self.workspace_path / repo.dest
        # fmt: off
        self.info_3(
            repo.dest + ":", "Update remote", ui.reset,
            ui.bold, remote.name, ui.reset,
            "to new url:", ui.brown, f"({remote.url})"
        )
        # fmt: on
        run_git(full_path, "remote", "set-url", remote.name, remote.url)

    def add_remote(self, repo: Repo, remote: Remote) -> None:
        full_path = self.workspace_path / repo.dest
        # fmt: off
        self.info_3(
            repo.dest + ":", "Add remote", ui.reset,
            ui.bold, remote.name, ui.reset, ui.brown, f"({remote.url})"
        )
        # fmt: on
        self.run_git(full_path, "remote", "add", remote.name, remote.url)


#!/usr/bin/env python3
import time
from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
from collections import OrderedDict
from flask import Flask, send_file
from werkzeug.debug import DebuggedApplication
app = Flask(__name__, static_folder="../frontend", static_url_path="")
app.debug = True
class EchoApplication(WebSocketApplication):

    def on_open(self):
        print("Connection opened")

    def on_message(self, message):
        print(message)
        self.ws.send(message)

    def on_close(self, reason):
        print(reason)

@app.route("/")
def startpage():
    return send_file('../frontend/index.html')

WebSocketServer(
    ('0.0.0.0', 5000),
    Resource(OrderedDict([('^/test', EchoApplication),
                    ("^/.*", DebuggedApplication(app))]))
    , debug=True
).serve_forever()


import bpy
import colorsys
import numpy as np

###############################################################################
# Utility functions
###############################################################################

#Generates a list with the names of the objects
def MakeObjectNames(ObjectName,NumberOfObjects):
    """
    Parameters
    ----------
    ObjectName : String
        Name of the object to be created.
    NumberOfObjects : int
        Number of names to be created.

    Returns
    -------
    NamesContainer : list
        List of strings with the names of the objects.

    """
    NamesContainer=[]
    NamesContainer.append(ObjectName)

    for k in range(1,NumberOfObjects):
        if k<=9:
            NamesContainer.append(ObjectName+".00"+str(k))
        elif k>9 and k<=99:
            NamesContainer.append(ObjectName+".0"+str(k))
        else:
            NamesContainer.append(ObjectName+"."+str(k))
    return NamesContainer

def GetCentersLocations(NumberOfItems,stretch):
    """
    Parameters
    ----------
    NumberOfItems : int
        Row or solumn length.
    stretch : float
        boundaries of the visualization square

    Returns
    -------
    centerLocations : list
        List with the center locations of each cube in the heatmap

    """

    xItems,yItems = NumberOfItems
    xStretch,yStretch = stretch

    xGrid=np.linspace(xStretch,-xStretch,xItems+1)
    yGrid=np.linspace(yStretch,-yStretch,yItems+1)

    centerLocations=[]

    for k in range(yItems):

        midY=(yGrid[k+1]+yGrid[k])/2

        for i in range(xItems):

            midX=(xGrid[i+1]+xGrid[i])/2
            currentLoc=(midX,0,midY)
            centerLocations.append(currentLoc)

    return centerLocations

def JoinGeometryByNames(GeometryNames):

    scene = bpy.context.scene
    objectsToJoin=[]
    for nme in GeometryNames:
        objectsToJoin.append(bpy.data.objects[nme])

    ctx = bpy.context.copy()
    ctx["active_object"] = objectsToJoin[0]
    ctx["selected_objects"] = objectsToJoin
    ctx["selected_editable_bases"] = [scene.object_bases[nme] for nme in GeometryNames]
    bpy.ops.object.join(ctx)

###############################################################################
# Geometry functions
###############################################################################

def AddGeometryByKind(Kind,Name,Location,Scale):
    '''
    Add a mesh object to the scee and change it's name
    Parameters
    ----------
    Kind : string
        Name of the mesh to be added. Takes the values of Sphere, Cube, Cylinder and
        Torus
    Name : string
        New name of the geometry.
    Location : tuple
        Location of the object.
    Scale : tuple
        Scale of the object.

    Returns
    -------
    None.

    '''

    GeometryNames = ["Sphere","Cube","Cylinder","Torus","Suzanne"]
    GeometryFunctions = [bpy.ops.mesh.primitive_uv_sphere_add,bpy.ops.mesh.primitive_cube_add
                        ,bpy.ops.mesh.primitive_cylinder_add,bpy.ops.mesh.primitive_torus_add
                        ,bpy.ops.mesh.primitive_monkey_add]

    NameToLocation = {}

    for val,name in enumerate(GeometryNames):
        NameToLocation[name] = val

    try:

        funcIndex = NameToLocation[Kind]
        GeometryFunctions[funcIndex](location=Location)
        bpy.data.objects[Kind].scale = Scale
        bpy.data.objects[Kind].data.name = Name
        bpy.data.objects[Kind].name = Name

        if Kind == "Torus":
            bpy.data.objects[Name].rotation_euler = (np.pi/2,0,0)

        if Kind == "Suzanne":
            bpy.data.objects[Name].rotation_euler = (0,0,np.pi)

    except ValueError:
        print("Not recognized type")

def AddElementsFromLocations(Locations,Scale,Kind,Name):

    """
        Parameters
    ----------
    Locations : list,array-like
        Location of the objects.
    Scale : float
        Scale of the geometry
    Kind : str
        Kind of geometry to be added.
    Name : str
        Name of the geometry

    Returns
    -------
    objectNames : list
        Names of the geometries.
    """

    objectNames=MakeObjectNames('GeometryForMatrix'+Name,len(Locations))
    nObjects=len(Locations)

    for k in range(nObjects):

        AddGeometryByKind(Kind,objectNames[k],tuple(Locations[k]),(Scale,Scale,Scale))

    return objectNames

###############################################################################
# Text Geometry functions
###############################################################################

def InsertAndChangeText(TextLocation,TextLabel,Name,scale,rotation):
    """
    Parameters
    ----------
    TextLocation : tuple
        Location of the text object
    TextLabel : string
        Text to add to the text object
    Name : string
        Name of the text object
    scale : float
        Scale of the text object
    rotation : tuple
        Rotation of the text object

    Returns
    -------
    None

    """

    bpy.ops.object.text_add(location=TextLocation,enter_editmode=True)
    for k in range(4):
        bpy.ops.font.delete(type='PREVIOUS_OR_SELECTION')
    for char in TextLabel:
        bpy.ops.font.text_insert(text=char)
    bpy.ops.object.editmode_toggle()
    bpy.data.objects['Text'].data.name=Name
    bpy.data.objects['Text'].name=Name
    bpy.data.objects[Name].rotation_euler=rotation
    bpy.data.objects[Name].scale=(scale,scale,scale)

###############################################################################
# Material functions
###############################################################################

def AddTypeAnodizedMetalMaterial(GeometryName,RGBData):
    """
    Simple RGB and BSDF principled node mixed.
    Parameters
    ----------
    GeometryName : string
        Geometry name of the object.
    RGBData : tuple, list
        RGB values for the rgb shader output.

    Returns
    -------
    None.

    """

    r,g,b=RGBData
    currentMaterial = bpy.data.materials.new(name='TypeA'+GeometryName)
    currentMaterial.use_nodes = True
    nodes = currentMaterial.node_tree.nodes
    rgb = nodes.new("ShaderNodeRGB")
    rgb.outputs[0].default_value = (r,g,b,1)

    bsdfA = nodes.new("ShaderNodeBsdfAnisotropic")
    bsdfA.distribution = 'BECKMANN'
    bsdfA.inputs[1].default_value = 0.1
    bsdfA.inputs[2].default_value = 0.5
    currentMaterial.node_tree.links.new(rgb.outputs[0],bsdfA.inputs[0])

    bsdfG = nodes.new("ShaderNodeBsdfGlossy")
    bsdfG.distribution = 'BECKMANN'
    bsdfG.inputs[1].default_value = 0.1
    currentMaterial.node_tree.links.new(rgb.outputs[0],bsdfG.inputs[0])

    mixShader = nodes.new("ShaderNodeMixShader")
    mixShader.inputs[0].default_value = 0.5
    currentMaterial.node_tree.links.new(bsdfA.outputs[0],mixShader.inputs[1])
    currentMaterial.node_tree.links.new(bsdfG.outputs[0],mixShader.inputs[2])

    materialOutput=nodes.get("Material Output")
    currentMaterial.node_tree.links.new(mixShader.outputs[0],materialOutput.inputs[0])
    bpy.data.objects[GeometryName].data.materials.append(currentMaterial)

def AddTypeAMaterial(GeometryName,RGBData):
    """
    Simple RGB and BSDF principled node mixed.
    Parameters
    ----------
    GeometryName : string
        Geometry name of the object.
    RGBData : tuple, list
        RGB values for the rgb shader output.

    Returns
    -------
    None.

    """

    r,g,b=RGBData
    currentMaterial = bpy.data.materials.new(name='TypeA'+GeometryName)
    currentMaterial.use_nodes = True
    nodes = currentMaterial.node_tree.nodes
    rgb = nodes.new("ShaderNodeRGB")
    rgb.outputs[0].default_value = (r,g,b,1)

    bsdf = nodes.new("ShaderNodeBsdfPrincipled")
    bsdf.inputs[4].default_value = 0.5
    bsdf.inputs[7].default_value = 1
    bsdf.inputs[15].default_value = 1

    currentMaterial.node_tree.links.new(rgb.outputs[0],bsdf.inputs[0])
    currentMaterial.node_tree.links.new(rgb.outputs[0],bsdf.inputs[3])
    materialOutput=nodes.get("Material Output")
    currentMaterial.node_tree.links.new(bsdf.outputs[0],materialOutput.inputs[0])
    bpy.data.objects[GeometryName].data.materials.append(currentMaterial)

###############################################################################
# Render Settings
###############################################################################

bpy.context.scene.render.engine = 'CYCLES'
bpy.context.scene.render.threads_mode = 'FIXED'
bpy.context.scene.render.threads = 3
bpy.context.scene.render.resolution_x = 1200
bpy.context.scene.render.resolution_y = 1200
bpy.context.scene.render.tile_x = 384
bpy.context.scene.render.tile_y = 256
bpy.context.scene.cycles.device = 'GPU'
bpy.context.scene.cycles.samples = 750

###############################################################################
# Scene settings
###############################################################################

bpy.data.objects['Cube'].data.name = 'StartCube'
bpy.data.objects['Cube'].name = 'StartCube'
bpy.data.objects['StartCube'].select_set(state = True)
bpy.data.objects['StartCube'].scale = (6,6,6)
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.bevel(offset=0.15,vertex_only=False)
bpy.ops.object.editmode_toggle()
bpy.ops.object.shade_smooth()
bpy.data.objects['StartCube'].select_set(state = False)

bpy.ops.mesh.primitive_plane_add(size = 1, enter_editmode=False, location=(0, 0, 0))
bpy.data.objects['Plane'].scale = (2,2,1)
bpy.data.objects['Plane'].rotation_euler[0] = np.pi/2

bpy.data.objects["Camera"].location = (0,4,0)
bpy.data.objects["Camera"].rotation_euler = (-np.pi/2,np.pi,0)

bpy.data.objects['Light'].data.use_nodes = True
bpy.data.objects['Light'].data.node_tree.nodes['Emission'].inputs[1].default_value = 0.5
bpy.data.objects['Light'].data.type = 'AREA'
bpy.data.objects['Light'].location = (0,0,4.5)
bpy.data.objects["Light"].rotation_euler = (0,0,0)
bpy.data.objects['Light'].scale = (50,50,50)

###############################################################################
# Visualization settings
###############################################################################

maxScale = 0.025
nItems = [15,25]
delta = 0.2
xStretch = nItems[0]*maxScale+delta
yStretch = nItems[1]*maxScale+delta
stretch = [xStretch,yStretch]

center = GetCentersLocations(nItems,stretch)
names = AddElementsFromLocations(center,maxScale,"Cube","Test")

CropPoint = int(np.random.random()*len(names))
ColorClassA = np.random.random(3)
ColorClassB = np.random.random(3)
NamesClassA = names[0:CropPoint]
NamesClassB = names[CropPoint:len(names)]

for nme in NamesClassA:
    AddTypeAnodizedMetalMaterial(nme,ColorClassA)

for nme in NamesClassB:
    AddTypeAnodizedMetalMaterial(nme,ColorClassB)

labels = ["Class A", "Class B"]
nlabels= len(labels)
labelLocations = [[-1.2*xStretch,0,val] for val in np.linspace(-yStretch,0,2*nlabels)][::-1]
labelNames = AddElementsFromLocations(labelLocations[0:nlabels],maxScale,"Cube","lab")

for k,lab in enumerate(labels):
    location = np.array(labelLocations[k]) - np.array([2*maxScale,-0.1,maxScale/2])
    InsertAndChangeText(location,lab,lab+"text",3*maxScale,(np.pi/2,0,np.pi))
    AddTypeAMaterial(lab+"text",(0,0,0))

AddTypeAnodizedMetalMaterial(labelNames[0],ColorClassA)
AddTypeAnodizedMetalMaterial(labelNames[1],ColorClassB)


#!/usr/bin/env python
# coding: utf-8

# In[6]:

import pyttsx3

# In[9]:

import PyPDF2

# In[13]:

hikaye = open("deep-learning.pdf","rb")

# In[12]:

pdfOkuyucu = PyPDF2.PdfFileReader(hikaye)

# In[14]:

from PyPDF2 import PdfReader

# In[16]:

pdfOkuyucu = PyPDF2.PdfReader(hikaye)

# In[18]:

engine = pyttsx3.init()

# In[19]:

voices = engine.getProperty('voices')

# In[20]:

engine.setProperty('voice',voices[0].id)

# In[31]:

for sayfa_numarasi in range(0,len(pdfOkuyucu.pages)):
    sayfa = pdfOkuyucu.pages[sayfa_numarasi]
    yazi = sayfa.extract_text
    engine.say(yazi)
    engine.runAndWait()

# In[ ]:


# Lawrence McAfee

# ~~~~~~~~ import ~~~~~~~~
from modules.node.HierNode import HierNode
from modules.node.LeafNode import LeafNode
from modules.node.Stage import Stage
from modules.node.block.CodeBlock import CodeBlock as cbk
from modules.node.block.ImageBlock import ImageBlock as ibk
from modules.node.block.MarkdownBlock import MarkdownBlock as mbk

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
blocks = [
    mbk("In regression trees, the recursive binary splitting technique is used to divide a particular feature in the dataset into two regions. The splitting is carried out by choosing a value of the feature that minimizes the regression error measure. This step is done for all the predictors in the dataset by finding a value that reduces the squared error of the final tree. This process is repeated continuously for every sub-tree or sub-region until a stopping criterion is reached. For example, we can stop the algorithm when no region contains less than ten observations. An example of a tree resulting from the splitting of a feature space into six regions is shown in Figure 23-2."),
    ibk(None, "Figure 23-2. Left: An example of splitting a 2-D dataset into sub-trees/regions using the recursive binary splitting technique. Right: The resulting tree from the partitioning on the left."),
]

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Content(LeafNode):
    def __init__(self):
        super().__init__(
            "Growing a Regression Tree",
            Stage.REMOVE_EXTRANEOUS,
            Stage.ORIG_BLOCKS,
            # Stage.CUSTOM_BLOCKS,
            # Stage.ORIG_FIGURES,
            # Stage.CUSTOM_FIGURES,
            # Stage.CUSTOM_EXERCISES,
        )
        self.add(mbk("# Growing a Regression Tree"))
        [self.add(a) for a in blocks]

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Growinga(HierNode):
    def __init__(self):
        super().__init__("Growing a Regression Tree")
        self.add(Content())

# eof