#   Programmer: limodou
#   E-mail:     limodou@gmail.com
#
#   Copyleft 2006 limodou
#
#   Distributed under the terms of the GPL (GNU Public License)
#
#   NewEdit is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   $Id: SnippetWindow.py,v 1.11 2004/11/27 15:52:08 limodou Exp $

import wx
import os
import sys
from modules import common
from modules.Debug import error

class WizardPanel(wx.Panel):
    def __init__(self, parent, mainframe):
        wx.Panel.__init__(self, parent, -1)
        self.parent = parent
        self.mainframe = mainframe

        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.refresh = wx.Button(self, -1, tr('Refresh'))
        self.Bind(wx.EVT_BUTTON, self.OnRefresh, id=self.refresh.GetId())
        self.sizer.Add(self.refresh, 0, wx.LEFT, 2)

        style = wx.TR_SINGLE|wx.TR_HAS_BUTTONS|wx.TR_TWIST_BUTTONS
        if wx.Platform == '__WXMSW__':
            style = style | wx.TR_ROW_LINES
        elif wx.Platform == '__WXGTK__':
            style = style | wx.TR_NO_LINES

        self.tree = wx.TreeCtrl(self, -1, style = style)
        self.sizer.Add(self.tree, 1, wx.EXPAND)
        self.root = self.tree.AddRoot(tr('Wizard'))
        self.tree.SetPyData(self.root, 0)

        self.loadData()

        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnEnter, id = self.tree.GetId())

        self.SetSizer(self.sizer)
        self.SetAutoLayout(True)

    def OnRefresh(self, event):
        self.loadData()

    def loadData(self):
        self.tree.CollapseAndReset(self.root)

        self.items = {}
        self.ids = 1

        #check and create wizard path
        wizardpath = os.path.join(self.mainframe.app.workpath, 'wizard')
        if not os.path.exists(wizardpath):
            os.mkdir(wizardpath)

        self._loadPath(self.root, wizardpath)

        x = common.get_config_file_obj()
        if x.wizard.path:
            if isinstance(x.wizard.path, list):
                for p in x.wizard.path:
                    self._loadPath(self.root, p)
            else:
                self._loadPath(self.root, p)

        self.tree.Expand(self.root)

    def _loadPath(self, root, path):
        import glob
        files = os.listdir(path)
        for f in files:
            if os.path.isdir(os.path.join(path, f)):
                files = glob.glob(os.path.join(path, f, '*.wiz'))
                if files:
                    wizfile = files[0]
                    obj = self._addNode(root, wizfile)
                    self._loadPath(obj, os.path.join(path, f))

    def _addNode(self, root, wizfile):
        from modules import dict4ini

        x = dict4ini.DictIni(wizfile, encoding='utf-8')
        obj = self.tree.AppendItem(root, x.options.name)
        self.items[self.ids] = x
        self.tree.SetPyData(obj, self.ids)
        self.ids += 1
        return obj

    def OnEnter(self, event):
        i = self.tree.GetPyData(event.GetItem())
        if not i: return
        x = self.items[i]
        mod, path = importfile(x)
        datafile = ''
        if x.options.datafile == 'open':
            from modules import FileDialog
            datafile = FileDialog.openfiledlg(tr('Open'), tr('Input a data file:'))
        old_path = os.getcwd()
        try:
            os.chdir(path)
            try:
                if x.options.execute == 'wizard':
                    from modules.EasyGuider import EasyCommander
                    easy = EasyCommander.EasyCommander(parent=self, easyfile=mod, inline=True, cmdoption='', outputencoding=x.options.encoding)
                    easy.inipickle = datafile
                    if x.options.output == 'inline':
                        import StringIO
                        buf = StringIO.StringIO()
                        easy.outputfile = buf
                        if easy.run():
                            self.mainframe.document.AddText(common.decode_string(buf.getvalue(), x.options.encoding))
                    elif x.options.output == 'save':
                        from modules import FileDialog
                        datafile = FileDialog.savefiledlg(tr('Save'), tr('Input saving filename:'))
                        if datafile:
                            easy.outputfile = datafile
                            if easy.run():
                                self.mainframe.editctrl.new(datafile, encoding=x.options.encoding)
                    elif x.options.output == 'newfile':
                        import StringIO
                        buf = StringIO.StringIO()
                        easy.outputfile = buf
                        if easy.run():
                            document = self.mainframe.editctrl.new()
                            document.SetText(common.decode_string(buf.getvalue(), x.options.encoding))
                    else:
                        if easy.run():
                            common.showmessage(self, tr("Completed!"))
                elif x.options.execute == 'program':
                    easy = mod
                    easy.datafile = datafile
                    if x.options.output == 'inline':
                        import StringIO
                        buf = StringIO.StringIO()
                        easy.outputfile = buf
                        if easy.run(self.mainframe, x):
                            self.mainframe.document.AddText(common.decode_string(buf.getvalue(), x.options.encoding))
                    elif x.options.output == 'save':
                        from modules import FileDialog
                        datafile = FileDialog.savefiledlg(tr('Save'), tr('Input saving filename:'))
                        if datafile:
                            easy.outputfile = datafile
                            if easy.run(self.mainframe, x):
                                self.mainframe.editctrl.new(datafile, encoding=x.options.encoding)
                    elif x.options.output == 'newfile':
                        import StringIO
                        buf = StringIO.StringIO()
                        easy.outputfile = buf
                        if easy.run(self.mainframe, x):
                            document = self.mainframe.editctrl.new()
                            document.SetText(common.decode_string(buf.getvalue(), x.options.encoding))
                    else:
                        if easy.run(self.mainframe, x):
                            common.showmessage(self, tr("Completed!"))
            except:
                error.traceback()
                common.showerror(self, tr("There is something wrong, see the error.log!"))
        finally:
            os.chdir(old_path)

        if path:
            del sys.path[0]

def importfile(x):
    dirname = os.path.dirname(x.getfilename())
    importfile = os.path.join(dirname, x.options.file)
    path = os.path.dirname(os.path.abspath(importfile))
    filename, ext = os.path.splitext(os.path.basename(importfile))
    if sys.modules.has_key(filename):
        del sys.modules[filename]
    if path:
        sys.path.insert(0, dirname)
    mod = __import__(filename)
    return mod, path


import aws_cdk as cdk

from mwaa_cdk.mwaa_cdk_vpc import MwaaCdkStackVPC
from mwaa_cdk.mwaa_cdk_dev_env import MwaaCdkStackDevEnv
from mwaa_cdk.mwaa_cdk_prd_env import MwaaCdkStackPrdEnv

env_EU=cdk.Environment(region="eu-west-2", account="XXXXXXXXXXX")
mwaa_props = {'dagss3location': 'mwaa-094459-devops-demo','mwaa_env' : 'mwaa-devops-demo', 'mwaa_secrets_var':'airflow/variables', 'mwaa_secrets_conn':'airflow/connections'}

app = cdk.App()

mwaa_devopswld_vpc = MwaaCdkStackVPC(
    scope=app,
    id="mwaa-devops-vpc",
    env=env_EU,
    mwaa_props=mwaa_props
)

mwaa_devopswld_env_dev = MwaaCdkStackDevEnv(
    scope=app,
    id="mwaa-devops-dev-environment",
    vpc=mwaa_devopswld_vpc.vpc,
    env=env_EU,
    mwaa_props=mwaa_props
)

#mwaa_devopswld_env_prd = MwaaCdkStackPrdEnv(
#    scope=app,
#    id="mwaa-devopswld-prd-environment",
#    vpc=mwaa_devopswld_backend.vpc,
#    env=env_EU,
#    mwaa_props=mwaa_props
#)

app.synth()


import ctypes

# 键盘 Hex 码
keysHexCode = {
  'z': 0x2c, 'x': 0x2d, 'c': 0x2e, 'v': 0x2f, 'b': 0x30, 'n': 0x31, 'm': 0x32, # C4~B4
  'a': 0x1e, 's': 0x1f, 'd': 0x20, 'f': 0x21, 'g': 0x22, 'h': 0x23, 'j': 0x24, # C5~B5 (中央)
  'q': 0x10, 'w': 0x11, 'e': 0x12, 'r': 0x13, 't': 0x14, 'y': 0x15, 'u': 0x16, # C6~B6
}

POINTER = ctypes.POINTER(ctypes.c_ulong)
SendInput = ctypes.windll.user32.SendInput

class KeyBoardInput(ctypes.Structure):
  _fields_ = [
    ('wVK', ctypes.c_ushort),
    ('wScan', ctypes.c_ushort),
    ('dwFlags', ctypes.c_ulong),
    ('time', ctypes.c_ulong),
    ('dwExtraInfo', POINTER)
  ]

class HardwareInput(ctypes.Structure):
  _fields_ = [
    ('uMsg', ctypes.c_ulong),
    ('wParamL', ctypes.c_short),
    ('wParamH', ctypes.c_ushort)
  ]

class MouseInput(ctypes.Structure):
  _fields_ = [
    ('dx', ctypes.c_ulong),
    ('dy', ctypes.c_ulong),
    ('mouseData', ctypes.c_ulong),
    ('dwFlags', ctypes.c_ulong),
    ('time', ctypes.c_ulong),
    ('dwExtraInfo', POINTER)
  ]

class InputInterface(ctypes.Union):
  _fields_ = [
    ('ki', KeyBoardInput),
    ('hi', HardwareInput),
    ('mi', MouseInput)
  ]

class Input(ctypes.Structure):
  _fields_ = [
    ('type', ctypes.c_ulong),
    ('ii', InputInterface)
  ]

