from django.shortcuts import render
from .forms import MyForm
from django.contrib import messages
from base64 import b64encode
from .editing import trim_image_to_square
import pickle
pickled_model = pickle.load(open('knn_model_images.pkl', 'rb'))

def one_view(request):
    if request.method == 'POST':
        one_form = MyForm(request.POST, request.FILES)
        if one_form.is_valid():
            # name = one_form.cleaned_data
            image_file = one_form.cleaned_data.get('img')
            data = image_file.read()
            encoded = b64encode(data).decode()
            mime = 'image/jpeg;'
            edited_image_array = trim_image_to_square(image_file)
            edited_image_array = pickled_model.predict(edited_image_array.reshape(1, -1))
            # edited_image_array = edited_image_array.reshape(1, -1)

            """
            data = image_file.read()
            encoded = b64encode(data).decode()
            mime = 'image/jpeg;'
            context = {"image": f"data:{mime}base64,{encoded}",
                       'data': name.get('name'),
                       'one_form': MyForm()
                       }
            """
            context = {'image': edited_image_array, 'one_form': MyForm(), "image2": f"data:{mime}base64,{encoded}"}
            messages.success(request, "Data is in order")
            return render(request, 'myapp/home.html', context)
        else:
            messages.error(request, one_form.errors)
            return render(request, 'myapp/home.html', {'one_form': MyForm()})
    else:
        return render(request, 'myapp/home.html', {'one_form': MyForm()})

def methodology(request):
    return render(request, 'myapp/methodology.html', {})


from chimerax.core.errors import UserError

_valid_db_commands = {
    'pdb':          'rcsb',
    'pdbe_updated': 'pdbe',
    'pdbe':         'pdbe',
    'pdbj':         'pdbj'
}

_cif_sources = {
    'rcsb': 'http://files.rcsb.org/download/{}-sf.cif',
    'pdbe': 'http://www.ebi.ac.uk/pdbe/entry-files/download/r{}sf.ent',
    # Only the coordinates are updated, not the data
    'pdbj': 'https://pdbj.org/rest/downloadPDBfile?format=sf&id={}'
}

_cif_filenames = {
    'rcsb': '{}-sf.cif',
    'pdbe': 'r{}sf.cif',
    'pdbj': 'r{}sf.cif',
}

_compressed = {
    'rcsb': False,
    'pdbe': False,
    'pdbj': True
}

def fetch_structure_factors(session, pdb_id, fetch_source='rcsb', ignore_cache=False, **kw):
    '''Get a structure factor file in CIF format by PDB identifier via the Internet'''
    if len(pdb_id) != 4:
        raise UserError('PDB identifiers are 4 characters long, got "{}"'.format(pdb_id))
    if fetch_source not in _cif_sources.keys():
        fetch_source = _valid_db_commands.get(fetch_source, None)
    if fetch_source is None:
        raise UserError('Fetching structure factors is not implemented for "fromDatabase {}"! Must be one of the following: {}'.format(
            fetch_source, ', '.join(_valid_db_commands.keys())
        ))
    import os
    pdb_id = pdb_id.lower()
    save_name = _cif_filenames[fetch_source].format(pdb_id)
    url = _cif_sources[fetch_source].format(pdb_id)
    from chimerax.core.fetch import fetch_file
    filename = fetch_file(session, url, '{} structure factors'.format(pdb_id),
        save_name, 'PDB-SF',
        uncompress=_compressed[fetch_source],
        ignore_cache=ignore_cache
        )

    # Double check that a cif file was downloaded instead of an HTML error
    # message saying the ID does not exist
    with open(filename, 'r') as f:
        line = f.readline()
        if not line.startswith(('data_', '#')):
            f.close()
            os.remove(filename)
            raise UserError('Structure factors could not be retrieved! Are you '
                'sure this is an x-ray structure?')

    return filename

def fetch_structure_factors_pdbe(session, pdb_id, **kw):
    return fetch_structure_factors(session, pdb_id, fetch_source='pdbe', **kw)

def fetch_structure_factors_pdbe_updated(session, pdb_id, **kw):
    return fetch_structure_factors(session, pdb_id, fetch_source='pdbe', **kw)

def fetch_structure_factors_pdbj(session, pdb_id, **kw):
    return fetch_structure_factors(session, pdb_id, fetch_source='pdbj', **kw)

def fetch_wrapper(fetch_func):
    def _fetch(session, pdb_id, fetch_source='rcsb', ignore_cache=False,
            structure_factors=False, over_sampling=2.0, **kw):
        models, status = fetch_func(session, pdb_id, ignore_cache=ignore_cache, **kw)
        if structure_factors:
            if len(models) != 1:
                raise UserError('Structure factors can only be used with a single model!')
            m = models[0]
            sf_file = fetch_structure_factors(session, pdb_id, fetch_source=fetch_source,
                ignore_cache=ignore_cache, **kw)
            from chimerax.clipper.symmetry import get_map_mgr
            mmgr = get_map_mgr(m, create=True)
            mmgr.add_xmapset_from_mtz(sf_file, oversampling_rate = over_sampling)
            return [mmgr.crystal_mgr], status
        return models, status
    return _fetch


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

# In[ ]:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# In[ ]:

def convert_rgb_to_gray(im1):
    m=im1.shape[0]
    n=im1.shape[1]
    im2=np.zeros((m,n))
    for i in range(m):
        for j in range(n):
            im2[i,j]=get_distance(im1[i,j,:])
    return im2

# In[ ]:

def get_distance(v,w=[1/3,1/3,1/3]):
    a,b,c=v[0],v[1],v[2]
    w1,w2,w3=w[0],w[1],w[2]
    d=((a**2)*w1 +
      (b**2)*w2 +
      (c**2)*w3)**.5
    return d

# In[ ]:

def get_default_mask_for_mean():
    return np.array([1,1,1,1,1,1,1,1,1]).reshape(3,3)/9

# In[ ]:

def apply_mask(part_of_img):
    mask = get_default_mask_for_mean()
    return sum(sum(part_of_img*mask))

# In[ ]:

b1 = np.array([1,1,1,1,1,1,1,1,1]).reshape(3,3)/9
b1

# In[ ]:

img_1 = mpimg.imread('resim.jpg')
img_2 = convert_rgb_to_gray(img_1)
get_ipython().run_line_magic('matplotlib', 'inline')
plt.figure(figsize=(20,20))
plt.subplot(1,3,1),plt.imshow(img_1)

# In[ ]:

def get_median_for_55(poi):
    s1 = poi.reshape(1,25)
    s1.sort()
    return s1[0,13]

# In[ ]:

def get_median(poi):
    s1 = poi.reshape(1,9)
    s1.sort()
    return s1[0,4]

# In[ ]:

def get_mean_filter_for_55(im_1):
    m = im_1.shape[0]
    n = im_1.shape[1]
    im_2 = np.zeros((m,n))

    for i in range (3,m-3):
        for j in range (3,n-3):
            poi = im_1[i-2:i+3,j-2:j+3]
            im_2[i,j] = get_median_for_55(poi)
    return im_2

# In[ ]:

def get_mean_filter(im_1):
    m = im_1.shape[0]
    n = im_1.shape[1]
    im_2 = np.zeros((m,n))

    for i in range (1,m-1):
        for j in range (1,n-1):
            poi = im_1[i-1:i+2,j-1:j+2]
            im_2[i,j] = get_median(poi)
    return im_2

# In[ ]:

apply_mask(img_2[1:4,1:4])

# In[ ]:

img_55 = get_mean_filter_for_55(img_2)

# In[ ]:

plt.figure(figsize=(20,20))
plt.subplot(1,2,1),plt.imshow(img_2, cmap = 'gray')
plt.subplot(1,2,2),plt.imshow(img_55, cmap = 'gray')

# In[ ]:


from re import template
from django.shortcuts import render
from django.http import HttpResponse
from blog.models import *
from accounts.models import Profil
from game.models import Gaming

def index(request):

    posts = Post.objects.filter(status='publié')[:4]
    direction = Direction.objects.order_by('-id')[:3]
    partenaires = Partnaire.objects.order_by('-id')[:4]
    games = Gaming.objects.all()[:8]
    authors = Profil.objects.all()[:2]

    template_name = 'layouts/index.html'
    context = {
        'posts': posts,
        'authors': authors,
        'games': games,
        'direction': direction,
        'partenaires': partenaires,
    }

    return render(request, template_name, context)


def backword(text):
	temp = []
	text = text.replace("", "BREAKSPACE_HOLDER")
	text = text.split("BREAKSPACE_HOLDER")
	ltext = len(text)
	for x in text:
		ltext = ltext - 1
		temp.append(text[ltext])
	text = "".join(temp)
	del temp
	return text
	del text


"""Extensions to Python :py:mod:`dataclasses`, for streamlined class definition.
"""
import collections
import copy
import dataclasses
import enum
import functools
import re
import typing
from . import basic
from . import exceptions

import logging
_log = logging.getLogger(__name__)

class RegexPatternBase():
    """Dummy parent class for :class:`RegexPattern` and
    :class:`ChainedRegexPattern`.
    """
    pass

