# -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 09:18:49 2012
@author: nfisher
Chooses the sql to grab data for ContributionFigure graph.
"""
class ChooseSQL:

    def __doc__(self):
        return 'Create a structured query based on ( activity, pollutant, feedstock ) inputs'

    def __init__(self, activity, pollutant, feedstock, schema):
        self.schema = schema
        self.act = activity
        self.pol = pollutant
        self.feed = feedstock
        self.queryString = ''

        self.rawTable = feedstock + '_raw'

        if( pollutant == 'NOx' or pollutant == 'NH3' ):
            self.fertTable = feedstock + '_nfert'

        if( (pollutant == 'VOC') and
            (feedstock == 'CG' or feedstock == 'SG') ):

            self.chemTable = feedstock + '_chem'

    """
    This method chooses which tables to query based on the inputs
    """
    def getQuery(self):

    #-- pre-define the test cases for which there are zero emissions
        if self.feed == 'FR' and self.act == 'Harvest':
            return self.__returnFRHarv__() #special case

        elif self.feed == 'FR':
            return self.__returnNull__()

    #fertilizer only looks at nh3 and nox from fertilizer application
        elif( ( self.act == 'Fertilizer' ) and
                ( self.pol != 'NOx' and self.pol != 'NH3' ) ):
            return self.__returnNull__()

    #chemical only looks at voc from herbicide and pesticide
        elif( self.act == 'Chemical' and self.pol != 'VOC'):
            return self.__returnNull__()

    #zero cases for CS and WS
        elif( ( self.feed == 'CS' or self.feed == 'WS')
            and
            (self.act == 'Non-Harvest' or
            self.act == 'Chemical')):
            return self.__returnNull__()

    #--- end of pre-defined cases for which there are zero emissions

        elif( ( ( self.pol == 'CO' or self.pol.startswith('SO') )
                    and
                ( self.act == 'Non-Harvest' or
                self.act == 'Harvest' or
                self.act == 'Transport' )
              )
                or
              ( self.pol == 'VOC'
                    and not
                ( self.feed == 'CG' or self.feed == 'SG' )
              )
            ):

            #query raw table for sox and co. query raw table for voc only when feedstock
            #is not corn grain or switchgrass (_chem emissions occur here)
            return self.__queryRaw__()

        elif( (self.pol.startswith('PM') )
                and
                (self.act == 'Non-Harvest' or
                self.act == 'Harvest' or
                self.act == 'Transport')):

            return self.__queryRaw__()

        elif( (self.pol == 'NH3' or self.pol == 'NOx' ) ):
            return self.__queryRawFert__()

        elif( (self.pol == 'VOC' )
                and
                (self.feed == 'CG' or self.feed == 'SG' )
            ):

            return self.__queryRawChem__()

        else:

            raise Exception('Error in test structure\nInputs were: %s, %s, %s'%(self.feed, self.pol, self.act))

    """
    Handle cases where there are no values to return
    """
    def __returnNull__(self):
        self.queryString = 'No activity at this location'

    """
    Special case for Forest Residue
    """
    def __returnFRHarv__(self):
        self.queryString = 'FR Harvest'

    """
    Assemble queries that need only the '*_raw' tables.
    """
    def __queryRaw__(self):

        if self.pol.startswith('PM'):
            sumPollutant = "(sum(%s) + sum(fug_%s))" % (self.pol, self.pol)

        else:
            sumPollutant = "sum(%s)" % (self.pol)

        if self.act == 'Harvest':
            act = ' ' + self.act
        else:
            act = self.act

        self.queryString = """
with
    activitySum as (select distinct fips, %s as x
		from %s.%s where description ilike '%% %s' group by fips),

    totalSum as (select distinct fips, %s as x
		from %s.%s group by fips)

select (a.x/t.x) as x from activitySum a, totalSum t
where a.fips = t.fips and t.x > 0.0 and a.x > 0.0;

""" % (sumPollutant,
       self.schema, self.rawTable, '%'+act+'%',
       sumPollutant,
       self.schema, self.rawTable)

#        if self.feed == 'CG' and (self.pol == 'CO' or self.pol == 'SO2'):
#            print self.queryString

    '''
    Assemble queries that need the '*_raw' and '*_fert' tables.

    This part seems very odd.
    If you are not actually intersested in fertilizers, but are doing a calculation
    to get Nox and nh3, shouldnt you not care about fert.x for the ration in the first part?
    '''
    def __queryRawFert__(self):
        if self.act != 'Fertilizer':
            ratio = "(act.x)/(raw.x + fert.x)"
            conditions = ", activitySum act where act.fips = raw.fips and act.fips = fert.fips and act.x > 0.0"

        else:
            ratio = "(fert.x)/(raw.x+fert.x)"
            conditions = "where raw.fips = fert.fips"

        self.queryString = """
            WITH

                activitySum as (select distinct fips, sum(%s) as x
                from %s.%s where description ilike '%s' group by fips),

                rawSum as (select distinct r.fips, sum(r.%s) as x
                from %s.%s r group by r.fips),

                fertSum as (select distinct fips, sum(%s) as x
                from %s.%s group by fips)

                select (%s) as x
                FROM rawSum raw, fertSum fert %s
                and raw.x > 0.0 and fert.x > 0.0;

            """ % (self.pol, self.schema, self.rawTable, '%'+self.act+'%',
                   self.pol, self.schema, self.rawTable,
                   self.pol, self.schema, self.fertTable,
                   ratio,
                   conditions)

    """
    Assemble queries that need the '*_raw' and '*_chem' tables.

    Almost identical code to queryRawFert(), kept separate for the sake of
    being explicit
    """
    def __queryRawChem__(self):

        if self.act != 'Chemical':
            ratio = "(act.x)/(raw.x + chem.x)"
            conditions = ", activitySum act where act.fips = raw.fips and act.fips = chem.fips and act.x > 0.0"

        else:
            ratio = "(chem.x)/(raw.x+chem.x)"
            conditions = "where raw.fips = chem.fips"

        self.queryString = """
WITH

    activitySum as (select distinct fips, sum(%s) as x
		from %s.%s where description ilike '%% %s' group by fips),

    rawSum as (select distinct r.fips, sum(r.%s) as x
		from %s.%s r group by r.fips),

    chemSum as (select distinct fips, sum(%s) as x
		from %s.%s group by fips)

select (%s) as x
		from rawSum raw, chemSum chem %s and raw.x > 0.0 and chem.x > 0.0;

""" % (self.pol, self.schema, self.rawTable, '%'+self.act+'%',
       self.pol, self.schema, self.rawTable,
       self.pol, self.schema, self.chemTable,
       ratio,
       conditions)


# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase

from loan_app.factories import (
    ApplicationTypeFactory, FieldTypeFactory, FieldFactory
)
from loan_app.models import Field
from loan_app.tests.rest_api.base import (
    CreateUserTestCaseMixin, AssertAreFieldsEqualTestCaseMixin
)

class FieldApiTestCase(
    CreateUserTestCaseMixin,
    AssertAreFieldsEqualTestCaseMixin,
    APITestCase
):
    def test_create_field(self):
        application_type = ApplicationTypeFactory()
        field_type = FieldTypeFactory()
        test_data = {
            'key': 'surname',
            'name': u'фамилия',
            'field_type': field_type.key,
            'required': True,
        }
        self.client.force_authenticate(user=self.get_django_superuser())
        response = self.client.post(
            reverse(
                viewname='loan_app:field-list',
                kwargs={
                    u'application_type_key': application_type.key,
                },
            ),
            test_data,
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        field_object = Field.objects.get(
            key=test_data['key'],
            application_type__key=application_type.key,
        )
        self.assert_are_fields_equal(test_data, field_object)

    def test_update_field(self):
        field = FieldFactory(required=False)
        application_type = field.application_type
        url = reverse(
            viewname='loan_app:field-detail',
            kwargs={
                u'application_type_key': application_type.key,
                u'pk': field.key,
            },
        )
        field_type = field.field_type
        test_data = {
            'key': u'new-{field_key}'.format(field_key=field.key),
            'name': u'new-{field_name}'.format(field_name=field.name),
            'field_type': field_type.key,
            'required': True,
        }
        self.client.force_authenticate(user=self.get_django_superuser())
        response = self.client.put(url, test_data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        field_object = Field.objects.get(
            key=test_data['key'],
            application_type__key=application_type.key,
        )
        self.assert_are_fields_equal(test_data, field_object)


class Node:
    # in Class we need value and pointer
    def __init__(self, value=None, next_node=None):
        self.value = value
        self.next_node = next_node

    def get_value(self):
        return self.value

    def get_next(self):
        return self.next_node

    def set_next(self, new_next):
        self.next_node = new_next

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.length = 0

    def add_to_tail(self, value):
        new_node = Node(value, None)

        if self.head == None:
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next_node = new_node
            self.tail = new_node

    def add_to_head(self, value):
        new_node = Node(value, None)

        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            new_node.next_node = self.head
            self.head = new_node

    def contains(self, value):
        if not self.head:
            return False

        current = self.head

        while current:
            if current.value == value:
                return True
            else:
                current = current.next_node
        return False

    def dequeue(self):
      if not self.head:
        return None
      else:
        self.head = self.head.next_node

    def len(self):
        count = 0
        current = self.head

        while current:
            count += 1
            current = current.next_node
        return count

# Setting up a LinkedList for testing
ll = LinkedList()
ll.add_to_tail(1)
ll.add_to_tail(2)
ll.add_to_tail(4)
ll.add_to_tail(5)
ll.add_to_tail(6)

print(ll.len())     # should return 5
print(ll.head.value)    # should return 1
print(ll.head.next_node.next_node.value)    # should return 4
ll.dequeue()    # will remove 1 from head
ll.dequeue()    # will remove 2 from new head
print(ll.head.value)    # As new head, should return 4
print(ll.len())     # should return 3


from flask import current_app

def remove_index(index_name='bill'):
    current_app.elasticsearch.indices.delete(index=index_name, ignore=[400, 404])

def create_index(index_name='bill'):
    created = False
    # index settings
    settings = {
      "mappings": {
        "properties": {
          "last_action_date": {
            "type": "date",
            "ignore_malformed": True
          }
        }
      }
    }
    try:
        if not current_app.elasticsearch.indices.exists(index_name):
            # Ignore 400 means to ignore "Index Already Exist" error.
            current_app.elasticsearch.indices.create(index=index_name, ignore=400, body=settings)
            print('Created Index')
        created = True
    except Exception as ex:
        print(str(ex))
    finally:
        return created

def add_to_index(index, model):
    if not current_app.elasticsearch:
        print("not current_app.elasticsearch")
        return
    payload = {}
    for field in model.__searchable__:
        payload[field] = getattr(model, field)
    current_app.elasticsearch.index(index=index, id=model.id,
                                    body=payload)

def remove_from_index(index, model):
    if not current_app.elasticsearch:
        return
    current_app.elasticsearch.delete(index=index, doc_type=index, id=model.id)

def make_query(index, query_params, page, per_page, time_limit="1y", returned_val="id"):
    # returned_val - str "id" (id from DB and elasticsearch) or "leginfo_id"
    if not current_app.elasticsearch:
        return [], 0

    search_field = ['title', 'subject', 'text']

    search_conditions = [{'fuzzy': {field: {"value": query_param, "fuzziness": "0"}}} for field in search_field
                         for query_param in query_params]
    time_lim_q = "now-" + str(time_limit)
    search = current_app.elasticsearch.search(
        index = index,
        body ={'query': {
                'bool': {
                    "minimum_should_match": "1",
                    'should': [search_conditions],
                    "filter" : [
                      { "range" : { "date_published" : { "gte" : time_lim_q}}}
                    ]
                },
              },
              'from': (page - 1) * per_page,
              'size': per_page,
              'sort': [{
                 'last_action_date': {
                    'order': 'desc'
                     }
                 }]
               })
    vals = []
    if returned_val == "id":
        vals = [int(hit['_id']) for hit in search['hits']['hits']]
    elif returned_val == "leginfo_id":
        vals = [hit['_source']["leginfo_id"] for hit in search['hits']['hits']]
    return vals, search['hits']['total']['value']

"""
from init_app import app

