###########################################################
#
# Copyright (c) 2005, Southpaw Technology
#                     All Rights Reserved
#
# PROPRIETARY INFORMATION.  This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#

__all__ = ['AppSObjectCheckinWdg']

from pyasm.prod.biz import SessionContents
from tactic.ui.cgapp import CheckinWdg
#from pyasm.prod.web import MayaCheckinWdg
from pyasm.web import DivWdg, SpanWdg,  Table, HtmlElement, FloatDivWdg, WebContainer, WidgetSettings, Widget
from pyasm.widget import SwapDisplayWdg, SelectWdg, CheckboxWdg, ProdIconButtonWdg, HiddenWdg, ThumbWdg, IconWdg, TextAreaWdg
from pyasm.search import SObject, Search
from pyasm.biz import Project, Pipeline, Snapshot
from pyasm.common import Common, Xml
from tactic.ui.widget import TextBtnWdg, ActionButtonWdg

class AppSObjectCheckinWdg(CheckinWdg):

    PUBLISH_BUTTON = 'Publish'
    ARGS_KEYS = {

        "search_type": {
            'description': "search type that this panel works with",
            'type': 'TextWdg',
            'order': 0,
            'category': '1. Required'
        },
       "texture_search_type": {
            'description': "texture search type that this panel works with",
            'type': 'TextWdg',
            'order': 1,
            'category': '1. Required'
        },
        "process": {
            'description': "The process this panel is looking at e.g. {@GET(state.process)}",
            'type': 'TextWdg',
            'order': 1,
            'category': '2. Options'
        }

       }

    def list_references(self):
        '''lists whether references can be checked in with this widget'''
        return False

    def get_context_data(self):
        process = self.process_select.get_value()
        labels, values = super(AppSObjectCheckinWdg,self).get_context_data(\
            self.search_type, process)

        return labels, values

    def get_display(self):

        self.search_type = self.kwargs.get('search_type')
        self.texture_search_type = self.kwargs.get('texture_search_type')
        assert self.search_type

        app_name = WebContainer.get_web().get_selected_app()
        # add an outside box

        top = DivWdg(css='spt_view_panel')
        #div = DivWdg(css="maq_search_bar")
        div = DivWdg()
        div.add_color("background", "background2", -15)
        self.set_as_panel(top)

        top.add(div)
        div.add_style("margin: 5px")

        div.add_style("padding: 10px")

        div.add_style("font-style: bold")

        process_div = DivWdg()
        process_div.add_style("padding-left: 10px")
        div.add(process_div)
        process_div.add( self.get_process_wdg(self.search_type))
        process_div.add( self.get_context_filter_wdg() )
        process_div.add(HtmlElement.br(clear="all"))

        div.add( HtmlElement.br() )
        checkin_options = DivWdg(css='spt_ui_options')
        checkin_options.add_style("padding: 10px")

        swap = SwapDisplayWdg()
        #swap.set_off()
        title = SpanWdg("Check in Options")
        SwapDisplayWdg.create_swap_title(title, swap, checkin_options, is_open=False)
        div.add(swap)
        div.add(title)

        checkin_options.add( self.get_file_type_wdg() )
        checkin_options.add( self.get_snapshot_type_wdg() )
        checkin_options.add(HtmlElement.br(1))
        checkin_options.add( self.get_export_method_wdg() )
        checkin_options.add( self.get_checkin_as_wdg() )

        #self.add( self.get_render_icon_wdg() )

        # For different export methods
        checkin_options.add( self.get_currency_wdg() )

        checkin_options.add( self.get_reference_option())
        checkin_options.add( self.get_auto_version_wdg())
        checkin_options.add( self.get_texture_option(app=app_name))
        checkin_options.add( self.get_handoff_wdg())

        if not self.context_select.get_value(for_display=True):
            self.add(DivWdg('A context must be selected.', css='warning'))
            return

        div.add(checkin_options)

        top.add( self.get_introspect_wdg() )
        top.add(HtmlElement.br(2))

        # create the interface
        table = Table()
        table.set_max_width()
        #table.set_class("table")
        table.add_color('background','background2')
        #table.add_style('line-height','3.0em')
        #table.add_row(css='smaller')
        tr = table.add_row(css='smaller')
        tr.add_style('height', '3.5em')
        table.add_header(" ")
        table.add_header(" ")
        th = table.add_header("Instance")
        th.add_style('text-align: left')
        table.add_header(self.get_checkin())
        table.add_header("Sandbox")
        tr.add_color('background','background2', -15)

        # get session and handle case where there is no session
        self.session = SessionContents.get()
        if self.session == None:
            instance_names = []
            asset_codes = []
            node_names = []
        else:
            instance_names = self.session.get_instance_names()
            asset_codes = self.session.get_asset_codes()
            node_names = self.session.get_node_names()

        # get all of the possible assets based on the asset codes
        search = Search(self.search_type)
        search.add_filters("code", asset_codes)
        assets = search.get_sobjects()
        assets_dict = SObject.get_dict(assets, ["code"])

        if self.session:
            self.add("Current Project: %s" % self.session.get_project_dir() )
        else:
            self.add("Current Project: Please press 'Introspect'")

        count = 0
        for i in range(0, len(node_names) ):
            node_name = node_names[i]
            if not self.session.is_tactic_node(node_name) and \
                not self.session.get_node_type(node_name) in ['transform','objectSet']:
                    continue
            instance_name = instance_names[i]

            # backwards compatible:
            try:
                asset_code = asset_codes[i]
            except IndexError as e:
                asset_code = instance_name

            # skip if this is a reference
            if self.list_references == False and \
                    self.session.is_reference(node_name):
                continue

            table.add_row()

            # check that this asset exists
            asset = assets_dict.get(asset_code)
            if not asset:
                continue

            # list items if it is a set
            if asset.get_value('asset_type', no_exception=True) in ["set", "section"]:
                self.current_sobject = asset
                self.handle_set( table, instance_name, asset, instance_names)
                count +=1
            # if this asset is in the database, then allow it to checked in
            if asset:
                if self.session.get_snapshot_code(instance_name, snapshot_type='set'):
                    continue

                # hack remember this
                self.current_sobject = asset
                self.handle_instance(table, instance_name, asset, node_name)

            else:
                table.add_blank_cell()
                table.add_cell(instance_name)

            count += 1

        if count == 0:
            table.add_row_cell("
No assets in session to checkin
")

        top.add(table)

        if not self.session:
            return

        non_tactic_nodes = self.session.get_instance_names(is_tactic_node=False)
        title = HtmlElement.b("Unknown List")
        swap = SwapDisplayWdg.get_triangle_wdg()

        div = DivWdg(id="unknown list")

        top.add(swap)
        top.add(title)

        SwapDisplayWdg.create_swap_title( title, swap, div)
        unknown_table = Table()
        unknown_table.add_color('background','background2')
        unknown_table.set_max_width()
        div.add(unknown_table)

        for instance in non_tactic_nodes:
            self.handle_unknown_instance(unknown_table, instance)

        top.add(div)
        return top

    def get_file_type_wdg(self):
        '''drop down which selects which file type to export to'''
        # add a filter
        div = DivWdg()

        filter_div = FloatDivWdg(HtmlElement.b("File Type:"), width="15em")
        div.add(filter_div)

        select = SelectWdg()
        select.set_name("file_type")
        select.set_id("file_type")

        app = WebContainer.get_web().get_selected_app()

        if app == 'Maya':
            select.set_option("values", "mayaAscii|mayaBinary|obj|collada")
            select.set_option("labels", "Maya Ascii (.ma)|Maya Binary (.mb)|Wavefront .obj|Collada (.dae)")
        elif app == 'Houdini':
            select.set_option("values", "otl")
            select.set_option("labels", "Houdini Digital Asset(.otl)")
        elif app == 'XSI':
            select.set_option("values", "emdl|dotXSI|obj")
            select.set_option("labels", "3D Model (.emdl)|SoftImage dotXSI (.xsi)|Wavefront .obj")
        else:
            select.set_option("values", "mayaAscii|mayaBinary|obj|collada")
            select.set_option("labels", "Maya Ascii (.ma)|Maya Binary (.mb)|Wavefront .obj|Collada (.dae)")

        select.add_style("font-size: 0.8em")
        select.add_style("margin-top: 5px")
        select.add_style("margin-right: 10px")
        select.set_persistence()

        div.add(select)
        return div

    def get_checkin(self):
        '''the button which initiates the checkin'''
        # create the button with the javascript function
        widget = Widget()
        #button = TextBtnWdg(label=self.PUBLISH_BUTTON, size='large', width='100', side_padding='20', vert_offset='-5')
        #button.get_top_el().add_class('smaller')
        button = ActionButtonWdg(title=self.PUBLISH_BUTTON, tip='Publish the selected assets')
        button.add_style('margin-bottom: 10px')
        #button.add_color("background", "background")

        hidden = HiddenWdg(self.PUBLISH_BUTTON, '')
        button.add( hidden )

        '''
        status_sel = SelectWdg('checkin_status', label='Status: ')
        status_sel.set_option('setting', 'checkin_status')
        status_sel.set_persist_on_submit()
        status_sel.add_empty_option('-- Checkin Status --')
        widget.add(status_sel)
        '''
        widget.add(button)

        # custom defined
        server_cbk = "pyasm.prod.web.AssetCheckinCbk"
        #TODO: make other Publish Buttons call their own handle_input function
        exec( Common.get_import_from_class_path(server_cbk) )
        exec( "%s.handle_input(button, self.search_type, self.texture_search_type)" % server_cbk)

        return widget

    """

    def get_export_method_wdg(self):
        '''Checkbox that determines whether to use export or file/save'''
        is_unchecked = True
        default_cb = None
        div = DivWdg()

        title = FloatDivWdg(HtmlElement.b("Export Method:"), width="15em")
        div.add(title)

        for value in ['Export', 'Save', 'Pipeline']:
            span = SpanWdg(css="med")
            checkbox = CheckboxWdg("export_method")

            checkbox.set_option("value", value)
            checkbox.set_persistence()
            if value == 'Export':
                default_cb = checkbox
            if checkbox.is_checked():
                is_unchecked = False
            checkbox.add_behavior({'type': 'click_up',
                    'propagate_evt': True,
                    "cbjs_action": "spt.toggle_checkbox(bvr, '.spt_ui_options', 'export_method')"})
            span.add(checkbox)
            span.add(value)
            div.add(span)

        if is_unchecked:
            default_cb.set_checked()

        batch_cb = CheckboxWdg('use_batch', label='batch script')
        batch_cb.set_persistence()
        span = SpanWdg(batch_cb, css='med')
        span.add_style('border-left: 1px solid #888')
        div.add(span)
        return div

    """

    def get_render_icon_wdg(self):
        '''Checkbox determines whether to create icon'''
        div = DivWdg()
        div.add("Create Icon: ")
        checkbox = CheckboxWdg("render")
        checkbox.set_persistence()
        div.add(checkbox)
        return div

    def handle_set(self, table, instance_name,  asset,  session_instances):
        asset_code = asset.get_code()

        # get all of the reference instances from the latest published
        snapshot = Snapshot.get_latest_by_sobject(asset, "publish")
        # if there is no publish snapshot, then this is definitely not
        # a set, so handle it like an instance
        if not instance_name in session_instances:
            return
        if not snapshot:
            self.handle_instance(table, instance_name, asset)
            return

        xml = snapshot.get_xml_value("snapshot")

        # skip if none are in session
        set_instances = xml.get_values("snapshot/ref/@instance")

        # TODO should get it based on the set's asset code so that
        # if the sesssion's set is older, it will still work
        session_set_items = self.session._get_data().get_nodes_attr(\
            "session/node[@set_asset_code='%s']" %asset_code, 'instance')
        count = 0

        set_instances_in_session = []
        set_instances_not_in_session = []
        for set_instance in set_instances:

            # backwards compatible:
            tmp_set_instance = set_instance
            if set_instance.find(":") != -1:
                print("WARNING: snapshot '%s' has deprecated maya instance names" % snapshot.get_code())
                set_instance, tmp = set_instance.split(":")

            # make sure the set_instance comes from this set
            if set_instance in session_set_items:
                count += 1
                set_instances_in_session.append(tmp_set_instance)

            else:
                set_instances_not_in_session.append(tmp_set_instance)

        if count == 0:
            return

        self.handle_instance(table, instance_name, asset)

        # display all of the set instance that are in session
        for set_instance in set_instances_in_session:

            ref_snapshot = snapshot.get_ref_snapshot("instance",
                set_instance)
            ref_asset = ref_snapshot.get_sobject()

            # backwards compatible
            if set_instance.find(":") != -1:
                print("WARNING: snapshot '%s' has deprecated maya instance names" % snapshot.get_code())
                set_instance, tmp = set_instance.split(":")

            self.handle_instance(table, set_instance, ref_asset, publish=False)

        widget = Widget(" ")
        if set_instances_not_in_session:
            widget = Widget()
            widget.add(IconWdg("warning", icon=IconWdg.ERROR))
            widget.add("missing set items from last publish")
        th, td = table.add_row_cell(widget)

        for set_instance in set_instances_not_in_session:

            ref_snapshot = snapshot.get_ref_snapshot("instance",
                set_instance)
            ref_asset = ref_snapshot.get_sobject()

            # backwards compatible
            if set_instance.find(":") != -1:
                print("WARNING: snapshot '%s' has deprecated maya instance names" % snapshot.get_code())
                set_instance, tmp = set_instance.split(":")

            self.handle_missing_instance(table, set_instance, ref_asset)

        if set_instances_not_in_session:
            table.add_row_cell(" ")

    def handle_instance(self, table, instance, asset, node_name='', publish=True, allow_ref_checkin=False):

        # handle the case where asset is not defined
        if not asset:
            table.add_row()
            table.add_blank_cell()
            table.add_blank_cell()

            # FIXME: Maya specific
            parts = instance.split(":")
            instance_name = parts[0]
            asset_code = parts[1]

            if instance_name == asset_code:
                table.add_cell(instance_name)
            else:
                table.add_cell(instance)
            td = table.add_cell()
            td.add("< %s node >" % self.session.get_node_type(instance_name))
            table.add_blank_cell()
            return

        # get the pipeline for this asset and handlers for the pipeline
        process_name = self.process_select.get_value()
        handler_hidden = self.get_handler_input(asset, process_name)
        pipeline = Pipeline.get_by_sobject(asset)

        # TEST: switch this to using node name instead, if provided
        if node_name:
            instance_node = self.session.get_node(node_name)
        else:
            instance_node = self.session.get_node(instance)

        if instance_node is None:
            return
        if Xml.get_attribute(instance_node,"reference") == "true":
            is_ref = True
        else:
            is_ref = False

        namespace = Xml.get_attribute(instance_node, "namespace")
        if not namespace:
            namespace = instance

        asset_code = asset.get_code()
        is_set = False
        if asset.get_value('asset_type', no_exception=True) in ['set','section']:
            is_set = True

        tr = table.add_row()

        if is_set:
            tr.add_class("group")

        if publish and (allow_ref_checkin or not is_ref):
            checkbox = CheckboxWdg("asset_instances")
            if is_set:
                checkbox = CheckboxWdg("set_instances")

            checkbox.set_option("value", "%s|%s|%s" % \
                        (namespace, asset_code, instance) )
            checkbox.set_persist_on_submit()

            td = table.add_cell(checkbox)

        else:
            td = table.add_blank_cell()

        # only one will be added even if there are multiple
        if handler_hidden:
            td.add(handler_hidden)

        # add the thumbnail
        thumb = ThumbWdg()
        thumb.set_name("images")
        thumb.set_sobject(asset)
        thumb.set_icon_size(60)
        table.add_cell(thumb)

        info_wdg = Widget()
        info_wdg.add(HtmlElement.b(instance))

        if not node_name:
            node_name = '%s - %s' %(asset_code, asset.get_name())
        info_div = DivWdg(node_name)
        info_div.add_style('font-size: 0.8em')
        info_wdg.add(info_div)
        info_div.add(HtmlElement.br(2))
        if pipeline:
            info_div.add(pipeline.get_code())
        table.add_cell(info_wdg)

        #  by default can't checkin references
        if not allow_ref_checkin and is_ref:
            #icon = IconWdg("error", IconWdg.ERROR)
            #td = table.add_cell(icon)
            td = table.add_cell()
            td.add(HtmlElement.b("Ref. instance"))
            '''
            import_button = ProdIconButtonWdg('import')
            import_button.add_event('onclick', "import_instance('%s')"  %instance)
            td.add(import_button)
            '''
            table.add_cell(self.get_save_wdg(self.current_sobject) )

        elif publish:
            textarea = TextAreaWdg()
            textarea.set_persist_on_submit()
            textarea.set_name("%s_description" % instance)
            textarea.set_attr("cols", "35")
            textarea.set_attr("rows", "2")
            table.add_cell(textarea)
            table.add_cell(self.get_save_wdg(self.current_sobject) )
        else:
            table.add_blank_cell()
            table.add_blank_cell()

    def handle_missing_instance(self, table, instance, asset):

        asset_code = asset.get_code()

        table.add_row()

        table.add_blank_cell()

        # add the thumbnail
        thumb = ThumbWdg()
        thumb.set_name("images")
        thumb.set_sobject(asset)
        thumb.set_icon_size(45)
        table.add_cell(thumb)

        info_wdg = Widget()
        info_wdg.add("%s" % instance)
        info_wdg.add("
%s
" % asset_code )
        table.add_cell(info_wdg)

        table.add_blank_cell()

    def handle_unknown_instance(self, table, instance):
        '''handle unassigned or non-tactic nodes'''

        table.add_row()
        table.add_blank_cell()
        icon = IconWdg("unknown", icon=IconWdg.UNKNOWN)
        table.add_cell(icon)

        info_wdg = Widget()
        info_wdg.add("%s" % instance)
        table.add_cell(info_wdg)
        table.add_blank_cell()
        table.add_blank_cell()


class Employee:

    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname
        # self.email = f"{fname}.{lname}@gmail.com"

    def explain(self):
        return f"This is {self.fname} {self.lname}"

    @property
    def email(self):
        if self.fname == None or self.lname == None:
            return "Email is not set! please set it using setter."

        return f"{self.fname}.{self.lname}@gmail.com"

    @email.setter
    def email(self, string):
        print('Setting now...')
        names = string.split("@")[0]
        self.fname = names.split(".")[0]
        self.lname = names.split(".")[1]

    @email.deleter
    def email(self):
        self.fname = None
        self.lname = None

anindo_dey = Employee("Anindo", "Dey")

print(anindo_dey.email)
anindo_dey.fname = "BB"

print(anindo_dey.email)

# email setter
anindo_dey.email = "this.that@gmail.com"
print(anindo_dey.email)

# email deleter
del anindo_dey.email

print(anindo_dey.email)

oops - setters and property decorators.py


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

# In[2]:

import h5py
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn import svm
from numpy import mean
from numpy import std
from sklearn.metrics import accuracy_score
import warnings
warnings.filterwarnings(action="ignore",category=DeprecationWarning)
warnings.filterwarnings(action="ignore",category=FutureWarning)

# In[3]:

def h5opener(filename):
    with h5py.File(filename,'r') as f:
#         print("Keys: %s" % f.keys())
        X = f['x'][:]
        Y = f['y'][:]
    return X,Y

def plotUtil(filename, outlier_remove = 'no'):
    if(outlier_remove == 'yes'):
        X,Y = outlier_removal(filename)
    else:
        X,Y = h5opener(filename)

    numClasses = len(list(set(Y)))
    colors = ['red', 'green', 'blue']
    for i in range(numClasses):
        plt.scatter(X[Y==i,0],X[Y==i,1],c = colors[i], label = ('Class '+ str(i)), edgecolors='k')
    plt.xlabel('Feature 1')
    plt.ylabel('Feature 2')
    plt.legend(loc = 'upper right' )
    plt.title(filename)
    plt.show()
    print('\n')

def outlier_removal(filename):
    X,Y = h5opener(filename)
    X1 = X[:,0]   #feature 1
    X2 = X[:,1]   #feature 2
#     print('Original No of Examples: ', len(X))

    meanX1 = mean(X1)
    sdX1   = std(X1)
    meanX2 = mean(X2)
    sdX2   = std(X2)

    X1temp = []
    X2temp = []
    Ytemp  = []

    cur_idx = 0
    for x in X1:
        if( (x > (meanX1 - 2*sdX1)) and (x < (meanX1 + 2*sdX1))):
            X1temp.append(x)
            X2temp.append(X2[cur_idx])
            Ytemp.append(Y[cur_idx])
        cur_idx += 1
    X1 = []
    X2 = []
    Y  = []
    cur_idx = 0
    for x in X2temp:
        if (x > (meanX2 - 3*sdX2)) and (x < (meanX2 + 3*sdX2)):
            X2.append(x)
            X1.append(X1temp[cur_idx])
            Y.append(Ytemp[cur_idx])
        cur_idx += 1

    X = np.vstack((X1,X2)).T
    Y = np.asarray(Y)
#     print('No of Examples after removing outliers: ', len(X))

    return X,Y

# In[4]:

def kernel_predict(X,Y, kernel_type, c):

    xmin,xmax = X[:,0].min()-1, X[:,0].max()+1
    ymin,ymax = X[:,1].min()-1, X[:,1].max()+1
    xx, yy = np.meshgrid(np.arange(xmin,xmax,0.02), np.arange(ymin,ymax,0.02))
    if(kernel_type=='linear'):
        svm_model = svm.SVC(kernel= kernel_type,C = c).fit(X,Y)
    elif(kernel_type=='rbf'):
        svm_model = svm.SVC(kernel = kernel_type, gamma = 'auto',C = c).fit(X,Y)
    else: print('Kernel type not supported')

#     print(svm_model.support_vectors_)

    Z = svm_model.predict(np.c_[xx.ravel(),yy.ravel()])
    Z = Z.reshape(xx.shape)
    plt.contourf(xx,yy,Z, cmap = plt.cm.coolwarm, alpha = 0.8)

    plt.scatter(X[:,0],X[:,1], c=Y, cmap=plt.cm.coolwarm, s=25,edgecolors='k')
    plt.xlabel('Feature 1')
    plt.ylabel('Feature 2')
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
#     plt.title('Dataset: '+ filename + '   ' + 'Kernel: '+kernel_type)
    plt.show()
    print('\n')

# In[22]:

def rbf_own(X,Y):
    rbf = np.zeros((X.shape[0],Y.shape[0]))
    for i,x in enumerate(X):
        for j,y in enumerate(Y):
            rbf[i,j] = np.exp((-1*np.linalg.norm(x-y)**2))   #for data4, use gamma = 9, 1 o/w
    return rbf

# In[23]:

def predict_own(kernel,test_data, dual_coef_,support_vectors_):
    w = np.zeros(len(test_data))
    rbf_kernel = rbf_own(support_vectors_, test_data)
    for j in range(len(test_data)):
        for i in range(0,len(support_vectors_)):
            if(kernel =='linear'):
                w[j]+= ((np.dot(support_vectors_[i],test_data[j]))*dual_coef_[0,i])
            elif(kernel == 'rbf'):
                w[j]+= (rbf_kernel[i,j]*dual_coef_[0,i])
            else:
                print("Invalid Kernel Type: " + kernel)

    for j in range(len(test_data)):
        if(w[j] < 0):
            w[j] = 0
        else:
            w[j] = 1

    return w

# In[24]:

if __name__ == '__main__':

    #DATASET 4
    print("DATASET 4")
    print("-------------------------")

    X,Y = outlier_removal('data_4.h5')      #for data4, use gamma = 9, 1 o/w
    X_train = X[0: int(0.8*len(Y)),:]
    Y_train = Y[0: int(0.8*len(Y))]
    X_test  = X[int(0.8*len(Y)):len(Y),:]
    Y_test  = Y[int(0.8*len(Y)):len(Y)]

    clf = svm.SVC(kernel = 'linear', C=1).fit(X_train, Y_train)
    y_pred_inbuilt = clf.predict(X_test)
    acc1 = accuracy_score(Y_test, y_pred_inbuilt) * 100

    y_pred_own = predict_own('linear',X_test,clf.dual_coef_,clf.support_vectors_)
    acc2 = accuracy_score(Y_test, y_pred_own) * 100

    print("Accuracy using Linear Kernel:")
    print("Accuracy using SVM prediction function = ", acc1)
    print("Accuracy using own prediction function = ", acc2)

    clf = svm.SVC(kernel = 'rbf', C=1).fit(X_train, Y_train)
    y_pred_inbuilt = clf.predict(X_test)
    acc1 = accuracy_score(Y_test, y_pred_inbuilt) * 100

    y_pred_own = predict_own('rbf',X_test,clf.dual_coef_,clf.support_vectors_)
    acc2 = accuracy_score(Y_test, y_pred_own) * 100

    print("Accuracy using RBF Kernel:")
    print("Accuracy using SVM prediction function = ", acc1)
    print("Accuracy using own prediction function = ", acc2)

    #DATASET 5
    print("DATASET 5")
    print("-------------------------")
    X,Y = outlier_removal('data_5.h5')      #for data4, use gamma = 9, 1 o/w
    X_train = X[0: int(0.8*len(Y)),:]
    Y_train = Y[0: int(0.8*len(Y))]
    X_test  = X[int(0.8*len(Y)):len(Y),:]
    Y_test  = Y[int(0.8*len(Y)):len(Y)]

    clf = svm.SVC(kernel = 'linear', C=1).fit(X_train, Y_train)
    y_pred_inbuilt = clf.predict(X_test)
    acc1 = accuracy_score(Y_test, y_pred_inbuilt) * 100

    y_pred_own = predict_own('linear',X_test,clf.dual_coef_,clf.support_vectors_)
    acc2 = accuracy_score(Y_test, y_pred_own) * 100

    print("Accuracy using Linear Kernel:")
    print("Accuracy using SVM prediction function = ", acc1)
    print("Accuracy using own prediction function = ", acc2)

    clf = svm.SVC(kernel = 'rbf', C=1).fit(X_train, Y_train)
    y_pred_inbuilt = clf.predict(X_test)
    acc1 = accuracy_score(Y_test, y_pred_inbuilt) * 100

    y_pred_own = predict_own('rbf',X_test,clf.dual_coef_,clf.support_vectors_)
    acc2 = accuracy_score(Y_test, y_pred_own) * 100

    print("Accuracy using RBF Kernel:")
    print("Accuracy using SVM prediction function = ", acc1)
    print("Accuracy using own prediction function = ", acc2)

# In[ ]:

# In[ ]:


import tkinter as tk
from tkinter import filedialog
import os

#No commant in you want to insert manual path
#path = input("Enter path: ")

#No comment if you want to change default phrase
#phrase = input("Enter phrase: ")
phrase = "tua evidenziazione"

#This open up file finder
root = tk.Tk()
root.withdraw()
path = filedialog.askopenfilename()

#Open file in python and read it
with  open(path, encoding="mbcs") as f:
    lines = f.readlines()

#Delete full line if there is in that line the phrase
with open(path, 'w', encoding="mbcs") as f:
    for line in lines:
        if line.strip("\n").find(phrase) == -1 :
            f.write(line)


def check_square(x, y):
    nx, ny = (x // 3) * 3, (y // 3) * 3
    temp = []
    temp.append(grid[nx][ny:ny+3])
    temp.append(grid[nx + 1][ny:ny+3])
    temp.append(grid[nx + 2][ny:ny+3])
    temp_sum = 0
    print(temp)
    for i in temp:
        if 0 in i:
            return 0
        temp_sum += sum(i)

    return temp_sum

def check(x, y):
    if 0 not in grid[x] and 0 not in list(zip(*grid))[y] and not check_square(x, y):
        if sum(grid[x]) == 45 and sum(list(zip(*grid))[y]) == 45 and check_square == 45:
            return True
    return False

def sudoku(idx):
    if idx == count:
        return
    x, y = blank[idx]
    for i in range(1, 10):
        grid[x][y] = i
        if check(x, y):
            sudoku(idx + 1)

grid = [list(map(int, input().split())) for _ in range(9)]
blank = []
for i in range(9):
    for j in range(9):
        if not grid[i][j]:
            blank.append((i, j))
count = len(blank)
print(check_square(0,1))
print(check_square(1,4))
visited = [[0] * 9 for _ in range(9)]
for i in range(9):
    print(grid[i])

'''
0 3 5 4 6 9 2 7 8
7 8 2 1 4 5 6 0 9
0 6 0 2 7 8 1 3 5
3 2 1 0 4 6 8 9 7
8 0 4 9 1 3 5 0 6
5 9 6 8 2 0 4 1 3
9 1 7 6 5 2 0 8 0
6 0 3 7 0 1 9 5 2
2 5 8 3 9 4 7 6 0

'''


"""
TODO
    incomplete, trying to visualize model activations on different class types to see the abstract idea of what
    the filters key off of.

    Base code from HW3

    Might find help here for the classes
    https://towardsdatascience.com/how-to-visualize-convolutional-features-in-40-lines-of-code-70b7d87b0030

"""

import random
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter1d

import torch

def rescale(x):
    low, high = x.min(), x.max()
    x_rescaled = (x - low) / (high - low)
    return x_rescaled

def blur_image(X, sigma=1):
    X_np = X.cpu().clone().numpy()
    X_np = gaussian_filter1d(X_np, sigma, axis=2)
    X_np = gaussian_filter1d(X_np, sigma, axis=3)
    X.copy_(torch.Tensor(X_np).type_as(X))
    return X

def jitter(X, ox, oy):
    """
    Helper function to randomly jitter an image.

    Inputs
    - X: PyTorch Tensor of shape (N, C, H, W)
    - ox, oy: Integers giving number of pixels to jitter along W and H axes

    Returns: A new PyTorch Tensor of shape (N, C, H, W)
    """
    if ox != 0:
        left = X[:, :, :, :-ox]
        right = X[:, :, :, -ox:]
        X = torch.cat([right, left], dim=3)
    if oy != 0:
        top = X[:, :, :-oy]
        bottom = X[:, :, -oy:]
        X = torch.cat([bottom, top], dim=2)
    return X

def create_class_visualization(target_y, model, dtype, **kwargs):
    """
    Generate an image to maximize the score of target_y under a pretrained model.

    Inputs:
    - target_y: Integer in the range [0, 1000) giving the index of the class
    - model: A pretrained CNN that will be used to generate the image
    - dtype: Torch datatype to use for computations

    Keyword arguments:
    - l2_reg: Strength of L2 regularization on the image
    - learning_rate: How big of a step to take
    - num_iterations: How many iterations to use
    - blur_every: How often to blur the image as an implicit regularizer
    - max_jitter: How much to gjitter the image as an implicit regularizer
    - show_every: How often to show the intermediate result
    """
    model.type(dtype)
    l2_reg = kwargs.pop('l2_reg', 1e-3)
    learning_rate = kwargs.pop('learning_rate', 25)
    num_iterations = kwargs.pop('num_iterations', 100)
    blur_every = kwargs.pop('blur_every', 10)
    max_jitter = kwargs.pop('max_jitter', 16)
    show_every = kwargs.pop('show_every', 25)

    # Randomly initialize the image as a PyTorch Tensor, and make it requires gradient.
    img = torch.randn(1, 1, 44, 40).mul_(1.0).type(dtype).requires_grad_()

    for t in range(num_iterations):
        # Randomly jitter the image a bit; this gives slightly nicer results
        ox, oy = random.randint(0, max_jitter), random.randint(0, max_jitter)
        img.data.copy_(jitter(img.data, ox, oy))

        scores = model(img)
        correct_score = scores[:, target_y]
        correct_score.backward(torch.ones([1]))
        R_I = l2_reg * 2 * img.data
        img.grad.data -= R_I
        gradient = learning_rate * img.grad / img.grad.norm(2)
        img.data += gradient

        img.grad.data.zero_()

        # Undo the random jitter
        img.data.copy_(jitter(img.data, -ox, -oy))

        # As regularizer, clamp and periodically blur the image
        # for c in range(3):
        #     lo = float(-SQUEEZENET_MEAN[c] / SQUEEZENET_STD[c])
        #     hi = float((1.0 - SQUEEZENET_MEAN[c]) / SQUEEZENET_STD[c])
        #     img.data[:, c].clamp_(min=lo, max=hi)
        if t % blur_every == 0:
            blur_image(img.data, sigma=0.5)

        # Periodically show the image
        if t == 0 or (t + 1) % show_every == 0 or t == num_iterations - 1:
            plt.imshow(img.data.clone().cpu().squeeze(), cmap="gray")
            # class_name = class_names[target_y]
            # plt.title('%s\nIteration %d / %d' % (class_name, t + 1, num_iterations))
            plt.gcf().set_size_inches(4, 4)
            plt.axis('off')
            plt.show()

    return img.data.cpu()


#!/usr/bin/env python

from itertools import zip_longest

from .currency_converter import CurrencyConverter, CURRENCY_FILE, parse_date
from ._version import __version__

def grouper(iterable, n, fillvalue=None):
    """Group iterable by n elements.

    >>> for t in grouper('abcdefg', 3, fillvalue='x'):
    ...     print(''.join(t))
    abc
    def
    gxx
    """
    return list(zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue))

def main():
    import argparse

    parser = argparse.ArgumentParser(prog="currency_converter")
    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s, version {__version__}",
    )
    parser.add_argument("amount", type=float)
    parser.add_argument("currency")

    parser.add_argument(
        "-t",
        "--to",
        help="target currency, default is %(default)s",
        default="EUR",
    )

    parser.add_argument(
        "-d",
        "--date",
        help="date of rate, with format %%Y-%%m-%%d",
        default=None,
    )

    parser.add_argument(
        "-v",
        "--verbose",
        help=(
            "display available currencies, use twice (-vv) to "
            "also display details of missing rates completion"
        ),
        action="count",
        default=0,
    )

    parser.add_argument(
        "--decimal",
        help="use decimal.Decimal internally",
        action="store_true",
    )

    parser.add_argument(
        "-f",
        "--file",
        help="change currency file used, default is %(default)s",
        default=CURRENCY_FILE,
    )

    args = parser.parse_args()

    c = CurrencyConverter(
        currency_file=args.file,
        fallback_on_wrong_date=True,
        fallback_on_missing_rate=True,
        decimal=args.decimal,
        verbose=args.verbose > 1,
    )
    currencies = sorted(c.currencies)

    if args.verbose:
        print(f"{len(currencies)} available currencies:")
        for group in grouper(currencies, 10, fillvalue=""):
            print(" ".join(group))
        print("")

        currencies.sort(key=lambda u: c.bounds[u].last_date, reverse=True)
        currencies.sort(key=lambda u: c.bounds[u].first_date)
        for currency in currencies:
            first_date, last_date = c.bounds[currency]
            print(
                "{}: from {} to {} ({} days)".format(
                    currency, first_date, last_date, 1 + (last_date - first_date).days
                )
            )
        print("")

    if args.currency not in c.currencies:
        print(rf'/!\ "{args.currency}" is not in available currencies:')
        for group in grouper(currencies, 10, fillvalue=""):
            print(" ".join(group))
        exit(1)

    if args.date is not None:
        date = parse_date(args.date)
    else:
        date = c.bounds[args.currency].last_date

    new_amount = c.convert(
        amount=args.amount,
        currency=args.currency,
        new_currency=args.to,
        date=date,
    )

    print(f"{args.amount:,.3f} {args.currency} = {new_amount:,.3f} {args.to} on {date}")

if __name__ == "__main__":
    main()


import math
from enum import Enum
from typing import Tuple

class Collection(Enum):
    TOP_LEFT = 0
    TOP_RIGHT = 1
    BOT_LEFT = 2
    BOT_RIGHT = 3

class Zone(Enum):
    TOP_TOP = 0,
    TOP_LEFT = 1,
    TOP_CENTER = 2,
    TOP_RIGHT = 3,
    BOT_LEFT = 4,
    BOT_CENTER = 5,
    BOT_RIGHT = 6,
    BOT_BOT = 7

class Zones:

    api = None
    scanner = None

    # collection_margin = {
    #     Collection.TOP_LEFT: {"left": 50, "top": 50, "right": 50, "bottom": 50},
    #     Collection.TOP_RIGHT: {"left": 50, "top": 50, "right": 50, "bottom": 50},
    #     Collection.BOT_LEFT: {"left": 50, "top": 50, "right": 50, "bottom": 50},
    #     Collection.BOT_RIGHT: {"left": 50, "top": 50, "right": 50, "bottom": 50}
    # }

    # zone_position = {
    #     Zone.TOP_TOP: (0, -125),
    #     Zone.TOP_LEFT: (-100, -25),
    #     Zone.TOP_CENTER: (0, -25),
    #     Zone.TOP_RIGHT: (100, -25),
    #     Zone.BOT_LEFT: (-100, 25),
    #     Zone.BOT_CENTER: (0, 50),
    #     Zone.BOT_RIGHT: (100, 25),
    #     Zone.BOT_BOT: (0, 125)
    # }

    # zone_margin = {
    #     Zone.TOP_TOP: {"left": 75, "top": 0, "right": 75, "bottom": 50},
    #     Zone.TOP_LEFT: {"left": 25, "top": 50, "right": 25, "bottom": 25},
    #     Zone.TOP_CENTER: {"left": 75, "top": 50, "right": 75, "bottom": 25},
    #     Zone.TOP_RIGHT: {"left": 25, "top": 50, "right": 25, "bottom": 25},
    #     Zone.BOT_LEFT: {"left": 25, "top": 25, "right": 25, "bottom": 50},
    #     Zone.BOT_CENTER: {"left": 75, "top": 50, "right": 75, "bottom": 25},
    #     Zone.BOT_RIGHT: {"left": 25, "top": 25, "right": 25, "bottom": 50},
    #     Zone.BOT_BOT: {"left": 75, "top": 50, "right": 75, "bottom": 0}
    # }

    ## Test settings
    collection_margin = {
        Collection.TOP_LEFT: {"left": 25, "top": 25, "right": 25, "bottom": 25},
        Collection.TOP_RIGHT: {"left": 25, "top": 25, "right": 25, "bottom": 25},
        Collection.BOT_LEFT: {"left": 25, "top": 25, "right": 25, "bottom": 25},
        Collection.BOT_RIGHT: {"left": 25, "top": 25, "right": 25, "bottom": 25}
    }

    zone_position = {
        Zone.TOP_TOP: (0, -75),
        Zone.TOP_LEFT: (-50, -12.5),
        Zone.TOP_CENTER: (0, -12.45),
        Zone.TOP_RIGHT: (50, -12.5),
        Zone.BOT_LEFT: (-50, 12.5),
        Zone.BOT_CENTER: (0, 12.5),
        Zone.BOT_RIGHT: (50, 12.5),
        Zone.BOT_BOT: (0, 75)
    }

    zone_margin = {
        Zone.TOP_TOP: {"left": 25, "top": 0, "right": 25, "bottom": 50},
        Zone.TOP_LEFT: {"left": 25, "top": 12.5, "right": 25, "bottom": 12.5},
        Zone.TOP_CENTER: {"left": 25, "top": 12.5, "right": 25, "bottom": 12.5},
        Zone.TOP_RIGHT: {"left": 25, "top": 12.5, "right": 25, "bottom": 12.5},
        Zone.BOT_LEFT: {"left": 25, "top": 12.5, "right": 25, "bottom": 12.5},
        Zone.BOT_CENTER: {"left": 25, "top": 12.5, "right": 25, "bottom": 12.5},
        Zone.BOT_RIGHT: {"left": 25, "top": 12.5, "right": 25, "bottom": 12.5},
        Zone.BOT_BOT: {"left": 25, "top": 50, "right": 25, "bottom": 0}
    }

    def __init__(self, api, scanner) -> None:
        self.api = api
        self.scanner = scanner

    def at_collection(self) -> bool:
        collection = self.selected_collection()
        margin = self.collection_margin[collection]

        beacon_pos = self.selected_collection_position()
        cart_pos = self.scanner.current_cart_pos()

        beacon_margin_left      = float(beacon_pos[0] - margin["left"])
        beacon_margin_top       = float(beacon_pos[1] + margin["top"])
        beacon_margin_right     = float(beacon_pos[0] + margin["right"])
        beacon_margin_bottom    = float(beacon_pos[1] - margin["bottom"])

        in_horizontal   = beacon_margin_left < cart_pos[0] < beacon_margin_right
        in_vertical     = beacon_margin_top > cart_pos[1] > beacon_margin_bottom

        return in_horizontal and in_vertical

    def collection_from_beacon_id(self, id: int) -> Collection:
        collection_api_points = {
            0: Collection.TOP_LEFT,
            1: Collection.TOP_RIGHT,
            2: Collection.BOT_LEFT,
            3: Collection.BOT_RIGHT
        }

        return collection_api_points.get(id, None)

    def selected_collection(self) -> Collection:
        collection_api_points = {
            0: Collection.TOP_LEFT,
            2: Collection.TOP_RIGHT,
            9: Collection.BOT_LEFT,
            11: Collection.BOT_RIGHT
        }

        collection_id = self.api.webserver.collection

        return collection_api_points.get(collection_id, None)

    def in_zone(self) -> bool:
        zone = self.selected_zone()
        margin = self.zone_margin[zone]

        zone_pos = self.zone_position[zone]
        cart_pos = self.scanner.current_cart_pos()

        zone_margin_left      = float(zone_pos[0] - margin["left"])
        zone_margin_top       = float(zone_pos[1] + margin["top"])
        zone_margin_right     = float(zone_pos[0] + margin["right"])
        zone_margin_bottom    = float(zone_pos[1] - margin["bottom"])

        in_horizontal   = zone_margin_left < cart_pos[0] < zone_margin_right
        in_vertical     = zone_margin_top > cart_pos[1] > zone_margin_bottom

        return in_horizontal and in_vertical

    def selected_zone(self) -> Zone:
        zone_api_points = {
            1: Zone.TOP_TOP,
            3: Zone.TOP_LEFT,
            4: Zone.TOP_CENTER,
            5: Zone.TOP_RIGHT,
            6: Zone.BOT_LEFT,
            7: Zone.BOT_CENTER,
            8: Zone.BOT_RIGHT,
            10: Zone.BOT_BOT
        }

        zone_id = self.api.webserver.zone

        return zone_api_points.get(zone_id, None)

    def selected_collection_position(self) -> Tuple[int, int]:
        id = self.selected_collection().value

        return self.scanner.beacons[id].position

    def selected_zone_position(self) -> Tuple[int, int]:
        id = self.selected_zone()

        return self.zone_position[id]

    def selected_collection_rotation(self, x: float, y: float) -> float:
        (col_x, col_y) = self.selected_collection_position()

        delta_x = col_x - x
        delta_y = col_y - x

        rotation_radian = math.atan2(delta_x, delta_y)

        return math.degrees(rotation_radian)

    def selected_zone_rotation(self, x: float, y: float) -> float:
        (zone_x, zone_y) = self.selected_zone_position()

        delta_x = zone_x - x
        delta_y = zone_y - x

        rotation_radian = math.atan2(delta_x, delta_y)

        return math.degrees(rotation_radian)


import sys
import time

VERBOSE = False
USABLE = True
ENFORCE_VERSION = False
COERCE_DISPOSAL_METHOD = True

# If the gif provides 0 as a frame delay, use this instead
DEFAULT_FRAME_DELAY = 10
# The minimum allowed frame delay.  Any non-zero lower frame delay will be set to this instead.
MINIMUM_FRAME_DELAY = 1

# between 0 and 65535
def chr16(num):
    return chr(num % 256) + chr(num // 256)

def ord16(letters):
    return letters[0] + letters[1] * 256

class Gif_Image(object):
    def __init__(self):
        self.comments = []
        self.graphics_extension_block = False
        self.user_input_required = None
        self.disposal_method = None
        self.frame_delay = DEFAULT_FRAME_DELAY
        self.transparent_color_index = None
        self.image_block = None
        self.x = None
        self.y = None
        self.width = None
        self.height = None
        self.lzw_data = None
        self.decompressed_data = None
        self.interlaced = None
        self.color_table = None

    def set_frame_delay(self, frame_delay):
        self.frame_delay = frame_delay or DEFAULT_FRAME_DELAY
        # Enforce the minimum frame delay
        if self.frame_delay < MINIMUM_FRAME_DELAY:
            self.frame_delay = MINIMUM_FRAME_DELAY

    def clear_graphics_extension_block(self):
        self.graphics_extension_block = False
        self.user_input_required = None
        self.disposal_method = None
        self.frame_delay = None
        self.transparent_color_index = None

    def set_decompressed_data(self, data):
        self.decompressed_data = data
        self.lzw_data = None

    def decompress_data(self):
        if not self.decompressed_data and self.lzw_data:
            self.set_decompressed_data(self.lzw_data.parse_stream_data())

    def process_data(self):
        '''Set additional data after decompressing.'''
        # If the data is too short, append transparent color indexes, or default to 0, until it's the right length.
        if len(self.decompressed_data) < self.width * self.height:
            if self.transparent_color_index is None:
                color_index = 0
            else:
                color_index = self.transparent_color_index
            self.decompressed_data += bytes(
                [color_index] * (self.width * self.height - len(self.decompressed_data))
            )
        # Deinterlace if needed.
        if self.interlaced:
            self.deinterlace()
        # In some gifs transparent_color_index is beyond the end of the color table, so clamp it to the end.
        if self.transparent_color_index is not None:
            if self.transparent_color_index >= len(self.color_table):
                self.transparent_color_index = len(self.color_table) - 1

    def deinterlace(self):
        # The rows of an Interlaced image are arranged in the following order:
        #       Group 1 : Every 8th row, starting with row 0.
        #       Group 2 : Every 8th row, starting with row 4.
        #       Group 3 : Every 4th row, starting with row 2.
        #       Group 4 : Every 2nd row, starting with row 1.
        new_data = bytearray(len(self.decompressed_data))
        original_row = 0
        for interlace_range in (
                range(0, self.height, 8),
                range(4, self.height, 8),
                range(2, self.height, 4),
                range(1, self.height, 2)
        ):
            for new_row in interlace_range:
                self.add_deinterlaced_row(new_row, original_row, new_data)
                original_row += 1
        self.decompressed_data = new_data[:len(self.decompressed_data)]

    def add_deinterlaced_row(self, new_row, original_row, new_data):
        # Copy the data over from the original data one row at a time.
        new_data[new_row * self.width:new_row * self.width + self.width] = \
            self.decompressed_data[original_row * self.width:original_row * self.width + self.width]

# Counting bits starting at 0
class Gif(object):
    """class to manipulate gifs"""

    GIF87a = b'GIF87a'
    GIF89a = b'GIF89a'

    def __init__(self, filename, decompress=False, data=None):
        if VERBOSE:
            print('loading', filename)
            start_time = time.time()
        self.decompress = decompress
        self.images = []
        self.filename = filename
        if not data:
            data = open(filename, 'rb').read()
        self.data = data
        self.version = data[:6]
        assert self.version in (self.GIF87a, self.GIF89a)
        # Where in self.data is the next piece of data, if variability is needed.
        self.tell = 6
        self.parse_headers()
        self.current_image = None
        self.parse_blocks()
        if VERBOSE:
            print('took %.2f seconds' % (time.time() - start_time))

    def __repr__(self):
        return '<Gif: "%s" %s>' % (self.filename, self.dims)

    def parse_headers(self):
        self.dims = (ord16(self.data[6:8]), ord16(self.data[8:10]))

        screen_descriptor = self.data[10]
        # bits 0-2 are the bits pixel in the image minus 1 (0-7 => 1-8)
        global_color_table_entry_size = 1 + (screen_descriptor & 7)
        # the number of entries in the global color table can be calculated as such
        global_color_table_entries = 1 << global_color_table_entry_size  # = 2 ** global_color_table_entry_size
        # bit 3 is whether the global color table is sorted by most used colors
        self.global_color_table_sorted = screen_descriptor & 8
        if self.global_color_table_sorted and self.version == self.GIF87a:
            self.global_color_table_sorted = 0
        # bits 4-6 are the bits in an entry of the original color palette minus 1 (0-7 => 1-8)
        self.color_resolution = 1 + (screen_descriptor >> 4 & 7)  # bitshift to go to bits 0-2, then (1 + 2 + 4)
        # bit 7 is whether the global color table exists
        self.global_color_table_exists = bool(screen_descriptor & 128)

        # The index in the global color table (if it exists) for the background of the screen
        self.background_color_index = self.data[11]

        # The aspect ratio of a pixel. I'm going to ignore it.
        # the ratio defines width:height
        aspect_ratio_byte = self.data[12]
        if aspect_ratio_byte:
            # This is the specific math it uses to define the ratio
            self.pixel_aspect_ratio = (aspect_ratio_byte + 15) / 64
        else:
            # If not set then it's disabled
            self.pixel_aspect_ratio = 1
        self.tell = 13
        if self.global_color_table_exists:
            self.global_color_table = self.parse_color_table(global_color_table_entries)
        else:
            self.global_color_table = []

    def parse_color_table(self, table_entries):
        bytes = 3 * table_entries
        data = self.data[self.tell:self.tell + bytes]
        self.tell += bytes
        return [data[i:i+3] for i in range(0, bytes, 3)]

    def parse_blocks(self):
        while 1:
            try:
                separator = self.data[self.tell]
            # Some gifs don't include the end of file char.
            except IndexError:
                break
            self.tell += 1
            # '\x3b' = 59 is the end of file char
            if separator == 59:
                break
            if self.current_image is None:
                # graphics extension block, image block
                self.current_image = Gif_Image()
            # '\x2c' = 44 is the local image block
            if separator == 44:
                self.parse_image_block()
                self.images.append(self.current_image)
                self.current_image = None
            elif separator == 33:  # 89a '\x21' = 33
                if ENFORCE_VERSION and self.version == self.GIF87a:
                    raise GIFError('87a gif has 89a block')
                label = self.data[self.tell]
                self.tell += 1
                if label == 249:  # '\xf9' = 249
                    self.parse_graphics_control_block()
                elif label == 1:  # '\x01' = 1
                    self.parse_plain_text_block()
                elif label == 255:  # '\xff' = 255
                    self.parse_application_block()
                elif label == 254:  # '\xfe' = 254
                    self.parse_comment_block()
                else:
                    raise GIFError('Unknown \\x21/33 block label %s' % label)
            elif separator == 0:  # Invalid, but probably a dangling terminator.
                continue
            else:
                raise GIFError('Unknown separator label %s' % separator)

    def parse_image_block(self):
        self.current_image.x = ord16(self.data[self.tell:self.tell + 2])
        self.tell += 2
        self.current_image.y = ord16(self.data[self.tell:self.tell + 2])
        self.tell += 2

        self.current_image.width = ord16(self.data[self.tell:self.tell + 2])
        self.tell += 2
        self.current_image.height = ord16(self.data[self.tell:self.tell + 2])
        self.tell += 2

        packed = self.data[self.tell]
        self.tell += 1
        # Bits 0-2 The size of the local color table (see same bits for global color table)
        color_table_entry_size = 1 + (packed & 7)  # (1 + 2 + 4)
        color_table_entries = 1 << color_table_entry_size  # = 2 ** color_table_entry_size
        # Bits 3-4 Reserved
        # Bit 5 Is the local color table sorted
        self.current_image.color_table_sorted = packed & 32
        # Sorted color table isn't allowed in 87a
        if self.current_image.color_table_sorted and ENFORCE_VERSION and self.version == self.GIF87a:
            self.current_image.color_table_sorted = 0
        # Bit 6 Is the image interlaced
        self.current_image.interlaced = bool(packed & 64)
        # Bit 7 Is there a local color table
        local_color_table = bool(packed & 128)

        if local_color_table:
            self.current_image.color_table = self.parse_color_table(color_table_entries)
        else:
            # Use the global color table if there's no local one
            self.current_image.color_table = self.global_color_table
        # Find cases where the transparent index is out of bounds and force it off.
        # TODO See if there's a usual way to handle this.
        if self.current_image.transparent_color_index is not None and self.current_image.transparent_color_index > len(self.current_image.color_table):
            self.current_image.transparent_color_index = None
        self.current_image.lzw_data = self.parse_image_data()
        if self.decompress:
            self.current_image.decompress_data()

    def parse_image_data(self):
        # Make these local due to the tight loops.
        tell = self.tell
        data = self.data
        lzw_data = bytearray()
        minimum_lzw_code_size = data[tell]
        tell += 1
        while 1:
            length = data[tell]
            if not length:
                break
            # This tell usage is backwards from the norm so we can do a single assignment to self.tell.
            tell += length + 1
            lzw_data += data[tell - length:tell]
        # Re-assign to self.tell and add 1 from the length check that was just done.
        self.tell = tell + 1
        return Gif_LZW(minimum_lzw_code_size, lzw_data)

    def parse_graphics_control_block(self):
        block_size = self.data[self.tell]
        if block_size != 4:
            raise GIFError(
                'Unexpected block size in graphics control extension block (expected 4, got %d)' % block_size
            )
        self.tell += 1
        self.current_image.graphics_extension_block = True
        packed_bit = self.data[self.tell]
        self.tell += 1
        # Bit 0 Is the later color index byte has data
        has_transparent_color_index = packed_bit & 1
        # Bit 1 Is user input is required to move to the next image (ignored)
        self.current_image.user_input_required = packed_bit & 2
        # Bits 2-4 Gives one of 4 methods to dispose of the previous image
        disposal_method = packed_bit >> 2 & 7  # bitshift to go to bits 0-2, then (1 + 2 + 4)
        if disposal_method > 3:
            if COERCE_DISPOSAL_METHOD:
                disposal_method = 0
            else:
                raise GIFError(
                    'Previous image disposal method is invalid (expected 0, 1, 2, or 3, got %d' % disposal_method
                )
        self.current_image.disposal_method = disposal_method
        # Bits 5-7 last 3 bits are reserved
        # Set frame delay, or use the default if it's zero.
        self.current_image.set_frame_delay(ord16(self.data[self.tell:self.tell + 2]))
        self.tell += 2
        if has_transparent_color_index:
            self.current_image.transparent_color_index = self.data[self.tell]
        else:
            self.current_image.transparent_color_index = None
        self.tell += 1
        if self.data[self.tell] != 0:
            raise GIFError('Graphics control block terminator not found')
        self.tell += 1

    # Ignored
    def parse_plain_text_block(self):
        # block is 15 bytes long, the first 2 are read in parse_blocks(), and last 1 is terminator
        self.tell += 12
        if self.data[self.tell] != 0:
            raise GIFError('Plain text block terminator not found')
        self.tell += 1
        # graphics extension block affects the next block of plain text or image type. Since we're ignoring plain text,
        #  drop the related graphics extension info
        if self.current_image.graphics_extension_block:
            self.current_image.clear_graphics_extension_block()

    # Ignored
    def parse_application_block(self):
        # Block header indicates this is 11 bytes long, so jump forward this 1 byte and those 11.
        self.tell += 12
        data_length = self.data[self.tell]
        # Process sub-blocks until a 0.
        while data_length:
            self.tell += data_length + 1
            data_length = self.data[self.tell]
        self.tell += 1

    def parse_comment_block(self):
        # Process sub-blocks until a 0.
        while 1:
            comment_length = self.data[self.tell]
            self.tell += 1
            if not comment_length:
                break
            self.current_image.comments.append(self.data[self.tell:self.tell + comment_length])
            self.tell += comment_length

class Gif_LZW(object):
    # If the code table has reached the 2**12 limit, the code table may not be added to
    maximum_bit_size = 12

    bit_ands = [2 ** i - 1 for i in range(13)]

    def __init__(self, minimum_size, data):
        self.minimum_size = minimum_size
        self.clear_code = 1 << self.minimum_size
        self.end_of_information_code = self.clear_code + 1

        # The code_table will be reset to the inside of reset_code_table.
        self.code_table = []
        self.default_code_table = [None] * (1 << self.maximum_bit_size)
        self.default_code_table[:1 << minimum_size] = [bytes((i,)) for i in range(1 << minimum_size)]

        self.stream = bytearray()
        self.data = data

    def _get_next_code(self):
        value_buffer = 0
        value_buffer_bits = 0
        bit_ands = self.bit_ands
        code_size = self.code_size
        for byte in self.data:
            if value_buffer_bits >= code_size:
                value = value_buffer & bit_ands[code_size]
                value_buffer >>= code_size
                value_buffer_bits -= code_size
                yield value
                code_size = self.code_size
            value_buffer += (byte << value_buffer_bits)
            value_buffer_bits += 8

    def parse_stream_data(self):
        self.reset_code_table()
        get_next_code = self._get_next_code()
        while 1:
            response = self._parse_stream_data(get_next_code)
            # Fake tail recursion by returning end_of_information_code.
            if response == self.end_of_information_code:
                continue
            else:
                break
        return self.stream

    def _parse_stream_data(self, get_next_code):
        # Localize variable due to the loop.
        next_code_index = self.next_code_index
        code_table = self.code_table
        clear_code = self.clear_code
        end_of_information_code = self.end_of_information_code
        stream = self.stream
        # The code table is only allowed to grow to a specific size.
        table_immutable = False
        prev_code = clear_code
        # Some gifs don't respect the standard, so we don't ensure there's at least one clear code.
        # The while loop is because clear codes can appear at any time, even right after another one.
        while prev_code == clear_code:
            try:
                prev_code = next(get_next_code)
            except StopIteration:
                return
            if prev_code == end_of_information_code:
                return
        # The first code must be in the initial code table.
        stream += code_table[prev_code]
        for code in get_next_code:
            # If it's going to reference an existing code.
            if code < next_code_index:
                # Handle clear code and end of info code.
                if code == clear_code:
                    self.reset_code_table()
                    # No tail recursion, so here we are. Wipe out prev_code like this.
                    return self.end_of_information_code
                if code == end_of_information_code:
                    return
                K_code = code
            # If it's referencing a new code.
            else:
                K_code = prev_code

            # If the code table can still grow.
            if not table_immutable:
                # This is what the gif LZW algorithm does to add entries to the code table.
                # K_code depends on the above if/else block.
                code_table[next_code_index] = code_table[prev_code] + bytes((code_table[K_code][0],))
                next_code_index += 1
                # If the code index is crossing the next threshold (2**x).
                if next_code_index == self.next_code_table_grow:
                    if self.code_size == self.maximum_bit_size:
                        # Gifs aren't allowed to grow beyond this hard limit per code.
                        table_immutable = True
                    else:
                        self.set_code_size(self.code_size + 1)
            # Add to the stream.
            stream += code_table[code]
            # Set the previous code for the next loop.
            prev_code = code
        return 0

    def reset_code_table(self):
        self.code_table[:] = self.default_code_table
        # Track what the next index for a code in self.code_table will be.
        self.next_code_index = self.end_of_information_code + 1
        self.set_code_size(self.minimum_size + 1)

    def set_code_size(self, size):
        self.code_size = size
        self.next_code_table_grow = 1 << size

    def assure_clear_code(self, code):
        if code != self.clear_code:
            raise GIFError('Expected clear code, got something else (%d != %d)' % (self.clear_code, code))

class GIFError(Exception):
    pass

def fit_to(start_dims, dims=(1920, 1080)):
    width, height = start_dims
    w = dims[0] / width
    h = dims[1] / height
    if w < h:
        w2 = dims[0]
        h2 = height * w
    else:
        w2 = width * h
        h2 = dims[1]
    return (int(float(w2)), int(float(h2)))

# Threaded decompression, doesn't speed up with the python implementation of LZW.
def decompress_gif(g):
    from dmgen import threaded_worker, gen, cores
    with gen.timer():
        with threaded_worker.threaded_worker(threads=max(1, cores.CORES - 1)) as tw:
            for i in g.images:
                tw.put(i.decompress_data)
            for i in g.images:
                tw.get()

# Multiprocessed decompression, does speed up with the python implementation of LZW.
def decompress_gif_mp(g):
    from dmgen import gen, cores
    import multiprocessing as mp
    q_put = mp.Queue()
    q_get = mp.Queue()
    args = (q_put, q_get)
    processes = []
    with gen.timer():
        # Start the processes.
        for i in range(max(1, cores.CORES)):
            p = mp.Process(target=atomic_decompress, args=args)
            p.daemon = True
            p.start()
            processes.append(p)
        # Put the data.
        for index, data in enumerate(g.images):
            q_put.put((index, data))
        # Put the data to end the processes.
        for i in range(len(processes)):
            q_put.put(0)
        # Get the data and set on the objects.
        for i in g.images:
            index, data = q_get.get()
            g.images[index].set_decompressed_data(data)

# Multiprocess target function for decompression.
def atomic_decompress(q_get, q_put):
    while 1:
        # Get the data.
        data = q_get.get()
        # End process if no value.
        if not data:
            return
        # Run the function and return the data.
        index, gif_img = data
        gif_img.decompress_data()
        q_put.put((index, gif_img.decompressed_data))


from django.shortcuts import render
from django.http import HttpResponseRedirect,Http404
from django.urls import reverse
from .models import Topic,Entry
from .forms import TopicForm,EntryForm
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
    return render(request, 'learning_logs/index.html')

@login_required
def topics(request):
    """display all theme"""
    topics = Topic.objects.filter(owner=request.user).order_by('date_added')
    #topics = Topic.objects.filter(owner=user).order_by('date_added')
    context = {'topics':topics}
    return render(request,'learning_logs/topics.html',context)

@login_required
def topic(request,topic_id):
    """display a single theme and it`s all items"""
    topic = Topic.objects.get(id=topic_id)
    """ensure the requested theme belong to current user"""
    if topic.owner != request.user:
        raise Http404
    entries = topic.entry_set.order_by('date_added')
    context = {'topic':topic,'entries':entries}
    return render(request,'learning_logs/topic.html',context)

@login_required
def new_topic(request):
    """add a new theme"""
    if request.method != 'POST':
        """not submit data:create a new form"""
        form = TopicForm()
    else:
        """POST submitted data to manage"""
        form = TopicForm(request.POST)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user
            new_topic.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))

    context = {'form':form}
    return render(request,'learning_logs/new_topic.html',context)