class RegexPattern(collections.UserDict, RegexPatternBase):
    """Wraps :py:class:`re.Pattern` with more convenience methods for the use case
    of parsing information in a string, using a regex with named capture groups
    corresponding to the data fields being collected from the string.
    """
    def __init__(self, regex, defaults=None, input_field=None,
        match_error_filter=None):
        """Constructor.

        Args:
            regex (str or :py:class:`re.Pattern`): regex to use for string
                parsing. Should contain named match groups corresponding to the
                fields to parse.
            defaults (dict): Optional. If supplied, any fields not matched by the
                named match groups in *regex* will be set equal to their values here.
            input_field (str): Optional. If supplied, add a field to the match with
                the supplied name which will be set equal to the contents of the
                input string on a successful match.
            match_error_filter (bool or :class:`RegexPattern` or :class:`ChainedRegexPattern`):
                Optional. If supplied, determines whether a ValueError is raised
                when the :meth:`match` method fails to parse a string (see below.)

        Attributes:
            data (dict): Key:value pairs corresponding to the contents of the
                matching groups from the last successful call to :meth:`match`, or
                empty if no successful call has been made. From
                :py:class:`collections.UserDict`.
            fields (frozenset): Set of fields matched by the pattern. Consists of the
                union of named match groups in *regex*, and all keys in *defaults*.
            input_string (str): Contains string that was input to last call of
                :meth:`match`, whether successful or not.
            is_matched (bool): True if the last call to :meth:`match` was
                successful, False otherwise.
        """
        try:
            if isinstance(regex, re.Pattern):
                self.regex = regex
            else:
                self.regex = re.compile(regex, re.VERBOSE)
        except re.error as exc:
            raise ValueError('Malformed input regex.') from exc
        if self.regex.groups != len(self.regex.groupindex):
            # _log.warning("Unnamed match groups in regex")
            pass
        if self.regex.groups == 0:
            # _log.warning("No named match groups in regex")
            pass

        if not defaults:
            self._defaults = dict()
        else:
            self._defaults = defaults.copy()
        self.input_field = input_field
        self._match_error_filter = match_error_filter
        self._update_fields()

    def clear(self):
        """Erase field values parsed from a pre-existing match.
        """
        self.data = dict()
        self.input_string = ""
        self.is_matched = False

    def _update_fields(self):
        self.regex_fields = frozenset(self.regex.groupindex.keys())
        self.fields = self.regex_fields.union(self._defaults.keys())
        if self.input_field:
            self.fields = self.fields.union((self.input_field, ))
        self.clear()

    def update_defaults(self, d):
        """Update the default values used for the match with the values in *d*.
        """
        if d:
            self._defaults.update(d)
            self._update_fields()

    def match(self, str_, *args):
        """Match *str\_* using Python :py:func:`re.fullmatch` with *regex* and
        populate object's fields according to the values captured by the named
        capture groups in *regex*.

        Args:
            str\_ (str): Input string to parse.
            args: Optional. Flags (as defined in Python :py:mod:`re`) to use in
                the :py:func:`re.fullmatch` method of the *regex* and *match_error_filter*
                (if defined.)

        Raises:
            :class:`~exceptions.RegexParseError`: If :meth:`match` fails to parse
                the input string, and the following conditions on *match_error_filter*
                are met. If *match_error_filter* not supplied
                (default), always raise when :meth:`match` fails. If *match_error_filter*
                is bool, always/never raise. If *match_error_filter*
                is a :class:`RegexPattern` or :class:`ChainedRegexPattern`, attempt
                to :meth:`match` the input string that caused the failed match
                against the value of *match_error_filter*. If it matches, do not
                raise an error; otherwise raise an error.
            :class:`~exceptions.RegexSuppressedError`: If :meth:`match` fails to
                parse the input string and the above conditions involving
                *match_error_filter* are not met. One of RegexParseError or
                RegexSuppressedError is always raised on failure.
        """
        self.clear() # to be safe
        self.input_string = str_
        m = self.regex.fullmatch(str_, *args)
        if not m:
            self.is_matched = False
            if hasattr(self._match_error_filter, 'match'):
                try:
                    self._match_error_filter.match(str_, *args)
                except Exception as exc:
                    raise exceptions.RegexParseError(
                        f"Couldn't match {str_} against {self.regex}.")
                raise exceptions.RegexSuppressedError(str_)
            elif self._match_error_filter:
                raise exceptions.RegexSuppressedError(str_)
            else:
                raise exceptions.RegexParseError(
                    f"Couldn't match {str_} against {self.regex}.")
        else:
            self.data = m.groupdict(default=NOTSET)
            for k,v in self._defaults.items():
                if self.data.get(k, NOTSET) is NOTSET:
                    self.data[k] = v
            if self.input_field:
                self.data[self.input_field] = m.string

            self._validate_match(m)
            if any(self.data[f] is NOTSET for f in self.fields):
                bad_names = [f for f in self.fields if self.data[f] is NOTSET]
                raise exceptions.RegexParseError((f"Couldn't match the "
                    f"following fields in {str_}: " + ', '.join(bad_names) ))
            self.is_matched = True

    def _validate_match(self, match_obj):
        """Hook for post-processing of match, running after all fields are
        assigned but before final check that all fields are set.
        """
        pass

    def __str__(self):
        if not self.is_matched:
            str_ = ', '.join(self.fields)
        else:
            str_ = ', '.join([f'{k}={v}' for k,v in self.data.items()])
        return f"<{self.__class__.__name__}({str_})>"

    def __copy__(self):
        if hasattr(self._match_error_filter, 'copy'):
            match_error_filter_copy = self._match_error_filter.copy()
        else:
            # bool or None
            match_error_filter_copy = self._match_error_filter
        obj = self.__class__(
            self.regex.pattern,
            defaults=self._defaults.copy(),
            input_field=self.input_field,
            match_error_filter=match_error_filter_copy,
        )
        obj.data = self.data.copy()
        return obj

    def __deepcopy__(self, memo):
        obj = self.__class__(
            copy.deepcopy(self.regex.pattern, memo),
            defaults=copy.deepcopy(self._defaults, memo),
            input_field=copy.deepcopy(self.input_field, memo),
            match_error_filter=copy.deepcopy(self._match_error_filter, memo)
        )
        obj.data = copy.deepcopy(self.data, memo)
        return obj

class RegexPatternWithTemplate(RegexPattern):
    """Adds formatted output to :class:`RegexPattern`.
    """
    def __init__(self, regex, defaults=None, input_field=None,
        match_error_filter=None, template=None, log=_log):
        """Constructor.

        Args:
            template (str): Optional. Template string to use for formatting
                contents of match in :meth:`format` method. Contents of the matched
                fields will be subsituted using the {}-syntax of python string
                formatting.

        Other arguments are the same as in :class:`RegexPattern`.
        """
        super(RegexPatternWithTemplate, self).__init__(regex, defaults=defaults,
            input_field=input_field, match_error_filter=match_error_filter)
        self.template = template
        for f in self.fields:
            if f not in self.template:
                log.warning("Field %s not included in output.", f)

    def format(self):
        """Return *template* string, templated with the values obtained in the last
        successful call to :meth:`match`.
        """
        if self.template is None:
            raise AssertionError('Template string needs to be defined.')
        if not self.is_matched:
            raise ValueError('No match')
        return self.template.format(**self.data)

    def __copy__(self):
        if hasattr(self._match_error_filter, 'copy'):
            match_error_filter_copy = self._match_error_filter.copy()
        else:
            # bool or None
            match_error_filter_copy = self._match_error_filter
        obj = self.__class__(
            self.regex.pattern,
            defaults=self._defaults.copy(),
            input_field=self.input_field,
            match_error_filter=match_error_filter_copy,
            template=self.template
        )
        obj.data = self.data.copy()
        return obj

    def __deepcopy__(self, memo):
        obj = self.__class__(
            copy.deepcopy(self.regex.pattern, memo),
            defaults=copy.deepcopy(self._defaults, memo),
            input_field=copy.deepcopy(self.input_field, memo),
            match_error_filter=copy.deepcopy(self._match_error_filter, memo),
            template=copy.deepcopy(self.template, memo)
        )
        obj.data = copy.deepcopy(self.data, memo)
        return obj

class ChainedRegexPattern(RegexPatternBase):
    """Class which takes an 'or' of multiple :class:`RegexPattern`\s, to parse
    data that may be represented as a string in one of multiple formats.

    Matches are attempted on the supplied RegexPatterns in order, with the first
    one that succeeds determining the parsed field values. Public methods work
    the same as on :class:`RegexPattern`.
    """
    def __init__(self, *string_patterns, defaults=None, input_field=None,
        match_error_filter=None):
        """Constructor.

        Args:
            string_patterns (iterable of :class:`RegexPattern`): Individual
                regexes which will be tried, in order, when :meth:`match` is
                called. Parsing will be done by the first RegexPattern whose
                :meth:`match` succeeds.

        .. note::
           The constructor changes attributes on :class:`RegexPattern` objects
           passed as *string_patterns*, so once the object is created its
           component :class:`RegexPattern` objects shouldn't be accessed on
           their own.

        Other arguments and attributes are the same as in :class:`RegexPattern`.
        """
        # NB, changes attributes on patterns passed as arguments, so
        # once created they can't be used on their own
        new_pats = []
        for pat in string_patterns:
            if isinstance(pat, RegexPattern):
                new_pats.append(pat)
            elif isinstance(pat, ChainedRegexPattern):
                new_pats.extend(pat._patterns)
            else:
                raise ValueError("Bad input")
        self._patterns = tuple(string_patterns)
        if input_field:
            self.input_field = input_field
        self._match_error_filter = match_error_filter
        for pat in self._patterns:
            if defaults:
                pat.update_defaults(defaults)
            if input_field:
                pat.input_field = input_field
            pat._match_error_filter = None
            pat._update_fields()
        self._update_fields()

    @property
    def is_matched(self):
        return (self._match >= 0)

    @property
    def data(self):
        if self.is_matched:
            return self._patterns[self._match].data
        else:
            return dict()

    def clear(self):
        for pat in self._patterns:
            pat.clear()
        self._match = -1
        self.input_string = ""

    def _update_fields(self):
        self.fields = self._patterns[0].fields
        for pat in self._patterns:
            if pat.fields != self.fields:
                raise ValueError("Incompatible fields.")
        self.clear()

    def update_defaults(self, d):
        if d:
            for pat in self._patterns:
                pat.update_defaults(d)
        self._update_fields()

    def match(self, str_, *args):
        self.clear()
        self.input_string = str_
        for i, pat in enumerate(self._patterns):
            try:
                pat.match(str_, *args)
                if not pat.is_matched:
                    raise ValueError()
                self._match = i
            except ValueError:
                continue
        if not self.is_matched:
            if hasattr(self._match_error_filter, 'match'):
                try:
                    self._match_error_filter.match(str_, *args)
                except Exception as exc:
                    raise exceptions.RegexParseError((f"Couldn't match {str_} "
                        f"against any pattern in {self.__class__.__name__}."))
                raise exceptions.RegexSuppressedError(str_)
            elif self._match_error_filter:
                raise exceptions.RegexSuppressedError(str_)
            else:
                raise exceptions.RegexParseError((f"Couldn't match {str_} "
                    f"against any pattern in {self.__class__.__name__}."))

    def __str__(self):
        if not self.is_matched:
            str_ = ', '.join(self.fields)
        else:
            str_ = ', '.join([f'{k}={v}' for k,v in self.data.items()])
        return f"<{self.__class__.__name__}({str_})>"

    def format(self):
        if not self.is_matched:
            raise ValueError('No match')
        return self._patterns[self._match].format()

    def __copy__(self):
        new_pats = (pat.copy() for pat in self._patterns)
        return self.__class__(
            *new_pats,
            match_error_filter=self._match_error_filter.copy()
        )

    def __deepcopy__(self, memo):
        new_pats = (copy.deepcopy(pat, memo) for pat in self._patterns)
        return self.__class__(
            *new_pats,
            match_error_filter=copy.deepcopy(self._match_error_filter, memo)
        )

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