with app.app_context():
    print(make_query("bill", ["chinese"], 1, 10, time_limit="1y"))
"""


import re
import csv
from openpyxl import load_workbook

def readxlsx (filepath):
    tempoMap = {}
    wb=load_workbook(filepath)
    sheet=wb.active
    max_row=sheet.max_row
    #max_column=sheet.max_column
    for i in range(2,max_row+1):
        key = None
        for j in range(4,6):
            cell_obj=sheet.cell(row=i,column=j)
            if (j==4):
                key = cell_obj.value
            if (j==5):
                tempoMap[key] = cell_obj.value
    return tempoMap

# Handle cf[11001] = 12
def updateStringPatternOne (content,tempoMap):
    for k,v in content.items():
        matches = re.findall(r'cf\[11001\] *= *[0-9]+', v)
        for match in matches:
            num = match.split('=')[-1]
            v = re.sub(r'cf\[11001\] *= *[0-9]+', 'Team = \'' + str(tempoMap[int(num)]) +'\'', v, 1)
            content[k]=v

# Handle cf[11001] != 12
def updateStringPatternTwo (content,tempoMap):
    for k,v in content.items():
        matches = re.findall(r'cf\[11001\] *!= *[0-9]+', v)
        for match in matches:
            num = match.split('=')[-1]
            v = re.sub(r'cf\[11001\] *!= *[0-9]+', 'Team != \'' + str(tempoMap[int(num)]) +'\'', v, 1)
            content[k]=v

# Handle cf[11001] in (12,13)
def updateStringPatternThree (content,tempoMap):
    for k,v in content.items():
        matches = re.findall(r'cf\[11001\] *in *\([0-9, ]*\)',v)
        for match in matches:
            teamString = transformString(match.split('in')[-1],tempoMap)
            v = re.sub(r'cf\[11001\] *in *\([0-9, ]*\)', 'Team in ' + teamString, v, 1)
            content[k]=v

# Handle cf[11001] not in (12,13)
def updateStringPatternFour (content,tempoMap):
    for k,v in content.items():
        matches = re.findall(r'cf\[11001\] *not *in *\([0-9, ]*\)',v)
        for match in matches:
            teamString = transformString(match.split('in')[-1],tempoMap)
            v = re.sub(r'cf\[11001\] *not *in *\([0-9, ]*\)', 'Team not in ' + teamString, v, 1)
            content[k]=v

# Helper method
def transformString(numberString,tempoMap):
    stringList = numberString.replace(' ','').replace('(','').replace(')','').split(',')
    newList=[]
    for number in stringList:
        newList.append(str(tempoMap[int(number)]))
    retString = '(\'' + '\',\''.join(newList) + '\')'
    return str(retString)

# Handle cf[11001] = "12"
def updateStringPatternFive(content,tempoMap):
    for k,v in content.items():
        matches = re.findall(r'cf\[11001\] *= *"[0-9]+"', v)
        for match in matches:
            num = match.replace('\"','').split('=')[-1]
            v = re.sub(r'cf\[11001\] *= *"[0-9]+"', 'Team = \'' + str(tempoMap[int(num)]) +'\'', v, 1)
            content[k]=v

# Handle cf[11001] != "12"
def updateStringPatternSix(content,tempoMap):
    for k,v in content.items():
        matches = re.findall(r'cf\[11001\] *!= *"[0-9]+"', v)
        for match in matches:
            num = match.replace('\"','').split('=')[-1]
            v = re.sub(r'cf\[11001\] *!= *"[0-9]+"', 'Team != \'' + str(tempoMap[int(num)]) +'\'', v, 1)
            content[k]=v

# Replace remaining cf[11001] with Team
def replaceCf(content):
    for k,v in content.items():
        v = re.sub(r'cf\[11001\]', 'Team', v)
        content[k]=v

# Write Map to a csv file
def writeCsv(content):
    w = csv.writer(open('filter.csv','w'))
    w.writerow(['id','reqcontent'])
    for k,v in content.items():
        w.writerow([k,v])


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import image_cropping.fields

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0003_account_points'),
    ]

    operations = [
        migrations.AddField(
            model_name='account',
            name=b'cropping',
            field=image_cropping.fields.ImageRatioField(b'profile_pic', '250x250', hide_image_field=False, size_warning=False, allow_fullsize=False, free_crop=False, adapt_rotation=False, help_text=None, verbose_name='cropping'),
            preserve_default=True,
        ),
    ]


"""
take any element and insert at correct position

space efficiency