@login_required
def new_entry(request,topic_id):
    """add a new entry in a certain topic"""
    topic = Topic.objects.get(id=topic_id)

    if request.method != 'POST':
        """not post data,create a null form"""
        form = EntryForm
    else:
        """manage the posted data"""
        form = EntryForm(data=request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id]))

    context = {'topic':topic,'form':form}
    return render(request,'learning_logs/new_entry.html',context)

@login_required
def edit_entry(request,entry_id):
    """edit existed items """
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    """ensure the requested theme belong to current user"""
    if topic.owner != request.user:
        raise Http404
    if request.method != 'POST':
        """first request,use current item to fill the form"""
        form = EntryForm(instance=entry)
    else:
        """get the data from the POST and deal with it"""
        form = EntryForm(instance=entry,data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id]))

    context = {'entry':entry,'topic':topic,'form':form}
    return render(request,'learning_logs/edit_entry.html',context)

@login_required
def del_entry(request,entry_id):
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    entry.delete()
    return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id]))


# coding: utf-8
import boto3
session = boto3.Session(profile_name='default')
session
ec2 = session.resource('ec2')
ec2
key_name
key_name = 'auto_key'
key_path = key_name + '.pem'
key = ec2.create_key_pair(KeyName=key_name)
key.key_material
with open(key_path, 'w') as key_file:
    key_file.write(key.key_material)