NOTSET = basic.sentinel_object_factory('NotSet')
"""
Sentinel object to detect uninitialized values for fields in :func:`mdtf_dataclass`
objects, for use in cases where ``None`` is a valid value for the field.
"""

MANDATORY = basic.sentinel_object_factory('Mandatory')
"""
Sentinel object to mark all :func:`mdtf_dataclass` fields that do not take a default
value. This is a workaround to avoid errors with non-default fields coming after
default fields in the dataclass auto-generated ``__init__`` method under
`inheritance <https://docs.python.org/3/library/dataclasses.html#inheritance>`__:
we use the second solution described in `<https://stackoverflow.com/a/53085935>`__.
"""

def _mdtf_dataclass_get_field_types(obj, f):
    """Common functionality for :func:`_mdtf_dataclass_type_coercion` and
    :func:`_mdtf_dataclass_type_check`. Given a :py:class:`datacalsses.Field`
    object *f*, return either a tuple of the type its value should be coerced to
    and a tuple of the valid types its value can have, or (None, None) to signal
    a case we don't handle.
    """
    if not f.init:
        # ignore fields that aren't handled at init
        return (None, None)
    value = getattr(obj, f.name)
    # ignore unset field values, regardless of type
    if value is None or value is NOTSET:
        return (None, None)
    # guess what types are valid
    new_type = None
    if f.type is typing.Any or isinstance(f.type, typing.TypeVar):
        return (None, None)
    if dataclasses.is_dataclass(f.type):
        # ignore if type is a dataclass: use this type annotation to
        # implement dataclass inheritance
        if not isinstance(obj, f.type):
            raise exceptions.DataclassParseError((f"Field {f.name} specified "
                f"as dataclass {f.type.__name__}, which isn't a parent class "
                f"of {obj.__class__.__name__}."))
        return (None, None)
    elif isinstance(f.type, typing._GenericAlias) \
        or isinstance(f.type, typing._SpecialForm):
        # type is a generic from typing module, eg "typing.List"
        if f.type.__origin__ is typing.Union:
            new_type = None # can't do coercion, but can test type
            valid_types = list(f.type.__args__)
        elif issubclass(f.type.__origin__, typing.Generic):
            return (None, None) # can't do anything in this case
        else:
            new_type = f.type.__origin__
            valid_types = [new_type]
    else:
        new_type = f.type
        valid_types = [new_type]
    # Get types of field's default value, if present. Dataclass doesn't
    # require defaults to be same type as what's given for field.
    if not isinstance(f.default, dataclasses._MISSING_TYPE):
        valid_types.append(type(f.default))
    if not isinstance(f.default_factory, dataclasses._MISSING_TYPE):
        valid_types.append(type(f.default_factory()))
    return (new_type, valid_types)

def _mdtf_dataclass_type_coercion(self, log):
    """Do type checking on all dataclass fields after the auto-generated
    ``__init__`` method, but before any ``__post_init__`` method.

    .. warning::
       Type checking logic used is specific to the ``typing`` module in python
       3.7. It may or may not work on newer pythons, and definitely will not
       work with 3.5 or 3.6. See `<https://stackoverflow.com/a/52664522>`__.
    """
    for f in dataclasses.fields(self):
        value = getattr(self, f.name, NOTSET)
        new_type, valid_types = _mdtf_dataclass_get_field_types(self, f)
        try:
            if valid_types is None or isinstance(value, tuple(valid_types)):
                continue # don't coerce if we're already a valid type
            if new_type is None or hasattr(new_type, '__abstract_methods__'):
                continue # can't do type coercion
            else:
                if hasattr(new_type, 'from_struct'):
                    new_value = new_type.from_struct(value)
                elif isinstance(new_type, enum.Enum):
                    # need to use item syntax to create enum from name
                    new_value = new_type.__getitem__(value)
                else:
                    new_value = new_type(value)
                # https://stackoverflow.com/a/54119384 for implementation
                object.__setattr__(self, f.name, new_value)
        except (TypeError, ValueError, dataclasses.FrozenInstanceError) as exc:
            raise exceptions.DataclassParseError((f"{self.__class__.__name__}: "
                f"Couldn't coerce value {repr(value)} for field {f.name} from "
                f"type {type(value)} to type {new_type}.")) from exc
        except Exception as exc:
            log.exception("%s: Caught exception: %r", self.__class__.__name__, exc)
            raise exc

def _mdtf_dataclass_type_check(self, log):
    """Do type checking on all dataclass fields after ``__init__`` and
    ``__post_init__`` methods.

    .. warning::
       Type checking logic used is specific to the ``typing`` module in python
       3.7. It may or may not work on newer pythons, and definitely will not
       work with 3.5 or 3.6. See `<https://stackoverflow.com/a/52664522>`__.
    """
    for f in dataclasses.fields(self):
        value = getattr(self, f.name, NOTSET)
        if value is None or value is NOTSET:
            continue
        if value is MANDATORY:
            raise exceptions.DataclassParseError((f"{self.__class__.__name__}: "
                f"No value supplied for mandatory field {f.name}."))

        _, valid_types = _mdtf_dataclass_get_field_types(self, f)
        if valid_types is not None and not isinstance(value, tuple(valid_types)):
            log.exception("%s: Failed type check for field '%s': %s != %s.",
                self.__class__.__name__, f.name, type(value), valid_types)
            raise exceptions.DataclassParseError((f"{self.__class__.__name__}: "
                f"Expected {f.name} to be {f.type}, got {type(value)} "
                f"({repr(value)})."))

DEFAULT_MDTF_DATACLASS_KWARGS = {'init': True, 'repr': True, 'eq': True,
    'order': False, 'unsafe_hash': False, 'frozen': False}

# declaration to allow calling with and without args: python cookbook 9.6
# https://github.com/dabeaz/python-cookbook/blob/master/src/9/defining_a_decorator_that_takes_an_optional_argument/example.py

def mdtf_dataclass(cls=None, **deco_kwargs):
    """Wrap the Python :py:func:`~dataclasses.dataclass` class decorator to customize
    dataclasses to provide rudimentary type checking and conversion. This
    is hacky, since dataclasses don't enforce type annontations for their fields.
    A better solution would be to use the third-party
    `cattrs <https://github.com/Tinche/cattrs>`__ package, which has essentially
    the same aim.

    The decorator rewrites the class's constructor as follows:

    1. Execute the auto-generated ``__init__`` method from Python
       :py:func:`~dataclasses.dataclass`.

    2. Verify that fields with ``MANDATORY`` default have been assigned values.
       We have to work around the usual :py:func:`~dataclasses.dataclass` way of
       doing this, because it leads to errors in the signature of the auto-generated
       ``__init__`` method under inheritance (mandatory fields can't come after
       optional fields in the signature.)

    3. Execute the class's ``__post_init__`` method, if defined, which can do
       more complex type coercion and validation.

    4. Finally, check each field's value to see if it's consistent with the given
       type information. If not, attempt to coerce it to that type, using a
       ``from_struct`` method on that type if it exists.

    .. warning::
       Unlike :py:func:`~dataclasses.dataclass`, all fields **must** have a
       *default* or *default_factory* defined. Fields which are mandatory must
       have their default value set to the sentinel object ``MANDATORY``.
       This is necessary in order for dataclass inheritance to work properly, and
       is not currently enforced when the class is decorated.

    Args:
        cls (class): Class to be decorated.
        deco_kwargs: Optional. Keyword arguments to pass to the Python
            :py:func:`~dataclasses.dataclass` class decorator.

    Raises:
        :class:`~exceptions.DataclassParseError`: If we attempted to construct an
            instance without giving values for ``MANDATORY`` fields, or if values
            of some fields after ``__post_init__`` could not be coerced into the
            types given in their annotation.
    """
    dc_kwargs = DEFAULT_MDTF_DATACLASS_KWARGS.copy()
    dc_kwargs.update(deco_kwargs)
    if cls is None:
        # called without arguments
        return functools.partial(mdtf_dataclass, **dc_kwargs)

    if not hasattr(cls, '__post_init__'):
        # create dummy __post_init__ if none defined, so we can wrap it.
        # contrast with what we do below in regex_dataclass()
        def _dummy_post_init(self, *args, **kwargs): pass
        type.__setattr__(cls, '__post_init__', _dummy_post_init)

    # apply dataclasses' decorator
    cls = dataclasses.dataclass(cls, **dc_kwargs)

    # Do type coercion after dataclass' __init__, but before user __post_init__
    # Do type check after __init__ and __post_init__
    _old_post_init = cls.__post_init__

    @functools.wraps(_old_post_init)
    def _new_post_init(self, *args, **kwargs):
        if hasattr(self, 'log'):
            _post_init_log = self.log  # for object hierarchy
        else:
            _post_init_log = _log  # fallback: use module-level logger
        _mdtf_dataclass_type_coercion(self, _post_init_log)
        _old_post_init(self, *args, **kwargs)
        _mdtf_dataclass_type_check(self, _post_init_log)
    type.__setattr__(cls, '__post_init__', _new_post_init)

    return cls