O(nsquare), O(1)
easy
for continuous inflow of numbers
"""

def insertionsort(list):
    for i in range(1, len(list)):
        key = list[i]
        j = i-1
        while j>=0 and key<list[j]:
            list[j+1] = list[j]
            j -= 1
        list[j+1] = key
    return list

print(insertionsort([3,4,1,2,5,6,7]))


import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import smtplib
import webbrowser as wb
import os
import pyautogui
import psutil
import pyjokes
from covid import Covid
from quotes import Quotes
import pywhatkit as kit

en=pyttsx3.init()

#en.say("hello this is Jarvis")
voices = en.getProperty('voices')
en.setProperty('voice' ,voices[1].id)
def speak(audio):
    en.say(audio)

    en.runAndWait()

speak("hey boss this is friday and I am ai assistant")

def time():
    Time=datetime.datetime.now().strftime("%I:%M:%S")
    speak("time in  24 hrs format and is")
    speak(Time)

#time()
def quotes():

    quotes = Quotes()
    persons = quotes.random()
    l=str(persons[1])
    print(l,"\n")
    speak(l)

def date():
    year= int(datetime.datetime.now().year)
    month= int(datetime.datetime.now().month)
    date= int(datetime.datetime.now().day)
    speak("date is")
    speak(date)
    speak("month is")
    speak(month)
    speak("year is")
    speak(year)
#date()

def wishme():
    speak("welcome back boss!")
    #speak("current time in  24 hrs format and it is")
    ##time()
    #speak("current date is")
    ##date()
    hour=datetime.datetime.now().hour
    if hour>=6 and hour<12:
        speak("good morning")
    elif hour>=12 and hour<15:
        speak("good afternoon")
    elif hour>=15 and hour<20:
        speak("good evening")
    elif hour>=20 and hour<24:
        speak("good night")
    else:
        speak("good night")
    speak("friday at your service tell meh how can i help you")

#wishme()

def takecommand():
    r=sr.Recognizer()
    with sr.Microphone() as source:
        print("listening....")
        r.pause_threshold=1
        audio=r.listen(source)

    try:
        print("recognizing..")
        query=r.recognize_google(audio,language='en-in')
        print(query)

    except Exception as e:
        print(e)
        speak("say that again boss....")
        return "none"
    return query

def sendemail(to,content):
    server=smtplib.SMTP("smtp.gmail.com",587)
    server.eclo()
    server.starttls()
    server.login('sadiqshaik1211@gmail.com','Sadiqshaik@1234')
    server.sendmail('sadiqshaik1211@gmail.com',to,content)
    server.close()

def screenshot():
    img = pyautogui.screenshot()
    img.save("C:\\Users\\sadiq shaik\\Desktop\\car\\ss.png")

def cpu():
    usage = str(psutil.cpu_percent())
    speak("cpu is at"+usage)
    battery = psutil.sensors_battery()
    speak("the battery is at")
    speak(battery.percent )

def jokes():
    speak(pyjokes.get_joke())

def covid():
    speak("which country boss ")
    case= takecommand().lower()
    #covid=Covid(source="worldometers")
    covid=Covid()
    cases=covid.get_status_by_country_name(str(case))
    for x in cases:
        print(x,":",cases[x])

def whatsapp():
    speak("what you want to send boss")
    msg=takecommand().lower()
    speak("tell the hour time")
    hour=takecommand()
    speak("tellthe minutes")
    min=takecommand()
    kit.sendwhatmsg("+919629595614",str(msg),int(hour),int(min))

def name():
    speak("my name is friday")
def boss():
    speak("sadiq shaik")
if __name__=="__main__":
    wishme()
    while True:
        query=takecommand().lower()

        if 'time'in query:
            time()
        elif 'boss' in query:
            boss()
        elif 'date' in query:
            date()
        elif 'name' in query:
            name()
        elif 'quotes' in query:
            quotes()
        elif 'wikipedia' in query:
            speak("boss I am searching.....")
            query = query.replace("wikipedia","")
            result=wikipedia.summary(query,sentences=2)
            print("friday:",result)
            speak(result)

        elif 'send mail' in query:
            try:
                speak("what should i write ")
                content =takecommand()
                to='sadiqshaik1211@gmail.com'
                sendemail(to,content)
                speak("email is sent successfully" )
            except Exception as e:
                print(e)
                speak("I cant able to send due to bad network connection")

        elif 'search' in query:
            speak("what you want to search")
            chromepath="C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
            search= takecommand().lower()
            wb.get(chromepath).open_new_tab(search+'.com')

        elif 'log out' in query:
            os.system("shutdown -l")

        elif 'restart' in query:
            os.system("shutdown /r /t 1")

        elif 'shutdown' in query:
            os.system("shutdown /s /t 1")

        elif 'note this one' in query:
            speak("what to remember boss")
            data = takecommand()
            speak("you said me to remember that"+data)
            remember=open('data.txt','w')
            remember.write(data)
            remember.close()

        elif 'do you remember anything' in query:
            remember=open('data.txt','r')
            speak("you said to remember that "+remember.read())

        elif 'play songs'in query:
            song_dir='C:\\Users\sadiq shaik\Desktop\Musicfiles'
            songs=os.listdir(song_dir)
            os.startfile(os.path.join(song_dir,songs[1]))

        elif 'screenshot' in query:
            screenshot()
            speak("yeah screenshot is done and yeah it is great content")

        elif 'battery' in query:
            cpu()
            speak("percent")
        elif 'covid news' in query:
            covid()

        elif 'joke' in query:
            jokes()
            speak("it is really good right hahahaha")

        elif " send whatsapp message":
            whatsapp()
            speak("your msg is sending")

        elif "offline" in query:
            speak("yep   done!")
            quit()


# a5_uno.py
# Chris VanKerkhove cjv47; Omar Rasheed oyr2
# None
# 5/9/2018
# skeleton by:
#     Anthony Poon (ATP65)
#     Victoria Litvinova (VL242) - simple edits
#     Lillian Lee (LJL2) - simple edits
# April 27, 2018

"""
This module contains an implementation of an Uno-like game using standard
52-card playing cards.
"""
import random
import a5_player
import a5_unocard
from a5_card import Card
from a5_unocard import UnoCard
from a5_unocard import WildUnoCard
from a5_unogamestate import UnoGameState

class Uno():
    """
    Uno is a game where players take turns attempting to get rid of the cards in
    their hand by adding them to a shared pile.  The first player with no cards in
    his/her hand wins.  This is a version of Uno with a few simplified rules and
    using a standard 52-card deck rather than a specialized deck.

    This class maintains the game state, defines and enforces rules for player
    actions, and evaluates and declares a winner.  More detailed rules will be
    listed in the method specifications of the appropriate method.

    Instance Attributes:
        players [list of Players]: A list of players in this game, in play order.
        deck [list of UnoCards, may be empty]: A list of remaining cards to draw
                from.
        pile [list of UnoCards, may be empty]: A list of cards in the shared pile in
                the order added.
        gameState [UnoGameState]: Stores the state of the game between player turns.
    """

    STARTING_HAND_SIZE = 5 # How many cards to give each player at the beginning of the game.
    NUM_ATTEMPTS_BEFORE_DRAW = 5 # How many attempts we give a player before forcing them to draw a card.

    def __init__(self, p):
        """
        Creates a new game of Uno and sets it up.  In doing this, we create a new,
        shuffled deck, deal out the players, and set up a default play order.

        One way that this implementation of Uno differs from the normal game is that
        we're using the suits and ranks of standard playing cards.  Because a
        standard playing card deck has only 52 cards (without Jokers) and a standard
        Uno deck has 108 cards, we will instead use three copies of a standard card
        deck to make sure we have enough cards.

        Preconditions:
            p [list of Players]: A list of players for this game, in play order, where
                the first player is at index 0.  This list must be non-empty and contain
                only Player instances and have at least 2 players.
        """
        # Create a deck combining three decks of standard cards and shuffle it.
        self.deck = a5_unocard.full_deck() + a5_unocard.full_deck() + a5_unocard.full_deck()
        random.shuffle(self.deck)
        self.pile = [] # The pile starts empty.

        # Set the players and draw out a starting hand for each player.
        self.players = p
        for player in self.players:
            player.setStartingHand(self._drawHand())

        # This object models the game state between player turns.  Create one in
        # default state.
        self.gameState = UnoGameState()

    def _drawHand(self):
        """
        A helper method that creates and returns a list of cards drawn from the
        deck.  Cards should be drawn from the front of the deck (at index 0) and
        removed from the deck.  The returned hand is a list of the cards removed
        from the deck.  The size of the hand should not be larger than
        self.STARTING_HAND_SIZE or however many cards are remaining in the deck,
        whichever is smaller.

        Requirement: This should be implemented using a while loop.  You are not
            required to include loop invariant comments.

        Returns:
            A list of cards drawn from the deck.
        """
        playerhand = []
        if self.STARTING_HAND_SIZE < len(self.deck):
            while len(playerhand) < self.STARTING_HAND_SIZE:
                playerhand.append(self.deck.pop(0))
        else:
            l = len(self.deck)
            while len(playerhand) < l:
                playerhand.append(self.deck.pop(0))
        return playerhand

    def play(self):
        """
        Start and execute the game of Uno.  This method does not end until a winner
        is declared and the game is over.  This method controls the flow of the game,
        following and updating the between-player state that is stored in
        self.gameState.

        The general flow of the game should look like this:
            1. Determine who the next player is from the self.gameState.nextPlayer
                attribute and the list of players.
            2. If the previous player played a card that caused this player to draw
                extra cards (as seen in the self.gameState.numExtraCardDraw attribute),
                as long as there are that many cards remaining in the deck, draw and
                remove them from the front of the deck and add them to the next player's
                hand.
            3. Allow the next player to perform their turn.
            4. Update the game state for the next player.

        Requirement: This should be implemented using a while loop.  You are not
            required to include loop invariant comments.
        Hint: When finding the next Player instance in the list of players, the
            gameState.nextPlayer pointer can exceed the length of the list of players.
            You need to calculate the remainder of places by which the pointer exceeds
            the length of the list to find the appropriate player.
        Hint: Make use of the helper functions below.

        Preconditions:
            Game has not yet been played.
        """

        while self._isGameOver() == False and self.deck != []:
            if self.gameState.numExtraCardDraw > 0:
                for each in range(self.gameState.numExtraCardDraw):
                    currentPlayer = self.gameState.nextPlayer % len(self.players)
                    self.players[currentPlayer].addCardToHand(self.deck.pop(0))
                self.gameState.numExtraCardDraw = 0
            self._performPlayerTurn(self.players[self.gameState.nextPlayer % 3])
            self.gameState.updateNextPlayer()

    def _printStartMessage(self):
        """
        A helper method that just prints out the start message at the beginning
        of the game.
        """
        print("Welcome to CS 1110 Uno using regular playing cards.")
        print()
        print("Rules:")
        print("\t* Take turns removing cards from your hand and adding them to the " +
                "pile.")
        print("\t* Added cards must match either the suit or the rank of the top " +
                "card of the pile.")
        print("\t* Tens reverse the play order.")
        print("\t* Jacks skip the next player.")
        print("\t* Queens force the next player to draw two cards (if available in " +
                "the deck).")
        print("\t* Kings are wild cards.")
        print("\t* Aces are wild cards that also force the next player to draw four" +
                " cards.")
        print("\t* Cards that force players to draw cards do not chain and do not " +
                "cause turn to be skipped.")
        print("\t* First player with no cards in hand wins the game!")
        print()
        print("Starting game with " + str(len(self.players)) + " players: " +
                str([p.name for p in self.players]))

    def _isGameOver(self):
        """
        A helper method that checks to see if the game is over.  The game is over
        when there is a player with zero cards in their hand.  Returns True if the
        game is over, False otherwise.
        """
        for player in self.players:
            # This is the first player with a zero-length hand; declare them the winner.
            if len(player.hand) == 0:
                print()
                print("The game is over!  " + player.name + " won!")
                for player in self.players:
                    print(player.name + " had ending hand: " + str(list(map(str, player.hand))))
                return True

        # Otherwise, we've gone through the entire list of players and no one has
        # won yet.
        return False

    def _performPlayerTurn(self, player):
        """
        A helper method that attempts to execute the turn for a particular player.
        The player has up to self.NUM_ATTEMPTS_BEFORE_DRAW to pick a card that can
        actually be placed on top of the pile.  The player can also choose to return
        None to draw a card immediately.  If a good card is chosen, then the card is
        removed from the hand, placed on the pile, and any action associated is
        performed.  if not, then the player draws a new card and their turn ends.

        Preconditions:
            player [Player]: A non-None player object, whose turn is the current turn.
        """
        # Determine what is the top card on the pile; either None if the pile is
        # empty or the last thing in the list.
        if len(self.pile) == 0:
            topCardInPile = None
        else:
            topCardInPile = self.pile[len(self.pile) - 1]

        # We'll perform this loop up to a maximum of NUM_ATTEMPTS_BEFORE_DRAW times
        for i in range(self.NUM_ATTEMPTS_BEFORE_DRAW):

            # Ask the player to give us a card to try to play.
            card = player.suggestACard(topCardInPile, self.NUM_ATTEMPTS_BEFORE_DRAW - i - 1)

            # If the card is None, no need to try further.
            if card == None:
                break

            # If the card is playable on top of the pile, do so and return without
            # drawing a card.
            if card.isPlaceableOnTop(topCardInPile):

                # Move the card to the pile.
                player.removeCardFromHand(card)
                self.pile.append(card)

                # Perform any action that the card has on the game state.
                card.performAction(self.gameState)

                # Return so that the player does not draw a card.
                return

            # If the card was not playable, we notify the player, and try again.
            else:
                player.notifyNotAcceptableCard(card)

        # We got here because either the player ran out of attempts or chose to draw
        # explicitly. Draw a card, so long as the deck has more cards.
        if len(self.deck) > 0:
            player.addCardToHand(self.deck.pop(0))

"""
This sets up and starts a game of Uno.
"""
if __name__ == '__main__':
    p = []
    p.append(a5_player.HumanConsolePlayer())
    p.append(a5_player.RandomAiPlayer("HAL 9000"))
    p.append(a5_player.RandomAiPlayer("WOPR"))
    p.append(a5_player.RandomAiPlayer("Skynet"))
    p.append(a5_player.RankThenSuitAiPlayer("lil pump"))

    # TODO: Students, after you implement the RankThenSuitAiPlayer, add a 5th
    # player to the game using your new RankThenSuitAiPlayer implementation.  This
    # should result in one human player, three random AI players and one "smarter"
    # rank-then-suit AI player.

    u = Uno(p)
    u.play()


"""Asynchronous Advantage Actor-Critic (A3C) algorithm (A3C) using Pytorch
and multiprocessing. The most simple implementation for continuous action.

Adapted from Morvan Zhou's implementation at
https://github.com/MorvanZhou/pytorch-A3C/
by Zhengdong Wang for PySC2.

"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys
import numpy as np

import gym
import cheese_gym  # pylint: disable=unused-import

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as mp

from .utils import v_wrap
from .utils import set_init
from .utils import push_and_pull
from .utils import record

# Required for PySC2.
from absl import flags  # pylint: disable=wrong-import-order
FLAGS = flags.FLAGS
FLAGS(sys.argv)

os.environ['OMP_NUM_THREADS'] = '1'

class Net(nn.Module):
  """Simple network."""

  def __init__(self, s_dim, a_dim):
    super(Net, self).__init__()
    self.s_dim = s_dim
    self.a_dim = a_dim
    self.pi1 = nn.Linear(s_dim, 200)
    self.pi2 = nn.Linear(200, a_dim)
    self.v1 = nn.Linear(s_dim, 100)
    self.v2 = nn.Linear(100, 1)
    set_init([self.pi1, self.pi2, self.v1, self.v2])
    self.distribution = torch.distributions.Categorical

  def forward(self, x):  # pylint: disable=arguments-differ
    """Forward pass."""
    pi1 = F.relu6(self.pi1(x))
    logits = self.pi2(pi1)
    v1 = F.relu6(self.v1(x))
    values = self.v2(v1)
    return logits, values

  def choose_action(self, s):
    """Given a state, return the network action recommendation."""
    self.eval()
    logits, _ = self.forward(s)
    prob = F.softmax(logits, dim=1).data
    m = self.distribution(prob)
    return m.sample().numpy()[0]

  def loss_func(self, s, a, v_t):
    """Calculate loss."""
    self.train()
    logits, values = self.forward(s)
    td = v_t - values
    c_loss = td.pow(2)
    probs = F.softmax(logits, dim=1)
    m = self.distribution(probs)
    exp_v = m.log_prob(a) * td.detach().squeeze()
    a_loss = -exp_v
    total_loss = (c_loss + a_loss).mean()
    return total_loss