class KeyBoard():

  # 按下按键
  def pressKey(self, keyCode):
    hexKeyCode = keysHexCode[keyCode]
    inputInst = InputInterface()
    inputInst.ki = KeyBoardInput(0, hexKeyCode, 0x0008, 0, ctypes.pointer(ctypes.c_ulong(0)))
    pointer = Input(ctypes.c_ulong(1), inputInst)
    SendInput(1, ctypes.pointer(pointer), ctypes.sizeof(pointer))

  # 松开按键
  def releaseKey(self, keyCode):
    hexKeyCode = keysHexCode[keyCode]
    inputInst = InputInterface()
    inputInst.ki = KeyBoardInput(0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(ctypes.c_ulong(0)))
    pointer = Input(ctypes.c_ulong(1), inputInst)
    SendInput(1, ctypes.pointer(pointer), ctypes.sizeof(pointer))


from collections import Counter

def solution(topping):
    cnt = 0
    c = Counter(topping)
    s = set()
    for i in topping:
        c[i] -= 1
        s.add(i)
        if c[i] == 0:
            c.pop(i)
        if len(c) == len(s):
            cnt += 1
    return cnt

프로그래머스/unrated/132265. 롤케이크 자르기/롤케이크 자르기.py


from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.mail import send_mail

def home(request):
    return render(request, 'index.html')

def about(request):
    return render(request, 'about.html')

def service(request):
    return render(request, 'service.html')