def is_regex_dataclass(obj):
    """Returns True if *obj* is a :func:`regex_dataclass`.
    """
    return hasattr(obj, '_is_regex_dataclass') and obj._is_regex_dataclass == True

def _regex_dataclass_preprocess_kwargs(self, kwargs):
    """Edit kwargs going to the auto-generated __init__ method of this dataclass.
    If any fields are regex_dataclasses, construct and parse their values first.

    Raises a DataclassParseError if different regex_dataclasses (at any level of
    inheritance) try to assign different values to a field of the same name. We
    do this by assigning to a :class:`~src.util.basic.ConsistentDict`.
    """
    new_kw = filter_dataclass(kwargs, self, init='all')
    new_kw = basic.ConsistentDict.from_struct(new_kw)
    for cls_ in self.__class__.__bases__:
        if not is_regex_dataclass(cls_):
            continue
        for f in dataclasses.fields(self):
            if not f.type == cls_:
                continue
            if f.name in kwargs:
                val = kwargs[f.name]
            elif not isinstance(f.default, dataclasses._MISSING_TYPE):
                val = f.default
            elif not isinstance(f.default_factory, dataclasses._MISSING_TYPE):
                val = f.default_factory()
            else:
                raise exceptions.DataclassParseError(f"Can't set value for {f.name}.")
            new_d = dataclasses.asdict(f.type.from_string(val))
            new_d = filter_dataclass(new_d, self, init='all')
            try:
                new_kw.update(new_d)
            except exceptions.WormKeyError as exc:
                raise exceptions.DataclassParseError((f"{self.__class__.__name__}: "
                    f"Tried to make inconsistent field assignment when parsing "
                    f"{f.name} as an instance of {f.type.__name__}.")) from exc
    post_init = dict()
    for f in dataclasses.fields(self):
        if not f.init and f.name in new_kw:
            post_init[f.name] = new_kw.pop(f.name)
    return (new_kw, post_init)

def regex_dataclass(pattern, **deco_kwargs):
    """Decorator combining the functionality of :class:`RegexPattern` and
    :func:`mdtf_dataclass`: dataclass fields are parsed from a regex and coerced
    to appropriate classes.

    Specifically, this is done via a ``from_string`` classmethod, added by this
    decorator, which creates dataclass instances by parsing an input string with
    a :class:`RegexPattern` or :class:`ChainedRegexPattern`. The values of all
    fields returned by the :meth:`~RegexPattern.match` method of the pattern are
    passed to the ``__init__`` method of the dataclass as kwargs.

    Additionally, if the type of one or more fields is set to a class that's
    also been decorated with regex_dataclass, the parsing logic for that field's
    regex_dataclass will be invoked on that field's value (i.e., a string obtained
    by regex matching in *this* regex_dataclass), and the parsed values of those
    fields will be supplied to this regex_dataclass constructor. This is our
    implementation of composition for regex_dataclasses.

    .. note::
       Unlike :func:`mdtf_dataclass`, type coercion here is done *after*
       ``__post_init__`` for these dataclasses. This is necessary due to
       composition: if a regex_dataclass is being instantiated as a field of
       another regex_dataclass, all values being passed to it will be strings
       (the regex fields), and type coercion is the job of ``__post_init__``.
    """
    dc_kwargs = DEFAULT_MDTF_DATACLASS_KWARGS.copy()
    dc_kwargs.update(deco_kwargs)

    def _dataclass_decorator(cls):
        if '__post_init__' not in cls.__dict__:
            # Prevent class from inheriting __post_init__ from parents if it
            # doesn't overload it (which is why we use __dict__ and not
            # hasattr().) __post_init__ of all parents will have been called when
            # the parent classes are instantiated by _regex_dataclass_preprocess_kwargs.
            def _dummy_post_init(self, *args, **kwargs): pass
            type.__setattr__(cls, '__post_init__', _dummy_post_init)

        # apply dataclasses' decorator
        cls = dataclasses.dataclass(cls, **dc_kwargs)
        # check that all DCs specified as fields are also in class hierarchy
        # so that we inherit their fields; probably no way this could happen though
        for f in dataclasses.fields(cls):
            if is_regex_dataclass(f.type) and f.type not in cls.__mro__:
                raise TypeError((f"{cls.__name__}: Field {f.name} specified as "
                    f"{f.type.__name__}, but we don't inherit from it."))

        _old_init = cls.__init__
        @functools.wraps(_old_init)
        def _new_init(self, first_arg=None, *args, **kwargs):
            if isinstance(first_arg, str) and not args and not kwargs:
                # instantiate from running regex on string, if a string is the
                # only argument to the constructor
                self._pattern.match(first_arg)
                first_arg = None
                kwargs = self._pattern.data
            new_kw, other_kw = _regex_dataclass_preprocess_kwargs(self, kwargs)
            for k,v in other_kw.items():
                # set field values that aren't arguments to _old_init
                object.__setattr__(self, k, v)
            if first_arg is None:
                _old_init(self, *args, **new_kw)
            else:
                _old_init(self, first_arg, *args, **new_kw)

            _mdtf_dataclass_type_coercion(self, _log)
            _mdtf_dataclass_type_check(self, _log)
        type.__setattr__(cls, '__init__', _new_init)

        def _from_string(cls_, str_, *args):
            """Create an object instance from a string representation *str\_*.
            Used by :func:`regex_dataclass` for parsing field values and automatic
            type coercion.
            """
            cls_._pattern.match(str_, *args)
            return cls_(**cls_._pattern.data)
        type.__setattr__(cls, 'from_string', classmethod(_from_string))

        type.__setattr__(cls, '_is_regex_dataclass', True)
        type.__setattr__(cls, '_pattern', pattern)
        return cls
    return _dataclass_decorator

def dataclass_factory(dataclass_decorator, class_name, *parents, **kwargs):
    """Function that returns a dataclass (ie, a decorated class) whose fields
    are the union of the fields in *parents*, which the new dataclass inherits
    from.

    Args:
        dataclass_decorator (function): decorator to apply to the new class.
        class_name (str): name of the new class.
        parents: collection of other mdtf_dataclasses to inherit from. Order in
            the collection determines the MRO.
        kwargs: Optional; arguments to pass to dataclass_decorator when it's
            applied to produce the returned class.
    """
    def _to_dataclass(self, cls_, **kwargs_):
        f"""Method to create an instance of one of the parent classes of
        {class_name} by copying over the relevant subset of fields.
        """
        # above docstring gets templated
        new_kwargs = filter_dataclass(self, cls_)
        new_kwargs.update(kwargs_)
        return cls_(**new_kwargs)

    def _from_dataclasses(cls_, *other_dcs, **kwargs_):
        f"""Class method to create a new instance of {class_name} from instances
        of its parents, along with any other field values passed in kwargs.
        """
        # above docstring gets templated
        new_kwargs = dict()
        for dc in other_dcs:
            new_kwargs.update(filter_dataclass(dc, cls_))
        new_kwargs.update(kwargs_)
        return cls_(**new_kwargs)

    methods = {
        'to_dataclass': _to_dataclass,
        'from_dataclasses': classmethod(_from_dataclasses),
    }
    for dc in parents:
        method_nm = 'to_' + dc.__name__
        methods[method_nm] = functools.partialmethod(_to_dataclass, cls_=dc)
    new_cls = type(class_name, tuple(parents), methods)
    return dataclass_decorator(new_cls, **kwargs)

def filter_dataclass(d, dc, init=False):
    """Return a dict of the subset of fields or entries in *d* that correspond to
    the fields in dataclass *dc*.

    Args:
        d (dict, dataclass or dataclass instance): Object to take field values from.
        dc (dataclass or dataclass instance): Dataclass defining the set of fields
            that are returned. Values of fields in *d* that are not fields of *dc*
            are discarded.
        init (bool or 'all'): Optional, default False. Controls whether `init-only fields
            <https://docs.python.org/3/library/dataclasses.html#init-only-variables>`__
            are included:

            - If False: Include only the fields of *dc* as returned by
              :py:func:`dataclasses.fields`.
            - If True: Include only the arguments to *dc*\'s constructor (i.e.,
              include any init-only fields and exclude any of *dc*\'s fields
              with *init*\=False.)
            - If 'all': Include the union of the above two options.

    Returns:
        dict: The subset of key:value pairs from *d* such that the keys are
        included in the set of *dc*\'s fields specified by the value of *init*.
    """
    assert dataclasses.is_dataclass(dc)
    if dataclasses.is_dataclass(d):
        if isinstance(d, type):
            d = d() # d is a class; instantiate with default field values
        d = dataclasses.asdict(d)
    if not init or (init == 'all'):
        ans = {f.name: d[f.name] for f in dataclasses.fields(dc) if f.name in d}
    else:
        ans = {f.name: d[f.name] for f in dataclasses.fields(dc) \
            if (f.name in d and f.init)}
    if init or (init == 'all'):
        init_fields = filter(
            (lambda f: f.type == dataclasses.InitVar),
            dc.__dataclass_fields__.values()
        )
        ans.update({f.name: d[f.name] for f in init_fields if f.name in d})
    return ans