get_ipython().run_line_magic('ls', '-l auto_key.pem')
import os, stat
os.chmod(key_path, stat.S_IRUSR | stat.S_IWUSR)
get_ipython().run_line_magic('ls', '-l auto_key.pem')
ec2.images.filter(Owners=['amazon'])
list(ec2.images.filter(Owners=['amazon']))
len(list(ec2.images.filter(Owners=['amazon'])))
img = ec2.Image('ami-0c6b1d09930fac512')
img.name
ami_name = 'amzn2-ami-hvm-2.0.20190508-x86_64-gp2'
filters = [{'Name': 'name', 'Vaules': [ami_name]}]
list(ec2.images.filter(Owners=['amazon'], Filters=filters))
filters = [{'Name': 'name', 'Values': [ami_name]}]
list(ec2.images.filter(Owners=['amazon'], Filters=filters))
img
instances = ec2.create_instances(ImageId=img.id, MinCount=1, MaxCount=1, InstanceType='t2.micro', KeyName=key.key_name)
instance
instances
instances
ec2.Instance(id='i-0252aa153d68d58c4')
inst = instances[0]
inst.terminate()
instances = ec2.create_instances(ImageId=img.id, MinCount=1, MaxCount=1, InstanceType='t2.micro', KeyName=key.key_name)
inst = instances[0]
inst.public_dns_name
inst.wait_until_running()
inst.reload()
inst.public_dns_name
inst.security_groups()
inst.security_groups
inst.public_ip_address
# Look up the security group
#Autorize incoming connections from out public IP address. on port 22 (the port SSH uses)
sec_group = ec2.describe_security_groups(GroupIds=['sg-38213147'])
sec_group = inst.describe_security_groups(GroupIds=['sg-38213147'])
security_group = ec2.SecurityGroup('sg-38213147')
security_group
sg = security_group
sg
sg = ec2.SecurityGroup(inst.security_groups[0]['GroupId'])
sg
sg.authorize_ingress(IpPermissions=[{'FromPort': 22, 'ToPort': 22, 'IpProtocol': 'TCP', 'IpRanges':[{'CidrIp': '24.226.120.5/32', 'Description': 'my-ip-address'}]}])
get_ipython().run_line_magic('history', '')