class Worker(mp.Process):
  """A3C worker to play games."""

  def __init__(self, gnet, opt, global_ep, global_ep_r, res_queue, name, N_S,
               N_A, UPDATE_GLOBAL_ITER, GAMMA, MAX_EP):
    super(Worker, self).__init__()
    self.name = 'worker_%i' % name
    self.g_ep = global_ep
    self.g_ep_r = global_ep_r
    self.res_queue = res_queue
    self.gnet = gnet
    self.opt = opt
    # Local network.
    self.lnet = Net(N_S, N_A)
    self.env = gym.make('SC2Game-v0').unwrapped
    self.UPDATE_GLOBAL_ITER = UPDATE_GLOBAL_ITER
    self.GAMMA = GAMMA
    self.MAX_EP = MAX_EP

  def run(self):
    total_step = 1
    while self.g_ep.value < self.MAX_EP:
      s = self.env.reset()
      buffer_s, buffer_a, buffer_r = [], [], []
      ep_r = 0.
      while True:
        # Choose the next smart agent action.
        a = self.lnet.choose_action(v_wrap(s[None, :]))

        # Create an iterable of actions to take.
        # The first is the smart action for the learning agent.
        # The second is a random action for the random agent.
        actions = [a, np.random.randint(self.lnet.a_dim)]

        # Record states and rewards.
        s_, r, done, _ = self.env.step(actions)
        ep_r += r
        buffer_a.append(a)
        buffer_s.append(s)
        buffer_r.append(r)

        # Update global and assign to local net.
        if total_step % self.UPDATE_GLOBAL_ITER == 0 or done:
          # Sync.
          push_and_pull(self.opt, self.lnet, self.gnet, done, s_, buffer_s,
                        buffer_a, buffer_r, self.GAMMA)
          buffer_s, buffer_a, buffer_r = [], [], []

          # Output information and save replay if episode completed.
          if done:
            self.env.save_replay('SmartCheeseAgent')
            record(self.g_ep, self.g_ep_r, ep_r, self.res_queue, self.name)
            break

        s = s_
        total_step += 1

    self.res_queue.put(None)


#!/usr/bin/python3
# -*- coding:utf-8 -*-

"""
1er fichier qui reprend
les valeurs du fichiers txt
pour les écrire dans patient_rdv.json
et lancer p1check_value.py
"""

from pickle import load
import os
import json
import subprocess

file=open('./patient_agenda/events16/patient_calendar.txt','rb')
data=load(file)
file.close()

for (key, value) in data.items():
    print("Key: " + key)
    print("Valeur: " + str(value))

print("\nLOOP Finished !\n")

data_list1 = []
for value in data.items():
    data_list1.append(value)

try:
    if os.path.getsize('./patient_agenda/events16/doc_events/patient_rdv.json'):
        print("+ File 'patient_rdv.json' exist !")
        with open('./patient_agenda/events16/doc_events/patient_rdv.json', 'w') as datafile:
            json.dump(data_list1, datafile, indent=4)
except FileNotFoundError as msg:
    print("File doesn't exist, but it has been created !")
    with open('./patient_agenda/events16/doc_events/patient_rdv.json', 'w') as datafile:
        json.dump(data_list1, datafile, indent=4)

for (key, value) in data.items():
    print(key, value)
    print("\n")

subprocess.call('./patient_agenda/events16/doc_events/conver_value.py')


#!/usr/bin/env python3
import argparse
import os

extensions = ['.c', '.cpp', '.cxx', '.cc', '.C', '.CPP', '.c++', '.cp']

def check_cxx(file):
    for extension in extensions:
        if file.endswith(extension):
            return True
    return False

def go(cur, fr):
    for dr in os.listdir(cur):
        abs_path = os.path.join(cur, dr)
        if os.path.isdir(abs_path):
            go(abs_path, fr)
        elif check_cxx(dr):
            fr.write(abs_path + "\n")

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--dir', required=True, help="name of dir")
    args = parser.parse_args()
    rp = os.path.abspath(args.dir)
    print(rp)
    with open("files_for_ESCA.txt", "w") as fr:
        go(rp, fr)

if __name__ == '__main__':
    main()


from rest_framework import serializers
from django.contrib.auth import get_user_model

from .models import Post, Comment, Tag, Follow
from tweetapp import services as likes_services

User = get_user_model()

class FollowSerializer(serializers.ModelSerializer):
    class Meta:
        model = Follow
        fields = ('user',)

    def create(self, validate_data):
        user_follow = validate_data.get('user')
        user_following = self.context['request'].user

        if Follow.objects.filter(user=user_follow, follower=user_following).exists():
            message = f'You are unfollowing {user_follow}'
            obj = Follow.objects.filter(id=Follow.objects.get(user=user_follow, follower=user_following).id)
            obj.delete()
            raise serializers.ValidationError(message)
        elif user_following.id == user_follow.id:
            message = 'You can not follow yourself'
            raise serializers.ValidationError(message)
        else:
            follow = Follow.objects.create(
                user=user_follow,
                follower=user_following
            )
            message = f'You are following {user_follow}'
            raise serializers.ValidationError(message)
            return follow

        # if Follow.objects.create(user=user_follow, follower=user_following):

        #     raise serializers.ValidationError(message)
        # elif user_following.id == user_follow.id:
        #     message = 'You can not follow yourself'
        #     raise serializers.ValidationError(message)
        # else:
        #     follow = Follow.objects.create(
        #         user=user_follow,
        #         follower=user_following
        #     )
        #     return follow

class FanSerializer(serializers.ModelSerializer):
    full_name = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            'username',
            'full_name',
        )

    def get_full_name(self, obj):
        return obj.get_full_name()

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = ('text', 'post_id', 'created_at', 'id', 'author')

    def create(self, validated_data):
        request = self.context.get('request')
        validated_data['author_id'] = request.user.id
        comment = Comment.objects.create(**validated_data)
        return comment

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['author'] = instance.author.email
        representation['text'] = instance.text
        return representation

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ('title', 'slug')

class PostSerializer(serializers.ModelSerializer):
    created_at = serializers.DateTimeField(format='%d-%m-%Y %H:%M:%S', read_only=True)
    tags = serializers.SlugRelatedField(many=True, queryset=Tag.objects.all(), slug_field='slug')
    is_fan = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('text', 'image', 'created_at', 'id', 'tags', 'total_likes', 'is_fan')

    def get_is_fan(self, obj) -> bool:

        user = self.context.get('request').user
        return likes_services.is_fan(obj, user)

    def __get_image_url(self, instance):
        request = self.context.get('request')
        if instance.image:
            url = instance.image.url
            if request is not None:
                url = request.build_absolute_uri(url)
        else:
            url = ''
        return url

    def create(self, validated_data):
        request = self.context.get('request')
        validated_data['author_id'] = request.user.id
        tags = validated_data.pop('tags')
        post = Post.objects.create(**validated_data)
        for tag in tags:
            post.tags.add(tag)
        return post

    def to_representation(self, instance):
        if 'comments' not in self.fields:
            self.fields['comments'] = CommentSerializer(instance, many=True)
        representation = super().to_representation(instance)
        representation['text'] = instance.text
        representation['author'] = instance.author.email
        representation['image'] = self.__get_image_url(instance)
        representation['likes'] = instance.likes.all().count()
        return representation


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

import os
import sys
from itertools import product
import numpy as np
from PyQt4 import Qt, QtCore, QtGui
from pro_con_26_util.entity import *
from imageutil import *

class RockWidget(QtGui.QWidget):

    def __init__(self, parent=None, rock_array=np.zeros((8, 8)).astype(int), answer=make_answer()):
        # basic information
        self._rock_texture_name = os.path.join(os.path.split(__file__)[0], 'data', 'rockwall.png')
        self._texture_size = 32

        super(RockWidget, self).__init__(parent)

        self._rock_array = rock_array
        self._rock_texture = None
        self._rock_alpha = None
        self._rock_image = None
        self._answer = answer

        self.setRock(rock_array)
        self.setAnswer(answer)

        # set widget property
        hintedSize = self.sizeHint()
        self.setMinimumSize(hintedSize.width() / 2, hintedSize.height() / 2)
        self.setMaximumSize(hintedSize.width() * 2, hintedSize.height() * 2)

    def sizeHint(self):
        return QtCore.QSize(self._texture_size*self._rock_array.shape[1], \
                            self._texture_size*self._rock_array.shape[0])

    @QtCore.pyqtSignature('setRock(PyQt_PyObject)')
    def setRock(self, rock_array):
        self._rock_array = rock_array
        self._rock_texture = make_texture(np.zeros(rock_array.shape).astype(int), [self._rock_texture_name], size=self._texture_size)
        self._rock_alpha = make_alpha_channel(rock_array, size=self._texture_size)
        self.update()

    def getRock(self):
        return self._rock_array

    rock = QtCore.pyqtProperty('PyQt_PyObject', getRock, setRock)

    @QtCore.pyqtSignature('setAnswer(PyQt_PyObject)')
    def setAnswer(self, answer):
        self._answer = answer
        self.update()

    def getAnswer(self):
        return self._answer

    answer = QtCore.pyqtProperty('PyQt_PyObject', getAnswer, setAnswer)

    def grabbable(self, point):
        i = int(self._rock_array.shape[1] * point.x() / self.size().width())
        j = int(self._rock_array.shape[0] * point.y() / self.size().height())
        return bool(self._rock_array[j, i])

    def paintEvent(self, event):
        # calculate geometry and scale
        #g = self.geometry()
        g = self.size()
        s1 = min(g.width(), g.height())
        s1 = QtCore.QSize(s1, s1)
        r = QtCore.QPointF(float(s1.width()) / self._rock_texture.width(), \
                           float(s1.height()) / self._rock_texture.height())
        o = QtCore.QPointF()
        o.setX(0 if g.width() < g.height() else g.width() / 2 - s1.width() / 2)
        o.setY(0 if g.height() < g.width() else g.height() / 2 - s1.height() / 2)

        # set size of image
        rock_image = self._rock_image.scaled(s1)

        # drawing images
        painter = QtGui.QPainter()
        painter.begin(self)
        painter.drawImage(o, rock_image)
        painter.end()
        del painter

    def update(self):
        self._rock_image = QtGui.QImage(self._rock_texture)
        alpha = self._rock_alpha if self._answer['head_or_tail'] == 'H' \
            else self._rock_alpha.mirrored(horizontal=True, vertical=False)
        alpha = alpha.transformed(QtGui.QTransform().rotate(self._answer['rotation']))
        self._rock_image.setAlphaChannel(alpha)
        super(RockWidget, self).update()

# -*- end of class RockWidget -*-

if __name__ == '__main__':
    area, rocks = read_problem(os.path.join(os.path.split(__file__)[0], 'data', 'prob0.txt'))
    answers = read_answer(os.path.join(os.path.split(__file__)[0], 'data', 'answer.txt'))

    app = QtGui.QApplication(sys.argv)
    w = RockWidget(None, rocks[3], answers[3])
    w.show()
    sys.exit(app.exec_())


import random
import numpy as np
import json
from tqdm import tqdm
import os

def taint(data, n=None, ratio=None, seed=None):
    # data: json data of a file
    # ratio: ratio of words to be tainted
    # count words in data
    total_words = 0
    for item in data["form"]:
        total_words += len([w for w in item['words'] if w["text"].strip() != ""])
    if not total_words:
        print("No words in data.")
        return

    if ratio:
        n = int(ratio * total_words)
    elif not n and not ratio:
        print("Must pass at least one value for either ratio or n.")
        raise AssertionError

    random.seed(seed)

    tainted_ids = random.sample(range(total_words), min(total_words, n))
    word_count = 0
    for i, item in enumerate(data["form"]):
        for j, word in enumerate(item["words"]):
            if word["text"].strip() == "":
                continue
            if word_count in tainted_ids:
                data["form"][i]['words'][j]['text'] = '<tainted>'
            word_count += 1
    return data