def coerce_to_dataclass(d, dc, **kwargs):
    """Given a dataclass *dc* (may be the class or an instance of it), and a dict,
    dataclass or dataclass instance *d*, return an instance of *dc*\'s class with
    field values initialized from those in *d*, along with any extra values
    passed in *kwargs*.

    Because this constructs a new dataclass instance, it copies field values
    according to the *init*\=True logic in :func:`filter_dataclass`.

    Args:
        d (dict, dataclass or dataclass instance): Object to take field values from.
        dc (dataclass or dataclass instance): Class to instantiate.
        kwargs: Optional. If provided, override field values provided in *d*.

    Returns:
        Instance of dataclass *dc* with field values populated from *kwargs* and *d*.
    """
    new_kwargs = filter_dataclass(d, dc, init=True)
    if kwargs:
        new_kwargs.update(kwargs)
        new_kwargs = filter_dataclass(new_kwargs, dc, init=True)
    if not isinstance(dc, type):
        dc = dc.__class__
    return dc(**new_kwargs)


#!/usr/bin/python3

import os
from gestion_data import gestion_data
import matplotlib.pyplot as plt

class ft_linear_regression(gestion_data):
    def __init__(self, gestion_data):
        self.km_values = gestion_data.array_km
        self.price_values = gestion_data.array_price
        self.mean_km = self.calculate_mean_km(self.km_values)
        self.mean_price = self.calculate_mean_price(self.price_values)
        self.mean_km_values = self.calculate_mean_km_values(
            self.km_values, self.mean_km)
        self.mean_price_values = self.calculate_mean_price_values(
            self.price_values, self.mean_price)
        self.square_mean_km_values = self.calculate_square_mean_km_values(
            self.mean_km_values)
        self.square_mean_price_values = self.calculate_square_mean_price_values(
            self.mean_price_values)
        self.mean_km_x_price_values = self.calculate_mean_km_x_price_values(
            self.mean_km_values, self.mean_price_values)
        self.sum_square_km = self.calculate_sum_square_km(
            self.square_mean_km_values)
        self.sum_mean_km_x_price_values = self.calculate_sum_mean_km_x_price_values(
            self.mean_km_x_price_values)
        self.teta1 = self.calculate_teta1(
            self.sum_square_km, self.sum_mean_km_x_price_values)
        self.teta0 = self.calculate_teta0(
            self.mean_price, self.mean_km, self.teta1)
        self.price_linear_regression_values = self.calculate_price_linear_regression_values(
            self.km_values,
            self.teta0,
            self.teta1
        )

    def __str__(self):
        return 'linear regression calulator'

    def print_all_value(self):
        print("/* ******************** km_values                  ******************** */")
        print(self.km_values)
        print("/* ******************** price_values               ******************** */")
        print(self.price_values)
        print("/* ******************** mean_km                    ******************** */")
        print(self.mean_km)
        print("/* ******************** mean_price                 ******************** */")
        print(self.mean_price)
        print("/* ******************** mean_km_values             ******************** */")
        print(self.mean_km_values)
        print("/* ******************** mean_price_values          ******************** */")
        print(self.mean_price_values)
        print("/* ******************** square_mean_km_values      ******************** */")
        print(self.square_mean_km_values)
        print("/* ******************** square_mean_price_values   ******************** */")
        print(self.square_mean_price_values)
        print("/* ******************** mean_km_x_price_values     ******************** */")
        print(self.mean_km_x_price_values)
        print("/* ******************** sum_square_km              ******************** */")
        print(self.sum_square_km)
        print("/* ******************** sum_mean_km_x_price_values ******************** */")
        print(self.sum_mean_km_x_price_values)
        print("/* ******************** sum_square_km              ******************** */")
        print(self.sum_square_km)
        print("/* ******************** teta1                      ******************** */")
        print(self.teta1)
        print("/* ******************** teta0                      ******************** */")
        print(self.teta0)
        print("/* ******************** ************************** ******************** */")

    def calculate_mean_km(self, km_values):
        mean_km = 0
        for value in km_values:
            mean_km += value
        mean_km = mean_km / len(km_values)
        return mean_km

    def calculate_mean_price(self, price_values):
        mean_price = 0
        for value in price_values:
            mean_price += value
        mean_price = mean_price / len(price_values)
        return mean_price

    def calculate_mean_km_values(self, km_values, mean_km):
        mean_km_values = []
        for value in km_values:
            mean_km_values.append(value - mean_km)
        return mean_km_values

    def calculate_mean_price_values(self, price_values, mean_price):
        mean_price_values = []
        for value in price_values:
            mean_price_values.append(value - mean_price)
        return mean_price_values

    def calculate_square_mean_km_values(self, mean_km_values):
        square_mean_km_values = []
        for value in mean_km_values:
            square_mean_km_values.append(value ** 2)
        return square_mean_km_values

    def calculate_square_mean_price_values(self, mean_price_values):
        square_mean_price_values = []
        for value in mean_price_values:
            square_mean_price_values.append(value ** 2)
        return square_mean_price_values

    def calculate_mean_km_x_price_values(self, mean_km_values, mean_price_values):
        mean_km_x_price_values = []
        i = 0
        while i < len(mean_km_values):
            mean_km_x_price_values.append(
                mean_km_values[i] * mean_price_values[i])
            i += 1
        return mean_km_x_price_values

    def calculate_sum_square_km(self, square_mean_km_values):
        sum_square_km = 0
        for value in square_mean_km_values:
            sum_square_km += value
        return sum_square_km

    def calculate_sum_mean_km_x_price_values(self, mean_km_x_price_values):
        sum_mean_km_x_price_values = 0
        for value in mean_km_x_price_values:
            sum_mean_km_x_price_values += value
        return sum_mean_km_x_price_values

    def calculate_teta1(self, sum_square_km, sum_mean_km_x_price_values):
        return sum_mean_km_x_price_values / sum_square_km

    def calculate_teta0(self, mean_price, mean_km, teta1):
        return mean_price - (teta1 * mean_km)

    def calculate_price_linear_regression_values(self, km_values, teta0, teta1):
        price_linear_regression_values = []
        for value in km_values:
            price_linear_regression_values.append(teta0 + (teta1 * value))
        return price_linear_regression_values

    def generate_matploit_graph(self, km_values, price_values, price_linear_regression_values):
        plt.scatter(km_values, price_values, color='black')
        plt.plot(km_values, price_linear_regression_values,
                 color='blue', linewidth=3)

        plt.xticks()
        plt.yticks()
        plt.show()

    def create_result(self, teta0, teta1):
        if os.path.exists("result.txt"):
            os.remove("result.txt")
        f = open("result.txt", "w+")
        f.write(str(teta0) + "," + str(teta1) + "\n")
        f.close()

if __name__ == '__main__':
    try:
        gestion_data = gestion_data()
        gestion_data.print_all_value()

        ft_linear_regression = ft_linear_regression(gestion_data)
        ft_linear_regression.print_all_value()
        ft_linear_regression.create_result(
            ft_linear_regression.teta0, ft_linear_regression.teta1)
        ft_linear_regression.generate_matploit_graph(
            ft_linear_regression.km_values, ft_linear_regression.price_values,  ft_linear_regression.price_linear_regression_values)

        del gestion_data
        del ft_linear_regression
    except:
        exit(42)


import math
import torch.nn as nn
import torch.nn.functional as F

class GraphMultiHeadAttention(nn.Module):
    def __init__(self, num_head, query_size, key_size=None, value_size=None):
        super(GraphMultiHeadAttention, self).__init__()

        self.query_size = query_size
        self.num_head = num_head
        self.key_size = self.query_size if key_size is None else key_size
        self.value_size = self.key_size if value_size is None else value_size

        self.key_dim = self.key_size//self.num_head
        self.value_dim = self.value_size//self.num_head
        self.norm_factor = 1 / math.sqrt(self.key_dim)

        self.query_embed = nn.Linear(self.query_size, self.num_head*self.key_dim, bias=False)
        self.key_embed = nn.Linear(self.key_size, self.num_head*self.key_dim, bias=False)
        self.value_embed = nn.Linear(self.value_size, self.num_head*self.value_dim, bias=False)

        self.combine = nn.Linear(self.num_head*self.value_dim, self.value_size, bias=False)
        self.init_parameters()

    def init_parameters(self):
        norm_factor_value = 1 / math.sqrt(self.value_dim)
        norm_factor_combine = 1 / math.sqrt(self.value_size)

        nn.init.uniform_(self.query_embed.weight, -self.norm_factor, self.norm_factor)
        nn.init.uniform_(self.key_embed.weight, -self.norm_factor, self.norm_factor)
        nn.init.uniform_(self.value_embed.weight, -norm_factor_value, norm_factor_value)
        nn.init.uniform_(self.combine.weight, -norm_factor_combine, norm_factor_combine)

    def forward(self, queries, keys=None, values=None, edges=None, mask=None):
        batch_size, Q_size, _ = queries.size()
        Q = self.query_embed(queries).view(batch_size, Q_size, self.num_head, self.key_dim).permute(0, 2, 1, 3)

        if keys is None:
            KV_size = Q_size
            K = self.key_embed(queries).view(batch_size, KV_size, self.num_head, self.key_dim).permute(0, 2, 3, 1)
        else:
            KV_size = keys.size(-2)
            K = self.key_embed(keys).view(batch_size, KV_size, self.num_head, self.key_dim).permute(0, 2, 3, 1)

        if values is None:
            V = self.key_embed(queries).view(batch_size, KV_size, self.num_head, self.key_dim).permute(0, 2, 1, 3)
        else:
            V = self.key_embed(values).view(batch_size, KV_size, self.num_head, self.key_dim).permute(0, 2, 1, 3)

        attention = self.norm_factor * Q.matmul(K)

        if mask is not None:
            if mask.numel() * self.num_head == attention.numel():
                m = mask.view(-1, 1, Q_size, KV_size).expand_as(attention)
            else:
                m = mask.view(-1, 1, 1, KV_size).expand_as(attention)
            attention[m.bool()] = -float('inf')
        attention = F.softmax(attention, dim=-1)
        attention = attention.matmul(V).permute(0, 2, 1, 3).contiguous().view(-1, Q_size, self.num_head * self.value_dim)
        return self.combine(attention)