def slice_clip(filename, start, stop, n_samples, sr, mono=True):
    '''Slice a fragment of audio from a file.

    This uses pysoundfile to efficiently seek without
    loading the entire stream.

    Parameters
    ----------
    filename : str
        Path to the input file

    start : int
        The sample index of `filename` at which the audio fragment should start

    stop : int
        The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop])

    n_samples : int > 0
        The number of samples to load

    sr : int > 0
        The target sampling rate

    mono : bool
        Ensure monophonic audio

    Returns
    -------
    y : np.ndarray [shape=(n_samples,)]
        A fragment of audio sampled from `filename`

    Raises
    ------
    ValueError
        If the source file is shorter than the requested length

    '''

    with psf.SoundFile(str(filename), mode='r') as soundf:
        n_target = stop - start

        soundf.seek(start)

        y = soundf.read(n_target).T

        if mono:
            y = librosa.to_mono(y)

        # Resample to initial sr
        y = librosa.resample(y, soundf.samplerate, sr)

        # Clip to the target length exactly
        y = librosa.util.fix_length(y, n_samples)

        return y


def split(code):
    return [line for line in code]

num2words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \
             6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \
            11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', \
            15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', \
            19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', \
            50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', \
            90: 'Ninety', 0: 'Zero'}

def n2w(n):
    n = int(n)
    try:
        return num2words[n]
    except KeyError:
        try:
            print
            num2words[n - n % 10] + num2words[n % 10].lower()
        except KeyError:
            print('Number out of range')


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
        def getDiffMinMax(root):
            if not root.left and not root.right:  # leaf node
                return 0, root.val, root.val
            elif root.left and not root.right:  # root.right is None
                left_diff, left_min, left_max = getDiffMinMax(root.left)
                diff = max(left_diff, root.val - left_min, left_max - root.val)
                root_min, root_max = min(root.val, left_min), max(root.val, left_max)
            elif root.right and not root.left:  # root.left is None
                right_diff, right_min, right_max = getDiffMinMax(root.right)
                diff = max(right_diff, root.val - right_min, right_max - root.val)
                root_min, root_max = min(root.val, right_min), max(root.val, right_max)
            else:
                left_diff, left_min, left_max = getDiffMinMax(root.left)
                right_diff, right_min, right_max = getDiffMinMax(root.right)
                root_max = max(left_max, right_max, root.val)
                root_min = min(left_min, right_min, root.val)
                diff1 = max(root.val - min(left_min, right_min), max(left_max, right_max) - root.val)
                diff2 = max(left_diff, right_diff)
                diff = max(diff1, diff2)
            return diff, root_min, root_max

        return getDiffMinMax(root)[0]