def contact(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        subject = request.POST.get('subject')
        message = request.POST.get('message')
        form_data = {
            'name': name,
            'email': email,
            'subject': subject,
            'message': message,
        }
        message = '''
                From:\n\t\t{}\n
                Email:\n\t\t{}\n
                Subject:\n\t\t{}\n
                Message:\n\t\t{}\n
                '''.format(form_data['name'], form_data['email'],
                           form_data['subject'], form_data['message'])
        send_mail('You got a mail!', message, '', ['ciheonu36@gmail.com'])
        if send_mail:
            messages.success(request, f'Message sent successfully! ')
            return HttpResponseRedirect(request.path_info)
    return render(request, 'contact.html', {})


from django.core.paginator import Paginator
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import (
    LoginRequiredMixin, PermissionRequiredMixin
)
from django.shortcuts import render
from django.views.generic.base import TemplateView
from article.models import Article
from product.models import Product, WishlistTransaction
import arrow

class DashboardIndexView(LoginRequiredMixin, TemplateView):
    login_url = '/'
    template_name = 'dashboard.html'

    def get_context_data(self, **kwargs):
        context = super(DashboardIndexView, self).get_context_data(**kwargs)
        context['reg_stats'] = self.get_reg_stats()
        context['article_stats'] = self.get_article_stats()
        context['sales_stats'] = self.get_sales_stats()
        context['category_ratio'] = self.get_category_ratio()

        return context

    def get_reg_stats(self):
        result_data = []
        User = get_user_model()
        date = arrow.now()
        for day in range(1, 30):
            count = User.objects.filter(
                created_at__gte=date.floor('day').datetime,
                created_at__lte=date.ceil('day').datetime
            ).count()
            date = date.replace(days=-1)
            result_data.append(count)

        return result_data

    def get_article_stats(self):
        result_data = []
        date = arrow.now()
        for day in range(1, 30):
            count = Article.objects.filter(
                date__gte=date.floor('day').datetime,
                date__lte=date.ceil('day').datetime
            ).count()
            date = date.replace(days=-1)
            result_data.append(count)

        return result_data

    def get_sales_stats(self):
        result_data = []
        date = arrow.now()
        for day in range(1, 30):
            count = WishlistTransaction.objects.filter(
                date__gte=date.floor('day').datetime,
                date__lte=date.ceil('day').datetime
            ).count()
            date = date.replace(days=-1)
            result_data.append(count)

        return result_data

    def get_category_ratio(self):
        result_data = []
        for item in ['овощи', 'фрукты', 'рыба', 'мясо', 'напитки', 'алкоголь']:
            result_data.append(
                Product.objects.filter(category=item).count()
            )

        return result_data

class DashboardArticlesView(LoginRequiredMixin, PermissionRequiredMixin, TemplateView):
    login_url = '/'
    permission_required = (
        'articles.add_article',
        'articles.change_article',
        'articles.delete_article'
    )
    template_name = 'dashboard/article.html'

    def get_context_data(self, **kwargs):
        context = super(DashboardArticlesView, self).get_context_data(**kwargs)
        articles_query = Article.objects.all()
        paginator = Paginator(articles_query, 10)
        articles = paginator.page(1)
        index = articles.number - 1
        max_index = len(paginator.page_range)
        start_index = index - 3 if index >= 3 else 0
        end_index = index + 3 if index <= max_index - 3 else max_index
        page_range = paginator.page_range[start_index:end_index]
        context['articles'] = articles
        context['page_range'] = page_range

        return context


# 소수 찾기
def find_num(number):
    for i in range(2, number):
        if number % i == 0:
            return False
    else:
        return True

N = int(input())
nums = list(map(int, input().split()))
result = 0
for num in nums:
    if num != 1 and find_num(num):
        result += 1
print(result)


import sys
import time
import logging
import click
from flask.cli import with_appcontext
from flask import current_app
from . import SignalBus
from .utils import report_signal_count

def _get_models_to_flush(signalbus, signal_names, exclude):
    signal_names = set(signal_names)
    exclude = set(exclude)
    models_to_flush = signalbus.get_signal_models()
    if signal_names and exclude:
        logger = logging.getLogger(__name__)
        logger.warning('Specified both SIGNAL_NAMES and exclude option.')
    if signal_names:
        wrong_signal_names = signal_names - {m.__name__ for m in models_to_flush}
        models_to_flush = [m for m in models_to_flush if m.__name__ in signal_names]
    else:
        wrong_signal_names = exclude - {m.__name__ for m in models_to_flush}
    for name in wrong_signal_names:
        logger = logging.getLogger(__name__)
        logger.warning('A signal with name "%s" does not exist.', name)
    return [m for m in models_to_flush if m.__name__ not in exclude]

@click.group()
def signalbus():
    """Perform SignalBus operations."""

@signalbus.command()
@with_appcontext
@click.option('-e', '--exclude', multiple=True, help='Do not flush signals with the specified name.')
@click.option('-w', '--wait', type=float, help='The number of seconds "flush" will wait after'
              ' obtaining the list of pending signals, to allow concurrent senders to complete.'
              ' The default is %s seconds.' % SignalBus.flush.__defaults__[1])
@click.option('-r', '--repeat', type=float, help='Flush every FLOAT seconds.')
@click.argument('signal_names', nargs=-1)
def flush(signal_names, exclude, wait, repeat):
    """Send pending signals over the message bus.

    If a list of SIGNAL_NAMES is specified, flushes only those
    signals. If no SIGNAL_NAMES are specified, flushes all signals.

    This method assumes that auto-flushing is enabled for the given
    signal types, and therefore the number of pending signals is not
    too big. Having multiple processes that run this method in
    parallel is generally not a good idea.

    """

    signalbus = current_app.extensions['signalbus']
    models_to_flush = _get_models_to_flush(signalbus, signal_names, exclude)
    logger = logging.getLogger(__name__)
    logger.info('Started flushing %s.', ', '.join(m.__name__ for m in models_to_flush))

    while True:
        started_at = time.time()
        try:
            if wait is not None:
                signal_count = signalbus.flush(models_to_flush, wait=max(0.0, wait))
            else:
                signal_count = signalbus.flush(models_to_flush)
        except Exception:
            logger.exception('Caught error while sending pending signals.')
            sys.exit(1)

        report_signal_count(signal_count)

        if repeat is None:
            break
        else:
            time.sleep(max(0.0, repeat + started_at - time.time()))

@signalbus.command()
@with_appcontext
@click.option('-e', '--exclude', multiple=True, help='Do not flush signals with the specified name.')
@click.option('-r', '--repeat', type=float, help='Flush every FLOAT seconds.')
@click.argument('signal_names', nargs=-1)
def flushmany(signal_names, exclude, repeat):
    """Send a potentially huge number of pending signals over the message bus.

    If a list of SIGNAL_NAMES is specified, flushes only those
    signals. If no SIGNAL_NAMES are specified, flushes all signals.

    This command assumes that the number of pending signals might be
    huge. Using "flushmany" when auto-flushing is enabled for the
    given signal types is not recommended, because it may result in
    multiple delivery of messages.

    "flushmany" can be very useful when recovering from long periods
    of disconnectedness from the message bus, or when auto-flushing is
    disabled. If your database (and its SQLAlchemy dialect) supports
    "FOR UPDATE SKIP LOCKED", multiple processes will be able to run
    this command in parallel, without stepping on each others' toes.

    """

    signalbus = current_app.extensions['signalbus']
    models_to_flush = _get_models_to_flush(signalbus, signal_names, exclude)
    logger = logging.getLogger(__name__)
    logger.info('Started flushing %s.', ', '.join(m.__name__ for m in models_to_flush))

    while True:
        started_at = time.time()
        try:
            signal_count = signalbus.flushmany(models_to_flush)
        except Exception:
            logger.exception('Caught error while sending pending signals.')
            sys.exit(1)

        report_signal_count(signal_count)

        if repeat is None:
            break
        else:
            time.sleep(max(0.0, repeat + started_at - time.time()))

@signalbus.command()
@with_appcontext
@click.option('-e', '--exclude', multiple=True, help='Do not flush signals with the specified name.')
@click.option('-r', '--repeat', type=float, help='Flush every FLOAT seconds.')
@click.argument('signal_names', nargs=-1)
def flushordered(signal_names, exclude, repeat):
    """Send all pending messages in predictable order.

    If a list of SIGNAL_NAMES is specified, flushes only those
    signals. If no SIGNAL_NAMES are specified, flushes all signals.

    The order is defined by the "signalbus_order_by" attribute of the
    model class. When auto-flushing is disabled for the given signal
    types, this method guarantes that messages will be sent in the
    correct order. Having multiple processes that run this method in
    parallel is generally not a good idea.

    """

    signalbus = current_app.extensions['signalbus']
    models_to_flush = _get_models_to_flush(signalbus, signal_names, exclude)
    logger = logging.getLogger(__name__)
    logger.info('Started flushing %s.', ', '.join(m.__name__ for m in models_to_flush))

    while True:
        started_at = time.time()
        try:
            signal_count = signalbus.flushordered(models_to_flush)
        except Exception:
            logger.exception('Caught error while sending pending signals.')
            sys.exit(1)

        report_signal_count(signal_count)

        if repeat is None:
            break
        else:
            time.sleep(max(0.0, repeat + started_at - time.time()))

@signalbus.command()
@with_appcontext
def signals():
    """Show all signal types."""

    signalbus = current_app.extensions['signalbus']
    for signal_model in signalbus.get_signal_models():
        click.echo(signal_model.__name__)

@signalbus.command()
@with_appcontext
def pending():
    """Show the number of pending signals by signal type."""

    signalbus = current_app.extensions['signalbus']
    pending = []
    total_pending = 0
    for signal_model in signalbus.get_signal_models():
        count = signal_model.query.count()
        if count > 0:
            pending.append((count, signal_model.__name__))
        total_pending += count
    if pending:
        pending.sort()
        max_chars = len(str(pending[-1][0]))
        for n, signal_name in pending:
            click.echo('{} of type "{}"'.format(str(n).rjust(max_chars), signal_name))
    click.echo(25 * '-')
    click.echo('Total pending: {} '.format(total_pending))


from flask import Blueprint, render_template, request
from TheSmack.bubblesort.ava_bubblesort import bubble
from TheSmack.bubblesort.eva_bubblesort import bubble_sort, bubble_sort2
from TheSmack.bubblesort.risa_bubblesort import bubblesort
from TheSmack.bubblesort.linda_bubblesort import linda

bubblesort_bp = Blueprint('bubblesort', __name__,
                       template_folder='templates',
                       static_folder='static')

@bubblesort_bp.route('/ava', methods=['GET', 'POST'])
def ava_bubblesort():
    #set default values for variables list and sort
    list = 0
    sort = 0
    if request.method == 'POST':
        #get values from form
        values = request.form['list']
        b = bubble()
        #call addValues function from bubblesort.py
        b.addValues(values)
        #getList
        list = b.getList()
        #sort the lists
        sort = b.sort()
    return render_template("/bubbleSort/ava_bubblesort.html", list=list, sort=sort)

@bubblesort_bp.route('/eva', methods=['GET', 'POST'])
def eva_bubblesort():
    if request.method == 'POST':
        num1 = int(request.form['num1'])
        num2 = int(request.form['num2'])
        num3 = int(request.form['num3'])
        num4 = int(request.form['num4'])
        first_list = [num1, num2, num3, num4]
        unsorted_list = [num1, num2, num3, num4]
        sorted_list = bubble_sort(unsorted_list)
        return render_template("/bubbleSort/eva_bubblesort.html", num1=num1, num2=num2, num3=num3, num4=num4, unsorted_list=unsorted_list, sorted_list=sorted_list, first_list=first_list)
    return render_template("/bubbleSort/eva_bubblesort.html")

@bubblesort_bp.route('/evaform2', methods=['GET', 'POST'])
def eva_bubblesort2():
    if request.method == 'POST':
        string1 = request.form['string1']
        string2 = request.form['string2']
        string3 = request.form['string3']
        string4 = request.form['string4']
        list2 = [string1, string2, string3, string4]
        list = [string1, string2, string3, string4]
        sorted_list2 = bubble_sort2(list)
        return render_template("/bubbleSort/eva_bubblesort.html", string1=string1, string2=string2, string3=string3, string4=string4, list2=list2, list=list, sorted_list2=sorted_list2)
    return render_template("/bubbleSort/eva_bubblesort.html")

@bubblesort_bp.route('/risa', methods=['GET', 'POST'])
def risa_bubblesort():
    if request.method == 'POST':
        calc1 = int(request.form['calc1'])
        calc2 = int(request.form['calc2'])
        calc3 = int(request.form['calc3'])
        calc4 = int(request.form['calc4'])
        calc5 = int(request.form['calc5'])
        calc6 = int(request.form['calc6'])
        calc7 = int(request.form['calc7'])
        calc8 = int(request.form['calc8'])
        calc9 = int(request.form['calc9'])
        calc10 = int(request.form['calc10'])
        mycalclist = [calc1, calc2, calc3, calc4, calc5, calc6, calc7, calc8, calc9, calc10]
        mynumlist = [calc1, calc2, calc3, calc4, calc5, calc6, calc7, calc8, calc9, calc10]
        list_sorted = bubblesort(mycalclist)
        return render_template("/bubbleSort/risa_bubblesort.html", calc1=calc1, calc2=calc2, calc3=calc3, calc4=calc4, calc5=calc5, calc6=calc6, calc7=calc7, calc8=calc8, calc9=calc9, calc10=calc10, mynumlist=mynumlist, list_sorted=list_sorted, mycalclist=mycalclist)
    return render_template("/bubbleSort/risa_bubblesort.html")

#a decorator that prompts a specific page of the website
@bubblesort_bp.route('/linda', methods=['GET', 'POST'])
#define route function
def linda_bubblesort():
    #initialize the variables unsort and sort to 0
    unsort = 0
    sort = 0
    #use POST method to add/update data
    if request.method == 'POST':
        #request values from form
        values = request.form['list']
        l = linda()
        l.addValues(values)
        #pass the values into the list
        sort = l.sort()
        unsort = request.form['list']
    return render_template("/bubblesort/linda_bubblesort.html", sort=sort, unsort=unsort)


import pathlib

import click

CPP_CONTENT = """
#include <iostream>
#include "bsys.hpp"

void bsys::bsys::say_hello() {{
    std::cout << "Hello {name}" << std::endl;
}}
"""

@click.group()
def generate():
    """Generate cpp files."""
    pass

@generate.command()
@click.argument("where", type=click.Path(dir_okay=False, writable=True, allow_dash=True))
@click.argument("name", type=str)
def hello(where, name):
    where = pathlib.Path(where).expanduser().absolute()
    where.parent.mkdir(parents=True, exist_ok=True)
    print(f"writing to {where}")
    where.write_text(CPP_CONTENT.format(name=name))
    print("...  ok" if where.exists() else "...  failed")

if __name__ == "__main__":
    generate()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# System modules
import os
from setuptools import setup, find_packages

def read_file(file):
    """ Read file relative to this file
    """
    with open(os.path.join(os.path.dirname(__file__),file)) as f:
        return f.read()

# run setup
# take metadata from setup.cfg
setup(
    name = 'crosfee',
    version = '0.0.1',
    description = 'crowd-sourced field data error estimation',
    long_description = read_file("README.md"),
    keywords = [ 'crowd-sourced' ],
    license = 'GPLv3',
    author = 'Yann Büchau',
    author_email = 'yann.buechau@web.de',
    url = 'https://gitlab.com/nobodyinperson/master-thesis',
    classifiers = [
            'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
            'Programming Language :: Python :: 3.5',
            'Operating System :: OS Independent',
            'Topic :: Scientific / Engineering',
            'Topic :: Scientific/Engineering :: Atmospheric Science',
            'Topic :: Software Development :: Libraries :: Python Modules',
        ],
    test_suite = 'tests',
    tests_require = [ 'pandas', 'numpy', 'scipy' ],
    install_requires = [ 'pandas', 'numpy', 'scipy' ],
    packages = find_packages(exclude=['tests']),
    )


import hdbscan
from sklearn.metrics.pairwise import pairwise_distances
import numpy as np
from scipy.special import logit
import sklearn.metrics.pairwise as smp
import ipdb
import torch
import copy
from scipy.special import softmax
from torch.nn.utils import vector_to_parameters, parameters_to_vector

def fedavg(args, grad_in):
    grad = np.array(grad_in).reshape((args.num_workers, -1)).mean(axis=0)
    return grad.tolist()

def foolsgold(args, grad_history, grad_in, global_model, client):
    epsilon = 1e-5
    grad_history = np.array(grad_history)
    if grad_history.shape[0] != args.num_workers:
        grad_history = grad_history[:args.num_workers,:] + grad_history[args.num_workers:,:]

    similarity_maxtrix = smp.cosine_similarity(grad_history) - np.eye(args.num_workers)

    mv = np.max(similarity_maxtrix, axis=1) + epsilon

    alpha = np.zeros(mv.shape)
    for i in range(args.num_workers):
        for j in range(args.num_workers):
            if mv[j] > mv[i]:
                similarity_maxtrix[i,j] *= mv[i]/mv[j]

    alpha = 1 - (np.max(similarity_maxtrix, axis=1))
    alpha[alpha > 1] = 1
    alpha[alpha < 0] = 0
    alpha = alpha/np.max(alpha)
    alpha[(alpha == 1)] = 0.99
    alpha = (np.log((alpha / (1 - alpha)) + epsilon) + 0.5)
    alpha[(np.isinf(alpha) + alpha > 1)] = 1
    alpha[(alpha < 0)] = 0
    print("alpha:")
    print(alpha)

    # softmax alpha to make it summing up to 1
    alpha = softmax(alpha)
    update_weights = copy.deepcopy(grad_in[0])
    for key in grad_in[0].keys():
        update_weights[key] = update_weights[key] * alpha[0]
        for i in range(1, len(grad_in)):
            update_weights[key] += grad_in[i][key] * alpha[i]
        update_weights[key] = torch.div(update_weights[key], len(grad_in))

    ipdb.set_trace
    is_nan = torch.stack([torch.isnan(p).any() for p in global_model.parameters()]).any()
    if is_nan.item():
        print('The model has nan values')
        ipdb.set_trace()
    return update_weights, grad_history.tolist(), alpha

class Robust_Learning_Rate():
    def __init__(self, agent_data_sizes, n_params, args):
        self.agent_data_sizes = agent_data_sizes
        self.args = args
        self.n_params = n_params

    def aggregate_updates(self, global_model, agent_updates_dict):
        # adjust LR if robust LR is selected
        lr_vector = torch.Tensor([self.args.server_lr]*self.n_params).to(self.args.device)
        if self.args.robustLR_threshold > 0:
            lr_vector = self.compute_robustLR(agent_updates_dict)

        print(lr_vector)
        aggregated_updates = 0
        aggregated_updates = self.agg_comed(agent_updates_dict)

        cur_global_params = parameters_to_vector(global_model.parameters())
        new_global_params =  (cur_global_params + lr_vector*aggregated_updates).float()
        vector_to_parameters(new_global_params, global_model.parameters())
        updated_weights = global_model.state_dict()
        return updated_weights

    def compute_robustLR(self, agent_updates_dict):
        agent_updates_sign = [torch.sign(update) for update in agent_updates_dict.values()]
        sm_of_signs = torch.abs(sum(agent_updates_sign))

        sm_of_signs[sm_of_signs < self.args.robustLR_threshold] = -self.args.server_lr
        sm_of_signs[sm_of_signs >= self.args.robustLR_threshold] = self.args.server_lr
        return sm_of_signs.to(self.args.device)

    def agg_avg(self, agent_updates_dict):
        sm_updates = 0
        for _id, update in agent_updates_dict.items():
            sm_updates += update
        return sm_updates / len(agent_updates_dict.keys())

    def agg_comed(self, agent_updates_dict):
        agent_updates_col_vector = [update.view(-1, 1) for update in agent_updates_dict.values()]
        concat_col_vectors = torch.cat(agent_updates_col_vector, dim=1)
        return torch.median(concat_col_vectors, dim=1).values


import copy
import itertools
import time
import numpy as np
import pandas as pd

wordsList = ['david', 'selma', 'alex', 'quique', 'mamita']

class Crossword(object):
    def __init__(self, parentCrossword=None, insertPosition=None, insertOrientation=None, wordsList=None):
        '''
        # If self is an updated version of a previous Crossword object, input the following 3 parameters:
            :param parentCrossword: Crossword object - the previous iteration of which self is an updated version
            :param insertPosition: tuple (row, col) - position where first letter of next word will be inserted
            :param insertOrientation: int - 0 for 'across', 1 for 'down'

        # if self is a seed crossword (i.e. starting from a blank crossword), input only the following parameter:
            :param wordsList: list - ordered list of words to be inserted into the crossword
        '''

        # flag defaults to True; if the next word could not be inserted into parent crossword because
        # it was blocked by an existing word, flag will become False
        self.validInitialization = True

        # if this crossword is an updated version of another crossword
        if parentCrossword:
            self.wordsToInsert = parentCrossword.getWordsToInsert()[1:]
            self.lettersDict = parentCrossword.getLettersDict()
            self.positionsDict = parentCrossword.getPositionsDict()
            self.minRow = parentCrossword.getMinRow()
            self.maxRow = parentCrossword.getMaxRow()
            self.minCol = parentCrossword.getMinCol()
            self.maxCol = parentCrossword.getMaxCol()
            # insert next word 'across'
            if insertOrientation == 0:
                for index, char in enumerate(parentCrossword.getWordsToInsert()[0]):
                    # if position is blank
                    if (insertPosition[0], insertPosition[1] + index) not in self.positionsDict:
                        # add letter in that position
                        self.positionsDict[(insertPosition[0], insertPosition[1] + index)] = char
                        self.lettersDict[char].append((insertPosition[0], insertPosition[1] + index))
                        # update minCol
                        if index == 0:
                            self.minCol = min(self.minCol, insertPosition[1])
                    # if position is already taken by another letter
                    elif self.positionsDict[(insertPosition[0], insertPosition[1] + index)] != char:
                        # self is an invalid crossword; flip flag to False
                        self.validInitialization = False
                        break
                # if word inserted successfully, update maxCol
                else:
                    self.maxCol = max(self.maxCol, insertPosition[1] + len(parentCrossword.getWordsToInsert()[0]) - 1)
            # insert next word 'down'
            elif insertOrientation == 1:
                for index, char in enumerate(parentCrossword.getWordsToInsert()[0]):
                    # if position is blank
                    if (insertPosition[0] + index, insertPosition[1]) not in self.positionsDict:
                        # add letter in that position
                        self.positionsDict[(insertPosition[0] + index, insertPosition[1])] = char
                        self.lettersDict[char].append((insertPosition[0] + index, insertPosition[1]))
                        # update minRow
                        if index == 0:
                            self.minRow = min(self.minRow, insertPosition[0])
                    # if position is already taken by another letter
                    elif self.positionsDict[(insertPosition[0] + index, insertPosition[1])] != char:
                        # self is an invalid crossword; flip flag to False
                        self.validInitialization = False
                        break
                # if word inserted successfully, update maxRow
                else:
                    self.maxRow = max(self.maxRow, insertPosition[0] + len(parentCrossword.getWordsToInsert()[0]) - 1)

        # if this is a seed crossword (i.e. starting from a blank crossword)
        else:
            self.wordsToInsert = wordsList[1:]
            self.lettersDict = {'A':[], 'B':[], 'C':[], 'D':[], 'E':[], 'F':[], 'G':[], 'H':[], 'I':[], 'J':[], 'K':[],
                            'L':[], 'M':[], 'N':[], 'O':[], 'P':[], 'Q':[], 'R':[], 'S':[], 'T':[], 'U':[], 'V':[],
                            'W':[], 'X':[], 'Y':[], 'Z':[]}
            self.positionsDict = {}
            # insert initial word 'across' starting from (0, 0)
            for index, char in enumerate(wordsList[0]):
                self.lettersDict[char].append((0, index))
                self.positionsDict[(0, index)] = char
            self.minRow = 0
            self.maxRow = 0
            self.minCol = 0
            self.maxCol = len(wordsList[0]) - 1

    def getValidInitialization(self):
        return self.validInitialization
    def getWordsToInsert(self):
        return self.wordsToInsert.copy()
    def getLettersDict(self):
        return copy.deepcopy(self.lettersDict)
    def getPositionsDict(self):
        return self.positionsDict.copy()
    def getMinRow(self):
        return self.minRow
    def getMaxRow(self):
        return self.maxRow
    def getMinCol(self):
        return self.minCol
    def getMaxCol(self):
        return self.maxCol
    def getSize(self):
        return max(self.maxRow - self.minRow + 1, self.maxCol - self.minCol + 1)
    def setReIndexedPositionsDict(self):
        '''
        Re-indexes "self.positionsDict" so that the minimum row and column values are 0. Stores re-indexed
        arrangement to a variable called "self.reIndexedPositionsDict"
        '''
        self.reIndexedPositionsDict = {}
        for row, col in self.positionsDict:
            self.reIndexedPositionsDict[(row - self.minRow, col - self.minCol)] = self.positionsDict[(row, col)]
    def getReIndexedPositionsDict(self):
        return self.reIndexedPositionsDict.copy()
    def getReflectedPositionsDict(self):
        reflectedPositionsDict = {}
        for row, col in self.reIndexedPositionsDict:
            reflectedPositionsDict[(col, row)] = self.reIndexedPositionsDict[(row, col)]
        return reflectedPositionsDict.copy()

    def isValid(self):
        '''
        Checks validity of crossword; it must contain only, and all of, the words that were meant to be inserted
        :return: bool - True if crossword is valid, False if crossword is invalid
        '''
        wordsInCrossword = []
        # read & record words across each row
        for row in range(self.minRow, self.maxRow + 1):
            rowChars = ''
            for col in range(self.minCol, self.maxCol + 1):
                try:
                    rowChars += self.positionsDict[(row, col)]
                except KeyError:
                    rowChars += '/'
            wordsInRow = rowChars.split('/')
            # check for words that were not meant to be inserted
            for word in wordsInRow:
                if len(word) < 2:
                    continue
                elif word in wordsSet:
                    wordsInCrossword.append(word)
                else:
                    return False
        # read & record words down each column
        for col in range(self.minCol, self.maxCol + 1):
            colChars = ''
            for row in range(self.minRow, self.maxRow + 1):
                try:
                    colChars += self.positionsDict[(row, col)]
                except KeyError:
                    colChars += '/'
            wordsInCol = colChars.split('/')
            # check for words that were not meant to be inserted
            for word in wordsInCol:
                if len(word) < 2:
                    continue
                elif word in wordsSet:
                    wordsInCrossword.append(word)
                else:
                    return False
        # check for missing words or unintended duplicates by comparing the sorted list of words in the
        # crossword with the sorted list of words that were meant to be inserted
        return sorted(wordsInCrossword) == wordsList

    def printCrossword(self):
        array = np.full((self.maxRow - self.minRow + 1, self.maxCol - self.minCol + 1), ' ')
        for row, col in self.getPositionsDict():
            array[row - self.minRow, col - self.minCol] = self.getPositionsDict()[(row, col)]
        print(pd.DataFrame(array).to_string(header=False, index=False))
        print('size: ' + str(self.getSize()) + '\n')

def dfs(crossword):
    '''
    Depth first search. At each level, a new Crossword object is created as an update to the parent crossword.
    The next word is inserted at every position (& orientation) where the word and the parent crossword share
    a letter. If the word could not be inserted because it was blocked by an existing word, we return up one
    level to the parent crossword. When a complete, valid, and unique crossword is discovered, it is stored in
    a dictionary called "validCrosswords", and a dictionary of the letters occupying each position (and the
    reflection of this arrangement) is stored in a hashable list called "alreadyDiscovered".
    :param crossword: Crossword object - the parent crossword
    :return: None
    '''

    # if parent crossword could not be updated correctly with current position/orientation of inserted word
    if not crossword.getValidInitialization():
        return

    # if crossword is complete
    if not crossword.getWordsToInsert():
        # if crossword is valid
        if crossword.isValid():
            # if crossword is unique
            crossword.setReIndexedPositionsDict()
            if crossword.getReIndexedPositionsDict() not in alreadyDiscovered \
                    and crossword.getReflectedPositionsDict() not in alreadyDiscovered:
                # add crossword to alreadyDiscovered
                alreadyDiscovered.append(crossword.getReIndexedPositionsDict())
                # add crossword to validCrosswords according to its size
                try:
                    validCrosswords[crossword.getSize()].append(crossword)
                except KeyError:
                    validCrosswords[crossword.getSize()] = [crossword]
                    # if new smallest crossword discovered, print it
                    if crossword.getSize() == min(validCrosswords):
                        print('Smallest crossword discovered so far:')
                        crossword.printCrossword()
        return

    # if crossword is not yet complete
    for index, char in enumerate(crossword.getWordsToInsert()[0]):
        for existingLetterPosition in crossword.getLettersDict()[char].copy():
            # insert 'across'
            dfs(Crossword(parentCrossword=crossword,
                          insertPosition=(existingLetterPosition[0], existingLetterPosition[1] - index),
                          insertOrientation=0))
            # insert 'down'
            dfs(Crossword(parentCrossword=crossword,
                          insertPosition=(existingLetterPosition[0] - index, existingLetterPosition[1]),
                          insertOrientation=1))
    return

# execute DFS function for each unique order of words to be inserted
startTime = time.time()
for i in range(len(wordsList)):
    wordsList[i] = wordsList[i].upper()
wordsList.sort()
wordsSet = set(wordsList)
validCrosswords = {}
alreadyDiscovered = []
for perm in itertools.permutations(wordsList):
    dfs(Crossword(wordsList=list(perm)))

# print results
sortedValidCrosswords = {i:validCrosswords[i] for i in sorted(list(validCrosswords.keys()))}
sizes = list(sortedValidCrosswords.keys())
arrangements = []
count = 0
print('\nProcess completed.\n')
for i in sortedValidCrosswords:
    arrangements.append(len(sortedValidCrosswords[i]))
    for j in sortedValidCrosswords[i]:
        j.printCrossword()
        count += 1
arrangementsPerSizeDict = {'Size':sizes, 'Arrangements':arrangements}
df = pd.DataFrame(data=arrangementsPerSizeDict).to_string(index=False)
print(df)
print('\nTotal arrangements:', count)
print('(' + str(round(time.time() - startTime, 2)) + ' seconds)')


import functools
from urllib.parse import urlencode, urljoin

from django import forms, http
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.utils import display_for_field
from django.core import validators
from django.db.models import Exists, OuterRef
from django.forms.models import modelformset_factory
from django.http.response import (
    HttpResponseForbidden,
    HttpResponseNotAllowed,
    HttpResponseRedirect,
)
from django.shortcuts import get_object_or_404
from django.urls import re_path, resolve, reverse
from django.utils.encoding import force_str
from django.utils.html import format_html, format_html_join

import olympia.core.logger
from olympia import amo
from olympia.access import acl
from olympia.activity.models import ActivityLog
from olympia.addons.models import Addon, AddonReviewerFlags, AddonUser
from olympia.amo.admin import AMOModelAdmin, DateRangeFilter
from olympia.amo.forms import AMOModelForm
from olympia.amo.utils import send_mail
from olympia.files.models import File
from olympia.git.models import GitExtractionEntry
from olympia.ratings.models import Rating
from olympia.reviewers.models import NeedsHumanReview
from olympia.versions.models import Version
from olympia.zadmin.admin import related_content_link, related_single_content_link

from . import models
from .forms import AdminBaseFileFormSet, FileStatusForm

log = olympia.core.logger.getLogger('z.addons.admin')

class AddonReviewerFlagsInline(admin.TabularInline):
    model = AddonReviewerFlags
    verbose_name_plural = 'Reviewer Flags'
    can_delete = False
    view_on_site = False

class AddonUserBase:
    model = AddonUser
    raw_id_fields = (
        'addon',
        'user',
    )
    readonly_fields = ('user_profile_link',)
    extra = 0

    def user_profile_link(self, obj):
        if obj.pk:
            return format_html(
                'Admin User Profile ({})',
                reverse('admin:users_userprofile_change', args=(obj.user.pk,)),
                obj.user.email,
            )
        else:
            return ''

    user_profile_link.short_description = 'User Profile'

class AddonUserAdmin(AddonUserBase, AMOModelAdmin):
    pass

class AddonUserInline(AddonUserBase, admin.TabularInline):
    pass

class FileInlineChecks(admin.checks.InlineModelAdminChecks):
    def _check_relation(self, obj, parent_model):
        """File doesn't have a direct FK to Addon (it's via Version) so we have
        to bypass this check.
        """
        return []

class FileInline(admin.TabularInline):
    model = File
    extra = 0
    max_num = 0
    fields = (
        'created',
        'version__id',
        'version__version',
        'version__channel',
        'version__deleted',
        'status',
        'version__is_blocked',
        'version__needs_human_review',
    )
    editable_fields = ('status',)
    readonly_fields = tuple(set(fields) - set(editable_fields))
    can_delete = False
    view_on_site = False
    template = 'admin/addons/file_inline.html'
    checks_class = FileInlineChecks
    show_change_link = True

    def version__id(self, obj):
        return obj.version_id

    version__id.short_description = 'Version ID'

    def version__version(self, obj):
        return related_single_content_link(obj, 'version')

    version__version.short_description = 'Version'

    def version__channel(self, obj):
        return obj.version.get_channel_display()

    version__channel.short_description = 'Channel'

    def version__deleted(self, obj):
        return obj.version.deleted

    version__deleted.short_description = 'Deleted'
    version__deleted.boolean = True

    def version__is_blocked(self, obj):
        blockversion = getattr(obj.version, 'blockversion', None)
        if not blockversion:
            return ''
        url = blockversion.block.get_admin_url_path()
        template = 'Blocked'
        return format_html(template, url)

    version__is_blocked.short_description = 'Block status'

    def version__needs_human_review(self, obj):
        # Set by the prefetch_related() call below.
        return obj.needs_human_review

    version__needs_human_review.short_description = 'Needs human review'
    version__needs_human_review.boolean = True

    def get_formset(self, request, obj=None, **kwargs):
        self.instance = obj
        Formset = modelformset_factory(
            File,
            form=FileStatusForm,
            formset=AdminBaseFileFormSet,
            extra=self.get_extra(request, obj, **kwargs),
            min_num=self.get_min_num(request, obj, **kwargs),
            max_num=self.get_max_num(request, obj, **kwargs),
        )
        return Formset

    def has_add_permission(self, request, obj=None):
        return False

    def get_queryset(self, request):
        self.pager = amo.utils.paginate(
            request,
            Version.unfiltered.filter(addon=self.instance).values_list('pk', flat=True),
            30,
        )
        # A list coercion so this doesn't result in a subquery with a LIMIT
        # which MySQL doesn't support (at this time).
        versions = list(self.pager.object_list)
        qs = (
            super()
            .get_queryset(request)
            .filter(version__in=versions)
            .order_by('-version__id')
        )
        sub_qs = NeedsHumanReview.objects.filter(
            is_active=True, version=OuterRef('version')
        )
        return qs.select_related('version', 'version__blockversion').annotate(
            needs_human_review=Exists(sub_qs)
        )

class AddonAdmin(AMOModelAdmin):
    class Media(AMOModelAdmin.Media):
        css = {
            'all': (
                'css/admin/amoadmin.css',
                'css/admin/l10n.css',
                'css/admin/pagination.css',
                'css/admin/addons.css',
            )
        }
        js = AMOModelAdmin.Media.js + (
            'admin/js/jquery.init.js',
            'js/admin/l10n.js',
        )

    list_display = (
        '__str__',
        'type',
        'guid',
        'status',
        'average_daily_users',
        'average_rating',
        'authors_links',
        'reviewer_links',
        'reviewer_flags',
    )
    list_filter = (
        (
            'created',
            DateRangeFilter,
        ),
        'type',
        'status',
        (
            'addonuser__user__created',
            DateRangeFilter,
        ),
        (
            'addonuser__user__banned',
            admin.EmptyFieldListFilter,
        ),
        (
            'reviewerflags__auto_approval_disabled',
            admin.BooleanFieldListFilter,
        ),
        (
            'reviewerflags__auto_approval_disabled_unlisted',
            admin.BooleanFieldListFilter,
        ),
        (
            'reviewerflags__auto_approval_disabled_until_next_approval',
            admin.BooleanFieldListFilter,
        ),
        (
            'reviewerflags__auto_approval_disabled_until_next_approval_unlisted',
            admin.BooleanFieldListFilter,
        ),
        (
            'reviewerflags__auto_approval_delayed_until',
            DateRangeFilter,
        ),
        (
            'reviewerflags__auto_approval_delayed_until_unlisted',
            DateRangeFilter,
        ),
    )
    list_select_related = ('reviewerflags',)
    search_fields = ('id', 'guid__startswith', 'slug__startswith')
    search_by_ip_actions = (amo.LOG.ADD_VERSION.id,)
    search_by_ip_activity_accessor = 'addonlog__activity_log'
    search_by_ip_activity_reverse_accessor = 'activity_log__addonlog__addon'
    inlines = (
        AddonReviewerFlagsInline,
        AddonUserInline,
        FileInline,
    )
    readonly_fields = (
        'id',
        'created',
        'activity',
        'average_rating',
        'bayesian_rating',
        'guid',
        'total_ratings_link',
        'text_ratings_count',
        'weekly_downloads',
        'average_daily_users',
        'hotness',
    )

    fieldsets = (
        (
            None,
            {
                'fields': (
                    'id',
                    'created',
                    'name',
                    'slug',
                    'guid',
                    'default_locale',
                    'type',
                    'status',
                    'activity',
                ),
            },
        ),
        (
            'Details',
            {
                'fields': (
                    'summary',
                    'description',
                    'homepage',
                    'eula',
                    'privacy_policy',
                    'developer_comments',
                    'icon_type',
                ),
            },
        ),
        (
            'Support',
            {
                'fields': ('support_url', 'support_email'),
            },
        ),
        (
            'Stats',
            {
                'fields': (
                    'total_ratings_link',
                    'average_rating',
                    'bayesian_rating',
                    'text_ratings_count',
                    'weekly_downloads',
                    'average_daily_users',
                    'hotness',
                ),
            },
        ),
        (
            'Flags',
            {
                'fields': (
                    'disabled_by_user',
                    'requires_payment',
                    'is_experimental',
                    'reputation',
                ),
            },
        ),
        (
            'Dictionaries and Language Packs',
            {
                'fields': ('target_locale',),
            },
        ),
    )
    actions = ['git_extract_action']

    def get_queryset_annotations(self):
        # Add annotation for _unlisted_versions_exists/_listed_versions_exists
        # to avoid repeating those queries for each add-on in the list.
        sub_qs = Version.unfiltered.filter(addon=OuterRef('pk')).values_list('id')
        annotations = {
            '_unlisted_versions_exists': Exists(
                sub_qs.filter(channel=amo.CHANNEL_UNLISTED)
            ),
            '_listed_versions_exists': Exists(
                sub_qs.filter(channel=amo.CHANNEL_LISTED)
            ),
        }
        return annotations

    def get_queryset(self, request):
        return (
            Addon.unfiltered.all()
            .only_translations()
            .transform(Addon.attach_all_authors)
        )

    def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)

            return functools.update_wrapper(wrapper, view)

        urlpatterns = super().get_urls()
        custom_urlpatterns = [
            re_path(
                r'^(?P<object_id>.+)/git_extract/$',
                wrap(self.git_extract_view),
                name='addons_git_extract',
            ),
        ]
        return custom_urlpatterns + urlpatterns

    def get_rangefilter_addonuser__user__created_title(self, request, field_path):
        return 'author created'

    def authors_links(self, obj):
        # Note: requires .transform(Addon.attach_all_authors) to have been
        # applied to fill all_authors property and role on each user in it.
        authors = obj.all_authors
        return (
            format_html(
                '
{}
',
                format_html_join(
                    '',
                    '
{} ({}{})
',
                    (
                        (
                            urljoin(
                                settings.EXTERNAL_SITE_URL,
                                reverse(
                                    'admin:users_userprofile_change', args=(author.pk,)
                                ),
                            ),
                            author.email,
                            dict(amo.AUTHOR_CHOICES_UNFILTERED)[author.role],
                            ', Not listed' if author.listed is False else '',
                        )
                        for author in authors
                    ),
                ),
            )
            if authors
            else '-'
        )

    authors_links.short_description = 'Authors'

    def total_ratings_link(self, obj):
        return related_content_link(
            obj,
            Rating,
            'addon',
            related_manager='without_replies',
            text=obj.total_ratings,
        )

    total_ratings_link.short_description = 'Ratings'

    def reviewer_links(self, obj):
        links = []
        # _has_listed_versions_exists and _has_unlisted_versions_exists are
        # provided by annotations made in get_queryset()
        if obj._listed_versions_exists:
            links.append(
                (
                    urljoin(
                        settings.EXTERNAL_SITE_URL,
                        reverse('reviewers.review', args=['listed', obj.id]),
                    ),
                    'Review (listed)',
                )
            )
        if obj._unlisted_versions_exists:
            links.append(
                (
                    urljoin(
                        settings.EXTERNAL_SITE_URL,
                        reverse('reviewers.review', args=['unlisted', obj.id]),
                    ),
                    'Review (unlisted)',
                )
            )
        return format_html(
            '
{}
', format_html_join('', '
{}
', links)
        )

    reviewer_links.short_description = 'Reviewer links'

    def change_view(self, request, object_id, form_url='', extra_context=None):
        lookup_field = Addon.get_lookup_field(object_id)
        if lookup_field != 'pk':
            addon = None
            try:
                if lookup_field in ('slug', 'guid'):
                    addon = self.get_queryset(request).get(**{lookup_field: object_id})
            except Addon.DoesNotExist:
                raise http.Http404
            # Don't get in an infinite loop if addon.slug.isdigit().
            if addon and addon.id and addon.id != object_id:
                url = request.path.replace(object_id, str(addon.id), 1)
                if request.GET:
                    url += '?' + request.GET.urlencode()
                return http.HttpResponsePermanentRedirect(url)

        return super().change_view(
            request, object_id, form_url, extra_context=extra_context
        )

    def render_change_form(
        self, request, context, add=False, change=False, form_url='', obj=None
    ):
        context.update(
            {
                'external_site_url': settings.EXTERNAL_SITE_URL,
                'has_listed_versions': obj.has_listed_versions(include_deleted=True)
                if obj
                else False,
                'has_unlisted_versions': obj.has_unlisted_versions(include_deleted=True)
                if obj
                else False,
            }
        )

        return super().render_change_form(
            request=request,
            context=context,
            add=add,
            change=change,
            form_url=form_url,
            obj=obj,
        )

    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        if 'status' in form.changed_data:
            ActivityLog.objects.create(
                amo.LOG.CHANGE_STATUS, obj, form.cleaned_data['status']
            )
            log.info(
                'Addon "%s" status changed to: %s'
                % (obj.slug, form.cleaned_data['status'])
            )

    def git_extract_action(self, request, qs):
        addon_ids = []
        for addon in qs:
            GitExtractionEntry.objects.create(addon=addon)
            addon_ids.append(force_str(addon))
        kw = {'addons': ', '.join(addon_ids)}
        self.message_user(request, 'Git extraction triggered for "%(addons)s".' % kw)

    git_extract_action.short_description = 'Git-Extract'

    def git_extract_view(self, request, object_id, extra_context=None):
        if request.method != 'POST':
            return HttpResponseNotAllowed(['POST'])

        if not acl.action_allowed_for(request.user, amo.permissions.ADDONS_EDIT):
            return HttpResponseForbidden()

        obj = get_object_or_404(Addon, id=object_id)

        self.git_extract_action(request, (obj,))

        return HttpResponseRedirect(
            reverse('admin:addons_addon_change', args=(obj.pk,))
        )

    @admin.display(description='Activity Logs')
    def activity(self, obj):
        return related_content_link(obj, ActivityLog, 'addonlog__addon')

    @admin.display(description='Flags')
    def reviewer_flags(self, obj):
        fields = (
            field
            for field in AddonReviewerFlags._meta.get_fields()
            if field.name not in ('created', 'modified', 'addon')
        )
        try:
            contents = (
                (
                    field.verbose_name,
                    display_for_field(
                        getattr(obj.reviewerflags, field.name), field, False
                    ),
                )
                for field in fields
                if getattr(obj.reviewerflags, field.name)
            )
            if contents:
                return format_html(
                    '
{}
',
                    format_html_join(
                        '',
                        '
{}	{}
',
                        contents,
                    ),
                )
        except AddonReviewerFlags.DoesNotExist:
            pass