def tear(data, n_split=2):
    word_boxes = []
    for item in data["form"]:
        # left, top, right, bottom
        word_boxes.extend([w["box"] for w in item["words"] if w["text"].strip() != ""])
    if not len(word_boxes):
        print("No words in data.")
        return

    # define split location
    # find the min left & top and max right & bottom
    word_boxes = np.array(word_boxes)
    min_left = min(word_boxes[:, 0])
    min_top = min(word_boxes[:, 1])
    max_right = max(word_boxes[:, 2])
    max_bottom = max(word_boxes[:, 3])
    # candidate split points

    _splits = {}
    for i in range(n_split):
        for j in range(n_split):
            _left = min_left + i * (max_right - min_left) / n_split
            _right = _left + (max_right - min_left) / n_split
            _top = min_top + j * (max_bottom - min_top) / n_split
            _bottom = _top + (max_bottom - min_top) / n_split
            _splits[(_left, _top, _right, _bottom)] = []

    # put words into _splits
    for wb in word_boxes:
        wb_center = [(wb[0] + wb[2]) / 2, (wb[1] + wb[3]) / 2]
        for _sb in _splits:
            # if the center of word box is inside split
            if wb_center[0] >= _sb[0] and wb_center[0] <= _sb[2] and wb_center[1] >= _sb[1] and wb_center[1] <= _sb[3]:
                _splits[_sb].append(wb)
                break
        else:
            raise LookupError

    # adjust _splits margin according to word boxes
    split_boxes = []
    for _, _word_boxes_in_split in _splits.items():
        # may exist empty split
        if not len(_word_boxes_in_split):
            continue
        _word_boxes_in_split = np.array(_word_boxes_in_split)
        left = min(_word_boxes_in_split[:, 0])
        top = min(_word_boxes_in_split[:, 1])
        right = max(_word_boxes_in_split[:, 2])
        bottom = max(_word_boxes_in_split[:, 3])
        split_boxes.append([left, top, right, bottom])

    print(split_boxes)
    for i, item in enumerate(data["form"]):
        for j, word in enumerate(item["words"]):
            if word["text"].strip() == "":
                continue
            wb = word["box"]
            wb_center = ((wb[0] + wb[2]) / 2, (wb[1] + wb[3]) / 2)
            for sb_idx, sb in enumerate(split_boxes):
                if wb_center[0] >= sb[0] and wb_center[0] <= sb[2] and wb_center[1] >= sb[1] and wb_center[1] <= sb[3]:
                    data["form"][i]['words'][j]['box'] = [wb[0] - sb[0], wb[1] - sb[1], wb[2] - sb[0], wb[3] - sb[1]]
                    data["form"][i]['words'][j]['split'] = sb_idx
                    break
            else:
                raise LookupError

    return data

class NumpyEncoder(json.JSONEncoder):
    """ Custom encoder for numpy data types """
    def default(self, obj):
        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):

            return int(obj)

        elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
            return float(obj)

        elif isinstance(obj, (np.complex_, np.complex64, np.complex128)):
            return {'real': obj.real, 'imag': obj.imag}

        elif isinstance(obj, (np.ndarray,)):
            return obj.tolist()

        elif isinstance(obj, (np.bool_)):
            return bool(obj)

        elif isinstance(obj, (np.void)):
            return None

        return json.JSONEncoder.default(self, obj)

def generate_taint_dataset(data_dir, output_dir, ratio, seed=4321):
    all_files = os.listdir(data_dir)
    for file in tqdm(all_files, total=len(all_files)):
        if file[-5:] != '.json': continue
        input_file = os.path.join(data_dir, file)
        with open(input_file, 'r', encoding="utf8") as rf:
            data = json.load(rf)

        data_tainted = taint(data, ratio=ratio, seed=seed)

        output_file = os.path.join(output_dir, file)
        with open(output_file, 'w', encoding="utf8") as wf:
            json.dump(data_tainted, wf, indent=4, cls=NumpyEncoder)

def generate_tear_dataset(data_dir, output_dir, n_split=2):
    all_files = os.listdir(data_dir)
    for file in tqdm(all_files, total=len(all_files)):
        if file[-5:] != '.json': continue
        input_file = os.path.join(data_dir, file)
        with open(input_file, 'r', encoding="utf8") as rf:
            data = json.load(rf)

        data_torn = tear(data, n_split=n_split)

        output_file = os.path.join(output_dir, file)
        with open(output_file, 'w', encoding="utf8") as wf:
            json.dump(data_torn, wf, indent=4, cls=NumpyEncoder)

if __name__ == '__main__':
    #with open('dataset/testing_data/annotations/82092117.json', 'r') as rf:
    #    data = json.load(rf)
    #print(data)
    #data_torn = tear(data, n_split=2)
    #print(data_torn)
    for ratio in np.arange(0.1, 0.6, 0.1):
        if not os.path.isdir('/data4/jiayun/FUNSD/taint/{}/training_data/annotations'.format(ratio)):
            os.makedirs('/data4/jiayun/FUNSD/taint/{}/training_data/annotations'.format(ratio))
        if not os.path.isdir('/data4/jiayun/FUNSD/taint/{}/testing_data/annotations'.format(ratio)):
            os.makedirs('/data4/jiayun/FUNSD/taint/{}/testing_data/annotations'.format(ratio))
        generate_taint_dataset('/data4/jiayun/FUNSD/dataset/training_data/annotations', '/data4/jiayun/FUNSD/taint/{}/training_data/annotations'.format(ratio), ratio=ratio)
        generate_taint_dataset('/data4/jiayun/FUNSD/dataset/testing_data/annotations', '/data4/jiayun/FUNSD/taint/{}/testing_data/annotations'.format(ratio), ratio=ratio)
        print("{} taint done.".format(ratio))
    #generate_tear_dataset('/data4/jiayun/FUNSD/dataset/training_data/annotations', '/data4/jiayun/FUNSD/torn/training_data/annotations')
    #generate_tear_dataset('/data4/jiayun/FUNSD/dataset/testing_data/annotations', '/data4/jiayun/FUNSD/torn/testing_data/annotations')


import discord
import os
from discord.ext import commands

# importing database manager
import psycopg2

import datetime
from datetime import datetime as dtime

from dotenv import load_dotenv
load_dotenv()

TOKEN = os.getenv("TOKEN")
PASS = os.getenv("PASSWORD")
PORT = os.getenv("PORT")
USER = os.getenv("USER")
DB_NAME_CHEF = os.getenv("DB_NAME_CC")

conn = psycopg2.connect(f"dbname={DB_NAME_CHEF} host=localhost port={PORT} user={USER} password={PASS}")

class Codechef(commands.Cog):
    def __init__(self, client):
        self.client = client

    # command gives the list of present or future contests on codechef
    @commands.command()
    async def codechef(self, ctx, pre_or_fut='Present', all=None):

        # check if the user has requested present or future contests
        pre_or_fut = pre_or_fut[0].upper() + pre_or_fut[1:].lower()
        if pre_or_fut == "All":
            all = "all"
            pre_or_fut = 'Present'
        elif pre_or_fut not in ['Present', 'Future', "All"]:
            pre_or_fut = 'Present'

        conn_command = psycopg2.connect(f"dbname={DB_NAME_CHEF} host=localhost port={PORT}  user={USER} password={PASS}")
        c_command = conn_command.cursor()

        # store today and tomorrows date
        today_date = datetime.date.today()
        tom_delta = datetime.timedelta(hours=24)
        tom_date = today_date + tom_delta

        # store all contests in a list
        c_command.execute(f"SELECT * FROM {pre_or_fut}_Contests ORDER BY START")
        sorted_contests = c_command.fetchall()

        # function to convert all datetimes to dd mmm yyyy hh:mm:ss' format
        def dtime_conv(date_time):
            date_time = date_time[2][:11] + " " + date_time[2][12:]
            date_time = dtime.strptime(date_time, '%d %b %Y %H:%M:%S')
            return date_time

        # sort contests according to startime
        sorted_contests = sorted(sorted_contests, key=dtime_conv)

        threshold = datetime.timedelta(days=30)
        # all_sorted_contests = sorted_contests
        relevant_contests = []

        for contest in sorted_contests:
            time_s = dtime_conv(contest)
            time_e = contest[4]
            if (time_e - time_s) < threshold:
                relevant_contests.append(contest)

        if (all == "all"):
            relevant_contests = sorted_contests

        # in case of no contests available, a message is sent and the function returns
        if len(relevant_contests) == 0:
            await ctx.send("No Contests Available :slight_smile:. Check for longer contests by calling `!codechef all`")
            return

        # if contest list is not empty, an embed object is made
        embed = discord.Embed(
            title=f'__**{pre_or_fut} Contests**__',
            description='',
            colour=discord.Colour.green()
        )
        embed.set_author(name='Codechef', icon_url='https://static.dribbble.com/users/70628/screenshots/1743345/codechef.png')

        # customizing embed format.
        # here, we check if any of the start or end dates are 'today' or 'tomorrow'. If yes, they are
        # replaced by today or tomorrow for better readability
        for i in relevant_contests:
            start = i[2][:11]
            if (dtime.strptime(start, "%d %b %Y").date() == today_date):
                start = 'Today      '
            elif (dtime.strptime(start, "%d %b %Y").date() == tom_date):
                start = 'Tomorrow   '
            s_time = i[2][12:]
            if (s_time[1] == ':'):
                s_time = '0' + s_time

            end = i[3][:11]
            if (dtime.strptime(end, "%d %b %Y").date() == today_date):
                end = 'Today'
            elif (dtime.strptime(end, "%d %b %Y").date() == tom_date):
                end = 'Tomorrow'
            e_time = i[3][12:]
            if (e_time[1] == ':'):
                e_time = '0' + e_time

            name = '__'+'***'+i[1]+'***'+'__'
            time = '```'+'Start time'+'  |  '+'End time'+'\n'+start+' |  '+end+'\n'+s_time+'    |  '+e_time+'```'
            embed.add_field(name=name, value=time, inline=False)

        # send embed and close connection
        await ctx.send(embed=embed)
        conn_command.close()

def setup(client):
    client.add_cog(Codechef(client))


import sys
#coins is an array of coin values
#m is the size of the coins array
#target is the change we want to minimize
def minCoins(coins, m , target):
  memo = [0 for i in range(target+1)]
  #base case, if target = 0
  memo[0] = 0
  for i in range(1, target+1):
    memo[i] = sys.maxsize

  for i in range(1, target+1):
    for j in range(m):
      if (coins[j] <= i):
        res = memo[i - coins[j]]
        if (res!=sys.maxsize and res+1 < memo[i]):
          memo[i] = res + 1
  return memo[target]

print(minCoins([7, 6, 5, 1], 4, 11))


import scipy.io as sio
import numpy as np
from collections import Counter
import torch
import functions
import cv2
import os
import matplotlib
matplotlib.use('AGG')
import matplotlib.pyplot as plt

def yhat_distribution():
    path = "/wangshuo/zhaox/ImageProcessing/stain_classification/_mat/success.Oct.21_13:42.mat"
    data = sio.loadmat(path)
    for name in data['names']:
        name = name.strip()
        if name == "val":
            continue
        print("In %s:" % name)
        Y = data[name + "Y"]
        Yhat = data[name + "Yhat"]
        argYhat = np.argmax(Yhat, axis = 1)
        argY = np.argmax(Y, axis = 1)
        print("Y = ")
        print(Y)
        print("Yhat = ")
        print(np.round(Yhat, decimals = 2))
        print()
    Yhat = data['trainYhat']

def img2tensor(path):
    img = cv2.imread(path)
    img = img / 255
    img = img.transpose((2, 0, 1))
    img = img[np.newaxis, :, :, :]
    img = torch.FloatTensor(img)
    img = img.cuda()
    return img