import os
import random

from casting.actor import Actor
from casting.cast import Cast

from directing.director import Director

from services.keyboard_service import KeyboardService
from services.video_service import VideoService

from shared.color import Color
from shared.point import Point

FRAME_RATE = 15
MAX_X = 900
MAX_Y = 600
CELL_SIZE = 15
FONT_SIZE = 15
COLS = 60
CAPTION = "Greed"
WHITE = Color(255, 255, 255)

def main():

    # create the cast
    cast = Cast()

    # create the banner
    banner = Actor()
    banner.set_text("Points: 0")
    banner.set_font_size(FONT_SIZE)
    banner.set_color(WHITE)
    banner.set_position(Point(CELL_SIZE, 0))
    cast.add_actor("banners", banner)

    # create the miner
    x = int(MAX_X / 2)
    y = int(MAX_Y)-int(CELL_SIZE)
    position = Point(x, y)

    miner = Actor()
    miner.set_text("#")
    miner.set_font_size(FONT_SIZE)
    miner.set_color(WHITE)
    miner.set_position(position)
    cast.add_actor("miners", miner)

    # start the game
    keyboard_service = KeyboardService(CELL_SIZE)
    video_service = VideoService(CAPTION, MAX_X, MAX_Y, CELL_SIZE, FRAME_RATE)
    director = Director(keyboard_service, video_service, CELL_SIZE, FONT_SIZE)
    director.start_game(cast)