class FrozenAddonAdmin(AMOModelAdmin):
    raw_id_fields = ('addon',)

class ReplacementAddonForm(AMOModelForm):
    def clean_path(self):
        path = None
        try:
            path = self.data.get('path')
            site = settings.SITE_URL
            if models.ReplacementAddon.path_is_external(path):
                if path.startswith(site):
                    raise forms.ValidationError(
                        'Paths for [%s] should be relative, not full URLs '
                        'including the domain name' % site
                    )
                validators.URLValidator()(path)
            else:
                path = ('/' if not path.startswith('/') else '') + path
                resolve(path)
        except forms.ValidationError as validation_error:
            # Re-raise the ValidationError about full paths for SITE_URL.
            raise validation_error
        except Exception:
            raise forms.ValidationError('Path [%s] is not valid' % path)
        return path

class ReplacementAddonAdmin(AMOModelAdmin):
    list_display = ('guid', 'path', 'guid_slug', '_url')
    form = ReplacementAddonForm

    def _url(self, obj):
        guid_param = urlencode({'guid': obj.guid})
        return format_html(
            'Test',
            reverse('addons.find_replacement') + '?%s' % guid_param,
        )

    def guid_slug(self, obj):
        try:
            slug = models.Addon.objects.get(guid=obj.guid).slug
        except models.Addon.DoesNotExist:
            slug = '- Add-on not on AMO -'
        return slug

    def has_module_permission(self, request):
        # If one can see the changelist, then they have access to the module.
        return self.has_change_permission(request)

    def has_change_permission(self, request, obj=None):
        # If an obj is passed, then we're looking at the individual change page
        # for a replacement addon, otherwise we're looking at the list. When
        # looking at the list, we also allow users with Addons:Edit - they
        # won't be able to make any changes but they can see the list.
        if obj is not None:
            return super().has_change_permission(request, obj=obj)
        else:
            return acl.action_allowed_for(
                request.user, amo.permissions.ADDONS_EDIT
            ) or super().has_change_permission(request, obj=obj)