from opsvalidator.base import BaseValidator
from opsvalidator import error
from opsvalidator.error import ValidationError
from opsrest.utils.utils import get_column_data_from_row
import dhcptftpservervalidations
import ipaddress

class DHCPSrvStaticHostValidator(BaseValidator):
    resource = "dhcpsrv_static_host"

    def validate_modification(self, validation_args):
        mac_addresses = None
        set_tags = None
        client_id = None
        client_hostname = None
        lease_duration = None

        DHCPSrv_Static_Host = validation_args.resource_row
        ip_address = get_column_data_from_row(DHCPSrv_Static_Host,
                                              "ip_address")

        if not ipaddress.is_valid_ip_address(ip_address):
            details = "%s is an invalid IP address." % (ip_address)
            raise ValidationError(error.VERIFICATION_FAILED, details)

        if hasattr(DHCPSrv_Static_Host, "mac_addresses"):
            mac_addresses = get_column_data_from_row(DHCPSrv_Static_Host,
                                                     "mac_addresses")
        if (mac_addresses is not None) and \
           (not dhcptftpservervalidations.is_valid_mac_addresses(
                mac_addresses)):
            details = "Invalid MAC addresses."
            raise ValidationError(error.VERIFICATION_FAILED, details)

        if hasattr(DHCPSrv_Static_Host, "set_tags"):
            set_tags = get_column_data_from_row(DHCPSrv_Static_Host,
                                                "set_tags")

        if (set_tags is not None) and \
           (not dhcptftpservervalidations.is_valid_tags(set_tags)):
            details = "%s is invalid." % (set_tags)
            raise ValidationError(error.VERIFICATION_FAILED, details)

        if hasattr(DHCPSrv_Static_Host, "client_hostname"):
            client_hostname = get_column_data_from_row(DHCPSrv_Static_Host,
                                                       "client_hostname")

        if (client_hostname is not None):
            for hostname in client_hostname:
                if (not dhcptftpservervalidations.is_valid_tag(hostname)):
                    details = "%s is invalid." % (hostname)
                    raise ValidationError(error.VERIFICATION_FAILED, details)

        if hasattr(DHCPSrv_Static_Host, "client_id"):
            client_id = get_column_data_from_row(DHCPSrv_Static_Host,
                                                 "client_id")

        if (client_id is not None):
            for c_id in client_id:
                if (not dhcptftpservervalidations.is_valid_tag(c_id)):
                    details = "%s is invalid." % (c_id)
                    raise ValidationError(error.VERIFICATION_FAILED, details)

        if (mac_addresses is None) and (client_hostname is None) and \
           (client_id is None):
            details = "Any one of MAC address or hostname or client-id" \
                      " must be specified"
            raise ValidationError(error.VERIFICATION_FAILED, details)

        if hasattr(DHCPSrv_Static_Host, "lease_duration"):
            lease_duration = get_column_data_from_row(DHCPSrv_Static_Host,
                                                      "lease_duration")

        if (lease_duration is not None):
            for duration in lease_duration:
                if (not dhcptftpservervalidations.is_valid_lease_duration(
                        duration)):
                    details = "Lease duration should be 0 for infinite or" \
                              " between 2-65535."
                    raise ValidationError(error.VERIFICATION_FAILED, details)


# -*- coding: utf-8 -*-

################################################################################
#                                                                              #
# Author: David Chaloupka                                                      #
# Name:   Highscores                                                           #
#                                                                              #
#                                                                              #
# Development start: 2.9.2009                                                  #
# Last modification: 4.9.2009                                                  #
#                                                                              #
# Requires: Python 3.1                                                         #
#                                                                              #
#                                                                              #
# Desription:                                                                  #
# ----------                                                                   #
# Třída pro uchovávání highscores ve hrách. Záznamy si interně ukládá do       #
# self.records jako uspořádané dvojice (hráč, skóre). Na disk je pak uládá     #
# ve formě xml dokumentu. Jako šifrování je momentálně užit jednoduchý převod  #
# xml do base64. Pro změnu šifrování stačí přepsat metody cypher, decypher.    #
#                                                                              #
################################################################################

import xml.dom.minidom
import base64

class Highscores(object):
    MAX_NAME_LENGTH = 10

    def __init__(self, maxRecords):
        # maximální počet pozic v žebříčku highscores
        self.maxRecords = maxRecords
        # záznamy ve tvaru dvojic (jméno, skóre)
        self.records = []

    def _decypher(self, s):
        '''
        Přijímá byty a vrací jejich dešifrovanou podobu ve formě stringu.
        '''
        return base64.b64decode(s)

    def _cypher(self, s):
        '''
        Přijímá string a vrací jeho zašifrovanou podobu ve formě bytů.
        '''
        return base64.b64encode(s)

    def importData(self, fileName="highscores.txt"):
        file = None
        try:
            file = open(fileName, "rb")
            doc = xml.dom.minidom.parseString(self._decypher(file.read()))
            recordNodes = doc.getElementsByTagName("item")

            for node in recordNodes:
                name = node.getAttribute("playerName")
                score = int(node.getAttribute("score"))
                self.addHighscore(name, score)

        except IOError:
            # soubor je otevřený ale nemůže se číst
            if file:
                print("highscores.py: can't read input xml file \"%s\"" % fileName)
                self.records = []
            # jinak soubor neexistuje, což je korektní možnost (nebyl dosud vytvořen)
        except Exception:
            print("highscores.py: input xml file \"%s\" is inconsistent" % fileName)
        finally:
            if file: file.close()

    def exportData(self, fileName="highscores.txt"):
        # vytvoření xml
        doc = xml.dom.minidom.Document()

        rootElement = doc.createElement("highscores")
        doc.appendChild(rootElement)

        for name,score in self.records:
            item = doc.createElement("item")
            # uložení dat do uzlu
            item.setAttribute("playerName", name)
            item.setAttribute("score", str(score))

            rootElement.appendChild(item)

        file = None
        try:
            # zápis xml do souboru
            file = open(fileName, "wb")
            file.write(self._cypher(doc.toprettyxml(indent="", newl="\n", encoding="utf-8")))
            #doc.writexml(file, indent="", addindent="   ", newl="\n", encoding="utf-8")
        except IOError:
            print("highscores.py: can't write xml to file \"%s\"" % fileName)
        finally:
            if file: file.close()

    def __str__(self):
        '''
        Vrací highscores v úhledné podobě formátované. Jména jsou zarovnána nalevo,
        highscores napravo. Doplňuje potřebný minimální počet mezer.
        Př:
        1. ek            13,460
        2. dlouhé jméno   8,320
        3. poslední         111
        '''
        ret = ""

        longestRec = self._longestRecord()
        formatName = "<" + str(self.MAX_NAME_LENGTH) + "s"
        formatScore = ">" + str(longestRec[1]) + ",d"

        i = 1
        for name,score in self.records:
            if ret: ret += "\n"
            ret += format(i, ">2d") + ". " + format(name, formatName) + "  " + format(score, formatScore)
            i += 1
        return ret

    def _longestRecord(self):
        '''
        Vrátí nejdelší textovou reprezentaci jména a skóre, které jsou aktuálně
        uloženy jako tuple (nameLen, scoreLen). Metoda je použávána pro __str__(self).
        '''
        nameLen = 0
        scoreLen = 0

        for name, score in self.records:
            if len(name) > nameLen: nameLen = len(name)
            if len(format(score, ",d")) > scoreLen: scoreLen = len(format(score, ",d"))
        return (nameLen, scoreLen)

    def _cmpByScore(record):
        # porovnávací funkce záznamů podle jejich skóre
        return record[1]

    def isNewHighscore(self, candidateScore):
        '''
        Rozhoduje, zda je dané "candidateScore" dostatečně veliké na to, aby bylo
        přidáno do žebříčku. Jestli ano, vrací True, jinak False.
        '''
        if len(self.records) < self.maxRecords:
            return True

        for name,score in self.records:
            if score < candidateScore:
                return True
        return False

    def addHighscore(self, playerName, score):
        # ořízneme jméno na maximální povolenou délku
        playerName = playerName[:self.MAX_NAME_LENGTH]
        # přidáme záznam
        self.records.append((playerName, score))
        # záznamy seřadíme sestupně podle skóre
        self.records.sort(key=Highscores._cmpByScore, reverse=True)
        # přebytečné záznamy ořízneme
        self.records = self.records[:self.maxRecords]


import numpy as np
import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import matplotlib.pyplot as plt
import contractions                                 # Expanding contractions
from nltk.stem.wordnet import WordNetLemmatizer
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.linear_model import SGDClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report

print(' ------------------------------------------')
print('| Classifying Gender Dysphoria Disclosures |')
print('|  on Social Media with Machine Learning.  |')
print(' ------------------------------------------')
print()
print('Team members:    Cory J. Cascalheira')
print('                 Ivan Nieto Gomez   ')
print('                 Edgar Corrales Sotelo')
print()
print('Data Processing....')
print()

#num_of_lines = 2

dataset = pd.read_csv('df_truth.csv')
dataset.tail()
#print('Dataset size: ',dataset.shape)
# ------ ORIGINAL DATA --------
#print('Original Dataset: \n',dataset)
headers = list(dataset.columns.values)
#print(headers)