if __name__ == "__main__":
    main()


from flask import Flask, request, jsonify
import cv2
import numpy as np
import os
import base64

from eyebrow_suggestion import EyebrowShapingWaySuggestion
from makeup_suggestion import MakeoverSuggestion

app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
OUTPUT_FOLDER = 'processed'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER

# Create the upload folder if it doesn't exist
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
if not os.path.exists(OUTPUT_FOLDER):
    os.makedirs(OUTPUT_FOLDER)

obj = EyebrowShapingWaySuggestion()
msobj = MakeoverSuggestion()

@app.route('/process-image', methods=['POST'])
def upload_file():
    # Check if an image file is present in the request
    if 'image' not in request.files:
        return jsonify({'error': 'No image uploaded'}), 400

    # Get the uploaded file
    file = request.files['image']

    filename = file.filename
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    file.save(filepath)

    img, msg = obj.main(filepath)

    processed_image = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_COLOR)
    output_filename = f"processed_{filename}"
    output_filepath = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)
    cv2.imwrite(output_filepath, img)

    with open(output_filepath, 'rb') as f:
        encoded_image = base64.b64encode(f.read()).decode('utf-8')

    skin_tone, suggested_makeup = msobj.main(filepath)

    arr_string = ', '.join(str(x) for x in suggested_makeup)

    makeovers = f"Suggested Makeup for {skin_tone} skin tone: {arr_string}"
    response = {'message': msg,
                'processed_image': encoded_image,
                'makeover': makeovers}
    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True)