@admin.register(models.AddonRegionalRestrictions)
class AddonRegionalRestrictionsAdmin(AMOModelAdmin):
    list_display = ('created', 'modified', 'addon__name', 'excluded_regions')
    fields = ('created', 'modified', 'addon', 'excluded_regions')
    raw_id_fields = ('addon',)
    readonly_fields = ('created', 'modified')
    view_on_site = False

    def get_readonly_fields(self, request, obj=None):
        return self.readonly_fields + (('addon',) if obj else ())

    def addon__name(self, obj):
        return str(obj.addon)

    addon__name.short_description = 'Addon'

    def _send_mail(self, obj, action):
        message = (
            f'Regional restriction for addon "{obj.addon.name}" '
            f'[{obj.addon.id}] {action}: {obj.excluded_regions}'
        )
        send_mail(
            f'Regional Restriction {action} for Add-on',
            message,
            recipient_list=('amo-admins@mozilla.com',),
        )

    def delete_model(self, request, obj):
        self._send_mail(obj, 'deleted')
        super().delete_model(request, obj)

    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        self._send_mail(obj, 'changed' if change else 'added')

@admin.register(models.AddonBrowserMapping)
class AddonBrowserMappingAdmin(AMOModelAdmin):
    list_display = ('addon__name', 'browser', 'extension_id', 'created', 'modified')
    fields = ('addon', 'browser', 'extension_id')
    raw_id_fields = ('addon',)
    readonly_fields = ('created', 'modified')

    def addon__name(self, obj):
        return str(obj.addon)

    addon__name.short_description = 'Addon'