def manual_accuracy():
    modelpath = "/wangshuo/zhaox/ImageProcessing/stain_classification/_models/success.Oct.21_16:09.model"
    net = torch.load(modelpath)
    Yhat = []
    for filename in os.listdir("/wangshuo/zhaox/ImageProcessing/stain_classification/_data/cutted/train/tumorln/"):
        filename = "/wangshuo/zhaox/ImageProcessing/stain_classification/_data/cutted/train/tumorln/" + filename
        train = img2tensor(filename)
        Yhat.append(net(train).cpu().data.numpy()[0])
    Yhat = np.array(Yhat)

def tsne_fit(a, b):
    from sklearn import manifold
    tsne = manifold.TSNE(n_components=2, init='pca', random_state=501)
    data = sio.loadmat('/wangshuo/zhaox/val.mat')
    Yhat = data['Yhat']
    Y = data['Y']
    Yhat = Yhat[np.bitwise_or(Y[0] == a, Y[0] == b), np.array([False if i not in (a, b) else True for i in range(4)])]
    Y = Y[0][np.bitwise_or(Y[0] == a, Y[0] == b)]
    X_tsne = tsne.fit_transform(Yhat)
    X_norm = X_tsne
    x_min, x_max = X_tsne.min(0), X_tsne.max(0)
    # X_norm = (X_tsne - x_min) / (x_max - x_min)
    fig, ax = plt.subplots()
    ax.scatter(X_norm[:, 0], X_norm[:, 1], color = [plt.cm.Set1(yi) for yi in Y])
    plt.legend()
    plt.savefig('./tsne.png')

def cnter(matpath, K):
    cnts = {}
    data = sio.loadmat(matpath)
    for name in data['names']:
        name = name.strip()
        print(name + ":")
        Y = np.argmax(data[name + 'Y'], axis = 1)
        Yhat = np.argmax(data[name + 'Yhat'], axis = 1)
        cnt = np.zeros((K, K))
        for yi, yih in zip(Y, Yhat):
            cnt[yi, yih] += 1
        print(np.round(cnt / np.sum(cnt, axis = 1, keepdims = True), decimals = 2))
        cnts[name] = cnt
    return cnts

if __name__ == '__main__':
    cnts = cnter("/wangshuo/zhaox/ImageProcessing/stain_classification/_mat/success.Oct.26_21:18.mat", 4)


'''
This reader reads 100 batches with all content
'''
import os
import tensorflow as tf

feature_map = {
        'frames': tf.io.FixedLenFeature(
            shape=15, dtype=tf.string),
        'cameras': tf.io.FixedLenFeature(
            shape=[15 * 5],
            dtype=tf.float32)
        }

path = '/home/ulrich/Downloads/shepard_metzler_5_parts/'
test_files = os.listdir(path + 'test')
train_files = os.listdir(path + 'train')

for i, file in enumerate(train_files):
        train_files[i] = os.path.join(path, 'train', train_files[i])

raw_train = tf.data.TFRecordDataset(train_files)

def _convert_frame_data(jpeg_data):
    decoded_frames = tf.image.decode_jpeg(jpeg_data)
    return tf.image.convert_image_dtype(decoded_frames, dtype=tf.float32)

def _convert_frame_data(jpeg_data):
    decoded_frames = tf.image.decode_jpeg(jpeg_data)
    return tf.image.convert_image_dtype(decoded_frames, dtype=tf.float32)

def _smr_map(raw_frame):
    """
    returns:
    :context_frames: shape batch_size, context_size, 64, 64, 3
    :context_viewpoints: batch_size, context_size, 5
    :target_frames: batch_size, 64,64,3
    :target_vp: batch_size, 5
    """
    raw_data = tf.io.parse_single_example(raw_frame, features=feature_map)
    frames = raw_data['frames']
    viewpoints = raw_data['cameras']
    decoded_frames = tf.map_fn(_convert_frame_data, frames, dtype=tf.float32, back_prop=False)
    de_frames = tf.reshape(decoded_frames, [15, 64, 64, 3])
    de_vp = tf.reshape(viewpoints, [15, 5])

    # apply pos transformation
    pos = de_vp[:, 0:3]
    yaw = de_vp[:, 3:4]
    pitch = de_vp[:, 4:5]

    viewpoints = tf.concat([pos, tf.sin(yaw), tf.cos(yaw), tf.sin(pitch), tf.cos(pitch)], axis = 1)

    return de_frames, viewpoints

dataset = raw_train.map(_smr_map).shuffle(buffer_size = 1234).repeat().batch(100)


import pygame
import textwrap
from helpers import render_textrect

class Text(pygame.sprite.Sprite):
    def __init__(self, st):
        pygame.font.init()
        pygame.sprite.Sprite.__init__(self)
        self.st = st
        self.color = (0,0,0)
        self.size = 32
        self.rect = None
        self.font = None
        self.bgColor = (255,255,255,255)
        self.maxArea = None
        self.justification = 0

        self.prevText = None
        #CALL THIS LAST
        self.createImage()

    def createImage(self):
        if self.font:
            f = self.font
        else:
            f = pygame.font.get_default_font()

        if self.maxArea:
            r = self.maxArea
        else:
            r = pygame.Rect(0,0,1000, 1000)

        if self.rect:
            pos = self.rect.topleft
        else:
            pos = None
        self.image = render_textrect(self.st, pygame.font.Font(self.font, self.size), r, self.color, self.bgColor, self.justification)
        self.rect = self.image.get_rect()
        if pos is not None:
            self.rect.topleft = pos

    def setText(self, value):
        self.st = value
        if self.st != self.prevText:
            self.createImage()
            self.prevText = self.st
    def getText(self):
        return self.st
    def delText(self):
        del self.st

    string = text = property(getText, setText, delText, "")


import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
	"""a class to manage bullets fired from the ship"""
	def __init__(self, ai_game):
		#create a bullet object at the ship's current position

		'''To create a bullet instance, __init__() needs the current instance of
		AlienInvasion, and we call super() to inherit properly from Sprite.'''
		super().__init__()
		self.screen=ai_game.screen
		self.settings=ai_game.settings
		self.color=self.settings.bullet_color

		#create a bullet rect at (0,0) and then set correctposition
		self.rect=pygame.Rect(0,0,self.settings.bullet_width,self.settings.bullet_height)

		'''we set the bullet’s midtop attribute to match the ship’s midtop attribute.
		This will make the bullet emerge from the top of the ship,
		making it look like the bullet is fired from the ship.'''
		self.rect.midtop=ai_game.ship.rect.midtop

		#store the bullet's position as a decimal value
		self.y=float(self.rect.y)

	def update(self):
		#move the bullet up the screen
		#update the decimal position of the bullet
		self.y-=self.settings.bullet_speed
		#update the rect position
		self.rect.y=self.y

	def draw_bullet(self):
		#draw the bullet to the screen
		pygame.draw.rect(self.screen,self.color,self.rect)


from utils.functions import send_class
from discord.ext import commands, tasks
import discord
import os
import re

# If testing locally, use this instead of the OS environment variables
# TOKEN = ''

# with open('config.txt', 'r') as f:
#    TOKEN = f.readline().strip()

TOKEN = os.environ['CLASSBOT_TOKEN'].strip()
# print(TOKEN.strip())

# init member caching (for member count across guilds)
intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix=('c$', 'C$'), case_insensitive=True, help_command=None, intents=intents)
messages = []

# What to do when bot is online
@bot.event
async def on_ready():
    # Log events to console.
    print('Bot online.')
    print("Name: {}".format(bot.user.name))
    print("ID: {}".format(bot.user.id))

    print('In {} guilds'.format(len(bot.guilds)))
    members = [] # sum([guild.member_count for guild in bot.guilds])
    total_members = 0
    for guild in bot.guilds:
        for member in guild.members:
            members.append(member.id)
        total_members += guild.member_count
        print('In {}, with owner {}\t\tUsers: {}'.format(guild.name, guild.owner, guild.member_count))
        # print('Guild permissions: {}'.format(guild.me.guild_permissions))

    members = set(members)
    print('Serving a total of {} members'.format(total_members))
    print('Total unique members: {}'.format(len(members)))
    # Set status
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='c$info'))

# Parse every message
@bot.event
async def on_message(message):
    if message.author.bot:
        return

    # TODO Move string parsing to helper function
    potential_message = '[' and ']' in message.content
    classes = []
    if potential_message:
        # Search for quotes in the message
        msg = message.content.split('\n')
        # All quotes start with '> ' and end with new line
        msg = [x for x in msg if not x.startswith('> ')]
        if len(msg) > 0:
            # Remake the message but without the quote part.
            msg = ''.join(x for x in msg)
            msg = msg.upper()
            # Parse the message. Converting to a set removes duplicates.
            classes = list(set(re.findall('\\\\?\[([A-Za-z]{2,4})\s?(\d{3})\\\\?\]', msg)))

    # Find all classes in an input string.
    if len(classes) > 6:
        await message.channel.send("To reduce spam, please limit your message to 6 or less classes.")
        # Iterate through the courses
    elif len(classes) > 0:
        for course in classes:
            await send_class(message.channel, course)

    await bot.process_commands(message)

# Add a help command to the bot.
@bot.command(name='info', aliases=['help'])
async def await_info(ctx):
    desc = 'To get a class, do [`department` `number`]. For example: `[cs 225]`. This is case insensitive, ' \
           'and the space between the department and the class number is optional. '
    embed = discord.Embed(title='Help', description=desc, url='https://github.com/timot3/uiuc-classes-bot/')
    embed.add_field(name='AP - c$AP', value='Links the UIUC AP credit page')
    embed.add_field(name='Geneds - c$Gened', value='Links the Geneds by GPA page.')

    embed.add_field(name='API Latency', value=str(round(bot.latency * 1000, 1))+'ms.')
    embed.set_footer(text='Having issues with the bot? Send a DM to @10x engineer#9075')
    await ctx.send(embed=embed)

@bot.command(name='AP')
async def await_ap(ctx):
    await ctx.send('https://admissions.illinois.edu/Apply/Freshman/college-credit-AP')

@bot.command(name='geneds', aliases=['gened'])
async def await_ap(ctx):
    await ctx.send('http://waf.cs.illinois.edu/discovery/every_gen_ed_at_uiuc_by_gpa/')

@bot.command(name='users', aliases=['usercount'])
async def await_usercount(ctx):
    members = []
    for guild in bot.guilds:
        for member in guild.members:
            members.append(member.id)
    total_members = len(members)
    unique_members = len(set(members))
    guilds = len(bot.guilds)
    await ctx.send('Online with {} servers and {} total members (Unique members: {}).'
                   .format(guilds, total_members, unique_members))

# Run the bot.
bot.run(TOKEN)


def imprime_matriz(lista):
    for n in lista:
        print(n)

def cria_matriz(linhas, colunas):
    matriz = [] # cria lista vazia
    for i in range(linhas):
        linha = []
        for j in range(colunas):
            valor = int(input('Digite o valor do número ['+ str(i) + ','+ str(j) + ']'))
            linha.append(valor)
        matriz.append(linha)
    return  imprime_matriz(matriz)

cria_matriz(4,2)


#!/usr/bin/env python
from os.path import *
from dbgit import *
from label import *
from osx import *
from upconfig import *
from t import *

@osx
def main():
    cfg = upconfig()
    color = cfg.get("color","blue")
    submodules = session.query(Submodule.fullpath,Submodule.outdated).all()
    outdated = map(
        lambda s:s.fullpath,
        filter(lambda s:s.outdated,submodules)
    )
    not_outdated = map(
        lambda s:s.fullpath,
        filter(lambda s:not s.outdated,submodules)
    )
    print("%s submodules" % len(submodules))
    start()
    add_label(outdated,color)
    print("add_label %s dirs  in %ss" % (len(outdated),stop()))
    start()
    remove_label(not_outdated,color)
    print("remove_label %s dirs in %ss" % (len(not_outdated),stop()))