"""
Graph Mining - ALTEGRAD - Dec 2019
"""

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import collections

############## Task 1

##################
# your code here #

path = '../datasets/CA-HepTh.txt'
G = nx.read_edgelist(path, comments='#', delimiter='\t')
nr_nodes = G.number_of_nodes()
nr_edges = G.number_of_edges()
print('Number of nodes from graph G: ', nr_nodes)
print('Number of edges from graph G: ', nr_edges)

##################

############## Task 2

##################
# your code here #

#number of connected components
# Option 1
nr_connect_comp = sum(1 for _ in nx.connected_components(G))
print('Number of connected components: ',nx.algorithms.components.number_connected_components(G))
# Option 2
print('Number of connected components: ', nr_connect_comp)

if not nx.is_connected(G):
	# the largest connected component
	largest_cc = max(nx.connected_components(G), key=len)
	nr_nodes_largest_cc = len(largest_cc)
	subgraph_largest_cc = G.subgraph(list(largest_cc))
	nr_edges_largest_cc = subgraph_largest_cc.number_of_edges()
	print('Number of nodes from the largest connected component: ', nr_nodes_largest_cc)
	print('Number of edges from the largest connected component: ', nr_edges_largest_cc)
	print('Fraction nodes: ', nr_nodes_largest_cc / nr_nodes)
	print('Fraction edges: ', nr_edges_largest_cc / nr_edges)

##################

############## Task 3
# Degree
degree_sequence = [G.degree(node) for node in G.nodes()]

##################
# your code here #
min_degree = np.min(degree_sequence)
print('Minimum degree: ', min_degree)

max_degree = np.max(degree_sequence)
print('Maximum degree: ', max_degree)

mean_degree = np.mean(degree_sequence)
print('Mean degree: ', mean_degree)

##################

############## Task 4

##################
# your code here #

degreeCount = collections.Counter(degree_sequence)
deg, cnt = zip(*degreeCount.items())

fig1, ax1 = plt.subplots()
plt.bar(deg, cnt, width=0.80, color='r')

plt.title("Degree Histogram")
plt.ylabel("Frequency")
plt.xlabel("Degree")

ax1.plot()
fig1.savefig("degree_histogram.pdf")

fig2, ax2 = plt.subplots()
plt.bar(deg, cnt, width=0.80, color='g')

plt.title("log-log Degree Histogram")
plt.ylabel("Frequency")
plt.xlabel("Degree")

ax2.set_yscale('log')
ax2.set_xscale('log')

fig2.savefig("degree_histogram_log.pdf")

plt.show()

##################


import pyControl.hardware as _h
import pyControl.audio as _a

class Audio_poke():
    # Single IR beam, LED and Solenoid.  Audio amplifier to drive speaker.
    def __init__(self, port, rising_event = None, falling_event = None, debounce = 5):
        assert port.DAC is not None, '! Audio poke needs port with DAC.'
        self.input = _h.Digital_input(port.DIO_A, rising_event, falling_event, debounce)
        self.LED = _h.Digital_output(port.POW_A)
        self.SOL = _h.Digital_output(port.POW_B)
        if port.POW_C is not None:
            self.POW_C = _h.Digital_output(port.POW_C)
        self.audio_output = _a.Audio_output(port.DAC)

    def value(self):
        return self.input.value()


#coding:utf-8
"""
数据来源: http://data.eastmoney.com/cjsj/gdp.html

注意, 官方公布的GDP数据是名义GDP数据, 但是公布的GDP增速是GDP平减指数, 也就是减掉了物价指数之后的增速
"""

import pandas as pd
import matplotlib.pyplot as plt

names = ['季度']
for a in ['国内生产总值', '第一产业', '第二产业', '第三产业']:
    for b in ['绝对值(亿元)', '同比']:
        names.append(a + '-' + b)
df = pd.read_csv('./data.csv', header=None, names=names, sep=r'\s+')

df.set_index('季度')['国内生产总值-绝对值(亿元)'][::-4].plot(figsize=(10, 6), grid='on')
f = plt.gcf()
f.savefig('data.svg')

html = df.to_html(index=False)

gdp = pd.read_csv('gdp.csv')
gdp_sort = gdp.sort_values(by='时间').set_index('时间')
(gdp_sort[['第一产业增加值(亿元)','第二产业增加值(亿元)','第三产业增加值(亿元)']].apply(lambda x: x/gdp_sort['国内生产总值(亿元)'])).plot.bar(stacked=True, figsize=(12, 5), grid='on')
plt.title(u'GDP各产业结构')
f = plt.gcf()
f.savefig('gdp-struct.svg')

gdp_sort[-30:].plot(grid='on', figsize=(10, 6))
f = plt.gcf()
f.savefig('gdp.svg')
gdp_html = gdp.to_html(index=False)

gdp_inc = (gdp_sort / gdp_sort.shift(1) - 1)*100
gdp_inc = gdp_inc[['国内生产总值(亿元)']][-20:]
gdp_inc.columns = ['同比增长']
gdp_inc.plot(grid='on', figsize=(10, 6), style='o-')
plt.title(u'名义GDP年增长率')
f = plt.gcf()
f.savefig('gdp_inc.svg')

with open('data.html', 'w') as fp:
    fp.write('<meta content="text/html; charset=utf-8" http-equiv="content-type" /><style ' \
             'type="text/css">' \
             'table {border-collapse: collapse; margin-top:20px;}' \
             'th, td {border: 1px solid;}' \
             '</style>')
    fp.write(open('data.svg').read())
    fp.write(open('gdp.svg').read())
    fp.write(open('gdp_inc.svg').read())
    fp.write(open('gdp-struct.svg').read())
    fp.write(gdp_html.encode('utf-8', 'ignore'))
    fp.write(html.encode('utf-8', 'ignore'))