admin.site.register(models.DeniedGuid)
admin.site.register(models.Addon, AddonAdmin)
admin.site.register(models.FrozenAddon, FrozenAddonAdmin)
admin.site.register(models.ReplacementAddon, ReplacementAddonAdmin)
admin.site.register(models.AddonUser, AddonUserAdmin)


#
# Complete the 'degreeOfArray' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
from collections import Counter, defaultdict

def degreeOfArray(arr):
    # Write your code here
    maxDeg = 0
    num2count = defaultdict(int)
    firstSeen = {}
    lastSeen = {}
    for idx, num in enumerate(arr):
        num2count[num] += 1
        if num not in firstSeen:
            firstSeen[num] = idx
        lastSeen[num] = idx

        maxDeg = max(maxDeg, num2count[num])

    minLength = float("inf")
    for num in num2count:
        if num2count[num] == maxDeg:
            minLength = min(minLength, (lastSeen[num] - firstSeen[num]))

    return minLength + 1

Workday Senior Java Platform Developer/degreeOfArray.py


import datetime
from models.Color import Color
class CheckInput:

    #ACTION_CHOICES=[1,2,3,4,5,6,7,8]
    VALID_BRANDS = ["Suzuki","Honda", "Hyundai","Toyota", "Volkswagen","Lexus","Renault",
    "Mazda","Kia","Opel","Ford","Skoda","Mercedez Benz","Nissan","Jeep","Land Rover",
    "Mitsubishi","Volvo","Citroen","VW","Audi","BMW","Chevrolet","Mini"]

    def __init__(self):
        pass

    def is_valid_number_between(self, num, lower, higher):
        '''Tekur inn breytu og bil og segir til um hvort breytan se heiltala og se a bilinu'''
        errorprompt = Color.RED+'Incorrect input\nEnter numbers only'+Color.END
        try:
            num = int(num)
            if num > higher or num < lower:
                errorprompt = Color.RED+'Input out of range'+Color.END
                raise ValueError
            return None
        except ValueError:
            return errorprompt

    def is_valid_email(self, email):
        '''Tekur inn netfang og athugar hvort thad se gilt'''
        errorprompt = Color.RED+'Incorrect email\nEnter a valid email address'+Color.END
        try:
            atsymbol = email.index('@')
            email.index('.', atsymbol)
            return None
        except ValueError:
            return errorprompt

    def is_valid_number(self,num):
        '''Tekur inn breytu og athugar hvort ad hun se heiltala'''
        errorprompt = Color.RED+'Incorrect input\nEnter numbers only'+Color.END
        try:
            int(num)
            return None
        except ValueError:
            return errorprompt

    def is_valid_letter(self, letter, valid_letters):
        '''Tekur inn staf og lista af gildum stofum og athugar hvort stafurinn se gildur stafur'''
        errorprompt = Color.RED+'Incorrect input'+Color.END
        if letter in valid_letters:
            return None
        return errorprompt

    def is_string(self, string):
        '''Tekur inn streng og athugar hvort ad allt i strengnum se stafur'''
        errorprompt = Color.RED+'Incorrect input\nEnter letters only'+Color.END
        string = string.split()
        for i in string:
            if i.isalpha() == False:
                return errorprompt
        return None

    def is_valid_number_length(self, num, length):
        '''Tekur inn breytu og lengd a streng og athugar hvort að breytan se heiltala og se rett legnd'''
        errorprompt = Color.RED+'Incorrect input\nEnter numbers only'+Color.END
        try:
            int(num)
            if len(str(num)) != length:
                errorprompt = Color.RED+'Incorrect number of digits'+Color.END
                raise ValueError
            return None
        except ValueError:
            return errorprompt

    def is_valid_date(self, date,smaller_date):
        '''Tekur inn dagsetningu og athugar hvort ad hun se gild'''
        errorprompt = Color.RED+'Invalid date'+Color.END
        try:
            if '.' in date:
                seperator = '.'
            elif '/' in date:
                seperator = '/'
            elif '-' in date:
                seperator = '-'
            day,month,year = date.split(seperator)
            date = datetime.date(int(year),int(month),int(day))
            if smaller_date != '':
                if date < smaller_date:
                    errorprompt = Color.RED+'Return date must be at least one day after booking date'+Color.END
                    raise ValueError
            return None
        except ValueError:
            return errorprompt

    def is_carnum(self, carnum):
        errorprompt = Color.RED+'Incorrect input'+Color.END
        if len(carnum) == 5 and carnum.isalnum():
            return None
        return errorprompt