if __name__=="__main__":
    main()


import asyncio
import time

import peewee
import telepot
import telepot.aio
from InstagramAPI import InstagramAPI
from decouple import config
from telepot.aio.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton

from models import Image
from upload_photos import download_photo, change_image_status, \
    post_on_instagram

"""
$ python3.5 skeletona_route.py <token>
It demonstrates:
- passing a routing table to `MessageLoop` to filter flavors.
- the use of custom keyboard and inline keyboard, and their various buttons.
Remember to `/setinline` and `/setinlinefeedback` to enable inline mode for your bot.
It works like this:
- First, you send it one of these 4 characters - `c`, `i`, `h`, `f` - and it replies accordingly:
    - `c` - a custom keyboard with various buttons
    - `i` - an inline keyboard with various buttons
    - `h` - hide custom keyboard
    - `f` - force reply
- Press various buttons to see their effects
- Within inline mode, what you get back depends on the **last character** of the query:
    - `a` - a list of articles
    - `p` - a list of photos
    - `b` - to see a button above the inline results to switch back to a private chat with the bot
"""

try:
    Image.create_table()
except peewee.OperationalError:
    print('Tabela já existe')

message_with_inline_keyboard = None

image = None

chat_id_reply = None

login = InstagramAPI(config('USERNAME'), config('PASSWORD'))
login.login()
print(login)

def generate_post():

    global chat_id_reply
    global image
    image = download_photo()
    time.sleep(10)

    markup = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Yes', callback_data='yes'),
        InlineKeyboardButton(text='No', callback_data='no'),
    ]])

    url = image.url
    caption = image.caption

    post = "{} \n \n Caption: {} \n \n Do you want to post it?".format(
        url, caption)

    return {'markup': markup, 'url': url, 'caption': caption, 'post': post}

async def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print('Chat:', content_type, chat_type, chat_id)

    if content_type != 'text':
        return

    global chat_id_reply
    chat_id_reply = chat_id
    command = msg['text'][-1:].lower()
    print(command, msg['text'])

    result = generate_post()

    global message_with_inline_keyboard
    message_with_inline_keyboard = await bot.sendMessage(chat_id, result['post'],
                                                         reply_markup=result['markup'])

async def on_callback_query(msg):
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    print('Callback query:', query_id, from_id, data)
    print(msg)
    global chat_id_reply

    if data == 'yes':
        global image
        global login
        post_on_instagram(image, login)
        change_image_status(image)
        text = 'Image posted! Check it out at: https://www.instagram.com/{}/' \
               ' \n \n Click here to generate a /new_post'.format(
            config('USERNAME'))
        await bot.sendMessage(chat_id_reply, text=text)
    else:
        result = generate_post()
        await bot.sendMessage(chat_id_reply,
                              text=result['post'],
                              reply_markup=result['markup'])

bot = telepot.aio.Bot(config('TOKEN'))
answerer = telepot.aio.helper.Answerer(bot)

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot, {'chat': on_chat_message,
                                   'callback_query': on_callback_query, }).run_forever())
print('Listening ...')

loop.run_forever()


import snap
import numpy as np

def GraphVisualization(G1):
	labels = snap.TIntStrH()
	# page_name = snap.TIntStrH()
	# page_type = snap.TIntStrH()

	for NI in G1.Nodes():
	    labels[NI.GetId()] = str(NI.GetId())
	    # page_name[NI.GetId()] = str(targets['page_name'][NI.GetId()])
	    # page_type[NI.GetId()] = str(targets['page_type'][NI.GetId()])

	snap.DrawGViz(G1, snap.gvlDot, "output.png", " ", labels)

def PlotVisual(G1):
	snap.PlotInDegDistr(G1, "Facebook", "Facebook In Degree")
	snap.PlotWccDistr(G1, "Facebook", "Facebook - wcc distributaion")
	snap.PlotSccDistr(G1, "Facebook", "Facebook - scc distributaion")
	snap.PlotClustCf(G1, "Facebook", "Facebook - clustering coefficient")
	snap.PlotKCoreNodes(G1, "Facebook", "Facebook - k-core nodes")
	snap.PlotKCoreEdges(G1, "Facebook", "Facebook - k-core edges")

if __name__ == "__main__":
	G1 = snap.LoadEdgeList(snap.PUNGraph, "/home/hieu/data/ttpt/project/facebook_large/musae_facebook_edges.csv", 0, 1, ',')

	PlotVisual(G1)
	# GraphVisualization(G1)


"""The Digitization routines are for simulating electronics response in various
ways.  Oh, and we use USA spelling here, so use a 'zed' and like it."""

from gnomon.processors import Base

class VlenfSimpleDigitizer(Base.Processor):
    """The VLENF digitizer where the energy deposited is multiplied by a
    generic energy scale."""

    def __init__(self):
        """Initialize with defaults
        """
        Base.Processor.__init__(self)

        self.energy_scale = 80.0  # pe / MeV
        self.log.debug('Energy scale: %f', self.energy_scale)

        self.threshold = None
        self.set_threshold()

    def process(self, docs):
        new_docs = []
        hits_dict = {}

        for doc in docs:
            if doc['type'] != 'mchit':
                new_docs.append(doc)
                continue

            layer = doc['layer']
            view = doc['view']
            position_bar = doc['position_bar']

            key = (doc['run'], doc['event'], layer, doc['bar'], view)

            if key not in hits_dict.keys():
                hits_dict[key] = []

            counts_adc = doc['dedx'] * self.energy_scale

            digit = {}
            digit['type'] = 'digit'
            digit['run'] = doc['run']
            digit['event'] = doc['event']
            digit['layer'] = layer
            digit['bar'] = doc['bar']
            digit['view'] = view
            digit['counts_adc'] = counts_adc
            digit['position'] = position_bar  # this should be derived

            hits_dict[key].append(digit)

        partial_digit = None
        for key, value in hits_dict.iteritems():
            total_counts_adc = 0
            for partial_digit in value:
                total_counts_adc += partial_digit['counts_adc']

            total_counts_adc = int(total_counts_adc)

            if total_counts_adc > self.get_threshold():
                if partial_digit is not None:
                    partial_digit['counts_adc'] = total_counts_adc
                    new_docs.append(partial_digit)

        return new_docs

    def set_threshold(self, threshold=2):
        """Threshold for registering a hit

        Units are ADC counts"""
        self.threshold = threshold

    def get_threshold(self):
        return self.threshold


'''
ONLY COUNTS ORIGINAL ACKS FOR NOW, DUPES (SAME SEQ NUM) DISCARDED
'''
from scapy.all import *
import sys
import time

def get_sec(time_str):
	h, m, s = time_str.split(':')
	return int(s)

if len(sys.argv) != 5:
	print ("Usage: python3 buffer-delay.py <pcap_file> <src_ip> <dest_ip> <base_rtt>")
	sys.exit(1)

packets = rdpcap(sys.argv[1])
src_ip_addr = sys.argv[2]
dest_ip_addr = sys.argv[3]
base_rtt = float(sys.argv[4])

packettotal = 0
for packet in packets:
	packettotal = packettotal + 1

count = 0
index = 0
index2 = 0
tcp_pkt_dict = {}
tcp_pkt_actual = []
seen = []
ack = {}

##preprocessing
while (count < packettotal):
	pkt1 = packets[count]

	##scan for server
	if ((TCP in pkt1)) and (pkt1[IP].src == src_ip_addr):
		tcp_datalen = pkt1[IP].len -(20+(pkt1[TCP].dataofs*4))
		expected_seqnum = pkt1[TCP].seq + tcp_datalen
		tcp_pkt_dict[expected_seqnum] = index
		tcp_pkt_actual.append(pkt1)
		index += 1

	##scan for client acks
	if ((TCP in pkt1)) and (pkt1[IP].src == dest_ip_addr and pkt1[TCP].flags == 'A'):
		if (pkt1[TCP].ack not in seen):
			ack[index2] = pkt1
			seen.append(pkt1[TCP].ack)
			index2 += 1
	count += 1

rtt = []
curr_sec = -1
rtt_plot = []
rtt_cnt = 1
rtt_hold = []

##check for seq that triggers ack
for cnt, i in enumerate(seen):
	'''
	seq_list = tcp_pkt_dict.items()
	for item in seq_list:
		if item[1] == i:
			index = item[0]
			start_time = tcp_pkt_actual[index].time
			end_time = ack[cnt].time
			#print("cnt,index", str(cnt), str(index))
			#print("seq: " + str(item[1]) + "," + str(tcp_pkt_actual[index].seq))
			#print("ack: "+ str(i) + "," + str(ack[cnt].ack))
			#print(end_time,start_time)
			#sprint("RTT: " + str(end_time-start_time) + "ms")
			rtt.append(end_time-start_time)
			break
	'''
	if i in tcp_pkt_dict:
		index = tcp_pkt_dict[i]
		start_time = tcp_pkt_actual[index].time
		end_time = ack[cnt].time

		#handle graphing
		temp = time.strftime('%H:%M:%S', time.localtime(end_time/1000))
		if curr_sec == -1:
			curr_sec = get_sec(temp)
		if get_sec(temp) != curr_sec:
			inst_ave = sum(rtt_hold)/len(rtt_hold)
			rtt_plot.append([rtt_cnt,inst_ave])
			curr_sec = get_sec(temp)
			rtt_cnt += 1
			rtt_hold = []
		else:
			rtt_hold.append(end_time-start_time)

		#print("cnt,index", str(cnt), str(index))
		#print("seq: " + str(index) + "," + str(tcp_pkt_actual[index].seq))
		#print("ack: "+ str(i) + "," + str(ack[cnt].ack))
		#print(end_time,start_time)
		#sprint("RTT: " + str(end_time-start_time) + "ms")
		rtt.append(end_time-start_time)

'''
#add last second average rtt
inst_ave = sum(rtt_hold)/len(rtt_hold)
rtt_plot.append([rtt_cnt,inst_ave])
'''
ave_rtt = sum(rtt)/len(rtt)
print("ave RTT: " + str("{0:.2f}".format(round(ave_rtt,2))) + " ms")
buffer_delay = ( ((sum(rtt)/len(rtt))-base_rtt)/base_rtt ) *100
print("buffer delay: " + str(buffer_delay) + " %")
print("plot:" + str(rtt_plot))