def write_nexus_files(self, force=False, quiet=False):
        """
        Write nexus files to {workdir}/{name}/[0-N].nex, If the directory already
        exists an exception will be raised unless you use the force flag which
        will remove all files in the directory.

        Parameters:
        -----------
        force (bool):
            If True then all files in {workdir}/{name}/*.nex* will be removed.

        """

        ## clear existing files
        existing = glob.glob(os.path.join(self.workdir, self.name, "*.nex"))
        if any(existing):
            if force:
                for rfile in existing:
                    os.remove(rfile)
            else:
                path = os.path.join(self.workdir, self.name)
                raise IPyradWarningExit(EXISTING_NEX_FILES.format(path))

        ## parse the loci or alleles file
        with open(self.files.data) as infile:
            loci = iter(infile.read().strip().split("|\n"))

        ## use entered samples or parse them from the file
        if not self.samples:
            with open(self.files.data) as infile:
                samples = set((i.split()[0] for i in infile.readlines() \
                               if "//" not in i))
        else:
            samples = set(self.samples)

        ## keep track of how many loci pass filtering
        totn = len(samples)
        nloci = 0

        ## this set is just used for matching, then we randomly
        ## subsample for real within the locus so it varies
        if self._alleles:
            msamples = {i+rbin() for i in samples}
        else:
            msamples = samples

        ## write subsampled set of loci
        for loc in loci:
            ## get names and seqs from locus
            dat = loc.split("\n")[:-1]
            try:
                names = [i.split()[0] for i in dat]
                snames = set(names)
                seqs = np.array([list(i.split()[1]) for i in dat])
            except IndexError:
                print(ALLELESBUGFIXED)
                continue

            ## check name matches
            if len(snames.intersection(msamples)) == totn:

                ## prune sample names if alleles. Done here so it is randomly
                ## different in every locus which allele is selected from
                ## each sample (e.g., 0 or 1)
                if self._alleles:
                    _samples = [i+rbin() for i in samples]
                else:
                    _samples = samples

                ## re-order seqs to be in set order
                seqsamp = seqs[[names.index(tax) for tax in _samples]]

                ## resolve ambiguities randomly if .loci file otherwise
                ## sample one of the alleles if .alleles file.
                if not self._alleles:
                    seqsamp = _resolveambig(seqsamp)

                ## find parsimony informative sites
                if _count_PIS(seqsamp, self.params.minsnps):
                    ## keep the locus
                    nloci += 1

                    ## remove empty columns given this sampling
                    copied = seqsamp.copy()
                    copied[copied == "-"] == "N"
                    rmcol = np.all(copied == "N", axis=0)
                    seqsamp = seqsamp[:, ~rmcol]

                    ## write nexus file
                    if self._alleles:
                        ## trim off the allele number
                        samps = [i.rsplit("_", 1)[0] for i in _samples]
                        mdict = dict(zip(samps, [i.tostring() for i in seqsamp]))
                    else:
                        mdict = dict(zip(_samples, [i.tostring() for i in seqsamp]))
                    self._write_nex(mdict, nloci)

                    ## quit early if using maxloci
                    if nloci == self.params.maxloci:
                        break

        ## print data size
        if not quiet:
            path = os.path.join(self.workdir, self.name)
            path = path.replace(os.path.expanduser("~"), "~")
            print("wrote {} nexus files to {}".format(nloci, path))


from debug import Debug

d = Debug()
log = d.get_logger()

class Linker():
    def __init__(self):
        self._curr_ = None
        self._prev_ = None
    def on(self,n,e,context):

        if e is None:
            return (n,e)
        if self._prev_ is None:
            self._prev_ = e[1]

        self._curr_  = e[1]
        edge = (self._prev_, self._curr_)
        self._prev_  = self._curr_

        # remove cycles
        if edge[0] == edge[1]:
            return (n,None)

        return (n,edge)

class RankNeighbours():
    def __init__(self):
        self._prev_ = None
        self._curr_ = None
        self._vertex_context_ = None
        pass

    def on(self,n,e,context):
        if e is None:
            return (n,e)

        if self._vertex_context_ is None  or self._vertex_context_ != n :
            self._vertex_context_ = n
            self._prev_ = None

        if self._prev_ is None:
            self._prev_ = n

        self._curr_ = e[1]

        log ("vertex_context = %s" % self._vertex_context_)
        log ("node=%s" % n )
        log ("edge=%s" % str(e) )
        log ("prev=%s" % self._prev_)
        log ("curr=%s" % self._curr_ )

        edge = (self._prev_,self._curr_)
        log ("new edge: %s" % str(edge))

        self._prev_ =  self._curr_
        log  ("-------------------------------__")
        return (n,edge)


# -*- coding:utf-8 -*-
__author__ = 'evaseemefly'
__date__ = '2018/3/10 12:46'

import json
from datetime import datetime,date,timedelta,time
from django.forms.models import model_to_dict

def query2json(query_set):
    json_list=[]
    for model in query_set:
        obj=model_to_dict(model)
        '''
        To use a custom JSONEncoder subclass
         (e.g. one that overrides the default() method to serialize additional types),
         specify it with the cls kwarg; otherwise JSONEncoder is used.
        '''
        dic=json.dumps(obj,cls=CJsonEncoder)
        json_list.append(dic)
    return json_list

class CJsonEncoder(json.JSONEncoder):
    '''
    自定义的json序列化类，需要重写default方法
    '''
    def default(self, obj):
        '''
        解决date无法序列化的问题
        若传入的obj是一个date则str成 yyyy-mm-dd的
        :param obj:
        :return:
        '''
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, obj)


#HAMMING DISTNACE IS THE NUMBER OF POSITIONS BETWEEN 2 STRINGS OF EQUAL LENGTH WHERE THE
# CORRESPONDING SYMBOLS ARE DIFFERENT. MOSTLY APPLIED IN CODING THEORY AND COMMUNICATIONS
def hammingDistance(x, y):
    if type(x) and type(y)==str:
        if len(x)==len(y):
            hamming=0
            i = 0
            s1, s2 = [], []
            [[s1.append(ord(val))] for val in x] # the ord function returns the ASCII
            # equivalent of a letter
            [[s2.append(ord(val))] for val in y]
            for x in s1:
                if x!=s2[i]: # assumption, strings are of equal length
                    hamming+=1
                i+=1
            return hamming
        else:
            return "Strings not of equal length"

    elif type(x) and type(y)==int:
        return bin(x ^ y).count('1')
    else:
        return "Unknown format of inputs"
    # bin converts int to binary string
    # x^y is a logical operator which produces 0 when digits in corresponding positions match
    # and 1 if otherwise

print(hammingDistance(2,10))
protein_sequence1="GAATGCAGATGGACTCTAGA"
protein_sequence2="GAATAGCTAATCACTCTAGA"
print(hammingDistance(protein_sequence1,protein_sequence2))
print("There is a",
      int((len(protein_sequence1)-hammingDistance(protein_sequence1,protein_sequence2))/len(protein_sequence1)*100),
"% match between the 2 protein sequences")


import tempfile
import unittest
from pathlib import Path

from team.recorders.demonstration_recorder import DemonstrationRecorder

class RecordersTest(unittest.TestCase):
    def test_demonstration_recorder_filename(self):
        tempfile.tempdir = "./tmp"
        tmp_dir = tempfile.gettempdir()
        recorder = DemonstrationRecorder(data_path=tmp_dir)
        file_name = Path(recorder.next_filename).name
        self.assertEqual(file_name, "demonstration_1.json")

        f1 = tempfile.NamedTemporaryFile(suffix=".json", dir="./tmp")  # noqa
        file_name = Path(recorder.next_filename).name
        self.assertEqual(file_name, "demonstration_2.json")

        f2 = tempfile.NamedTemporaryFile(suffix=".json", dir="./tmp")  # noqa
        file_name = Path(recorder.next_filename).name
        self.assertEqual(file_name, "demonstration_3.json")


from sklearn import (preprocessing)
from csv_reader import csvReader
from skl_preped_models import (submission_models)
import numpy as np
import time

def one_hot_encoding(X_train, X_test=None):
    encoder = preprocessing.OneHotEncoder()

    if X_test == None:
        encoder.fit(X_train)
        X_train = encoder.transform(X_train)
    else:
        encoder.fit(np.vstack((X_train, X_test)))
        X_train = encoder.transform(X_train)
        X_test  = encoder.transform(X_test)
        return(X_train, X_test)
        return(X_train)

def get_data(directory, training, testing):
    train_file      = directory + '/' + training
    test_file       = directory + '/' + testing

    y_train, X_train    = csvReader().get_train(fname = train_file)
    index_test, X_test  = csvReader().get_test(fname = test_file)

    features = [0,1,3,4,6,8]
    X_train = X_train[:, features]
    X_test  = X_test[:, features]

    X_train, X_test     = one_hot_encoding(X_train, X_test)
    return([y_train, X_train, index_test, X_test])

def save_results(predictions, filename, directory):
    """Given a vector of predictions, save results in CSV format."""
    with open(directory + '/' + filename, 'w') as f:
        f.write("id,Action\n")
        for i, pred in enumerate(predictions):
            f.write("%d,%f\n" % (i + 1, pred))
    print('Results saved to: %s, in: %s' %(filename, directory))

if __name__ == '__main__':
    directory   = 'D:\Cooper\Google Drive\Kaggle_Amazon\data' #WINDOWS
    #directory   = 'C:\Google Drive\Kaggle_Amazon\data' #WINDOWS 2
    #directory   = '/Users/cooperoelrichs/Google Drive/Kaggle_Amazon/data' #MAC
    training    = 'train.csv'
    testing     = 'test.csv'
    results     = 'results.csv'

    y_train, X_train, index_test, X_test  = get_data(directory, training, testing)

    models, data, seed = [], [], 18
    for i, (model_name, model) in enumerate(submission_models):
        #if model_name != 'svc_rbf': continue
        if i > 0: continue
        t_now = time.time()
        print('Fitting model: %s' % model_name)
        model.fit(X_train, y_train)
        preds = model.predict_proba(X_test)[:, 1]
        save_results(preds, 'results_%s_%i.csv' %(model_name, i), directory)


import re, string, random
import boto3
import Core
from Core import logger, ddb

from HostInteraction import query_hosts, find_host, join_session

def register_new_game(gameId, session_hostname):
    Core.session_table.put_item(
        Item={
            'GameSessionId':gameId,
            'hostname': session_hostname
        }
    )

def lambda_handler(event, context):
    print(event)
    userId = event['userId']

    session_hostname = ''

    createGame = False

    # No gameId means we're requesting a new session
    if 'gameId' not in event or len(event['gameId']) == 0:

        # create a new gameId
        gid_length = int(Core.GAMEID_LENGTH)
        gameId = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(gid_length))

        # check with game servers to find a host
        session_hostname = find_host(userId)
        if not session_hostname:
            return {
                'statusCode': 503,
                'error':'NoHostFound'
            }

        createGame = True

    # gameId present, let's try to find the hostname for that session
    else:
        gameId = event['gameId']
        id_match = re.compile("[0-9A-Z]{6}")
        logger.info(f'parsed game ID {gameId}')

        # validate that it's a good gameId
        if not id_match.match(gameId):
            return {
                'statusCode': 400,
                'error': 'InvalidGameId'
            }

        # query DDB to find game session host

        get_session_resp = Core.session_table.get_item(
            Key={'GameSessionId':gameId}
        )

        if 'Item' not in get_session_resp:
            return {
                'statusCode': 404,
                'error': 'GameIdNotFound'
            }

        session_hostname = get_session_resp['Item']['hostname']

    # By the time we get here, the above logic will have defined:
    # gameId
    # userId (mandatory input)
    # session_hostname: determined either by a) finding the host associated with a session, or b) finding a brand new host
    # createGame: default false, only set to True if gameId is null

    resp_code = join_session(session_hostname, userId, gameId, createGame)

    if resp_code == 200:
        if createGame == True:
            register_new_game(gameId, session_hostname)

        return {
            'statusCode': 200,
            'host':session_hostname+':5000',
            'gameId':gameId
        }
    elif resp_code == 404:
        return {
            'statusCode': 404,
            'error': 'GameIdNotFound'
        }
    else:
        return {
            'statusCode': 500,
            'error': 'UnknownError'
        }