import discord

from discord.ext import commands

__author__ = "Some idiot with a keyboard"
__version__ = "0.0.0.0.0.0.0.1"

class Statistics():

    def __init__(self, bot):
        self.bot = bot

    @commands.group(pass_context=True)
    async def serverinfo(self, context):
        server = context.message.server
        online = len([m.status for m in server.members if m.status == discord.Status.online or m.status == discord.Status.idle])
        total_users = len(server.members)
        text_channels = len([x for x in server.channels if x.type == discord.ChannelType.text])
        voice_channels = len(server.channels) - text_channels
        created_at = ("Server created at: {}.".format(server.created_at.strftime("%d %b %Y %H:%M")))

        embed_data = discord.Embed(description=created_at)
        embed_data.add_field(name="Region", value=str(server.region))
        embed_data.add_field(name="Total Users", value="{}".format(total_users))
        embed_data.add_field(name="Online Users", value="{}".format(online))
        embed_data.add_field(name="Text Channels", value=text_channels)
        embed_data.add_field(name="Voice Channels", value=voice_channels)
        embed_data.add_field(name="Existing Roles", value=len(server.roles))
        embed_data.add_field(name="Server Owner", value=str(server.owner))
        embed_data.add_field(name="Server ID: ", value=server.id)

        if server.icon_url:
            embed_data.set_author(name=server.name, url=server.icon_url)
            embed_data.set_thumbnail(url=server.icon_url)
        else:
            embed_data.set_author(name=server.name)

        try:
            await self.bot.say(embed=embed_data)
        except discord.HTTPException:
            await self.bot.say("Embed Links Permission Required")
        return

    @commands.group(pass_context=True)
    async def userinfo(self, context):
        server = context.message.server
        roles = [x.name for x in context.message.author.roles if x.name != "@everyone"]
        user_joined = context.message.author.joined_at.strftime("%d %b %Y %H:%M")
        user_created = context.message.author.created_at.strftime("%d %b %Y %H:%M")
        game = "{}".format(context.message.author.status)
        if context.message.author.game is None:
            pass
        elif context.message.author.game.url is None:
            game = "Playing {}".format(context.message.author.game)
        else:
            game = "Streaming: {} {}".format(context.message.author.game, context.message.author.game.url)
        if roles:
            roles = sorted(roles, key=[x.name for x in server.role_hierarchy if x.name != "@everyone"].index)
            roles = ", ".join(roles)
        else:
            roles = "None"

        embed_data = discord.Embed(description=game)
        embed_data.add_field(name="Account created at: ", value=user_created)
        embed_data.add_field(name="Joined this server at: ", value=user_joined)
        embed_data.add_field(name="Roles: ", value=roles, inline=False)
        embed_data.add_field(name="User ID: ", value=context.message.author.id)

        name = str(context.message.author)
        name = " ~ ".join((name, context.message.author.nick)) if context.message.author.nick else name

        if context.message.author.avatar_url:
            embed_data.set_author(name=name, url=context.message.author.avatar_url)
            embed_data.set_thumbnail(url=context.message.author.avatar_url)
        else:
            embed_data.set_author(name=name)

        try:
            await self.bot.say(embed=embed_data)
        except discord.HTTPException:
            await self.bot.say("Embed Links Permission Required")
        return

def setup(bot):
    bot.add_cog(Statistics(bot))


from Jetronics.importedpage import *

# Create your views here.