import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.colors as colors
import matplotlib as mpl
mpl.rcParams['xtick.direction'] = 'in'
mpl.rcParams['ytick.direction'] = 'in'
mpl.rcParams["xtick.top"] = True
mpl.rcParams["ytick.right"] = True
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'Arial'
mpl.rcParams['mathtext.fontset'] = 'custom'
import numpy as np
data = np.loadtxt('180.txt')
r = data[:,0]
elst = data[:,1]
exch = data[:,2]
ind = data[:,3]
disp = data[:,4]
sapt = data[:,5]
fig, ax = plt.subplots(tight_layout=True)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
ax.set_xlabel(r'$R/\mathrm{Angstroms}$', fontsize=16)
ax.set_ylabel(r'$E/\mathrm{cm}^{-1}$', fontsize=16)
line_elst, = ax.plot(r,elst,linestyle=(0, (3, 1, 1, 1, 1, 1)))
line_exch, = ax.plot(r,exch,linestyle=(0, (5, 1)))
line_ind, = ax.plot(r,ind,linestyle=(0, (3, 1, 1, 1)))
line_disp, = ax.plot(r,disp,linestyle=(0, (1, 1)))
line_sapt, = ax.plot(r,sapt,'-')
axins = inset_axes(ax,width='45%',height='60%',loc=1)
axins.set_xlim(4.75,5.15)
axins.set_ylim(-160,110)
line_elst_sub, = axins.plot(r,elst,linestyle=(0, (3, 1, 1, 1, 1, 1)),label='Elst')
line_exch_sub, = axins.plot(r,exch,linestyle=(0, (5, 1)),label='Exch')
line_ind_sub, = axins.plot(r,ind,linestyle=(0, (3, 1, 1, 1)),label='Ind')
line_disp_sub, = axins.plot(r,disp,linestyle=(0, (1, 1)),label='Disp')
line_sapt_sub, = axins.plot(r,sapt,'-',label='SAPT0')
axins.legend(loc=2,bbox_to_anchor=(-1.19,1.03),fontsize='large')
figure_fig = plt.gcf()
figure_fig.savefig('180-SAPT.pdf', format='pdf', dpi=1000)


# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from typing import Set
from elasticsearch import Elasticsearch, helpers
from hashlib import sha1
import logging

class ElasticsearchPipeline:
    """Elasticsearch Pipeline to persist website text.

    src of some code: https://github.com/jayzeng/scrapy-elasticsearch/blob/master/scrapyelasticsearch/scrapyelasticsearch.py
    Licenced under Apache License, Version 2.0 https://github.com/jayzeng/scrapy-elasticsearch#licence
    """
    settings = None
    es = None
    item_buffer = []
    added_position_counter = 0
    website_text_hashes: Set[str] = set()
    logger = logging.getLogger(__name__)

    @classmethod
    def validate_settings(cls, settings):
        def validate_setting(setting_key):
            if settings[setting_key] is None:
                raise KeyError('%s is not defined in settings.py' % setting_key)

        required_settings = {'ELASTICSEARCH_INDEX'}

        for required_setting in required_settings:
            validate_setting(required_setting)

    @classmethod
    def init_es_client(cls, crawler_settings):
        es_settings = {}
        es_settings['hosts'] = crawler_settings.get('ELASTICSEARCH_SERVERS', 'localhost:9200')
        es_settings['timeout'] = crawler_settings.get('ELASTICSEARCH_TIMEOUT', 60)

        es = Elasticsearch(**es_settings)
        return es

    def close_spider(self, spider):
        if len(self.item_buffer):
            self.send_items()

    @classmethod
    def from_crawler(cls, crawler):
        ext = cls()
        ext.settings = crawler.settings
        cls.validate_settings(ext.settings)
        ext.es = cls.init_es_client(crawler.settings)
        return ext

    def index_item(self, item):
        index_name = self.settings['ELASTICSEARCH_INDEX']
        text_sha1_hash = sha1(item['text'].encode('utf-8')).hexdigest()
        if text_sha1_hash in self.website_text_hashes: # skip duplicates (meaning same website text)
            url = item['url']
            self.logger.warning(f"Duplicate website skipped {url}")
            return

        self.website_text_hashes.add(text_sha1_hash)
        item['added_position'] = self.added_position_counter
        self.added_position_counter += 1
        index_action = {
            '_index': index_name,
            '_source': dict(item)
        }

        self.item_buffer.append(index_action)

        if len(self.item_buffer) >= self.settings.get('ELASTICSEARCH_BUFFER_LENGTH', 500):
            self.send_items()
            self.item_buffer = []

    def send_items(self):
        helpers.bulk(self.es, self.item_buffer) # refresh="wait_for"

    def process_item(self, item, spider):
        self.index_item(item)
        return item


import scapy.all as scapy
import argparse
import os

cwd = os.getcwd()

from mac_vendor_lookup import MacLookup, BaseMacLookup

print("[*] Welcome")

BaseMacLookup.cache_path = cwd + "/mac-vendors.txt"

mac = MacLookup()
# mac.update_vendors()

"""
    Summary
        print(arp_request_packet.summary())
    Show -> Shows the packet details
        print(arp_request_packet.show())
    Parameters
        scapy.ls(scapy.ARP())
"""
def scan(ip_address):
    print("[+] Scanning Network")
    arp_request_packet = scapy.ARP(pdst=ip_address)
    broadcast_packet = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")

    arp_request_packet = broadcast_packet/arp_request_packet

    # answered_list, unanswered_list = scapy.srp(arp_request_packet, timeout=1)
    answered_list = scapy.srp(arp_request_packet, timeout=1, verbose=False)[0]

    # print(answered_list.summary())

    client_list = []

    for element in answered_list:
        client_dict = {
            "ip_address": element[1].psrc,
            "mac_address": element[1].hwsrc
        }

        client_list.append(client_dict)

    return client_list

def print_result_list(client_list):
    # Header
    print("IP\t\t\tMac Addres\t\tVendor")
    print('-----------------------------------------------------------------------')

    for element in client_list:
        vendor = str(get_vendor(element["mac_address"]))

        print(element["ip_address"] + '\t\t' + element["mac_address"] + '\t\t' + vendor + '\n')

def get_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument("-t", "--target", dest="target", help="Target IP / IP Range ")
    options = parser.parse_args()

    return options

def get_vendor(mac_address):
    vendor = "Unknown"

    try:
        vendor = mac.lookup(mac_address)
    except KeyError as e:
        pass

    return vendor

options = get_arguments()

client_list = scan(options.target)

print("[+] Network Scan Complete \n")

print_result_list(client_list)


from settings import app,db
import requests
from bs4 import BeautifulSoup
import re
from pprint import pprint as pp
from flask import render_template, request
from model import fetch
from models import WangYi as W
N = 100
def random_choose(n):
    return db.engine.execute(f"SELECT id,title FROM wangyi ORDER BY RANDOM() limit {n}")

@app.route('/n')
def fetch_news():
    news = random_choose(100)
    return render_template('main.html', n=news)

@app.route('/p')
def p():
    news_id = request.args.get('id')
    news = W.query.get(news_id)
    p = fetch(news.content)
    return render_template('p.html', t=news.title,c=news.content, p=p[0],cp=p[1])

@app.route('/')
def page():
    return render_template('main.html')

@app.route('/s')
def s():
    from model import say_represents
    return render_template('s.html',s=say_represents)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0',port=11001)


"""
Tests for opencadd.structure.pocket.core
"""

from pathlib import Path

import pandas as pd
import pytest

from opencadd.structure.pocket.core import Pocket
from opencadd.structure.pocket.subpocket import AnchorResidue
from opencadd.structure.pocket.utils import _format_residue_ids_and_labels

PATH_TEST_DATA = Path(__name__).parent / "opencadd/tests/data/pocket"

@pytest.mark.parametrize(
    "residue_ids, residue_labels, residue_ids_formatted, residue_labels_formatted",
    [
        ([1, 2, 3], [1, 2, 3], ["1", "2", "3"], ["1", "2", "3"]),
        ([1, 2], None, ["1", "2"], [None, None]),
    ],
)
def test_format_residue_ids_and_labels(
    residue_ids, residue_labels, residue_ids_formatted, residue_labels_formatted
):

    residue_ids, residue_labels = _format_residue_ids_and_labels(residue_ids, residue_labels)
    assert residue_ids == residue_ids_formatted
    assert residue_labels == residue_labels_formatted

class TestsAnchorResidue:
    """
    Test AnchorResidue class methods.
    """

    @pytest.mark.parametrize(
        "residue_id, residue_id_alternative, residue_center",
        [
            (1, None, [1, 1, 1]),
            (10, ["9", "11"], [35, 35, 35]),
            (4, ["3"], [3, 3, 3]),
            (6, ["7"], [4, 4, 4]),
            (5, None, None),
        ],
    )
    def test_from_dataframe(self, residue_id, residue_id_alternative, residue_center):
        """
        Test anchor residue cases.
        """

        dataframe = pd.DataFrame(
            {
                "residue.id": ["1", "2", "3", "7", "8", "9", "11"],
                "atom.name": ["CA", "CA", "CA", "CA", "CA", "CA", "CA"],
                "atom.x": [1.0, 2.0, 3.0, 4.0, 20.0, 30.0, 40.0],
                "atom.y": [1.0, 2.0, 3.0, 4.0, 20.0, 30.0, 40.0],
                "atom.z": [1.0, 2.0, 3.0, 4.0, 20.0, 30.0, 40.0],
            }
        )

        residue = AnchorResidue.from_dataframe(dataframe, residue_id)

        assert residue.id_alternative == residue_id_alternative
        if residue_center:
            assert pytest.approx(residue.center, residue_center, abs=1.0e-6)

class TestsPocket:
    """
    Test Pocket class methods.
    """

    @pytest.mark.parametrize(
        "filepath, name, residue_ids, residue_labels, centroid",
        [
            (
                PATH_TEST_DATA / "AAK1_4wsq_altA_chainA_protein.mol2",
                "example kinase",
                [127, 128, 129],
                [1, 2, 3],
                [-1.178433, 23.859733, 45.091933],
            )
        ],
    )
    def test_from_file(self, filepath, name, residue_ids, residue_labels, centroid):

        pocket = Pocket.from_file(filepath, residue_ids, name, residue_labels)

        assert pocket.name == name
        assert pocket.residues.equals(
            pd.DataFrame(
                {
                    "residue.id": [str(i) for i in residue_ids],
                    "residue.label": [str(i) for i in residue_labels],
                }
            )
        )
        assert pytest.approx(pocket.centroid, centroid, abs=1.0e-6)

    @pytest.mark.parametrize(
        "filepath, name, residue_ids, color, residue_labels",
        [
            (
                PATH_TEST_DATA / "AAK1_4wsq_altA_chainA_protein.mol2",
                "hinge",
                [127, 128, 129],
                "magenta",
                [46, 47, 48],
            )
        ],
    )
    def test_add_regions(self, filepath, name, residue_ids, color, residue_labels):

        pocket = Pocket.from_file(filepath, residue_ids, "", residue_labels)
        pocket.add_region(name, residue_ids, color, residue_labels)

        n_region_residues = len(residue_ids)
        region = pd.DataFrame(
            {
                "region.name": [name] * n_region_residues,
                "region.color": [color] * n_region_residues,
                "residue.id": [str(i) for i in residue_ids],
                "residue.label": [str(i) for i in residue_labels],
            }
        )
        assert pocket.regions.equals(region)

    @pytest.mark.parametrize(
        "filepath, name, residue_ids, color, residue_labels, center",
        [
            (
                PATH_TEST_DATA / "AAK1_4wsq_altA_chainA_protein.mol2",
                "hinge_region",
                [73, 128, 193],
                "magenta",
                [16, 47, 80],
                [1.957633, 21.923767, 41.69003333],
            )
        ],
    )
    def test_add_subpocket(self, filepath, name, residue_ids, color, residue_labels, center):

        print(residue_ids)
        print(residue_labels)
        pocket = Pocket.from_file(filepath, residue_ids, "", residue_labels)

        pocket.add_subpocket(name, residue_ids, color, residue_labels)
        subpocket = pocket._subpockets[0]

        assert subpocket.name == name
        assert subpocket.color == color
        assert pytest.approx(subpocket.center, center, abs=1.0e-6)
        assert pocket.subpockets.columns.to_list() == [
            "subpocket.name",
            "subpocket.color",
            "subpocket.center",
        ]

# TODO Test KlifsPocket