#import libraries
import matplotlib.pyplot as plt
import pandas as pd
import streamlit as st
import numpy as np
import seaborn as sns

st.balloons()
st.set_option('deprecation.showPyplotGlobalUse', False)
st.title("Dataset")

#import dataset
df = pd.read_csv('sample.csv')
#First thirty rows
tips = df.head()
#Display the table
st.table(tips)
st.header("Visualisation Using Seaborn")

#bar plot
st.subheader("Bar Plot")
tips.plot(kind='bar')
st.pyplot()

#Displot
st.subheader("Displot")
sns.displot(tips['Period'])
st.pyplot()

#pairplot
st.subheader("Pairplot")
sns.pairplot(tips,hue='STATUS',palette='rainbow')
st.pyplot()

fig = plt.figure()
fig.patch.set_facecolor('black')

cm = sns.light_palette("green", as_cmap=True)

tips.style.set_properties({'background-color': 'black',
                           'color': 'green'})


import string
from django import forms
from project_management.projects.models import Project, ProjectMembership, \
    DevelopmentProcess, DevelopmentEntity, ProjectRole
from django.contrib.auth.models import User
#from project_management.access_control.models import Role
from datetime import datetime

DATE_INPUT_FORMAT = '%m-%d-%Y'
default_date = datetime(1900, 0o1, 0o1).date()

class InitiationForm(forms.ModelForm):
    approval_date = forms.DateField(required=False)

    def __init__(self, *args, **kwargs):
        disable_fields = kwargs.pop('disabled', False) if kwargs else False
        instance = kwargs['instance']
        super(InitiationForm, self).__init__(*args, **kwargs)
        if instance and instance.id:
            self.fields['approval_date'].initial = instance.schedules.approval_date
        if disable_fields:
            for field in self.fields.itervalues():
                field.widget.attrs['disabled'] = True

    class Meta:
        model = Project
        fields = ('name', 'apex_body_owner', 'business_unit', 'owner',
                  'domain', 'project_type', 'customer', 'planned_effort',
                  'approval_type')

date_fields = ('planned_start_date', 'planned_end_date',
               'actual_start_date', 'actual_end_date')