class MissingOrderView(ListAPIView):
    serializer_class=MissingOrderSerializer

    def get_queryset(self):
        id = self.request.GET.get("id","")
        allmissingorder = MissingOrder.objects.all()
        if id :
            allmissingorder = allmissingorder.filter(id=id)

        return allmissingorder

    def post(self,request):

        try:
            product = self.request.data['product']
        except:
            product =""

        if product:
            productdetails = ProductModel.objects.filter(id=product)
            if productdetails.count():
                productdetails = productdetails.first()
            else:
                return Response({
                    "Status" : status.HTTP_404_NOT_FOUND,
                    "Message" : "Record Not Found"
                })
            serializer = MissingOrderSerializer(data=self.request.data,partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save(product=productdetails)

            return Response({
                "Status" : status.HTTP_200_OK,
                "Message" : "Data Created Succesfully"
            })
        else:
            serializer = MissingOrderSerializer(data=self.request.data,partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({
                "Status" : status.HTTP_200_OK,
                "Message" : "Data Created Succesfully"
            })

    def delete(self,request):

        id = self.request.GET.get("id","")

        if id:
            datas = MissingOrder.objects.filter(id=id)
            if datas.count():
                datas.first().delete()

            return Response({
                "Status" : status.HTTP_200_OK,
                "Message" : "Succesfully Deleted"
            })
        else:
            return Response({
                "Status" : status.HTTP_400_BAD_REQUEST,
                "Message" : "No ID FOUND"
            })

class OrderViews(ListAPIView):
    serializer_class = OrderSerializer
    pagination_class = Mypagination
    def get_queryset(self):

        id = self.request.GET.get("id","")
        statuscode = self.request.GET.get("statuscode","")
        userrandomid = self.request.GET.get("userrandomid","")
        productname = self.request.GET.get("productname","")
        allorder = OrderModel.objects.all()
        if id:
            allorder = allorder.filter(id=id)
        if userrandomid :
            allorder = allorder.filter(userrandomid=userrandomid)
        if statuscode:
            allorder = allorder.filter(status__statuscode = statuscode)
        if productname:
            allorder = allorder.filter(product_name__icontains = productname)

        return allorder

    def post(self,request):
        try:
            id = self.request.data['id']
        except:
            id =""

        if id:
            orderdata = OrderModel.objects.filter(id=id)
            if orderdata.count():
                orderdata = orderdata.first()
            else:
                return Response({
                    "Status" : status.HTTP_404_NOT_FOUND,
                    "Message" : "The Record Was Not Found"
                })

            serializer = OrderSerializer(orderdata,data=self.request.data,partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({
                "Status" : status.HTTP_200_OK,
                "Message" : "Succesfullly Updated"
            })
        else:
            mandatory = ['clientname','phone','city','address']
            data = Validate(self.request.data,mandatory)
            saved_data = {}
            if data==True:
                print("112355565",self.request.data)
                try:
                    settingsvalue = OrderSettingsModel.objects.get(key=1)
                    orderid = settingsvalue.value
                except:
                    settings = OrderSettingsModel.objects.create(value=1000,key=1)
                    orderid = settings.value

                alldata = self.request.data
                alldata['orderid'] = "JT" + str(orderid)
                statusvalue = StatusModel.objects.filter(statuscode=5)
                if statusvalue.count():
                    statusvalue = statusvalue.first()
                else:
                    return Response({"Status" : status.HTTP_404_NOT_FOUND,"Message" : "Order Status is Not Getting"})

                try:
                    serializer = OrderSerializer(data=alldata,partial=True)
                    serializer.is_valid(raise_exception=True)
                    serializer.save(status=statusvalue)

                    saved_data = serializer.data

                    print(saved_data)

                    newsettingsvalue = OrderSettingsModel.objects.get(key=1)
                    newsettingsvalue.value = int(orderid) + 1
                    newsettingsvalue.save()
                except:
                    pass

                duplicatemissingorder = MissingOrder.objects.filter(product__id=saved_data['product_id'],clientname=saved_data['clientname'],phone=saved_data['phone'],city=saved_data['city'])
                if duplicatemissingorder.count():
                    duplicatemissingorder.first().delete()
                else:
                    pass

                missingorder = MissingOrder.objects.filter(userrandomid = saved_data['userrandomid'])
                if missingorder.count():
                    missingorder.first().delete()
                else:
                    pass

                return Response({
                    "Status" : status.HTTP_200_OK,
                    "Message" : "Order Placed Succesfully"
                })
            else:
                return Response({
                    "Status" : status.HTTP_400_BAD_REQUEST,
                    "Message" : data
                })

    def delete(self,request):
        print(self.request.GET.get("id",""))
        id = self.request.GET.get("id","")
        if id:
            datas = OrderModel.objects.filter(id=id)
            if datas.count():
                datas.first().delete()

            return Response({
                "Status" : status.HTTP_200_OK,
                "Message" : "Succesfully Deleted"
            })
        else:
            return Response({
                "Status" : status.HTTP_400_BAD_REQUEST,
                "Message" : "No ID FOUND"
            })

class StatusChange(ListAPIView):
    def post(self,request):
        try:
            id = self.request.data['id']
        except:
            id = ""
        try:
            statuscode = self.request.data['statuscode']
        except:
            statuscode =""

        if id:
            order = OrderModel.objects.filter(id=id)
            if order.count():
                order = order.first()

            else:
                return Response({
                    "Status" : status.HTTP_404_NOT_FOUND,
                    "Message" : "Record Not Found"
                })

            if statuscode:
                statusdata = StatusModel.objects.filter(statuscode = statuscode)
                if statusdata.first():
                    statusdata = statusdata.first()
                else:
                    return Response({
                    "Status" : status.HTTP_404_NOT_FOUND,
                    "Message" : "Record Not Found"
                    })
            else:
                return Response({
                    "Status" : status.HTTP_400_BAD_REQUEST,
                    "Message" : "No Status code is present"
                })

            serializer = OrderSerializer(order,data=self.request.data,partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save(status=statusdata)

            return Response({
                "Status" : status.HTTP_200_OK,
                "Message" : "Succesfully Changed"
            })

        else:
            return Response({
                "Status" : status.HTTP_400_BAD_REQUEST,
                "Message" : "Something went wrong"
            })

class StatusChangeMultiply(ListAPIView) :

    def post(self,request):

        try:
            id = self.request.data['id']
        except:
            id=[]
        try:
            statuscode = self.request.data['statuscode']
        except:
            statuscode = 5

        if id:
            if statuscode:
                statusdata = StatusModel.objects.filter(statuscode = statuscode)
                if statusdata.count():
                    statusdata= statusdata.first()

            for x in id:
                orderdata = OrderModel.objects.filter(id=x).update(status = statusdata)

            return Response({
                "Status" : status.HTTP_200_OK,
                "Message" : "Status is succesfully Changed"
            })
        else:
            return Response({
                "Status" : status.HTTP_400_BAD_REQUEST,
                "Message" : "Product is not getting"
            })

class Getorderwithphone(ListAPIView):
    serializer_class = OrderSerializer
    def get_queryset(self):
        phone = self.request.GET.get("phone","")
        orders = OrderModel.objects.all()

        if phone:
            orders = orders.filter(phone=phone)

        return orders

class CsvReportView(ListAPIView):
    serializer_class = OrderSerializer
    def get_queryset(self):
        print(self.request.data)
        all = OrderModel.objects.all()
        return all

    def post(self,request):
        try:
            id = self.request.data['id']
        except:
            id = []

        print(id)
        if id :

            reportorder = OrderModel.objects.filter(id__in = id)

            serializer = OrderSerializer(reportorder,many=True)
            return Response({
                "Status" : "ok",
                "data" : serializer.data
            })
        else:
            reportorder = OrderModel.objects.all()

            serializer = OrderSerializer(reportorder,many=True)
            return Response({
                "Status" : "ok",
                "data" : serializer.data
            })

class MissingorderCsvReportView(ListAPIView):
    serializer_class = OrderSerializer
    def get_queryset(self):
        print(self.request.data)
        all = MissingOrder.objects.all()
        return all

    def post(self,request):
        try:
            id = self.request.data['id']
        except:
            id = []

        print(id)
        if id :

            reportorder = MissingOrder.objects.filter(id__in = id)

            serializer = MissingOrderSerializer(reportorder,many=True)
            return Response({
                "Status" : "ok",
                "data" : serializer.data
            })
        else:
            reportorder = MissingOrder.objects.all()

            serializer = MissingOrderSerializer(reportorder,many=True)
            return Response({
                "Status" : "ok",
                "data" : serializer.data
            })

class Getorderwithuser(ListAPIView):

    def get(self,request):
        orderid = self.request.GET.get("orderid","")
        if orderid:
            orderwithid = OrderModel.objects.filter(orderid=orderid)
            if orderwithid.count():
                singledata = orderwithid.first()
                userrandomid = singledata.userrandomid

            print(userrandomid)
            orders = OrderModel.objects.filter(userrandomid=userrandomid)

            allserializer = OrderSerializer(orders,many=True)
            singleserializer = OrderSerializer(singledata)
        return Response({
            "Status" : status.HTTP_200_OK,
            "alldata" : allserializer.data,
            "singledata" : singleserializer.data
        })

class DeletMultipleMissingOrder(ListAPIView):

    def delete(self,request):

        try:
            ids  = self.request.data['ids']
        except:
            ids = []

        if ids:
            Missingorders = MissingOrder.objects.filter(id__in = ids)
            if Missingorders.count():
                Missingorders.delete()

            return Response({"Status":status.HTTP_200_OK,"Message":"Succesfully Deleted"})
        else:
            return Response({"Status":status.HTTP_400_BAD_REQUEST,"Message":"Bad Request"})

class allOrder(ListAPIView):
    serializer_class = MultipleorderSerializer
    def get_queryset(self):
        allorder = OrderModel.objects.all()
        return allorder