text = dataset.iloc[:,1]            # text = dataset['text']
#print(text.shape)
#print(text)

# ---------------- EXPANDING CONTRACTIONS -------------------
n_text = []
expanded_words = []
for i in range(len(text)):
    a = str(text[i])
    # -------------- LOWERCASE ----------
    a_lower = a.lower()
    line = a_lower.split()
    for h in line:
        expanded_words.append(contractions.fix(h))
    expanded_text = ' '.join(expanded_words)
    n_text.append(expanded_text)
    expanded_words.clear()                  # Clearing List
#print(n_text)
#print('Original text: ' + text)
#print('Expanded_text: ' + n_text)

mySeries = pd.Series(n_text)
#print(mySeries)
# ----------------------------------------------------------

new_text = []
w_stopwords_text = []
for k in range(len(mySeries)):
    a = str(mySeries[k])
    # ----------------- REMOVING NUMBERS --------
    text_ = ''.join([i for i in a if not i.isdigit()])
    # -------- REMOVING SPECIAL CHARACTERS AND PUNCTUATION --------
    punc = '''!()-[]{};:'"\,“”<>’./?@#$%^&*ðÿ˜=∆+_~'''
    for j in text_:
        if j in punc:
            text_ = text_.replace(j,'')
    #print(text_)
    new_text.append(text_)
#print(new_text)

# -------------------- REMOVING STOP WORDS -------------------
for j in range(len(new_text)):
    text_tokens = word_tokenize(new_text[j])
    tokens_without_sw = [word for word in text_tokens if not word in stopwords.words('english')]
    filtered_sentence = (" ").join(tokens_without_sw)
    w_stopwords_text.append(filtered_sentence)
#print(w_stopwords_text)

col_text = pd.DataFrame(w_stopwords_text)
final_text = col_text[0]
#print(final_text)

# -------------------------------- NORMALIZING WORDS VIA LEMMATIZATION ---------------------------------
f_sent = []
xxx = []
yyy = []
for count in range(len(w_stopwords_text)):
    b = str(w_stopwords_text[count])
    words_sent = b.split()
    for j in words_sent:
        lemmatizer = WordNetLemmatizer()
        lem_sent = lemmatizer.lemmatize(j)
        f_sent.append(lem_sent)
    xxx = ' '.join(f_sent)
    yyy.append(xxx)
    f_sent.clear()
#print(yyy)

col_text = pd.DataFrame(yyy)
final_text = col_text[0]

# --------------- CLEANED DATA PLACED IN COLUMN #2 -----------
dataset.insert(2,'new_text',final_text)

#print('Clean Dataset: \n',dataset['new_text'].values)
print('1. Text Preprocessing Done!')

X = dataset['new_text'].values
y = dataset['dysphoria'].values
y_labels = np.unique(y)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=1)
#print(X_train.shape)
#print(X_test.shape)

vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(X_train)
X_test = vectorizer.transform(X_test)

# ---------------------------------------------------------------------------------
print('2. Classifiers')
print()

# ---------------------------------------------------------------------------------
print('2.1. Support Vector Machine (SVM - RBF)')
print()

svm = SVC(kernel = 'rbf', gamma = 0.1, C = 10.0, random_state = 1)
svm.fit(X_train,y_train)
y_pred = svm.predict(X_test)
svm_predictions = svm.predict(X_test)

print('     Misclassified samples (linear model): %d'%(y_test!=y_pred).sum())
print('     Accuracy: %.3f'%accuracy_score(y_test,y_pred))
print(classification_report(y_test, svm_predictions))
# ---------------------------------------------------------------------------------
print('2.2. Decision Tree')
print()

dt = DecisionTreeClassifier(criterion="entropy", random_state = 1)
dt.fit(X_train,y_train)
y_pred = dt.predict(X_test)
dt_predictions = dt.predict(X_test)

print('     Misclassified samples: %d'%(y_test!=y_pred).sum())
print('     Accuracy: %.2f'%accuracy_score(y_test,y_pred))
print(classification_report(y_test, dt_predictions))
print()

# ---------------------------------------------------------------------------------
print('2.3. Logistic Regression')
print()
log_reg = LogisticRegression(penalty='l2', C = 10, random_state = 1)
log_reg.fit(X_train, y_train)
y_pred = log_reg.predict(X_test)
log_reg_predictions = log_reg.predict(X_test)

print('     Misclassified samples: %d'%(y_test!=y_pred).sum())
print('     Accuracy: %.2f'%accuracy_score(y_test,y_pred))
print(classification_report(y_test, log_reg_predictions))
print()

# ---------------------------------------------------------------------------------
#print('2.4. Linear Regression')
#print()
#lr = LogisticRegression()
#lr.fit(X_train, y_train)
#y_pred = lr.predict(X_test)
#lr_predictions = lr.predict(X_test)

#print('     Misclassified samples: %d'%(y_test!=y_pred).sum())
#print('     Accuracy: %.2f'%accuracy_score(y_test,y_pred))
#print(classification_report(y_test, lr_predictions))
#print()
# ---------------------------------------------------------------------------------


#https://programmers.co.kr/learn/courses/30/lessons/17678

def stamp2time(stamp):
    return int(stamp[:2])*60 + int(stamp[-2:])

def time2stamp(time):
    h, m = divmod(time, 60)
    return f'{h:02d}' + ':' + f'{m:02d}'

def solution(n, t, m, timetable):
    firstbustime = 540 #09:00

    arr_times = [None]*n
    for i in range(n): arr_times[i] = list()

    for timestamp in timetable:
        time = stamp2time(timestamp)
        tt = (firstbustime - time) // t

        if (tt>=0):
            arr_times[0].append(time)
        elif (tt > -n): # -n+1 ~ -1
            arr_times[-tt].append(time)

    for i in range(n): arr_times[i].sort()

    waitq = []

    for i in range(n-1):
        waitq += arr_times[i]
        waitq = waitq[m:]
    waitq += arr_times[n-1]

    if len(waitq)<m:
        return time2stamp(firstbustime + (n-1)*t)
    else:
        return time2stamp(waitq[m-1]-1)


from django.urls import reverse

from rest_framework import status
from rest_framework.test import APITestCase

from model_bakery import baker

from emgapi import models as emg_models

class TestBiomeAPI(APITestCase):

    def setUp(self):
        self.data = {}

        self.data['_biomes'] = [
            {'lineage': 'root', 'depth': 1, 'lft': 1, 'rgt': 50},
            {'lineage': 'root:foo', 'depth': 2, 'lft': 2, 'rgt': 25},
            {'lineage': 'root:foo:bar', 'depth': 3, 'lft': 3, 'rgt': 12},
            {'lineage': 'root:foo:bar2', 'depth': 3, 'lft': 13, 'rgt': 24},
            {'lineage': 'root:foo2', 'depth': 2, 'lft': 26, 'rgt': 49},
            {'lineage': 'root:foo2:bar', 'depth': 3, 'lft': 27, 'rgt': 36},
            {'lineage': 'root:foo2:bar2', 'depth': 3, 'lft': 37, 'rgt': 48},
        ]
        for b in self.data['_biomes']:
            baker.make(
                'emgapi.Biome',
                depth=b['depth'],
                biome_name=b['lineage'].split(':')[-1],
                lineage=b['lineage'],
                lft=b['lft'],
                rgt=b['rgt'],
                pk=(self.data['_biomes'].index(b)+1)
            )

        self.data['samples'] = []
        for pk in range(2, len(self.data['_biomes'])+1):
            self.data['samples'].append(
                baker.make(
                    'emgapi.Sample',
                    pk=pk,
                    biome=emg_models.Biome.objects.get(pk=pk),
                    accession="ERS{:0>3}".format(pk),
                    is_private=False
                )
            )

        self.data['study'] = baker.make(
            'emgapi.Study',
            pk=1,
            secondary_accession="SPR0001",
            is_private=False,
            # add root until Biome is dropped from Study
            biome=emg_models.Biome.objects.get(lineage='root'),
            samples=self.data['samples']
        )

    def test_biomes_list(self):
        url = reverse('emgapi_v1:biomes-list')
        response = self.client.get(url)
        assert response.status_code == status.HTTP_200_OK
        rsp = response.json()

        assert len(rsp['data']) == 6
        expected = (
            'root:foo',
            'root:foo:bar',
            'root:foo:bar2',
            'root:foo2',
            'root:foo2:bar',
            'root:foo2:bar2',
        )
        biomes = rsp['data']
        for b in biomes:
            assert b['type'] == 'biomes'
            assert b['id'] in expected

    def tests_biomes_list_csv(self):
        url = reverse('emgapi_v1:biomes-list')
        response = self.client.get(f'{url}?format=csv')
        assert response.status_code == status.HTTP_200_OK
        rsp = str(b''.join(response.streaming_content))
        assert 'root' in rsp
        assert '?format=csv' in rsp

        url = reverse('emgapi_v1:biomes-list')
        response = self.client.get(f'{url}.csv')
        assert response.status_code == status.HTTP_200_OK
        rsp = str(b''.join(response.streaming_content))
        assert 'root' in rsp
        assert '.csv' in rsp

    def test_children(self):
        url = reverse('emgapi_v1:biomes-children-list', args=['root:foo'])
        response = self.client.get(url)
        assert response.status_code == status.HTTP_200_OK
        rsp = response.json()

        # Data
        assert len(rsp['data']) == 3

        biomes = rsp['data']
        for b in biomes:
            assert b['type'] == 'biomes'
            assert b['id'] in ('root:foo', 'root:foo:bar', 'root:foo:bar2')

    def test_samples(self):
        url = reverse('emgapi_v1:biomes-samples-list', args=['root:foo'])
        response = self.client.get(url)
        assert response.status_code == status.HTTP_200_OK
        rsp = response.json()

        # Data
        assert len(rsp['data']) == 3

        samples = rsp['data']
        for s in samples:
            assert s['type'] == 'samples'
            assert s['id'] in ('ERS002', 'ERS003', 'ERS004',)
            b = s['relationships']['biome']['data']
            assert b['type'] == 'biomes'
            assert b['id'] in ('root:foo', 'root:foo:bar', 'root:foo:bar2')

    def test_study(self):
        url = reverse('emgapi_v1:studies-detail', args=['SPR0001'])
        response = self.client.get(url)
        assert response.status_code == status.HTTP_200_OK
        rsp = response.json()

        # Data
        biomes = rsp['data']['relationships']['biomes']['data']
        assert len(biomes) == 6
        _expected_biomes = (
            'root:foo', 'root:foo:bar', 'root:foo:bar2',
            'root:foo2', 'root:foo2:bar', 'root:foo2:bar2'
        )
        for b in biomes:
            assert b['type'] == 'biomes'
            assert b['id'] in _expected_biomes