class PlanForm(forms.ModelForm):
    planned_start_date = forms.DateField(input_formats=[DATE_INPUT_FORMAT],
                                         required=False)
    planned_end_date = forms.DateField(input_formats=[DATE_INPUT_FORMAT],
                                       required=False)
    actual_start_date = forms.DateField(input_formats=[DATE_INPUT_FORMAT],
                                        required=False)
    actual_end_date = forms.DateField(input_formats=[DATE_INPUT_FORMAT],
                                      required=False)
    development_process = forms.ModelChoiceField(
        DevelopmentProcess.objects.all(), empty_label='Select',
        required=False)

    def __init__(self, *args, **kwargs):
        super(PlanForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            self.fields['development_environment'].queryset = \
                instance.development_environment.all()
            for date in date_fields:
                date_value = getattr(instance.schedules, date)
                if date_value != default_date:
                    self.fields[date].initial = date_value

    def save(self, force_insert=False, force_update=False, commit=True):
        project = super(PlanForm, self).save(commit=False)
        for field_name in date_fields:
            setattr(project.schedules, field_name,
                    self.cleaned_data[field_name])
        if commit:
            project.schedules.save()
            project.save()
        return project

    class Meta:
        model = Project
        fields = date_fields + ('objective', 'goals', 'project_scope',
                                'development_process', 'development_environment')

def make_responsibility_form(project=None):
    """
        (Factory) Make form for project responsibilities for specified project.
        The roles in a project typically are 'technical_leads', 'quality_leads',
        'developers', 'testers', 'technical_writers', 'configuration_manager',
        'release_manager', 'process_auditors', 'change_control_board'.
    """
    if not project:
        raise NameError('Project is not defined. Unable to create form.')
    choices = User.objects.filter(
        is_active=True).filter(
        is_staff=False).order_by('username')
    roles = ProjectRole.objects.all()

    def invert_dict(d):
        """ Invert a dict's keys and values. """
        new_dict = {}
        for k in d:
            for v in d[k]:
                new_dict.setdefault(v, []).append(k)
        return new_dict

    def get_responsibility_set():
        """ Returns a dict of people responsible for project specific roles. """
        responsibility_set = {}
        for role in roles:
            responsibility_set[role.group.name.replace(' ', '_')] = [pm.member.pk
                                                                     for pm in role.group.projectmembership_set.filter(project=project)]
        return responsibility_set

    def make_choice_fields(role):
        return forms.ModelMultipleChoiceField(queryset=choices, required=False)

    def make_fieldnames(role):
        return role.group.name.replace(' ', '_')

    def __init__(self, *args, **kwargs):
        """
            __init__ method of the dynamic form.
        """
        if 'data' not in kwargs:
            kwargs['data'] = get_responsibility_set()
        super(self.__class__, self).__init__(*args, **kwargs)

    def save(self, force_insert=False, force_update=False, commit=True):
        """
            Save method of the dynamic form.
        """
        responsiblity_set = invert_dict(self.cleaned_data)
        project.projectmembership_set.exclude(roles=None).delete()
        for user, role_names in responsiblity_set.items():
            membership = ProjectMembership(project=project, member=user)
            membership.save()
            for name in role_names:
                role = ProjectRole.objects.get(
                    group__name__exact=string.capwords(name.replace('_', ' ')))
                membership.roles.add(role.group)
        return project

    properties = dict(zip(map(make_fieldnames, roles) + ['project', '__init__', 'save'],
                          map(make_choice_fields, roles) + [project, __init__, save]))

    return type('ResponsibilityForm', (forms.Form,), properties)

class DevelopmentEnvironmentForm(forms.ModelForm):
    class Meta:
        fields = '__all__'
        model = DevelopmentEntity


import pandas as pd
from settings import config
import numpy as np
import difflib
import json

class Data():

    def get_data(self):
        self.df_dep = pd.read_csv(config.root+"/application/static/" + config.data_depto)
        self.df_mun = pd.read_csv(config.root+"/application/static/" + config.data_mun)
        self.geojson_depto = json.load(open(config.root+"/application/static/" + config.geojson_deptos))
        self.geojson_mun = json.load(open(config.root+"/application/static/" + config.geojson_mun))
        self.elementos =  [ele for ele in self.df_dep.columns.tolist() if ele not in config.not_elements and ele not in config.rangos]
        self.rangos =  [ele for ele in self.df_dep.columns.tolist() if ele not in config.not_elements and ele not in config.elementos]

    @staticmethod
    def change_names(input_pandas,desired_names,columnstring):
        column_values = input_pandas[columnstring].values
        for values in column_values:
            desired_name = difflib.get_close_matches(values, desired_names)
            input_pandas = input_pandas.replace(values, desired_name[0])
        return input_pandas

    def preprocess_samples(self):
        self.df.columns = map(str.lower, self.df.columns) # Se ponen todas los nombres de las columnas en lowercase (Algunos dataset de multilab están en mayúscula)
        f_da = self.df['departamento'].value_counts().reset_index()
        f_da.columns = ['departamento',"muestras"]
        muestras = f_da.replace("Bogotá", "CUNDINAMARCA")
        muestras['departamento'] = muestras['departamento'].str.upper()
        final = self.change_names(muestras,self.geojson["NOMBRE_DPT"].values,"departamento")
        return final

    def multilab_preprocess_means(self):
        self.df.columns = map(str.lower, self.df.columns)
        self.df = self.df.replace("Bogotá", "CUNDINAMARCA")
        self.df['departamento'] = self.df['departamento'].str.upper()
        self.df = self.change_names(self.df,self.geojson["NOMBRE_DPT"].values,"departamento")
        df_output = self.df.groupby('departamento').mean()
        return df_output.reset_index()


import os
import subprocess

from PyQt5 import QtWidgets

UI_FILE = os.path.join(os.path.dirname(__file__), 'gui.ui')

class Terminal(QtWidgets.QMainWindow):
    def __init__(self):
        super(Terminal, self).__init__()
        # uic.loadUi(UI_FILE, self)
        # self.lineEdit.returnPressed.connect(self.doCMD)
        # self.pushButtonInstall.clicked.connect(self.onClick)
        self.working_dir = "."

    def doCMD(self):
        cmd = self.lineEdit.text()
        self.lineEdit.setText("")

        if "cd " in cmd:
            vals = cmd.split(" ")
            if vals[1][0] == "/":
                self.working_dir = vals[1]
            else:
                self.working_dir = self.working_dir + "/" + vals[1]

            print(self.working_dir)
            subprocess.call(cmd, shell=True, cwd=self.working_dir)

            self.textBrowser.setText(self.textBrowser.toPlainText() + "\n$ " + cmd)
        else:
            try:
                result = subprocess.check_output(cmd, shell=True, cwd=self.working_dir)
            except Exception:
                self.textBrowser.setText(f"$ An error has occurred, `{cmd}` is a wrong or unknown command")
            else:
                self.textBrowser.setText(self.textBrowser.toPlainText() + "\n$ " + cmd + result.decode("utf-8"))

        self.textBrowser.verticalScrollBar().setValue(self.textBrowser.verticalScrollBar().maximum())

    # def onClick(self):
    #    if len(self.lineEditName.text()) < 1:
    #        QMessageBox.critical(self, "Install", "Install")
    #    else:
    #        os.system("sudo apt-get install " + self.lineEditName.text())


from django.shortcuts import render, get_object_or_404
from .models import DiscountProduct, Category, Vendor
from .forms import BrandForms
from shop import helpers
from shop.views import menu

def discount_product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    list_pro = DiscountProduct.objects.all()
    product_list = helpers.pg_records(request, list_pro, 6)
    context = {'category': category, 'categories': categories, 'product_list': product_list, 'menu': menu(request)}

    if category_slug:
        filter_discount = BrandForms(request.GET)
        category = get_object_or_404(Category, slug=category_slug)
        categories = category.get_descendants(include_self=True)
        breadcrumbs = Category.get_ancestors(category, include_self=True)

        list_pro = DiscountProduct.objects.filter(category__in=Category.objects.get(id=category.id)\
                                                                .get_descendants(include_self=True))

        vendors_ids = list_pro.values_list('vendor_id', flat=True).order_by().distinct()
        vendors = Vendor.objects.filter(id__in=vendors_ids)
        filter_discount.fields['brand'].queryset = Vendor.objects.filter(id__in=vendors_ids)

        product_list = helpers.pg_records(request, list_pro, 6)
        context = {'category': category, 'categories': categories,
                   'product_list': product_list, 'breadcrumbs': breadcrumbs,
                   'vendors': vendors, 'filter_discount': filter_discount,
                   'menu': menu(request)}

        if filter_discount.is_valid():
            if filter_discount.cleaned_data['brand']:
                list_pro = DiscountProduct.objects.filter(category__in=Category.objects.get(id=category.id)\
                                                                                .get_descendants(include_self=True))\
                                                                                .filter(vendor__in=filter_discount.cleaned_data['brand'])
                product_list = helpers.pg_records(request, list_pro, 100)
                context = {'category': category, 'categories': categories,
                           'product_list': product_list, 'breadcrumbs': breadcrumbs,
                           'vendors': vendors, 'filter_discount': filter_discount,
                           'menu': menu(request)}

    return render(request, 'discounts/discount_product_list.html', context)


#encoding:utf-8
from keras.models import Sequential
from keras.layers import Dense,GaussianDropout, GaussianNoise

model = Sequential()
model.add(Dense(32,activation='relu',input_dim=10))
model.add(GaussianDropout(0.1))
model.add(GaussianNoise(0.01))
model.add(Dense(10,activation='softmax'))
print(model.summary())


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

# In[4]:

# import the good stuff
import numpy as np
import matplotlib.pyplot as plt

# beginning of code
X, Y = [], [] # initializes the list of coordinates X and Y as empty lists
for line in open("C:/Users/John/Desktop/times.list", "r"): # define a loop that will iterate each line of your file. File path will vary. Windows users type drive's path (C,D,E...etc)

  values = [float(s) for s in line.split()] # split the current line around empty characters to form a string of tokens. Those tokens are then interpreted as floating points
  X.append(values[0])
  Y.append(values[1]) # the values stored in values are appended to the lists X and Y

plt.plot (X, Y) # start plotting X and Y
plt.xlabel ("Time (giga-annum)") # give your x-axis a label
plt.ylabel ("Redshift") # give your y-axis a label
plt.title ("Redshift as Function of Time") # give your plot a title
plt.show () # enjoy
# end of code

# In[ ]:

Plotting using list file (2nd method).py


import cv2

def display(pixels, title="Camera Output"):
    """Displays the given capture in a CV2 window. Useful for debugging

    Args:
        pixels: MxNx3 array of pixels
        title: The title of the window

    """
    cv2.namedWindow(title)
    cv2.moveWindow(title, 500, 500)
    cv2.imshow(title, pixels[:, :, 0:3])
    cv2.waitKey(0)
    cv2.destroyAllWindows()


#!/usr/bin/python3

import subprocess
import os
import datetime
import signal
import sys
import time
import traceback
import numpy as np

def printfl(text) :
    dt = datetime.datetime.now().strftime("%Y%m%d-%H:%M:%S")
    print(str(dt) + " " + str(text))
    sys.stdout.flush()
    sys.stderr.flush()

def is_python_proc_alive(proc) :
    return proc.poll() is None

def get_pid_array(cmd_line, match_exact=True):
    # cmd_line in format of path/cmd param1 param2
    # this matches EXACTLY with all pid that matches from left to right
    # return array of [pid], if not found, return []
    # it runs with pgrep -a -x
    # If match_exact is False, it matches all given cmd_line,
    # i.e. 'bin/ftrader' matches with 'bin/ftrader ftrader1' and
    # 'bin/ftrader ftrader2'
    line = cmd_line.strip().split(' ')
    pname = line[0].split('/')[-1]
    pid_array = []
    try :
        match_lines = subprocess.check_output(['pgrep', '-a', '-x', pname]).decode().strip().split('\n')
        for ml in match_lines:
            # format of [pid, path/pname, param1, ... ]
            ml = ml.strip().split(' ')

            if len(ml) - 1 < len(line):
                continue
            if match_exact and len(ml) - 1 != len(line):
                continue;

            # check the given parameters against the potential matches
            match = True
            for i, param in enumerate(line[1:]):
                if (ml[i+2] != param):
                    match = False
                    break
            if match:
                pid_array.append(ml[0])
    except Exception as e:
        pass

    return pid_array

def is_pid_alive(pid) :
    try :
        pid = int(pid)
    except:
        printfl(str(pid) + " not an integer! trying cmd line")
        return len(get_pid_array(pid))>0
    pids = [int(pid0) for pid0 in os.listdir('/proc') if pid0.isdigit()]
    return pid in pids

def kill_python_proc(proc) :
    try :
        while is_python_proc_alive(proc) :
            printfl ('sending sigterm')
            proc.send_signal(signal.SIGTERM)
            cnt = 3
            time.sleep(1)
            while cnt > 0 and is_python_proc_alive(proc):
                cnt -= 1
                time.sleep(1)
            if is_python_proc_alive(proc) :
                printfl ('sending sigkill')
                proc.send_signal(signal.SIGKILL)  #kill -9
                time.sleep(1)
    except Exception as e :
        printfl ('Exception in Kill: ' + str(e))
        traceback.print_exc()
        return 0
    return 1

# gracefully kills one python process (proc)
def kill_by_pid(pid) :
    try :
        if is_pid_alive(pid):
            printfl ("killing pid " + str(pid))
            os.system("kill " + str(pid))
            cnt = 3
            time.sleep(1)
            while cnt > 0 and is_pid_alive(pid):
                cnt -= 1
                time.sleep(1)
        else:
            printfl (str(pid) + " not alive, not killing")
            return

        if is_pid_alive(pid):
            printfl ( str(pid)  +' is alive, force killing with -9')
            os.system("kill -9 " + str(pid))
            time.sleep(1)
        if not is_pid_alive(pid):
            printfl("PID: "+ str(pid) + " killed")
        else:
            printfl( "ERROR!  " + str(pid) + " still alive, cannot be killed!")
    except Exception as e :
        printfl ('Exception in Kill: ' + str(e))
        traceback.print_exc()

# kills a program by its command line
# either an executable, i.e. bin/floor,
# or an executable plus parameters,
# i.e. 'bin/ftrader ftrader1'
# This matches all processes and kill them all
def kill_by_name(cmd_line):
    pid_array = get_pid_array(cmd_line)
    for pid in pid_array:
        kill_by_pid(pid)


import os, gc, inspect
from collections import defaultdict
import psutil

_REQUIRED = object()

class BadRequest(Exception):
    pass

def getarg(request, name, default=_REQUIRED, type=str, range=None):
    if name in request.args:
        value = type(request.args[name][0])
        if range is not None and not (range[0] <= value <= range[1]):
            raise BadRequest("Argument %r out of range (%d-%d)" % (name, range[0], range[1]))
        return value
    elif default is _REQUIRED:
        raise BadRequest("Missing argument: %s" % name)
    else:
        return default

PID = os.getpid()
def get_num_fds():
    proc = psutil.Process(PID)
    return proc.get_num_fds()

def get_leaks():
    relevant_types = frozenset(('SplashQWebPage', 'SplashQNetworkAccessManager',
        'QWebView', 'HtmlRender', 'PngRender', 'QNetworkRequest', 'QSize',
        'QBuffer', 'QPainter', 'QImage'))
    leaks = defaultdict(int)
    gc.collect()
    for o in gc.get_objects():
        if not inspect.isclass(o):
            cname = type(o).__name__
            if cname in relevant_types:
                leaks[cname] += 1
    return leaks


#!/usr/bin/python

# email_ab.py
# abstract email class

from django.core.mail import get_connection, EmailMessage

from django.template import Context, Template

from process import process
from django.conf import settings

import random

class email_ab(process):

    def mk_body( self, ep, context):

        body_template = \
                self.body_header + self.body_body + self.body_footer

        if not ep.emails:
            body_alert = """
Hello show organizer(s)!

This item does not have an email address, so it is getting sent to you.
Please review and forward it on to the presenter.

In case it isn't clear what this item is about, here is some context:
    name: {{ep.name}}
    authors: {{ep.authors}}
    released: {{ep.released}}
    conf_url: {{ep.conf_url}}
    conf_key: {{ep.conf_key}}
    room: {{ep.location}}
    start: {{ep.start}}

What follows is what was intended to be sent to the presenter:
"""
            body_template = body_alert + body_template\

        body = Template(
                body_template
                ).render(Context(context, autoescape=False))

        return body

    subject_template = "stub testing:{{ep.name}}"

    body_header = """
Hi,

This is Veyepar, the automated video processing system.

    """
    body_body = "stub testing:{{ep.description}}"

    body_footer = """
Email generated by https://github.com/CarlFK/veyepar/blob/master/dj/scripts/{{py_name}}
but replies go to real people.

Reference: http://veyepar.nextdayvideo.com/main/E/{{ep.id}}/
"""
    py_name = "email_ab.py"

    def more_context(self, ep):
        # hook to specify more context
        # like png url
        return {}

    def process_ep(self, ep):

        # if there is no email, use the client's.
        # like for lightning talks.
        emails = ep.emails or ep.show.client.contacts

        if self.options.verbose: print(emails)

        if emails:
            tos = [e.strip() for e in emails.split(',')]

            subject = Template(self.subject_template).render(
                    Context({'ep':ep}, autoescape=False))

            context = { 'ep':ep,
                    'py_name':self.py_name,
                    # 'MEDIA_URL':settings.MEDIA_URL,
                    }
            more_context = self.more_context(ep)
            for k in more_context:
                context[k] = more_context[k]

            body = self.mk_body(ep, context)

            # sender = 'Carl Karsten <carl@nextdayvideo.com>'
            sender = settings.EMAIL_SENDER
            cc = settings.EMAIL_CC
            # make a list of addresses:
            reply_tos = [sender, cc] + \
                    ep.show.client.contacts.split(',')
            # headers={Reply-To... needs to be a string of comma seperated
            reply_to = ','.join( reply_tos )
            headers = {
                     'Reply-To': reply_to,
                     'Cc': cc,
                    # 'From': sender,
                        }

            if self.options.test:
                print("tos:", tos)
                print("subject:", subject)
                print("headers:", headers)
                print("context:", context)
                print("body:", body)
                ret = False
            else:

                email = EmailMessage(subject, body, sender, tos, headers=headers )
                connection = get_connection()
                ret = connection.send_messages([email])
                print(tos, ret)
                ret = True # need to figure out what .send_messages returns

        else:
            print("no emails!")
            ret = False

        return ret

if __name__ == '__main__':
    p=email_ab()
    p.main()


import numpy as np
import scipy.io as sio
import os.path
import sys

directoryPath = "D:/SmartCampusData"

def dataArrange(line) :
    data = line.split(",")
    dataF = [float(datum) for datum in data]
    return dataF

def extractAndSave(path, type, name, date, size) :
    flag = False
    try :
        with open(path + "/" + name + "/CPSLogger/" + type + "/" + "CPSLogger_" + type + "_" + date + ".txt", 'r') as f :
            while True :
                line = f.readline().rstrip("\n")

                if not line : break
                if line[len(line)-1] == ',' : break
                if line[len(line)-1] == '-' : break
                if line[len(line)-1] == '.' : break

                dataF = line.split(",")

                if len(dataF) < 5 : break
                parsed = float(dataF[4])
                time = [[float(datum) for datum in dataF[0:3]]]

                if not flag:
                    data = np.array([parsed])
                    timeStamp = np.array(time)
                    flag = True
                else :
                    data = np.append(data, [parsed], axis=0)
                    timeStamp = np.append(timeStamp, time, axis=0)

    except IOError as error :
        print("Error occurred when processing memory : {0}".format(error))
    except :
        print("Unexpected error occurred : " + sys.exc_info()[0])
    if not flag :
        print("No Memory data")
        timeStamp = np.array([])
        data = np.array([])
    if not os.path.exists("../" + name) :
        os.mkdir("../" + name)
    if not os.path.exists("../" + name + "/" + type) :
        os.mkdir("../" + name + "/" + type)
    sio.savemat("../" + name + "/" + type + "/" + type + "_" + date + ".mat", {"timeStamp_" + type : timeStamp, type : data})


import nltk
import numpy as np
import six
import pdb

# the toy grammar
gram =     """ S   -> NP VP
        NP  -> Det N | Det Adj N
        VP  -> V NP | V NP PP
        PP  -> P Det Pla
        Det -> 'a' | 'the' | 'my' | 'your'
        NP  -> 'bob' | 'kevin' | 'kyle'
        N   -> 'man' | 'dog' | 'cat' | 'chicken' | 'bird' | 'pig' | 'lion' | 'bear'
        N   -> 'turkey' | 'wolf' | 'rabbit' | 'duck' | 'monkey'
        V   -> 'saw' | "killed" | 'caught' | 'chased' | 'played'
        P   -> 'in' | 'by'
        Pla ->  'park' | 'school' | 'forest'
        Adj  -> 'angry' | 'frightened' |  'little' | 'wild' | 'big'
        """

gram = """S -> NP VP
    NP -> Det N
    NP -> Det Adj N
    VP -> V NP
    VP -> V NP PP
    PP -> P Det Pla
    Det -> 'a'
    Det -> 'the'
    Det -> 'my'
    Det -> 'your'
    NP -> 'bob'
    NP -> 'kevin'
    NP -> 'kyle'
    N -> 'man'
    N -> 'dog'
    N -> 'cat'
    N -> 'chicken'
    N -> 'bird'
    N -> 'pig'
    N -> 'lion'
    N -> 'bear'
    N -> 'turkey'
    N -> 'wolf'
    N -> 'rabbit'
    N -> 'duck'
    N -> 'monkey'
    V -> 'saw'
    V -> 'killed'
    V -> 'caught'
    V -> 'chased'
    V -> 'played'
    P -> 'in'
    P -> 'by'
    Pla -> 'park'
    Pla -> 'school'
    Pla -> 'forest'
    Adj -> 'angry'
    Adj -> 'frightened'
    Adj -> 'little'
    Adj -> 'wild'
    Adj -> 'big'
    Nothing -> None"""

# form the CFG and get the start symbol
GCFG = nltk.CFG.fromstring(gram)
start_index = GCFG.productions()[0].lhs()

print(GCFG)
print(start_index)

# collect all lhs symbols, and the unique set of them
all_lhs = [a.lhs().symbol() for a in GCFG.productions()]
lhs_list = []
for a in all_lhs:
    if a not in lhs_list:
        lhs_list.append(a)

D = len(GCFG.productions())

print(all_lhs)
print(lhs_list)
print(D)

# this map tells us the rhs symbol indices for each production rule
rhs_map = [None]*D
count = 0
for a in GCFG.productions():
    rhs_map[count] = []
    for b in a.rhs():
        if not isinstance(b,six.string_types):
            s = b.symbol()
            rhs_map[count].extend(list(np.where(np.array(lhs_list) == s)[0]))
    count = count + 1

masks = np.zeros((len(lhs_list),D))
count = 0

print(rhs_map)

# this tells us for each lhs symbol which productions rules should be masked
for sym in lhs_list:
    is_in = np.array([a == sym for a in all_lhs], dtype=int).reshape(1,-1)
    masks[count] = is_in
    count = count + 1

print(masks)

# this tells us the indices where the masks are equal to 1
index_array = []
for i in range(masks.shape[1]):
    index_array.append(np.where(masks[:,i]==1)[0][0])
ind_of_ind = np.array(index_array)

max_rhs = max([len(l) for l in rhs_map])


# Test för att reproducera de Vries med parametrar passande de i de Vries (tror jag)

# Jag  har beräknat E(t) på samma sätt som de Vries gör (från I_tot och V_loop) samt satt
# T_cold och n_cold till en funktion lik den data de Vries använder. Stämmer det att
# T_cold är termala temperaturen och n_cold är termala elektron-densiteten? Ja
# T_cold är temperaturen för Maxwellianen. Främsta anledning till att evaluera avalanche och collisions etc
# n_cold är antalet fria elektroner i systemet, alla fria elektroner minus runaways

# Jag får inte samma I_p som de Vries I_tot utan den beter sig lite intressant men I_RE
# går mot I_p när tiden ökar så det är ju trevligt och kanske kan ganska enkelt förklaras
# med tanke på att det är olika ekvationer som används i simuleringarna
# Känslig för densitet och temperatur-utvecklingen

# Skenande-elektron-densiteten ökar också mer och mer och blir större än total-elektron-
# densiteten efter 150 s vilket inte är super - det vore bra med något som skulle kunna hindra
# n_re > n_tot, men det spelar egentligen inte jättestor roll då vi bara ska göra simuleringar
# i ca 10 s
# Antalet fria elektroner är konstant så om runaways försvinner uppkommer nya kalla elektroner

# Kan vara så att de Vries räknar ut E på ett annat sätt än jag har antagit från det han
# skrev, eftersom han senare skrev att han tar hänsyn till att Coulomb logaritmen ändras
# från 16 till 11 över tidens gång i beräkningen av E

# Bytte D0=0.03 mot D0=a**2/18\approx 0.05 men det blev bättre att ha D0=0.03 så jag bytte
# tillbaka

# Jag har ändrat Z från 1 till 2 i enighet med de Vries. För att få en någorlunda konstant
# I_p sänkte jag sedan B från 2.4 till 1.15 eftersom det funkade samt vi inte är säkra på vad
# de Vries har använt
#

# Till skillnad från de Vries får vi att I_re=I_p efter några sekunder oavsett om
# I_re(0)=5.5e5 A eller I_re(0)=6.5e5 A (de Vries får att detta endast stämmer för
# I_re(0)=6.5e5 A)

# Kappa parameter i de Vries, hoppar vissa effekter och löser dem med kappa
# DREAM hoppar inte dessa effekter
# Försöka få till den kappa som de Vries använder i vår kod
# Försöka hitta mer rimliga värden på kappa genom att analysera
# kappa = E_c_eff/E_c_free other.fluid, magnetfält och plasmats laddning påverkar
# Väte bas lägger till ytterliggare ett jonslag, Berrylium? Kol? Vi vill inte använda kol.
# Använd berrylium tror vi. De vries pratar om berrylium.
# Passa så att elektrondensiteten konstant genom att inte lägga tillför mycket Berryliym eller väte.

import numpy as np
import sys
from scipy import integrate
import matplotlib.pyplot as plt
from generate_current_profile import generate_current_profile_fun

sys.path.append('../../py/')

from DREAM.DREAMSettings import DREAMSettings
from DREAM import runiface
import DREAM.Settings.Equations.IonSpecies as Ions
import DREAM.Settings.Equations.RunawayElectrons as Runaways
import DREAM.Settings.Solver as Solver
import DREAM.Settings.CollisionHandler as Collisions
import DREAM.Settings.TransportSettings as Transport

#### Physical parameters ####

# Universal constants
e   = 1.60217662e-19  # Elementary charge [C]
c   = 299792458       # Speed of light [m/s]
m_e = 9.10938356e-31  # Electron mass [kg]

# Assumed constants in de Vries
A_c   = 3                   # Plasma cross section [m^2]
L_tor = 5e-6                # Inductance [H]
r_0   = 3                   # Major radius [m]
a     = np.sqrt(A_c/np.pi)  # Minor radius [m]
B     =2.4                 # Magnetic field [T]
tau_RE = 18
A0    = 0                   # Advection [???]
# Skippa advection helt och hållet
D0    = D0=a/2/tau_RE               # Diffusion [m^2/s ?]
# Jämförde DREAMs diffusionsterm (lossterm) med de Vries loss-term och fick fram
# att vi borde använda D0=a/2/tau_RE
# Enheter blir skumma men vi sätter in en 1a så att allt blir bra :)

# Time and radial parameters
tMax = 8.5    # Simulation time [s]
Nt   = 10000  # Number of time steps
Nr   = 1      # Number of radial steps

# Experimental data from de Vries (approximated)
t      = np.linspace(0,tMax,num=Nt+1)        # Time vector for time depending data
I_p    = 0.9*np.exp(-1/(10*(t+0.8490)))*1e6  # Time dependent plasma current [A]
dI_p   = np.gradient(I_p,t)                  # dI_p/dt, time derivative of the plasma current [A/s]
V_loop = 0.08+0.77/(t+1)**2.5                # Time dependent external torodial loop voltage [V]
n_e    = (0.285*np.exp(-t**2)+0.015)*1e19    # Time dependent density of thermal electrons [m^-3]
T_e    = (0.040+0.760/(t+1)**2)*1e3          # Time dependent thermal temperature [eV]

# Initial values in de Vries, changeable
I_re  = 6.5e5           # Initial runaway current [A]
n_re0 = I_re/(e*c*A_c)  # Initial density of runaway electrons [m^-3]

# Electric field calculated as in de Vries article
V_res = V_loop-L_tor*dI_p    # Time dependent resistive voltage [V] (V_res=I_tot*R_tot)
E     = V_res/(2*np.pi*r_0)  # Time dependent electric field strength [V/m]

# Total electron density
n = n_e[0]+n_re0  # Electron density [m^-3]

#### DREAM settings ####

ds = DREAMSettings()
#ds.collisions.collfreq_type = Collisions.COLLFREQ_TYPE_COMPLETELY_SCREENED
ds.collisions.collfreq_type = Collisions.COLLFREQ_TYPE_PARTIALLY_SCREENED

# Set E_field
ds.eqsys.E_field.setPrescribedData(E, times=t)

# Set thermal temperature and thermal electron density
ds.eqsys.T_cold.setPrescribedData(T_e, times=t)
ds.eqsys.n_cold.setPrescribedData(density=n_e, times=t)

# Set ions
ds.eqsys.n_i.addIon(name='D', Z=2, iontype=Ions.IONS_PRESCRIBED_FULLY_IONIZED, n=n/2)
#n=n säger hur många atomer. 1 atom med laddning 2 ger två elektroner så dela n med 2 om använder Z=2
# Lägg till ännu en rad för Berrylium, byt namn på det.
# Elektrondensitet som vi vill ha är n_e=n_D*Z_D+n_B*Z_B

# Runaway electrons
#ds.eqsys.n_re.setAvalanche(avalanche=Runaways.AVALANCHE_MODE_NEGLECT)
ds.eqsys.n_re.setAvalanche(avalanche=Runaways.AVALANCHE_MODE_FLUID_HESSLOW)
ds.eqsys.n_re.setInitialProfile(density=n_re0)

# Runaway loss
t = np.linspace(tMax/2, tMax/2, 1)
r = np.linspace(0, a, Nr+1)

A  = A0 * np.ones((1, Nr+1))  # istället för 'np.array([...])'
D  = D0 * np.ones((1, Nr+1))  # istället för 'np.array([...])'

ds.eqsys.n_re.transport.prescribeAdvection(ar=A, t=t, r=r)
ds.eqsys.n_re.transport.prescribeDiffusion(drr=D, t=t, r=r)
ds.eqsys.n_re.transport.setBoundaryCondition(Transport.BC_F_0)

ds.eqsys.n_re.setDreicer(Runaways.DREICER_RATE_DISABLED)

# Hot-tail grid settings
ds.hottailgrid.setEnabled(False)

# Disable runaway grid
ds.runawaygrid.setEnabled(False)

# Set up radial grid
ds.radialgrid.setB0(B)
ds.radialgrid.setMinorRadius(a)
ds.radialgrid.setMajorRadius(r_0)
ds.radialgrid.setWallRadius(a)
ds.radialgrid.setNr(Nr)

# Set solver type
ds.solver.setType(Solver.LINEAR_IMPLICIT) # semi-implicit time stepping

# include otherquantities to save to output
ds.other.include('fluid')

# Set time stepper
ds.timestep.setTmax(tMax)
ds.timestep.setNt(Nt)

ds.output.setTiming(stdout=True, file=True)

# Save and run DREAM settings
ds.save('settings_de_Vries_test_2.h5')
do = runiface(ds, 'output_de_Vries_test_2.h5', quiet=False)

#### Manage result ####

# Plot E_field
#do.eqsys.E_field.plot(r=[0,-1])
#plt.show()

# Plot I_p and I_re
n_re = do.eqsys.n_re[:]
I_re = n_re*e*c*A_c
tid=np.linspace(0,tMax,num=len(I_re))
plt.plot(tid,I_re)
do.eqsys.I_p.plot()
#plt.xlim(-1.5, 8.5)
#plt.ylim(0, 1e6)
plt.show()

# Plot n_tot and n_re
#do.eqsys.n_tot.plot(r=[0,-1])
#do.eqsys.n_re.plot(r=[0,-1])
#plt.show()

# Plot streaming parameter according to de Vries
#I_p = do.eqsys.I_p[:]
#T_J=1.602176565e-19*do.eqsys.T_cold[:] #Temperatur i joule
#v_th=np.sqrt(T_J/m_e)
#j_tot=I_p/A_c
#xi=np.abs(j_tot/(e*n*v_th))
#tid=np.linspace(0,tMax,num=len(xi))
#plt.plot(tid,xi)
#plt.show()

###################################################################################################
# Code for Troubleshooting
###################################################################################################

#dI_p_an    = 0.9*np.exp(-1/(10*(t+0.8490)))*(1/(10*(t+0.8490)**2))#*1e6

#plt.plot(t,I_p)
#plt.plot(t,dI_p)
#plt.xlim(-1.5, 8.5)
#plt.ylim(0, 1)
#plt.show()
#plt.plot(t,V_loop)
#plt.plot(t,n_e)
#plt.plot(t,T_e)
#plt.xlim(-1.5, 8.5)
#plt.ylim(0, 1)
#plt.show()
#print(str(I_p))

#E_c=7.66e-22*n_e

#plt.plot(t,E)
#plt.plot(t,E_c)
#plt.show()

#lnLambda=np.linspace(11,16,num=6) #-16
#for ln in lnLambda:
#    dI_re = 3*1e18*np.sqrt(np.pi / 21) * 1 / ln * (E - E_c) - 1 / 18
#    plt.plot(t, dI_re)
#    plt.show()

# Plot Coulomb logarithm
#lnLambdaC = do.other.fluid.lnLambdaC[:]
#lnLambdaT = do.other.fluid.lnLambdaT[:]
#tid=np.linspace(0,tMax,num=len(lnLambdaC))
#plt.plot(tid,lnLambdaC)
#plt.show()
#plt.plot(tid,lnLambdaT)
#plt.show()


# -*- coding: utf-8 -*-
__author__ = 'Lo'

import win32gui
import subprocess as s
from pykeyboard import PyKeyboard
import pyperclip
import time

k = PyKeyboard()

#打开notepad++
notepad = r"D:\Notepad++\notepad++.exe"
s.Popen(notepad)

#获取父窗口句柄
hwnd = win32gui.FindWindow("Notepad++",None)
print(win32gui.GetWindowText(hwnd))

#获取子窗口句柄
hwnd2 = win32gui.FindWindowEx(hwnd,None,"SysTabControl32",None)
print(win32gui.GetWindowText(hwnd2))

#键盘光标定位到编辑器上
win32gui.SetFocus(hwnd2)

#利用剪贴板将文字输入
#将文字写入剪贴板
pyperclip.copy(u'你好，世界---Hello World')

#将剪切板的文字复制到编辑器上
print(pyperclip.paste())
k.press_keys([k.control_key,'v'])


import datetime
dic_jogador={}
contratacoes=[]
times={}
nome_arq_contra='contratacoes.txt'
nome_arq_times='times.txt'
texto_padrao='====================\nDigite\n[1] para submenu dos jogadores\n[2] para submenu dos times\n[3] para submenu de contrataçoes\n[4] para submenu de relatorios\n[5] para sair '
texto_padrao2='====================\nDigite\n[1] para listar todos\n[2] para listar um\n[3] para incluir\n[4] para alterar\n[5] para excluir\n[6] para retornar ao menu principal '
texto_padrao3='====================\nDigite\n[1] para mostrar o nome do time e dados de jogadores que atuam em determinada posição\n[2] para mostrar dados de times com varios fundadores\n[3] para mostrar dado de jogadores com contratos entre datas\n[4] para voltar ao menu principal: '
def main():
    y=menu()
    while int(y)!=5:
        if y==1:
            jogadores()
        if y==2:
            x=menu2()
            if int(x)==1:
                listar_todos_times()
            if int(x)==2:
                listar_um_time()
            if int(x)==3:
                incluir_time()
                savetofile(times, nome_arq_times)
            if int(x)==4:
                alterar_time()
                savetofile(times, nome_arq_times)
            if int(x)==5:
                excluir_time()
                savetofile(times, nome_arq_times)
        if y==3:
            x=menu2()
            if int(x)==1:
                listar_todos_contrato()
            elif int(x)==2:
                listar_um_contrato()
            elif int(x)==3:
                incluir_contrato()
                savetofile(contratacoes, nome_arq_contra)
            elif int(x)==4:
                alterar_contrato()
                savetofile(contratacoes, nome_arq_contra)
            elif int(x)==5:
                excluir_contrato()
                savetofile(contratacoes, nome_arq_contra)
        if y==4:
            relatorios()
        y=menu()
    if y==5:
        print("Obrigado!")
def carregar():
    lerjogadores()
    if readfromfile(nome_arq_contra):
       contratacoes = readfromfile(nome_arq_contra)
    else:
        contratacoes=[]
    if readfromfile(nome_arq_times):
       times = readfromfile(nome_arq_times)
    else:
       times={}

def menu():
    texto_padrao='====================\nDigite\n[1] para submenu dos jogadores\n[2] para submenu dos times\n[3] para submenu de contrataçoes\n[4] para submenu de relatorios\n[5] para sair '
    print(texto_padrao)
    y=int(input("Digite sua opção: "))
    return y
def menu2():
    texto_padrao2='====================\nDigite\n[1] para listar todos\n[2] para listar um\n[3] para incluir\n[4] para alterar\n[5] para excluir\n[6] para retornar ao menu principal '
    print(texto_padrao2)
    y=int(input("Digite sua opção: "))
    return y

#funcao p/ salvar os dados em arquivo
def savetofile(datatosave, filename):
    f= open(filename,"w+")
    if type(datatosave) is list:
        print('salvando lista')
        for i in range(len(datatosave)):
            f.write(';'.join(contratacoes[i]))
            f.write('\n')
    elif type(datatosave) is dict:
        print('salvando dicionario')
        for k, v in datatosave.items():
            f.write(str(k) + '='+ str(v) + '\n')
    else:
        print('tipo de dado invalido: ',type(datatosave))
    f.close()
    return;

def savejogadores():
    arquivo=open("Jogadores.txt", "w")
    for jogador in dic_jogador:
        texto = str(jogador) + ";" + str(dic_jogador[jogador][0]) + ";" + str(dic_jogador[jogador][1]) + ";" + str(dic_jogador[jogador][2]) + ";" + str(dic_jogador[jogador][3]) + ";" + str(dic_jogador[jogador][4]) + ";" + str(dic_jogador[jogador][5]) + ";" + str(dic_jogador[jogador][6]) + ";" + str(dic_jogador[jogador][7]) + ";"
        arquivo.write(texto+"\n")
    arquivo.close()

#funcao p/ ler os dados do arquivo
def readfromfile(filename):
    if Existe_Arquivo(filename):
        f=open(filename,'r')
        if filename==nome_arq_contra:
            linha = f.readline()
            datatoread=[]
            while linha:
                datatoread.append(linha.strip().split(';'))
                linha = f.readline()
            return datatoread;
        elif filename==nome_arq_times:
            linha = f.readline()
            datatoread={}
            while linha:
                name, var = linha.partition("=")[::2]
                datatoread[name.strip()] = eval(var.strip())
                linha = f.readline()
            return datatoread;
        else:
            print('nome do arquivo invalido: ', filename)
        f.close()
    return False;

def lerjogadores():
    import os
    if os.path.exists('Jogadores.txt'):
       leitura=open('Jogadores.txt', 'r')
       for linha in leitura:
           cpf=""
           nome=""
           nascimento=""
           sexo=""
           peso=""
           altura=""
           e_mailtotal=""
           telefonetotal=""
           posicaototal=""
           contador = 0
           for letra in linha.rstrip():
               if letra == ";":
                  if contador == 1 and len(valor) > 0:
                     nome = valor
                  if contador == 2 and len(valor) > 0:
                     nascimento = valor
                  if contador == 3 and len(valor) > 0:
                     sexo = valor
                  if contador == 4 and len(valor) > 0:
                     peso = valor
                  if contador == 5 and len(valor) > 0:
                     altura = valor
                  if contador == 6 and len(valor) > 0:
                     e_mailtotal = valor
                  if contador == 7 and len(valor) > 0:
                     telefonetotal = valor
                  if contador == 8 and len(valor) > 0:
                     posicaototal = valor
                  contador = contador + 1
                  valor = ""
               if contador == 0:
                  cpf = cpf + letra
               if contador != 0 and letra != ";":
                  valor = valor + letra
           tupla=(nome, nascimento, sexo, peso, altura, e_mailtotal, telefonetotal, posicaototal)
           dic={cpf:tupla}
           dic_jogador.update(dic)

#funcao p/ verificar se o arquivo existe
def Existe_Arquivo(nome):
      import os
      if os.path.exists(nome):
          return True
      else:
          return False

#cria novos dados de jogadores
def jogadores():
    print("================")
    print("Jogadores")
    y=menu2()
    if y==1:
        if len(dic_jogador)==0:
            print('Não ha jogadores')
        else:
            for cpf in dic_jogador:
                print("CPF " + str(cpf))
                print("Nome " + str(dic_jogador[cpf][0]))
                print("Nascimento " + str(dic_jogador[cpf][1]))
                print("Sexo " + str(dic_jogador[cpf][2]))
                print("Peso " + str(dic_jogador[cpf][3]))
                print("Altura " + str(dic_jogador[cpf][4]))
                print("E-mails " + str(dic_jogador[cpf][5]))
                print("Telefones " + str(dic_jogador[cpf][6]))
                print("Posições " + str(dic_jogador[cpf][7]))
        jogadores()
    elif y==2:
        if len(dic_jogador)==0:
            print('Não há jogadores')
        else:
            i=int(input('Digite o CPF: '))
            for cpf in dic_jogador:
                if int(cpf)==i:
                    print("Nome " + str(dic_jogador[cpf][0]))
                    print("Data de nascimento " + str(dic_jogador[cpf][1]))
                    print("Sexo " + str(dic_jogador[cpf][2]))
                    print("Peso " + str(dic_jogador[cpf][3]))
                    print("Altura " + str(dic_jogador[cpf][4]))
                    print("E-mails " + str(dic_jogador[cpf][5]))
                    print("Telefones " + str(dic_jogador[cpf][6]))
                    print("Posições em jogo " + str(dic_jogador[cpf][7]))
        jogadores()
    elif y==3:
        cpf=int(input("Digite o CPF: "))
        for jogador in dic_jogador:
            if int(jogador)==cpf:
                print('CPF já cadastrado')
                jogadores()
        nome=input("Digite o nome do jogador: ")
        nascimento=input("Digite a data de nascimento do jogador: ")
        sexo=input("Digite o sexo do jogador: ")
        peso=input("Digite o peso do jogador: ")
        altura=input("Digite a altura do jogador: ")
        cont_e=0
        e_mailtotal=''
        email=input("Digite os e-mails do jogador - '' para terminar - : ")
        while email!='':
            if cont_e>1:
                e_mailtotal+=','+email
            else:
                e_mailtotal=email
            cont_e+=1
            email=input("Digite os e-mails do jogador - '' para terminar - : ")
        #
        cont_t=0
        telefonetotal=""
        telefone=input("Digite os telefones do jogador - '' para terminar - : ")
        while telefone != "":
            if cont_t > 1:
                   telefonetotal+=','+telefone
            else:
                    telefonetotal=telefone
            cont_t += 1
            telefone=input("Digite os telefones do jogador - '' para terminar - : ")
        #
        cont_p=0
        posicaototal=""
        posicao=input("Digite as posições do jogador - '' para terminar - : ")
        while posicao != "":
            if cont_p>1:
                posicaototal+=','+posicao
            else:
                posicaototal=posicao
            cont_p+=1
            posicao=input("Digite as posições do jogador - '' para terminar - : ")
        tupla=(nome, nascimento, sexo, peso, altura, e_mailtotal, telefonetotal, posicaototal)
        dic={cpf:tupla}
        dic_jogador.update(dic)
        savejogadores()
        jogadores()
    elif y==4:
        cpf=int(input("Digite o CPF: "))
        contador=0
        for jogador in dic_jogador:
            if int(jogador)==cpf:
                contador=1
        if contador==0:
            print("CPF Não cadastrado")
            jogadores()
        nome=input("Digite o nome do jogador: ")
        nascimento=input("Digite a data de nascimento do jogador: ")
        sexo=input("Digite o sexo do jogador: ")
        peso=input("Digite o peso do jogador: ")
        altura=input("Digite a altura do jogador: ")
        cont_e=0
        e_mails=""
        e_mailtotal=""
        while e_mails != "" or cont_e < 2:
            e_mails=input("Digite os e-mails do jogador - '' para terminar - : ")
            if e_mails != "":
                cont_e += 1
                if cont_e > 1:
                   e_mailtotal=e_mailtotal + ','
        e_mailtotal=e_mailtotal + e_mails
        #
        cont_t=0
        telefone=""
        telefonetotal=""
        while telefone != "" or cont_t < 2:
            telefone=input("Digite os telefones do jogador - '' para terminar - : ")
            if telefone != "":
                cont_t += 1
                if cont_t > 1:
                   telefonetotal=telefonetotal + ','
                telefonetotal=telefonetotal + telefone
        #
        cont_p=0
        posicao=""
        posicaototal=""
        while posicao != "" or cont_p < 2:
            posicao=input("Digite as posições do jogador - '' para terminar - : ")
            if posicao != "":
                cont_p += 1
                if cont_p > 1:
                   posicaototal=posicaototal + ','
                posicaototal=posicaototal + posicao
        tupla=(nome, nascimento, sexo, peso, altura, e_mailtotal, telefonetotal, posicaototal)
        dic={cpf:tupla}
        dic_jogador[cpf]=tupla
        savejogadores()
        jogadores()
    elif y==5:
         if len(dic_jogador)==0:
            print('Não há jogadores')
         else:
            cpf=int(input('Digite o CPF: '))
            contador=0
            if cpf in dic_jogador:
                dic_jogador.pop(cpf)
                jogadores()
                savejogadores()
                jogadores()
            else:
                print("CPF Não cadastrado")

#funções relacionadas a times
def listar_todos_times():
    if len(times)==0:
        print('Não há times registrados')
    else:
        for i in sorted(times):
            print((i, times[i]), end ="\n")
def listar_um_time():
    if len(times)==0:
        print('Não há times registrados')
    else:
        i=input('Digite o codigo do time: ')
        if i in times:
            print(i, times[i])
        else:
            print('Time nao registrado')
def incluir_time():
    info_time=[]
    cod=input('Digite o codigo do novo time: ')
    while cod in times:
        cod=input('Codigo de time já registrado\nDigite o codigo do novo time: ')
    nome=input('Digite o nome do time: ')
    info_time.append(nome)
    data_fun=input('Digite a data da fundação do time: ')
    info_time.append(data_fun)
    logra=input('Digite o logradouro da time: ')
    info_time.append(logra)
    nro=input('Digite o número do endereço da time: ')
    info_time.append(nro)
    cep=input('Digite o CEP do time: ')
    info_time.append(cep)
    cidade=input('Digite a cidade do time: ')
    info_time.append(cidade)
    estado=input('Digite o Estado do time: ')
    info_time.append(estado)
    quanti=input('Digite a quantidade de telefones do time: ')
    telefones=[]
    while len(telefones)!=int(quanti):
        tel=input('Digite o telefone do time: ')
        telefones.append(tel)
    info_time.append(telefones)
    nro_funda=input('Digite a quantidade de fundadores do time: ')
    fundadores=[]
    while len(fundadores)!=int(nro_funda):
        funda=input('Digite o nome do fundador: ')
        fundadores.append(funda)
    info_time.append(fundadores)
    times[cod]=info_time
def alterar_time():
    codi_alt=input('Digite o codigo do time a ser alterado: ')
    if codi_alt in times:
        time_alt=times.get(codi_alt)
        novo_dado=input('Digite o novo nome do time\nPressione enter para não alterar: ')
        if novo_dado!='':
            time_alt[0]=novo_dado
        novo_dado=input('Digite a nova data de fundação do time\nPressione enter para não alterar: ')
        if novo_dado!='':
            time_alt[1]=novo_dado
        novo_dado=input('Digite o novo logradouro do time\nPressione enter para não alterar: ')
        if novo_dado!='':
            time_alt[2]=novo_dado
        novo_dado=input('Digite o novo número do time\nPressione enter para não alterar: ')
        if novo_dado!='':
            time_alt[3]=novo_dado
        novo_dado=input('Digite o novo CEP do time\nPressione enter para não alterar: ')
        if novo_dado!='':
            time_alt[4]=novo_dado
        novo_dado=input('Digite a nova cidade do time\nPressione enter para não alterar: ')
        if novo_dado!='':
            time_alt[5]=novo_dado
        novo_dado=input('Digite o novo Estado do time\nPressione enter para não alterar: ')
        if novo_dado!='':
            time_alt[6]=novo_dado
        nro_novos_tel=input('Digite a nova quantidade de telefones do time\nPressione enter para não alterar: ')
        if nro_novos_tel!='':
            novos_tel=[]
            while len(novos_tel)!=int(nro_novos_tel):
                novo_dado=input('Digite o telefone do time: ')
                novos_tel.append(novo_dado)
            time_alt[7]=novos_tel
        nro_novos_funda=input('Digite a quantidade de fundadores\nPressione enter para não alterar: ')
        if nro_novos_funda!='':
            novos_funda=[]
            while len(ovos_funda)!=int(nro_novos_funda):
                novo_dado=input('Digite o nome do fundador: ')
                novos_funda.append(novo_dado)
            time_alt[8]=novos_funda
def excluir_time():
    dele=input('Digite o código do time a ser excluido: ')
    times.pop(dele)
#funções relacionadas a contratos
def listar_todos_contrato():
    if len(contratacoes)==0:
        print('Não há contratações')
    else:
         print(contratacoes)
def listar_um_contrato():
    if len(contratacoes)==0:
        print('Não há contratações')
    else:
        i=int(input('Digite a data do contrato: '))
        for d in range(len(contratacoes)):
            if contratacoes[d][2]==i:
                print(contratacoes[d])
def incluir_contrato():
    contrat_provi=[]
    CPF_jogador=input('Digite o CPF do jogador: ')
    if len(contratacoes)==0:
        contrat_provi.append(CPF_jogador)
        cod_time=input('Digite o codigo do time: ')
        contrat_provi.append(cod_time)
        print('Formato da data: DD/MM/AAAA')
        data_inicio=input('Digite a data do inicio do contrato: ')
        contrat_provi.append(data_inicio)
        salario=input('Digite o salário: ')
        contrat_provi.append(salario)
        mot_saida=input('Digite os motivos da saida: ')
        contrat_provi.append(mot_saida)
        contratacoes.append(contrat_provi)
    else:
        for f in range(len(contratacoes)):
            while CPF_jogador==contratacoes[f][0]:
                print('CPF ja registrado')
                CPF_jogador=input('Digite o CPF do jogador: ')
        contrat_provi.append(CPF_jogador)
        cod_time=input('Digite o codigo do time: ')
        for p in range (len(contratacoes)):
            while cod_time==contratacoes[p][1]:
                print('Código de time ja registrado')
                cod_time=input('Digite o codigo do time: ')
        contrat_provi.append(cod_time)
        data_inicio=input('Digite a data do inicio do contrato: ')
        for w in range(len(contratacoes)):
            while data_inicio==contratacoes[w][2]:
                print("Data ja registrada")
                data_inicio=input('Digite a data do inicio do contrato: ')
        contrat_provi.append(data_inicio)
        salario=input('Digite o salário: ')
        contrat_provi.append(salario)
        mot_saida=input('Digite os motivos da saida: ')
        contrat_provi.append(mot_saida)
        contratacoes.append(contrat_provi)
def alterar_contrato():
    alt=input('Digite a data do contrato a ser alterado: ')
    for i in range(len(contratacoes)):
        if alt==contratacoes[i][2]:
            idx=i
    print(contratacoes[idx])
    novo_dado=input('Digite o novo CPF: ')
    count=0
    while count==0:
        if novo_dado!='':
            for i in range(len(contratacoes)):
                if contratacoes[i][0]==novo_dado:
                    novo_dado=input('CPF já registrado\nDigite o novo CPF: ')
                else:
                    contratacoes[idx][0]=novo_dado
                    count=1
        else:
            count=1
    novo_dado=input('Digite o novo codigo de time: ')
    while count==1:
        if novo_dado!='':
            for i in range(len(contratacoes)):
                if contratacoes[i][1]==novo_dado:
                    novo_dado=input('Código de time já registrado\nDigite o novo codigo de time: ')
                else:
                    contratacoes[idx][1]=novo_dado
                    count=2
        else:
            count=2
    novo_dado=input('Digite a nova data de contrato: ')
    while count==2:
        if novo_dado!='':
            for i in range(len(contratacoes)):
                if contratacoes[i][2]==novo_dado:
                    novo_dado=input('Data já registrada\nDigite a nova data: ')
                else:
                    contratacoes[idx][2]=novo_dado
                count=3
        else:
            count=3
    novo_dado=input('Digite o novo salario: ')
    if novo_dado!='':
        contratacoes[idx][3]=novo_dado
    novo_dado=input('Digite o(s) novo(s) motivo(s) de saida: ')
    if novo_dado!='':
        contratacoes[idx][4]=novo_dado
def excluir_contrato():
    dele=input('Digite a data do contrato a ser excluido: ')
    for i in range(len(contratacoes)):
        if dele==contratacoes[i][2]:
            idx=i
    del contratacoes[i-1]

def relatorios():
    a=input(texto_padrao3)
    while a!='4':
        if int(a)==1:
            posi=input('Informe a posição: ')
            for k, v in dic_jogador.items():
                s=v[7].split(',')
                for o in range(len(s)):
                    if s[o]==posi:
                        for r in range(len(contratacoes)):
                            if k==contratacoes[r][0]:
                                for c, u in times.items():
                                    if contratacoes[r][1]==c:
                                        print('Nome do time: ',u[0],'\nInformações do jogador: ', v)
        if int(a)==2:
            lista_times=[]
            quant_funda=input('Informe a quantidade de fundadores: ')
            for p in times:
                if len(times[p][-1])>int(quant_funda):
                    lista_times.append(times[p][0])
            print(p, times[p])
        if int(a)==3:
            print('Formato das datas: DD/MM/AAAA')
            data_inicio=input('Informe a data de inicio dos contratos: ')
            day, month, year=map(int, data_inicio.split('/'))
            data1=datetime.date(year, month, day)
            data_termino=input('Informe a data limite dos contratos: ')
            day, month, year=map(int, data_termino.split('/'))
            data2=datetime.date(year, month, day)
            for d in range(len(contratacoes)):
                day, month, year=map(int, contratacoes[d][2].split('/'))
                shrek=datetime.date(year, month, day)
                if shrek>data1 and shrek<data2:
                    cpf=contratacoes[d][0]
                    print(dic_jogador[cpf])
                    time=contratacoes[d][1]
                    print(time, times[time])
        a=input(texto_padrao3)
lerjogadores()
if readfromfile(nome_arq_contra):
    contratacoes = readfromfile(nome_arq_contra)
else:
    contratacoes=[]
if readfromfile(nome_arq_times):
    times = readfromfile(nome_arq_times)
else:
    times={}

#inicia o programa
main()


import collections
import enum

from .constraints import Requirement
from .errors import NoPackageFound, SolverException
from .request import JobType

class RuleType(enum.Enum):
    internal_allow_update = 1
    job_install = 2
    job_remove = 3
    job_update = 4
    package_requires = 7
    package_same_name = 10
    package_implicit_obsoletes = 11
    package_installed = 12

    internal = 256

class PackageRule(object):
    @classmethod
    def _from_string(cls, rule_string, pool):
        """
        Creates a PackageRule from a rule string, e.g. '-numpy-1.6.0 | numpy-1.7.0'

        Because package full name -> id is not 1-to-1 mapping, this may fail
        when a package has multiple ids. This is mostly used for testing, to
        write reference rules a bit more easily.
        """
        packages_string = (s.strip() for s in rule_string.split("|"))
        package_literals = []
        for package_string in packages_string:
            if package_string.startswith("-"):
                positive = False
                package_string = package_string[1:]
            else:
                positive = True

            requirement = Requirement.from_package_string(package_string)
            package_candidates = pool.what_provides(requirement)
            if len(package_candidates) == 0:
                msg = "No candidate for package {0!r}".format(package_string)
                raise NoPackageFound(msg)
            elif len(package_candidates) > 1:
                msg = "> 1 candidate for package {0!r} requirement, cannot " \
                      "create rule from it" % package_string
                raise SolverException(msg)
            else:
                _id = pool.package_id(package_candidates[0])
                if positive:
                    package_literals.append(_id)
                else:
                    package_literals.append(-_id)
        return cls(package_literals)

    def __init__(self, literals, reason):
        self.literals = tuple(sorted(literals))
        self._reason = RuleType(reason)

    @property
    def is_assertion(self):
        return len(self.literals) == 1

    @property
    def reason(self):
        return self._reason

    def to_string(self, pool):
        parts = [pool.id_to_string(literal) for literal in self.literals]
        s = " | ".join(parts)

        if self._reason == RuleType.job_install:
            return "Install command rule ({})".format(s)
        elif self._reason == RuleType.job_update:
            return "Update to latest command rule ({})".format(s)
        elif self._reason == RuleType.job_remove:
            return "Remove command rule ({})".format(s)
        elif self._reason == RuleType.package_same_name:
            parts = [pool.id_to_string(abs(literal))
                     for literal in self.literals]
            s = " | ".join(parts)
            return "Can only install one of: ({})".format(s)
        elif self._reason == RuleType.package_installed:
            parts = [pool.id_to_string(abs(literal))
                     for literal in self.literals]
            s = " | ".join(parts)
            return "Should install one of: ({})".format(s)
        elif self._reason == RuleType.package_requires:
            source_id = abs(self.literals[0])
            source = pool._id_to_package[source_id]
            parts = [pool.id_to_string(literal)
                     for literal in self.literals[1:]]
            s = " | ".join(parts)
            return "{} {} requires ({})".format(source.name, source.version, s)
        else:
            return s

    def __eq__(self, other):
        return (isinstance(other, self.__class__)
                and self.literals == other.literals)

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

    def __hash__(self):
        return hash(self.literals)

class RulesGenerator(object):
    def __init__(self, pool, request, installed_map=None):
        self._rules_set = collections.OrderedDict()
        self._pool = pool

        self.request = request
        self.installed_map = installed_map or collections.OrderedDict()
        self.added_package_ids = set()

    def iter_rules(self):
        """
        Return an iterator over each created rule.
        """
        self.added_package_ids = set()
        for package in self.installed_map.values():
            self._add_installed_package_rules(package)
            self._add_package_rules(package)
        self._add_job_rules()
        return self._rules_set

    # ------------------------------
    # API to create individual rules
    # ------------------------------
    def _create_dependency_rule(self, package, dependencies, reason,
                                reason_details=""):
        """
        Create the rule for the dependencies of a package.

        This dependency is of the form (-A | R1 | R2 | R3) where R* are
        the set of packages provided by the dependency requirement.

        Parameters
        ----------
        package: PackageInfo
            The package with a requirement
        dependencies: sequence
            Sequence of packages that fulfill the requirement.
        reason: str
            A valid PackageRule.reason value
        reason_details: str
            Optional details explaining that rule origin.

        Returns
        -------
        rule: PackageRule or None
        """
        literals = [-self._pool.package_id(package)]

        for dependency in dependencies:
            if dependency != package:
                literals.append(self._pool.package_id(dependency))

        return PackageRule(literals, reason)

    def _create_conflicts_rule(self, issuer, provider, reason, reason_details=""):
        """
        Create a conflict rule between issuer and provider

        The rule is of the form (-A | -B)

        Parameters
        ----------
        issuer: PackageInfo
            Package declaring the conflict
        provider: PackageInfo
            Package causing the conflict
        reason: str
            One of PackageRule.reason
        reason_details: str
            Optional details explaining that rule origin.

        Returns
        -------
        rule: PackageRule or None
        """
        if issuer != provider:
            return PackageRule([-self._pool.package_id(issuer),
                                -self._pool.package_id(provider)], reason)

    def _create_install_one_of_rule(self, packages, reason):
        """
        Creates a rule to Install one of the given packages.

        The rule is of the form (A | B | C)

        Parameters
        ----------
        packages: sequence
            List of packages to choose from
        reason: str
            One of PackageRule.reason

        Returns
        -------
        rule: PackageRule
        """
        literals = [self._pool.package_id(p) for p in packages]
        return PackageRule(literals, reason)

    def _create_remove_rule(self, package, reason):
        """
        Create the rule to remove a package.

        For a package A, the rule is simply (-A)

        Parameters
        ----------
        package: PackageInfo
            The package with a requirement

        Returns
        -------
        rule: PackageRule or None
        """
        return PackageRule((-self._pool.package_id(package),), reason)

    # -------------------------------------------------
    # API to assemble individual rules from requirement
    # -------------------------------------------------
    def _add_rule(self, rule, rule_type):
        """
        Add the given rule to the internal rules set.

        Does nothing if the rule is None.

        Parameters
        ----------
        rule: PackageRule or None
            The rule to add
        rule_type: str
            Rule's  type
        """
        if rule is not None and rule not in self._rules_set:
            self._rules_set[rule] = None

    def _add_dependencies_rules(self, package, work_queue):
        for dependency in sorted(package.dependencies):
            requirement = Requirement.from_legacy_requirement_string(dependency)
            dependency_candidates = self._pool.what_provides(requirement)

            assert len(dependency_candidates) > 0, \
                ("No candidates found for requirement {0!r}, needed for "
                 "dependency {1!r}".format(requirement.name, package))

            rule = self._create_dependency_rule(package, dependency_candidates,
                                                RuleType.package_requires,
                                                str(dependency))
            self._add_rule(rule, "package")

            for candidate in dependency_candidates:
                work_queue.append(candidate)

    def _add_package_rules(self, package):
        """
        Create all the rules required to satisfy installing the given package.
        """
        work_queue = collections.deque()
        work_queue.append(package)

        while len(work_queue) > 0:
            p = work_queue.popleft()

            p_id = self._pool.package_id(p)
            if p_id not in self.added_package_ids:
                self.added_package_ids.add(p_id)
                self._add_dependencies_rules(p, work_queue)

                requirement = Requirement.from_legacy_requirement_string(p.name)
                obsolete_providers = self._pool.what_provides(requirement)
                for provider in obsolete_providers:
                    if provider != p:
                        if provider.name == p.name:
                            reason = RuleType.package_same_name
                        else:
                            reason = RuleType.package_implicit_obsoletes
                        rule = self._create_conflicts_rule(p, provider,
                                                           reason, str(p))
                        self._add_rule(rule, "package")

    def _add_install_job_rules(self, job):
        packages = self._pool.what_provides(job.requirement)
        if len(packages) > 0:
            for package in packages:
                if package not in self.installed_map:
                    self._add_package_rules(package)

            rule = self._create_install_one_of_rule(packages,
                                                    RuleType.job_install)
            self._add_rule(rule, "job")

    def _add_remove_job_rules(self, job):
        packages = self._pool.what_provides(job.requirement)
        for package in packages:
            rule = self._create_remove_rule(package, RuleType.job_remove)
            self._add_rule(rule, "job")

    def _add_update_job_rules(self, job):
        """
        Create rules that force the update of the package by requiring all of
        the standard rules then adding an additional rule for just the most
        recent version.
        """
        packages = self._pool.what_provides(job.requirement)
        if len(packages) == 0:
            return
        # An update request *must* install the latest package version
        def key(package):
            installed = self._pool.package_id(package) in self.installed_map
            return (package.version, installed)
        package = max(packages, key=key)
        self._add_package_rules(package)
        rule = PackageRule(
            (self._pool.package_id(package),),
            RuleType.job_update
        )
        self._add_rule(rule, "job")

    def _add_installed_package_rules(self, package):
        packages_all_versions = self._pool._packages_by_name[package.name]
        for other in packages_all_versions:
            self._add_package_rules(other)

    def _add_job_rules(self):
        for job in self.request.jobs:
            if job.kind == JobType.install:
                self._add_install_job_rules(job)
            elif job.kind == JobType.remove:
                self._add_remove_job_rules(job)
            elif job.kind == JobType.update:
                self._add_update_job_rules(job)
            else:
                msg = "Job kind {0!r} not supported".format(job.kind)
                raise NotImplementedError(msg)


"""add Tweet.content Model

Revision ID: 2d397dfdefbc
Revises: ee9d47c84311
Create Date: 2017-02-24 14:02:45.482000

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '2d397dfdefbc'
down_revision = 'ee9d47c84311'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('tweet', sa.Column('content', sa.String(length=256), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('tweet', 'content')
    # ### end Alembic commands ###


# coding=utf-8
import csv
import logging

from django.core.validators import MinValueValidator
from django.db import models
from django.forms import model_to_dict

logger = logging.getLogger(__name__)

class ImportFile(models.Model):
    file = models.FileField()
    total_entries = models.IntegerField(default=0)
    valid_entries = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'File Import'
        verbose_name_plural = 'File Imports'
        ordering = '-created_at',

    @classmethod
    def parse(cls, raw_file):
        file_import = cls.objects.create(file=raw_file)

        reader = csv.reader(file_import.file, delimiter=',')
        for i, row in enumerate(reader):
            file_import.total_entries += 1
            if i == 0:
                # skip header
                continue
            try:
                row = [line.decode('utf-8') for line in row]
                entry = ImportEntry.parse(file_import, row)
                if entry:
                    file_import.valid_entries += 1
            except:
                logger.exception('failed to import %s', row)

        file_import.save()
        return file_import

    def to_json(self):
        obj = model_to_dict(self, fields=[
            'pk',
            'total_entries',
            'valid_entries',
        ])
        obj['entries'] = [x.to_json() for x in self.entries.all()]
        return obj

class ImportEntry(models.Model):
    file = models.ForeignKey(ImportFile, related_name='entries')

    GROUP_FAME_CASE = 'frame_case'
    GROUP_FRAME = 'frame'
    GROUP_LENSES_CARE = 'lenses_care'
    GROUP_CHOICES = (
        (GROUP_FRAME, 'Оправа'),
        (GROUP_FAME_CASE, 'Футляр'),
        (GROUP_LENSES_CARE, 'Расствор для линз'),
    )
    group = models.CharField(max_length=255, choices=GROUP_CHOICES)
    group_name = models.CharField(max_length=255, choices=GROUP_CHOICES)
    manufacture = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    color = models.CharField(max_length=255, blank=True)
    volume = models.CharField(max_length=255, blank=True)
    description = models.TextField(max_length=5000, blank=True)
    origin_country = models.CharField(max_length=255)
    price_regular = models.IntegerField(validators=[
        MinValueValidator(1)
    ])
    price_discounted = models.IntegerField(validators=[
        MinValueValidator(1)
    ])

    class Meta:
        verbose_name = 'Entry'
        verbose_name_plural = 'Entries'

    @classmethod
    def parse(cls, file_import, columns):
        obj = cls()
        (obj.group_name,
         obj.manufacture,
         obj.name,
         # obj.color,
         # obj.volume,
         obj.description,
         obj.origin_country,
         obj.price_regular,
         obj.price_discounted) = columns

        group = obj.group_name.lower()
        if u'футляр' in group:
            obj.group = cls.GROUP_FAME_CASE
        elif u'линз' in group:
            obj.group = cls.GROUP_LENSES_CARE
        elif u'очк' in group or u'оправа' in group:
            obj.group = cls.GROUP_FRAME
        else:
            logger.exception('unknown group %s', group)
            return None

        obj.file = file_import
        obj.save()
        return obj

    def to_json(self):
        return model_to_dict(self)


# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------

import uuid
from msrest.pipeline import ClientRawResponse

from .. import models

class BaselinesOperations(object):
    """BaselinesOperations operations.

    You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    :ivar api_version: Client Api Version. Constant value: "2019-03-01".
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.api_version = "2019-03-01"

        self.config = config

    def list(
            self, resource_uri, metricnames=None, metricnamespace=None, timespan=None, interval=None, aggregation=None, sensitivities=None, filter=None, result_type=None, custom_headers=None, raw=False, **operation_config):
        """**Lists the metric baseline values for a resource**.

        :param resource_uri: The identifier of the resource.
        :type resource_uri: str
        :param metricnames: The names of the metrics (comma separated) to
         retrieve.
        :type metricnames: str
        :param metricnamespace: Metric namespace to query metric definitions
         for.
        :type metricnamespace: str
        :param timespan: The timespan of the query. It is a string with the
         following format 'startDateTime_ISO/endDateTime_ISO'.
        :type timespan: str
        :param interval: The interval (i.e. timegrain) of the query.
        :type interval: timedelta
        :param aggregation: The list of aggregation types (comma separated) to
         retrieve.
        :type aggregation: str
        :param sensitivities: The list of sensitivities (comma separated) to
         retrieve.
        :type sensitivities: str
        :param filter: The **$filter** is used to reduce the set of metric
         data returned.
Example:
Metric contains metadata A, B and
         C.
- Return all time series of C where A = a1 and B = b1 or
         b2
**$filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq
         ‘*’**
- Invalid variant:
**$filter=A eq ‘a1’ and B eq ‘b1’ and C
         eq ‘*’ or B = ‘b2’**
This is invalid because the logical or
         operator cannot separate two different metadata names.
- Return all
         time series where A = a1, B = b1 and C = c1:
**$filter=A eq ‘a1’
         and B eq ‘b1’ and C eq ‘c1’**
- Return all time series where A =
         a1
**$filter=A eq ‘a1’ and B eq ‘*’ and C eq ‘*’**.
        :type filter: str
        :param result_type: Allows retrieving only metadata of the baseline.
         On data request all information is retrieved. Possible values include:
         'Data', 'Metadata'
        :type result_type: str or
         ~azure.mgmt.monitor.v2019_03_01.models.ResultType
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of SingleMetricBaseline
        :rtype:
         ~azure.mgmt.monitor.v2019_03_01.models.SingleMetricBaselinePaged[~azure.mgmt.monitor.v2019_03_01.models.SingleMetricBaseline]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.monitor.v2019_03_01.models.ErrorResponseException>`
        """
        def prepare_request(next_link=None):
            if not next_link:
                # Construct URL
                url = self.list.metadata['url']
                path_format_arguments = {
                    'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str', skip_quote=True)
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                if metricnames is not None:
                    query_parameters['metricnames'] = self._serialize.query("metricnames", metricnames, 'str')
                if metricnamespace is not None:
                    query_parameters['metricnamespace'] = self._serialize.query("metricnamespace", metricnamespace, 'str')
                if timespan is not None:
                    query_parameters['timespan'] = self._serialize.query("timespan", timespan, 'str')
                if interval is not None:
                    query_parameters['interval'] = self._serialize.query("interval", interval, 'duration')
                if aggregation is not None:
                    query_parameters['aggregation'] = self._serialize.query("aggregation", aggregation, 'str')
                if sensitivities is not None:
                    query_parameters['sensitivities'] = self._serialize.query("sensitivities", sensitivities, 'str')
                if filter is not None:
                    query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
                if result_type is not None:
                    query_parameters['resultType'] = self._serialize.query("result_type", result_type, 'ResultType')
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Accept'] = 'application/json'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters, header_parameters)
            return request

        def internal_paging(next_link=None):
            request = prepare_request(next_link)

            response = self._client.send(request, stream=False, **operation_config)

            if response.status_code not in [200]:
                raise models.ErrorResponseException(self._deserialize, response)

            return response

        # Deserialize response
        header_dict = None
        if raw:
            header_dict = {}
        deserialized = models.SingleMetricBaselinePaged(internal_paging, self._deserialize.dependencies, header_dict)

        return deserialized
    list.metadata = {'url': '/{resourceUri}/providers/microsoft.insights/metricBaselines'}


import cv2
import numpy as np

def getred(img1, img2):
	img = cv2.imread("test.png")
	height = img.shape[0]
	width = img.shape[1]

	cv2.rectangle(img,(0,0),(width,height),(0,0,255),-1)
	#cv2.imshow('image', img2)
	#cv2.waitKey(0)
	#cv2.destroyAllWindows()
	for h in range(0,height):
		for w in range(0,width):
			pixel1 = img1[h,w]
			pixel2 = img2[h,w]
			if(pixel1 == pixel2):
				img[h,w] = img1[h,w]
	return img

def export_movie():
# 入力する動画と出力パスを指定。
	target = "out/two/"
	result = "redglass.avi"

# 動画の読み込みと動画情報の取得
	#img = cv2.imread(target+"0.png",cv2.IMREAD_GRAYSCALE)
	img = cv2.imread(target+"0.png", 0)
	img0 = img
	fps    = 10
	if len(img.shape) == 3:
		height, width, channels = img.shape[:3]
	else:
		height, width = img.shape[:2]
		channels = 1

# 形式はMP4Vを指定
	fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')

# 出力先のファイルを開く
	out = cv2.VideoWriter(result, int(fourcc), fps, (int(width), int(height)))

# 最初の1フレームを読み込む
	if not img is None:
		num = 1
	else:
		sys.exit(1)

# フレームの読み込みに成功している間フレームを書き出し続ける
	while (not img is None and num < 100):

# 読み込んだフレームを書き込み
		#out.write(cv2.cvtColor(getred(img0, img),cv2.COLOR_GRAY2RGB))
		out.write(getred(img0, img))

# 次のフレームを読み込み
		img = cv2.imread(target+str(num)+".png", 0)
		num = num + 1

if __name__ == '__main__':
	export_movie()


import json
import ast
import random
from model import User
from utils import get_5, add_words

# intermediate_1000 = [w.split(' = ')[0] for w in open('/root/Desktop/telega/eng_5_word/words_lists/intermediate_1000.txt', 'r').readlines()]
intermediate_1000 = open('/root/Desktop/telega/eng_5_word/words_lists/intermediate_1000.txt', 'r').read()
intermediate_1000 = ast.literal_eval(intermediate_1000)
# print(User.query().filter(User.user_chat == '205623050')[0].known_words)
def add_user(chat_id):
    active_5 = get_5(list(intermediate_1000.keys()))
    active_5 = dict((k,0) for k in active_5)
    User(user_chat=chat_id, active_5=str(active_5), known_words='[]', tmp='[]').save()
# add_user('205623050')

def dell_user(chat_id):
    user = User.query().filter(User.user_chat == chat_id)[0]
    user.delete()

def plus_active(chat_id, word):
    user = User.query().filter(User.user_chat == chat_id)[0]
    active = ast.literal_eval(user.active_5)   # {}
    active[word] = active[word] + 1
    User.query().filter(User.user_chat == chat_id)[0].update(active_5=str(active))

def count_known(chat_id):
    user = User.query().filter(User.user_chat == chat_id)[0]
    known = ast.literal_eval(user.known_words)  # []
    return len(known)

def update_user(chat_id):
    user = User.query().filter(User.user_chat == chat_id)[0]
    active = ast.literal_eval(user.active_5)   # {}
    old_known = ast.literal_eval(user.known_words) # []
    # tmp = ast.literal_eval(user.known_words)   # []
    new_known = [i for i in list(active.keys()) if active[i] == 3]
    known = old_known+ new_known
    User.query().filter(User.user_chat == chat_id)[0].update(known_words=str(known), tmp='[]')
    new_active = add_words(list(intermediate_1000.keys()), known, active)
    print('new active',new_active)
    User.query().filter(User.user_chat == chat_id)[0].update(active_5=str(new_active))

def get_tmp(chat_id):
    user = User.query().filter(User.user_chat == chat_id)[0]
    tmp = ast.literal_eval(user.tmp)
    return tmp

def get_btn_id(chat_id):
    user = User.query().filter(User.user_chat == chat_id)[0]
    id = user.btnID
    return id

def all_chat_id():
    users = User.query()
    IDs = [user.user_chat for user in users]
    return IDs
# print(all_chat_id())
def is_consist(chat_id):
    count = len(list(User.query().filter(User.user_chat == chat_id)))
    if count == 0:
        return False
    else:
        return True

def update_tmp(chat_id, new_tmp):
    User.query().filter(User.user_chat == chat_id)[0].update(tmp=new_tmp)

def update_btn_id(chat_id, new):
    if new == 999:
        User.query().filter(User.user_chat == chat_id)[0].update(btnID=0)
    else:
        User.query().filter(User.user_chat == chat_id)[0].update(btnID=new)

def get_4_wrong(chat_id, true_word):
    wrong_words = []
    user = User.query().filter(User.user_chat == chat_id)[0]
    knomn = ast.literal_eval(user.known_words)
    while len(wrong_words) != 4:
        word = random.choice(list(intermediate_1000.keys()))
        if word != true_word and word not in knomn and word not in wrong_words:
            wrong_words.append(word)
    return wrong_words

def result_msg(chat_id):
    msg = ''
    user = User.query().filter(User.user_chat == chat_id)[0]
    tmp = ast.literal_eval(user.tmp)
    wrong_words = [word.lower() for word in tmp if word.isupper()]
    print('результирующее сообщение')
    print(tmp)
    print(wrong_words)
    if len(wrong_words) == 0:
        msg = "Вы не допустили ни одной ошибки. Так держать!"
        return msg
    start_msg = f"Вы ошиблись в {len(wrong_words)} словах:\n\n"
    msg = start_msg
    for word in wrong_words:
        translate = intermediate_1000[word]
        part_msg = f"{word} - {translate}\n"
        msg = msg + part_msg
    return msg

def get_active(chat_id):
    user = User.query().filter(User.user_chat == chat_id)[0]
    active = ast.literal_eval(user.active_5)
    return active

for i in User.query():
    print(i.active_5)

# import datetime
# print(datetime.datetime.now())


from django.conf import settings
from django.conf.urls.static import static
if settings.USE_EXPLICIT_LANG_URL:
    from django.conf.urls.i18n import i18n_patterns as url_patterns
else:
    from django.conf.urls import patterns as url_patterns
from django.conf.urls import patterns, include, url

from django.contrib import admin

from carts.views import CartView, ItemCountView, CheckoutView, CheckoutFinalView
from orders.views import (
                    AddressSelectFormView,
                    UserAddressCreateView,
                    OrderList,
                    OrderDetail)
from newsletter.views import home, contact
from zakkabag.views import about, sitemap, set_language

admin.autodiscover()

def i18n_javascript(request):
    return admin.site.i18n_javascript(request)

#urlpatterns = url_patterns['',
urlpatterns = [
    # Examples:
    url(r'^$', home, name='home'),
    url(r'^home$', home, name='home'),
    url(r'^contact/$', contact, name='contact'),
    url(r'^about/$', about, name='about'),
    url(r'^about/sitemap$', sitemap, name='sitemap'),
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    url(r'^admin/jsi18n', i18n_javascript),  # added for AdminDateTimeWidget
    url(r'^admin/', include(admin.site.urls)),

    url(r'^products/', include('products.urls')),
    url(r'^categories/', include('products.urls_categories')),

    url(r'^orders/$', OrderList.as_view(), name='orders'),
    url(r'^orders/(?P<pk>\d+)/$', OrderDetail.as_view(), name='order_detail'),

    url(r'^cart/$', CartView.as_view(), name='cart'),
    url(r'^cart/count/$', ItemCountView.as_view(), name='item_count'),

    url(r'^checkout/$', CheckoutView.as_view(), name='checkout'),
    url(r'^checkout/address/$', AddressSelectFormView.as_view(), name='order_address'),
    url(r'^checkout/address/add/$', UserAddressCreateView.as_view(), name='user_address_create'),
    url(r'^checkout/final/$', CheckoutFinalView.as_view(), name='checkout_final'),

    url(r'^personalcenter/', include('personalcenter.urls')),
    # url(r'^crowdfundings/', include('crowdfundings.urls')),
    url(r'^newsletter/', include('newsletter.urls')),
    url(r'^auth/', include('authwrapper.urls')),
    url(r'^wechat/', include('wechat.urls')),
    url(r'^fileupload/', include('fileuploadwrapper.urls')),

    url(r'^accounts/', include('registration.backends.default.urls')),
    url(r'^setlang/$', set_language, name='setlang'),
    url(r'^phone_login/', include('phone_login.urls')),

    #url(r'^setlang/$', 'django.views.i18n.set_language', name = 'setlang'),

    #url(r'^ckeditor/', include('ckeditor.urls')),

    # url(r'^articles/comments/', include('django_comments.urls')),
#)
]

urlpatterns +=  [
#urlpatterns += patterns(
    url(r'^i18n/', include('django.conf.urls.i18n')),
#)
]

import os
if settings.DEBUG:
    if settings.USE_SAE_BUCKET: #'SERVER_SOFTWARE' in os.environ:
        pass
    else:
    	urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    	urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import requests
import xml.etree.ElementTree as ET

from get_qrz_key import get_session_key

base_url = 'http://xmldata.qrz.com/xml/current/'

# with open('qrz_key') as f:
#     SESSION_KEY = f.readline()

def get_latlon_cont(cont):
    if cont == 'NA':
        return 37.090240, -95.712891
    elif cont == 'EU':
        return 51.165691, 10.451526
    elif cont == 'AS':
        return 34.047863, 100.619655
    elif cont == 'OC':
        return -22.735910, 140.018765
    elif cont == 'AF':
        return -8.783195,34.508523
    elif cont == 'SA':
        return -8.783195, -55.491477
    else:
        return -82.862752, -135

def get_latlon(callsign):

    SESSION_KEY = get_session_key()

    payload = {'s':SESSION_KEY,'callsign':callsign}

    r = requests.get(base_url,params=payload)

    root = ET.fromstring(r.text)
    nspace = {'qrz': 'http://xmldata.qrz.com'}

    lat = root[0].findtext('qrz:lat', namespaces=nspace)
    lon = root[0].findtext('qrz:lon', namespaces=nspace)
    return lat,lon


"""park URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from web import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    path('createTask', views.createTask),
    path('acceptTask', views.acceptTask),
    path('finishTask', views.finishTask),
    path('deleteTask', views.deleteTask),
    path('deleteAllTasks', views.deleteAllTasks),
    path('currentTask', views.currentTask),
    path('admin', views.admin),
    # path('admin', views.admin),
    path('worker', views.worker),
    path('login', views.login),
    path('logout', views.logout),
    path('registration', views.registration),
    path('forbidden', views.access),
    path('', views.index),
]


# Import libraries
import numpy as np
import pandas as pd
import os
import os.path
import datetime as dt

# Print output to be displayed in terminal
print("\nBegin merge script.\nScanning for files.\n\nImporting files:")

# Get all .xlsx files from project root recursively
targetF = []
errFiles = ""
validFiles = ""
validCnt = 0
errCnt = 0

for root, subdirs, files in os.walk(os.curdir):
    for f in files:
        if f.endswith('.xlsx') and not (f == "master_table.xlsx" or f == "~$master_table.xlsx"):
            try:
                checkfile = open(os.path.join(root, f))
                checkfile.close()
                validCnt += 1
                print("  " + os.path.join(root, f))
                validFiles += "  " + os.path.join(root, f) + "\n"
                targetF.append(os.path.join(root, f))
            except:
                errCnt += 1
                errFiles += "  " + os.path.join(root, f[2:]) + "\n"
                pass

# Output a log file from the merge process
if errCnt == 0:
    logMsg = "Process executed at: {}\n\nFiles imported:\n".format(str(dt.datetime.now()).split('.')[0]) + validFiles + "\nNumber of files imported = {}\n\nImport successful!".format(validCnt)
    log_file = open('log.txt', 'w')
elif errCnt > 0:
    logMsg = "Process executed at: {}\n\nFiles imported:\n".format(str(dt.datetime.now()).split('.')[0]) + validFiles + "{} file(s) imported.\n\nWarning!!! Some files were in use during the time of import.".format(validCnt) \
    + "\nRun the script again in case there are changes from the affected files.\n\n{} file(s) affected:\n".format(errCnt) \
    + errFiles
    log_file = open('log.txt', 'w')
    print("\n{} file(s) imported.\nWarning!!! {} file(s) in use during runtime:\n".format(validCnt, errCnt) + \
          errFiles + "There may have been changes to the affected files.")

log_file.write(logMsg)
log_file.close()

# Load all .xlsx to dataframes and concatenate into master dataframe
dataframes = [pd.read_excel(t) for t in targetF]
df_master = pd.concat(dataframes)

# Exports a consolidated excel file
if os.path.exists('master_table.xlsx'):
    try:
        mstFile = open('master_table.xlsx','r')
        mstFile.close()
        df_master.to_excel('master_table.xlsx', index = False)
        print("\nMerge complete!")
    except PermissionError:
        errMsg = "\nERROR!!! UPDATE FAILED! Please close the master_table.xlsx file and run the script again."
        print(errMsg)
        # open('log.txt', 'a').write(errMsg)
        open('log.txt', 'w').write(errMsg)
else:
    df_master.to_excel('master_table.xlsx', index = False)
    print("\nMerge complete!")