import hashlib
import json
import time

import utils
from logger import get_logger

logger = get_logger()
logger.debug('test')

class BlockChain(object):
    def __init__(self):
        self.transaction_pool  = []
        self.chain = []
        self.create_block(0, self.hash({}))

    def create_block(self, nonce, previous_hash):
        block = utils.sorted_dict_by_key({
            'timestamp': time.time(),
            'transactions': self.transaction_pool,
            'nonce': nonce,
            'previous_hash': previous_hash
        })

        self.chain.append(block)
        self.transaction_pool = []
        return block

    def hash(self, block):
        sorted_block = json.dumps(block, sort_keys=True)
        encoded_block = hashlib.sha256(sorted_block.encode()).hexdigest()
        return encoded_block

    def add_transaction(self, sender_address, recipient_address, value):
        transaction = utils.sorted_dict_by_key({
            'sender_address': sender_address,
            'recipient_address': recipient_address,
            'value': float(value)
        })
        self.transaction_pool.append(transaction)
        return True

def pprint(chains):
    for i, chain in enumerate(chains):
        print(f'{"="*25} Chain {i} {"="*25}')
        for k, v in chain.items():
            if k == 'transactions':
                print(k)
                for d in v:
                    print(f'{"-"*60}')
                    for kk, vv in d.items():
                        print(f'{kk:30}{vv}')
            else:
                print(f'{k:15}{v}')

    print(f'{"="*60}', '\n'* 2)

if __name__ == '__main__':
    block_chain = BlockChain()
    pprint(block_chain.chain)

    block_chain.add_transaction('YU', 'TAK', 3)
    last_block = block_chain.chain[-1]
    previous_hash = block_chain.hash(last_block)
    block_chain.create_block(20, previous_hash)
    pprint(block_chain.chain)

    block_chain.add_transaction('JI', 'YU', 1.4)
    block_chain.add_transaction('AN', 'YU', 4.4)
    last_block = block_chain.chain[-1]
    previous_hash = block_chain.hash(last_block)
    block_chain.create_block(5, previous_hash)
    pprint(block_chain.chain)


import os
import re

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))

def find_version(*file_paths):
    with open(os.path.join(here, *file_paths), encoding='latin1') as fp:
        version_file = fp.read()
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError('Unable to find version string')

setup(
    name='sleeper',
    version=find_version('sleeper_analyzer', '__init__.py'),
    packages=find_packages(include=['sleeper_analyzer', 'sleeper_analyzer.*', 'sleeper_cli', 'sleeper_cli.*',
                                    'sleeper_gui', 'sleeper_gui.*']),
    url='https://github.com/Saciotto/Sleeper-football-fantasy-analyzer',
    license='MIT',
    author='Matheus Rossi Saciotto',
    author_email='saciotto@gmail.com',
    description='CLI application to analyze sleeper football fantasy leagues',
    entry_points={
        'console_scripts': [
            'sleeper = sleeper_cli.__main__:console_entry',
        ]
    }
)


import  numpy as np

def what_matrix():
    query=input("Entter what you want to do : ").lower()
    m=int(input("Enter nubmer of row  of your matrix: "))

    n=int(input("Enter number of column of your matrix: "))

    a=np.zeros((m ,n)).reshape(m,n)
    print("Enter the element of matrix")
    for i in range(m):
        for j in range(n):
            a[i,j]=int(input())

    # Identity(a,m,n)

    if m==n and query=="transpose":
        print(a)
        c=a.copy()
        transpose(c,m,n)
    elif query=="matrix multipication":
        m2=int(input("Enter nubmer of row  of your 2nd matrix: "))
        n2=int(input("Enter number of column of your 2nd matrix: "))
        d=np.zeros((m2,n2)).reshape(m2,n2)
        print("Enter the element of matrix")
        for i in range(m2):
            for j in range(n2):
                d[i,j]=int(input())
        if m==m2 and n==n2:
            matadd(a,d,m,n)

def Identity(mat,m,n):
    for i in range(m):
        for j in range(n):
            if i==j:
               if mat[i][j]==1:
                   continue
            else:
                if mat[i][j]==0:
                       continue

def transpose(mat,m,n):
    temp=np.zeros((m,n)).reshape(m,n)
    for i in range(m):
        for j in range(n):
            temp[i][j]=mat[j][i]
    print("Your transpose matrix is :")
    print(temp)

def matmul(mat1,mat2,m,n):
    temp=np.zeros((m,n)).reshape(m,n)
    for i in range(m):
        for j in range(n):
            temp[i][j]=mat1[i][j]
    print("Your transpose matrix is :")
    print(temp)
def matadd(mat1,mat2,m,n):
    temp=np.zeros((m,n)).reshape(m,n)
    for i in range(m):
        for j in range(n):
            temp[i][j]=mat1[i][j]+mat2[i][j]
    print("Your addation matrix is :")
    print(temp)
what_matrix()


import boto3
import json
import logging
from response import buildResponse

logger = logging.getLogger()
logger.setLevel(logging.INFO)

tableName = "blog-post"
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(tableName)

def lambda_handler(event, context):
    requestBody = json.loads(event["body"])
    post_id = requestBody["_id"]
    updateKey, updateValue = requestBody["updateKey"], requestBody["updateValue"]

    try:
        response = table.update_item(
            Key={
                "_id": post_id
            },
            UpdateExpression="set %s = :value" % updateKey,
            ExpressionAttributeValues={
                ":value": updateValue
            },
            ReturnValues="UPDATED_NEW"
        )

        body = {
            "Operation": "Update post",
            "Message": "Sucess",
            "UpdateAttributes": response
        }

        return buildResponse(200, body)
    except:
        logger.exception("Error handling here.")


#!/usr/bin/env python
import ephem
import datetime

Boston = ephem.Observer()
Boston.lat = "42.3462"
Boston.lon = "-71.0978"
Boston.date = datetime.datetime.now()
# %% these parameters are for super-precise estimates, not necessary.
Boston.elevation = 3  # meters
Boston.pressure = 1010  # millibar
Boston.temp = 25  # deg. Celcius
Boston.horizon = 0

sun = ephem.Sun()

print("Next sunrise in Boston will be: ", ephem.localtime(Boston.next_rising(sun)))
print("Next sunset in Boston will be: ", ephem.localtime(Boston.next_setting(sun)))


#!/usr/bin/env python
# -*- coding=utf-8 -*-

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

# Mock 服务器
class MockServer(Base):
    # table name
    __tablename__ = 'mock_server'

    # table columns
    mock_server_id = Column(Integer, primary_key=True)
    mock_server_name = Column(String(50), nullable=True)
    mock_server_ip = Column(String(15), nullable=True)
    mock_server_port = Column(Integer, nullable=False)
    mock_server_protocol = Column(String(20), nullable=True)
    mock_server_desc = Column(String(20), nullable=True)
    is_enabled = Column(String(1), nullable=True)
    mock_server_status = Column(String(1), nullable=True)

    def __repr__(self):
        return "<MockServer('%s')>" % (self.mock_server_name)

# Mock 服务
class MockService(Base):
    # table name
    __tablename__ = 'mock_service'

    # table columns
    mock_service_id = Column(Integer, primary_key=True)
    mock_server_id = Column(Integer, ForeignKey('mock_server.mock_server_id'))
    mock_service_name = Column(String(50), nullable=True)
    mock_service_uri = Column(String(100), nullable=True)
    mock_service_action = Column(String(20), nullable=True)
    mock_service_type = Column(String(20), nullable=True)
    mock_service_request = Column(String(1000), nullable=True)
    mock_service_response_for_success = Column(String(1000), nullable=True)
    mock_service_response_for_failed = Column(String(1000), nullable=True)
    mock_service_rollback = Column(String(100), nullable=True)
    is_successful = Column(String(1), nullable=True)
    is_enabled = Column(String(1), nullable=True)

    def __repr__(self):
        return "<MockService('%s')>" % (self.mock_service_name)


from django import forms
from django.contrib.auth.forms import UserChangeForm, UserCreationForm

from captcha.fields import CaptchaField

from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    """CustomUserCreationForm Form Class"""

    captcha = CaptchaField()

    class Meta:
        """Meta class for CustomUserCreationForm Form"""

        model = CustomUser
        fields = ("username", "email")

class CustomUserChangeForm(UserChangeForm):
    """CustomUserChangeForm Form Class"""

    class Meta:
        """Meta class for CustomUserChangeForm Form"""

        model = CustomUser
        fields = (
            "username",
            "first_name",
            "last_name",
            "email",
            "bio",
            "welcome_message",
            "profile_pic",
            "slug",
            "display_github",
        )

class ToggleSecureModeStatusForm(forms.ModelForm):
    """ToggleSecureModeStatusForm Form Class"""

    class Meta:
        """Meta class for ToggleSecureModeStatusForm Form"""

        model = CustomUser
        fields = ("secure_mode",)