import time
from .deployer_file import Deployer
from django.shortcuts import render
from rest_framework.views import APIView
from django.http.response import JsonResponse
import os
from AzureSite.settings import BASE_DIR
import json
import random
import string
import glob
from django.views.generic import TemplateView
from azure.storage.blob import BlockBlobService
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.storage import StorageManagementClient
from azure.mgmt.storage.models import StorageAccountCreateParameters
# from .databricks_linux import databricks

# read Data for form config File
def read_mapping():
    """

    :return: data containing sections and sectionAttributes to be shown on frontend
    """
    path = str(os.path.join(BASE_DIR, 'AzureSite\sections.json')).replace('\\', '/')
    with open(path) as file:
        data = json.load(file)
    return data

# Funtion for generating random unique id
def random_id(request):
    """

    :param request:
    :return: Returns a random string of 16 characters
    """
    uniqueID = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(16))
    return JsonResponse({'id': uniqueID})

def azure_account(data):
    """

    :param data: request data
    :return: resource_id and client_id
    """
    sections_data = data['sections']
    client_id = ''
    secret = ''
    tenant = ''
    subscription_id = ''
    try:
        for section in range(len(sections_data)):
            try:
                if sections_data[section]['title']=='Subscription Details':
                    subscription_id = sections_data[section]['sectionAttributes'][0]['value']
                    tenant = sections_data[section]['sectionAttributes'][1]['value']
                    client_id = sections_data[section]['sectionAttributes'][2]['value']
                    secret = sections_data[section]['sectionAttributes'][3]['value']
                    resource_group = sections_data[section]['sectionAttributes'][4]['value']
                elif sections_data[section]['title'] =='Storage Account Details':
                    storage_account_name = sections_data[section]['sectionAttributes'][0]['value']
            except Exception as e:
                print('error in for loop of azure_function', e)
        credentials = ServicePrincipalCredentials(
            client_id=client_id,
            secret=secret,
            tenant=tenant
        )

        resource_client = ResourceManagementClient(credentials, subscription_id)
        storage_client = StorageManagementClient(credentials, subscription_id)

    except Exception as e:
        print('error in azure_account function:', e)
    return resource_client, storage_client, storage_account_name, resource_group

class azure_functions(APIView):
    def get(self, request):
        return JsonResponse({"success": "No Data to Display"})

    def post(self, request):
        try:
            resource_client, storage_client, storage_account_name, resource_group = azure_account(request.data)
            # Checking availability for storage account name
            if storage_account_name != '':
                availability = storage_client.storage_accounts.check_name_availability(storage_account_name)
                reason = availability.reason
                if reason is not None and reason == "AlreadyExists":
                    return JsonResponse({"status": "success", "message": ""})
                else:
                    return JsonResponse({"status": "failed", "message": "Storage Account doesn't exist"})
            # Checking availability for resource group
            else:
                resource_availability = resource_client.resource_groups.check_existence(resource_group)
                if resource_availability:
                    return JsonResponse({"status": "success", "message": ""})
                else:
                    return JsonResponse({"status": "failed", "message": "Resource Group Doesn't exist"})
        except Exception as e:
            print('In azure_function exception', e)
            return JsonResponse({'status': 'failed'})

class index(TemplateView):
    template_name = "index.html"

    def get(self, request):
        try:
            form_data = read_mapping()
        except Exception as e:
            return render(request, self.template_name, context={'message': 'failed'})
        # return JsonResponse({'message': 'Successful'})
        return render(request, self.template_name, context={'message': 'Successful'})

class SupplyChain(APIView):

    def get(self, request):
        """

        :param request: request data
        :return: JsonResponse containing form sections detail
        """
        try:
            data = read_mapping()
        except Exception as e:
            return JsonResponse({'Output': 'Error in reading json file ' + str(e)})
        return JsonResponse({'message': 'Successful', 'formConfig': data})

    def post(self, request):
        """

        :param request: Request Data
        :return:
        """
        path = str(os.path.join(BASE_DIR +'\AzureSite\parameters.json')).replace('\\', '/')
        try:
            with open(path) as file:
                param_file = json.load(file)
                adf_parameters = param_file['ADFParameters']['values']
                vault_parameters = param_file['KeyVaultParameters']['values']
                adf_dict = { '$schema': param_file['general']['schema'],
                            'contentVersion': param_file['general']['contentVersion'], 'parameters': {}}
                vault_dict = { '$schema': param_file['general']['schema'],
                              'contentVersion': param_file['general']['contentVersion'], 'parameters': {}}
            # Container Name to be used in Azure Deployment
            container_name = param_file['containername']
            # Convert Parameter list to lowercase
            adf_parameters = list(map(lambda func: func.lower(), adf_parameters))
            vault_parameters = list(map(lambda func: func.lower(), vault_parameters))
        except Exception as e:
            print('error opening json file')
        try:
            section_data = request.data['sections']
        except Exception as e:
            return JsonResponse({"message": "error in request data" + str(e)})

        for section_attr in range(len(section_data)):
            try:
                sectionAttributes = section_data[section_attr]['sectionAttributes']
                for sectionAttribute in range(len(sectionAttributes)):
                    try:
                        name = sectionAttributes[sectionAttribute]['internalName']
                        value = sectionAttributes[sectionAttribute]['value']
                        if name.lower() in adf_parameters:
                            adf_dict['parameters'][name] = {'value': value}
                        if name.lower() in vault_parameters:
                            vault_dict['parameters'][name] = {'value': value}
                    except Exception as e:
                        print('error in inner loop', sectionAttribute, str(e))
            except Exception as e:
                print('error in in outer loop at index ', section_attr)
                return JsonResponse({'Output': 'error'})
        # For optional Table

        select_variables = ["SAP", "SalesForce", "Oracle", "BQ"]

        try:
            selected_value = adf_dict['parameters']['Sources']['value']
            # Extract submitted data for selected field

            if selected_value in select_variables:
                temp_param = (selected_value) + 'Tables'
                subsections = section_data[3]['subsections']['sections'][selected_value]['subsectionAttributes']

                schemas = []
                tables = []
                for i in range(len(subsections)):
                    if subsections[i]['internalName'] == selected_value+'Schema':
                        schemas = subsections[i]['value'].split(',')
                    elif subsections[i]['internalName'] == selected_value+'Tables':
                        tables = subsections[i]['value'].split(',')
                    else:

                        adf_dict['parameters'][subsections[i]['internalName']] = {'value': subsections[i]['value']}
                adf_dict['parameters'][temp_param] = {"value": []}
                for i in range(len(schemas)):
                    adf_dict['parameters'][temp_param]["value"].append({
                        "table_schema": schemas[i],
                        "table_name": tables[i]})
            else:
                # when Blob Option is choosen
                adf_dict['parameters']["BlobTable"] = {"value": []}
                tables = section_data[3]['subsections']['sections'][selected_value]['subsectionAttributes'][0]['value'].split(',')
                for table in range(len(tables)):
                    adf_dict['parameters']["BlobTable"]['value'].append({'table_name': tables[table]})

        except KeyError as e:
            print("Keyerror Exception in creating table data: ", e)
            return JsonResponse({"message": "error"})
        except Exception as e:
            print('Exception in creating table data: ', e)
            return JsonResponse({"message": "error"})

        # Get all required parameters from submitted data for Azure Deployment
        try:
            connectionstring = vault_dict['parameters']['StorageConnectionString']['value']
            account_name = vault_dict['parameters']['StorageAccountName']['value']
            access_key = vault_dict['parameters']['StorageAccessKey']['value']

            for key in range(len(section_data)):
                try:
                    if section_data[key]['title']=='Subscription Details':
                        subscription_id = section_data[key]['sectionAttributes'][0]['value']
                        tenant = section_data[key]['sectionAttributes'][1]['value']
                        client_id = section_data[key]['sectionAttributes'][2]['value']
                        secret = section_data[key]['sectionAttributes'][3]['value']
                        resource_group = section_data[key]['sectionAttributes'][4]['value']
                    elif section_data[key]['title'] =='Storage Account Details':
                        storage_account_name = section_data[key]['sectionAttributes'][0]['value']
                except Exception as e:
                    print("Exception in initializing various keys: ", e)
                    client_id = ''
                    secret = ''
                    tenant = ''
                    subscription_id = ''
                    resource_group = ''

        except KeyError as key:
            print('Key Not found', key)
        # Azure Deployment code
        try:
            with open('upload_files/ADFParameters.json', 'w') as adf:
                json.dump(adf_dict, adf)
            with open('upload_files/KeyVaultParameters.json', 'w') as kv:
                json.dump(vault_dict, kv)

            print("adf and kv files created")
            # resource_client, storage_client = azure_account(request.data)
            # Create a storage blob container to store the files
            # Create the BlockBlockService that is used to call the Blob service for the storage account.
            block_blob_service = BlockBlobService(
                account_name=account_name,
                account_key=access_key)
            print('blob created')
            # Create a container called 'quickstartblobs'.
            # container_name = 'marketplacecodes'
            create_container = False
            counter = 0
            while create_container != True and counter < 5:
                create_container = block_blob_service.create_container(container_name)
                counter = counter + 1
                print("create_container status: ", create_container)
                time.sleep(10)
            # Set the permission so the blobs are public.
            # block_blob_service.set_container_acl(
            #     container_name, public_access=PublicAccess.Container)
            # retrive conn string from storage variable "storageconnstring" for azure push

            blob_name_adf = "ADFParameters.json"
            blob_name_kv = "KeyVaultParameters.json"
            blob_client = BlockBlobService(connection_string=connectionstring)
            for filepath in glob.iglob('upload_files/*.json'):
                try:
                    file_name = filepath.split("\\")
                    response_obj = blob_client.create_blob_from_path(container_name=container_name, blob_name=file_name[1],
                                                             file_path=os.path.join(BASE_DIR, filepath))
                    print("blob_create status: ", response_obj)
                    time.sleep(5)
                except Exception as e:
                    print("Exception in creating Blob: ", e)

            # Deplayment of blobs
            try:
                deployment_obj = Deployer(resource_group, subscription_id, client_id, secret,
                                          tenant, container_name)
                adf_obj = deployment_obj.deploy("upload_files/DataFactoryDeployment.json",
                                                "upload_files/ADFParameters.json", connectionstring)
                kv_obj = deployment_obj.deploy("upload_files/KeyVaultDeployment.json",
                                               "upload_files/KeyVaultParameters.json", connectionstring)
            except Exception as e:
                print("Exception in deploy the data factory: ", e)
            # Remove conatiner from storage account after deployment
            try:
                try:
                    databricksToken = vault_dict['parameters']['DataBricksToken']
                    databricksScope = vault_dict['parameters']['DataBricksScope']
                    databricksURL = vault_dict['parameters']['DataBricksWorkspaceURL']
                    # databricks.main(databricksURL, databricksToken, databricksScope)
                except Exception as e:
                    print('exception in databricks function')

                time.sleep(720)
                delete_container = blob_client.delete_container(container_name)
                print("delete container: ", delete_container)
            except Exception as e:
                print("Exception in removing conatiner from storage account: ", e)
        except Exception as e:
            print("exception in azure conn: " + str(e))
        print('done')

        return JsonResponse({"message": "Successful"})


#!/usr/bin/env python
########## Rho value read function from a vtk file ###########################
def get_rho_tuple(number_of_cells):
    Filename = './with_axis_0_img_00000.vtk' #This file contains the phi value
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(Filename)
    reader.ReadAllScalarsOn()
    reader.Update()
    usg = reader.GetOutput().GetCellData().GetScalars()
    z = []
    for i in range(number_of_cells):
        z.append(usg.GetTuple(i)[0])
    return tuple(z)

############# function to convert cartesian to spherical polar co-ordinate #########
def cart2pol(mValue):
    r=numerix.linalg.norm(mValue,axis=0)
    theta=numerix.arccos(mValue[2,:]/r)
    phi=numerix.arctan2(mValue[1,:],mValue[0,:])
    # this section converts negative phi value to positive value by adding 2pi value
    neg_index=numerix.where(phi<0)
    phi[neg_index]=phi[neg_index]+2*np.pi

    return r,theta,phi

######## Index sorting function of y according to x #######################
def index_sorted(x,y):
    d = np.argsort(x)
    z = [0] * len(y)
    for i in range(len(d)):
        z[i] = y[d[i]]
    return z

############### Trapezoidal function for irregular grid size ###############
def trapz_irregular(x,y):
    n=len(x)
    index=1
    sum=0
    while index<=n-1:
        dx=x[index]-x[index-1]
        fx=0.5*(y[index-1]+y[index])
        sum=sum+fx*dx
        index=index+1

    return sum

################### Importing Modules ###############################
print('Import starts')

from fipy import FaceVariable, CellVariable, Gmsh2DIn3DSpace, VTKViewer, TransientTerm, ExplicitDiffusionTerm, DiffusionTerm, ExponentialConvectionTerm, DefaultSolver
from fipy.variables.variable import Variable
from fipy.tools import numerix
from mpl_toolkits.mplot3d import Axes3D
import time
import pickle
from shutil import copyfile
import vtk
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

plt.rcParams.update({'font.size':20})

print('Import finished')

# ### Load mesh details from a saved file
mesh=pickle.load(open("./mesh_details_cellsize_0pt008_extrude_1pt00001.p","rb"))
gridCoor = mesh.cellCenters
mUnit = gridCoor
mNorm = numerix.linalg.norm(mUnit,axis=0)
print('max mNorm='+str(max(mNorm)))
print('min mNorm='+str(min(mNorm)))
mAllCell = mUnit / mNorm

mAllCell_cartesian_save=mAllCell

#print(type(gridCoor))

msize=numerix.shape(mAllCell)
number_of_cells=msize[1]
print('Total number of cells = ' +str(number_of_cells))

################# Loading rho values from a saved file ##########################
rho_value = get_rho_tuple(number_of_cells) # get rho values from a previous .vtk file
rho = CellVariable(name=r"$\rho$",mesh=mesh,value=rho_value)

############# To convert into numpy array, save it in numpy file and again store it in a variable
np.save('rho_value.npy', rho)

rho_value=[]
rho_value=np.load('rho_value.npy')

# ### Convert m values into numpy array by saving and loading into a file
numerix.save('mValue_info.npy', mAllCell)

# load the state space coordinate array values
mValue=numerix.load('mValue_info.npy')
np.shape(mValue)

# ### Convert m values from cartesian to spherical polar

mvalue_sph_pol=numerix.asarray(cart2pol(mValue))

Phi_deg = mvalue_sph_pol[2,:]*(180.0/np.pi)
print('Phi_max_degree = '+str(max(Phi_deg)))
print('Phi_min_degree = '+str(min(Phi_deg)))

phi_angle_all=mvalue_sph_pol[2,:]

phi_value=0.0*numerix.pi # initial phi value
phi_step=1.0*360.0            # Phi value range(0,2pi) will be divided by phi_step
delta=(2*numerix.pi)/phi_step    # delta by which phi value will be increased
phi_save=[]  # this will save the values of Phi, which will be required to do the integration
total_size=0   # this will keep track the total number of cells being covered during calculation

m_cell_sph=[[],[],[]]

while phi_value< (2.0*numerix.pi):
    ######### Search index of phi where.....(phi_value-delta)<=phi_angle_all<(phi_value+delta) ##############
    index_phi=numerix.asarray(numerix.where((phi_angle_all>=phi_value) & (phi_angle_all<phi_value+delta)))
    #####################################################################################################
    r_at_index=mvalue_sph_pol[0,index_phi]
    theta_at_index=mvalue_sph_pol[1,index_phi]   # pulling out the values of the theta corresponding to index_phi

    ####################### Sorting rho according to sorted index of theta ########################
    xvar=theta_at_index[0,:] # storing the values of theta corresponding to index_phi into xvar

    rho_at_index=rho_value[index_phi] # pulling out the values of the rho corresponding to index_phi

    yvar=rho_at_index[0,:] # storing the values of rho corresponding to index_phi into xvar

    rho_sorted_acc_to_theta=index_sorted(xvar,yvar) # calling the index_sorted function
    rho_sorted_acc_to_theta=np.reshape(rho_sorted_acc_to_theta,(1,len(rho_sorted_acc_to_theta))) # reshaping into a single array

    theta_sorted=np.sort(theta_at_index) # theta value sorted
    theta_sorted=theta_sorted[0,:] # converting from 1Xn matrix to row array of n elements

    phi_new=phi_value*numerix.ones(len(theta_sorted))

    m_cell_modified_sph_pol=numerix.append(numerix.asarray(r_at_index),[numerix.asarray(theta_sorted),numerix.asarray(phi_new)],axis=0)

    #print(numerix.shape(m_cell_modified_sph_pol))
    m_cell_sph=numerix.append(m_cell_sph,(m_cell_modified_sph_pol),axis=1) #Appending the m values in spherical polar coordinate

    theta_sz=np.shape(theta_sorted)
    size=theta_sz[0]
    total_size=total_size+size # calculate total number of cells being covered during calculation

    phi_value=phi_value+delta # phi is increased by delta at end of each loop

print('Total number of cells covered = ' +str(total_size))
#type(m_cell_sph)

######## Converted the spherical polar coordinates back to cartesian coordinate #####################
m_x=(m_cell_sph[0,:]*numerix.sin(m_cell_sph[2,:])*numerix.cos(m_cell_sph[1,:]))
m_y=(m_cell_sph[0,:]*numerix.sin(m_cell_sph[2,:])*numerix.sin(m_cell_sph[1,:]))
m_z=m_cell_sph[0,:]*numerix.cos(m_cell_sph[2,:])

m_cellcenters_cart_modified=numerix.array([[m_x],[m_y],[m_z]])
#numerix.shape(m_cellcenters_cart_modified)

m_cellcenters_cart_modified=numerix.reshape(m_cellcenters_cart_modified,(3,total_size))

#mcell_new=m_cellcenters_cart_modified*CellVariable([1.0])

mcell_new=CellVariable(mesh=mesh, value=m_cellcenters_cart_modified)

#type(mcell_new)
#mcell_new.shape
#type(rho)
print('Calculation starts')

interpolated_rho=rho(mcell_new.globalValue, order=1)

pickle.dump(interpolated_rho, open("interpolated rho.p","wb") )


#!/usr/bin/env python
# Author: liuhuihui
# Date:   2015-01-13

import re

from libcom.lib_pub.logging_drv import log_info
from libcom.lib_cmd.inter_mode import *
from libcom.lib_cmd.config_mode import *
from libcom.lib_cmd.shell_mode import *
from libcom.lib_cmd.chg_mode import *
from libcom.device_adapt.nt_adapt import *
from libcom.packet_drv.Tester import *
from libcom.console_drv.console_drv import *
from libcom.config_topo.topo_controller import *

SUCCESS = 0
FAIL    = -1

#just for smoking define
def nfpp_send_arp_broad_smoking(dev_name, pkt_rate, intf_name):
    #set arguments
    nt_name = 'nt1'

    #set arp broad
    te = Tester()
    nt_ip = get_nt_ip(nt_name)
    nt_usrname = get_nt_usrname(nt_name)

    te.ConnectTester(nt_ip)
    te.TesterLogin(nt_usrname)
    te.TakeOwnership(intf_name)
    te.ResetPort(intf_name)
    te.traffic_config(intf_name, "create", rate_pps=pkt_rate, transmit_mode="continuous", pkts_per_burst = pkt_rate, mac_dst="ff.ff.ff.ff.ff.ff",\
                       mac_src="00.d0.f7.11.11.12", ip_src_addr='12.12.12.12', l3_protocol="arp")
    te.traffic_control(intf_name, "run")
    te.CloseConnect()

def nfpp_send_arp(dev_name, pkt_rate, smac, dmac, sip, dip, intf_name):
    #set arguments
    nt_name = 'nt1'

    #set arp broad
    te = Tester()
    nt_ip = get_nt_ip(nt_name)
    nt_usrname = get_nt_usrname(nt_name)

    te.ConnectTester(nt_ip)
    te.TesterLogin(nt_usrname)
    te.TakeOwnership(intf_name)
    #te.ResetPort(intf_name)
    te.traffic_config(intf_name, "create", rate_pps=pkt_rate, transmit_mode="continuous", pkts_per_burst = pkt_rate, mac_dst=dmac,\
                       mac_src=smac, ip_src_addr=sip, ip_dst_addr=dip, l3_protocol="arp")
    te.traffic_control(intf_name, "run")
    te.CloseConnect()

def nfpp_send_icmp_broad_smoking(dev_name, pkt_rate, smac, dmac, sip, dip, intf_name):
    #set arguments
    nt_name = 'nt1'

    #set arp broad
    te = Tester()
    nt_ip = get_nt_ip(nt_name)
    nt_usrname = get_nt_usrname(nt_name)

    te.ConnectTester(nt_ip)
    te.TesterLogin(nt_usrname)
    te.TakeOwnership(intf_name)
    te.ResetPort(intf_name)
    te.interface_config(intf_name, "config", src_mac_addr=smac, intf_ip_addr=sip, netmask='225.255.255.0', gateway=dip)
    te.traffic_config(intf_name, "create", rate_pps=pkt_rate, transmit_mode="continuous", pkts_per_burst = pkt_rate, mac_dst=dmac,\
                       mac_src=smac, ip_src_addr=sip, ip_dst_addr=dip, l3_protocol="ipv4", ip_protocol = "1", icmp_code=0, icmp_id=0,\
                       icmp_seq=0, icmp_type=0)
    te.traffic_control(intf_name, "run")
    te.CloseConnect()

def nfpp_show_host(dev_name, type):
    return run_cmd(dev_name, 'show nfpp '+type+'-guard host')

def nfpp_show_scan(dev_name, type):
    return run_cmd(dev_name, 'show nfpp '+type+'-guard scan')

def nfpp_clear_host(dev_name, type):
    enable(dev_name)
    run_cmd(dev_name, 'clear nfpp '+type+'-guard hosts')
    run_cmd(dev_name, 'clear nfpp '+type+'-guard scan')

def nt_stop_send(nt_name, intf_name):
    te = Tester()
    nt_ip = get_nt_ip(nt_name)
    nt_usrname = get_nt_usrname(nt_name)

    te.ConnectTester(nt_ip)
    te.TesterLogin(nt_usrname)
    te.ResetPort(intf_name)
    te.CloseConnect()

def nfpp_mod(dev_name):
    run_cmd(dev_name, 'end')
    configure(dev_name)
    run_cmd(dev_name, 'nfpp')


#!/usr/bin/python3
#

from array import array
from collections import deque
import itertools
import sys

debug = False

class Slot:

    def __init__(self, kind, D, H, M, T, Dn, Kn):
        self.kind = kind
        self.day = D
        self.start = H * 60 + M
        self.end = self.start + Dn * 60
        self.teacher = T
        self.capacity = Kn
        self.compatibles = set()

    def check_compatible(self, other):
        if self.day != other.day or \
                self.start >= other.end + 5 or self.end + 5 <= other.start:
                    self.compatibles.add(other)

    def compatible(self, other):
        return other in self.compatibles

    def __repr__(self):
        return "{}(day {}, {}:{:02}-{}:{:02}, teacher {}, capacity {})" \
               .format(self.kind, self.day,
                       self.start // 60, self.start % 60, self.end // 60, self.end % 60,
                       self.teacher, self.capacity)

def edmondskarp(residual, n1, n2, goal, expl, comp):
    total = n1 + n2 + 2
    source = 0
    sink = total - 1
    total_cap = 0
    parents = array('i', (-1 for _ in range(total)))
    parents_init = parents[:]
    cap = array('i', (0 for _ in range(total)))
    cap[source] = 999999
    to_see = deque([source])
    while to_see and total_cap < goal:
        node = to_see.popleft()
        for other in comp[node]:
            if other != node and other != source and parents[other] == -1 and residual[node*total+other] > 0:
                parents[other] = node
                c, r = cap[node], residual[node*total+other]
                cap[other] = c if c < r else r
                if other == sink:
                    path_cap = cap[other]
                    l = [other]
                    while parents[other] != -1:
                        p = parents[other]
                        l.append(p)
                        residual[p*total+other] -= path_cap
                        residual[other*total+p] += path_cap
                        other = p
                    total_cap += path_cap
                    if debug:
                        print("path_cap = {}, path = {}".format(path_cap, [expl[x] for x in l]))
                    to_see = deque([source])
                    parents = parents_init[:]
                    break
                else:
                    to_see.insert(0, other)
    if debug:
        print("Total capacity found: {} (goal was {})".format(total_cap, goal))
    return total_cap, residual

def problem():
    S = int(sys.stdin.readline())
    (N1, K1, D1, T1) = [int(i) for i in sys.stdin.readline().split()]
    FC = [Slot("FC", *[int(i) for i in sys.stdin.readline().split()], D1, K1) for _ in range(N1)]
    (N2, K2, D2, T2) = [int(i) for i in sys.stdin.readline().split()]
    IC = [Slot("IC", *[int(i) for i in sys.stdin.readline().split()], D2, K2) for _ in range(N2)]
    C = int(sys.stdin.readline())
    conflicts = set(tuple(int(i) for i in sys.stdin.readline().split()) for _ in range(C))
    gmask = set(x.day for x in FC + IC)
    for f in FC:
        for i in IC:
            if (f.teacher, i.teacher) not in conflicts:
                f.check_compatible(i)
    max_total = N1 + N2 + 2
    zeroes = array('i', (0 for _ in range(max_total * max_total)))
    for number_of_days in range(1, 7):
        for d in itertools.combinations(gmask, number_of_days):
            if debug:
                print("Checking days {}".format(d))
            fc = [c for c in FC if c.day in d]
            ic = [c for c in IC if c.day in d]
            n1 = len(fc)
            n2 = len(ic)
            total = 1 + n1 + n2 + 1 # Source + FCs + ICs + Sink
            capacities = zeroes[:total*total]
            comp = [[] for _ in range(n1+n2+2)]
            comp[0] = list(range(1, n1+1))
            for i in range(n1):
                for j in range(n2):
                    if fc[i].compatible(ic[j]):
                        capacities[(i+1)*total+j+1+n1] = S
                        comp[i+1].append(1+n1+j)
                        comp[1+n1+j].append(i+1)
            for i in range(n1):
                capacities[0*total+i+1] = fc[i].capacity
            for j in range(n2):
                capacities[(j+1+n1)*total+total-1] = ic[j].capacity
                comp[1+n1+j].append(1+n1+n2)
            expl = ["source"] + fc + ic + ["sink"]
            total_cap, residual = edmondskarp(capacities[:], n1, n2, S, expl, comp)
            if total_cap >= S:
                if debug:
                    print("Solution found (for {} capacity >= {} students):".format(total_cap, S))
                    for i in range(n1):
                        for j in range(n2):
                            index = (1 + i) * total + (n1 + 1 + j)
                            f = capacities[index] - residual[index]
                            if f > 0:
                                print("  - {} between {} and {}".format(f, fc[i], ic[j]))
                print(number_of_days)
                sys.exit(0)
    print(0)

if __name__ == '__main__':
    if sys.argv[1:2] == ["-d"]:
        debug = True
    problem()


import pandas as pd
from datetime import datetime, timedelta
import json
import ndjson

def twitterVolume(date, longitude):
	df = pd.read_excel('', sheet_name='Social unrest events prediction', converters={'Date':str})
	for i in df.index:
		if(df['Date'][i]==date+' 00:00:00'):
			res = []
			for x in range(longitude):
				res.append(df['Relevant Posts'][i-longitude])
				i += 1
			return res

def twitterSentiment(date, longitude):
	df = pd.read_excel('', sheet_name='Social unrest events prediction', converters={'Analysis Date':str})
	for i in df.index:
		if(df['Analysis Date'][i]==date+' 00:00:00'):
			res = []
			for x in range(longitude):
				res.append(df['Anger'][i-longitude])
				i += 1
			return res

def getCounts(date, lap):
	with open('') as f:
		data = json.load(f)
		x = datetime.strptime(date, '%Y-%m-%d')+timedelta(days=lap)
		day = x.strftime('%Y-%m-%d')
		return data[day]

def indicators(date, longitude, indicator):
	df = pd.read_excel('', sheet_name='Jordan', converters={'Date':str})
	start_date = datetime.strptime(date, '%Y-%m-%d')-timedelta(days=longitude)
	end_date = datetime.strptime(date, '%Y-%m-%d')-timedelta(days=1)
	days = [start_date + timedelta(days=x) for x in range((end_date-start_date).days + 2)]
	days1 = [x.strftime('%Y-%m-%d') for x in days]
	res = []
	for x in range(len(days1)-1):
		for i in df.index:
			if(str(df['Date'][i]).startswith(days1[x][0:7])):
				res.append(round(float(df[indicator][i]), 2))
	return res

longitude = 30
lap = 3

start_date = '2015-05-01'
end_date = '2019-01-01'

days_min = datetime.strptime(start_date, '%Y-%m-%d')
days_max = datetime.strptime(end_date, '%Y-%m-%d')
days = [days_min + timedelta(days=x) for x in range((days_max-days_min).days + 2)]
days1 = [x.strftime('%Y-%m-%d') for x in days]

data_0 = []
data_1 = []
data_2 = []
data_3 = []
data_4 = []
data_5 = []
data_6 = []
data_7 = []
data_8 = []
data_9 = []
data_10 = []
data_11 = []

for i in range(len(days1)-1):
	date = days1[i]
	res = {}
	indic = []
	indic.append([twitterVolume(date, longitude), twitterVolume(date, longitude)])
	indic.append([twitterSentiment(date, longitude), twitterSentiment(date, longitude)])
	indic.append([indicators(date, longitude, 'Copper'), indicators(date, longitude, 'Copper')])
	indic.append([indicators(date, longitude, 'Wheat'), indicators(date, longitude, 'Wheat')])
	indic.append([indicators(date, longitude, 'Maize'), indicators(date, longitude, 'Maize')])
	indic.append([indicators(date, longitude, 'Natrual gas'), indicators(date, longitude, 'Natrual gas')])
	indic.append([indicators(date, longitude, 'Iron ore'), indicators(date, longitude, 'Iron ore')])
	res['country'] = 'Jordan'
	res['date'] = (datetime.strptime(date, '%Y-%m-%d')+timedelta(days=lap)).strftime('%Y-%m-%d')
	c = getCounts(date, lap)
	res['counts'] = c
	res['indicators'] = indic
	if c<=0:
		data_0.append(res)
	elif c<=1:
		data_1.append(res)
	elif c<=2:
		data_2.append(res)
	elif c<=3:
		data_3.append(res)
	elif c<=4:
		data_4.append(res)
	elif c<=5:
	    data_5.append(res)
	elif c<=6:
	    data_6.append(res)
	elif c<=7:
		data_7.append(res)
	elif c<=8:
		data_8.append(res)
	elif c<=9:
	    data_9.append(res)
	elif c<=10:
	    data_10.append(res)
	else:
	    data_11.append(res)
	print(date + ' done')

data = [data_0, data_1, data_2, data_3, data_4, data_5, data_6, data_7, data_8, data_9, data_10, data_11]
for i in range(12):
	with open('jordan_'+str(i)+'.ndjson', 'w') as f:
		ndjson.dump(data[i], f)
	print(len(data[i]))


import scrapy
from scrapy.http import Request
import telnetlib
import time
from sprider163S.sqlpool  import sqlPool
from sprider163S.handle import handle
# scrapy crawl album
class AlbumSpider(scrapy.Spider):
    name = "album"
    allowed_domains = ["163.com"]
    sql=sqlPool()
    sidlist=sql.singerList()

    #print(sidlist)
    start_urls = []
    for e in sidlist:
        sid= e.get("sid")
        surl="https://music.163.com/artist/album?id="+sid
        start_urls.append(surl)

    def start_requests(self):
        for url in self.start_urls:
            time.sleep(2)
            yield scrapy.Request(url=url, callback=self.parse,
                                 headers=handle.get_headers())

    def parse(self, response):
        artist = response.xpath("//h2[@id='artist-name']/@data-rid")
        if (artist.__len__() > 0):
            list = []
            sid = response.xpath("//h2[@id='artist-name']/@data-rid")[0].extract()
            len = response.xpath("//ul[@id='m-song-module']//li//div/@title").__len__()
            for i in range(len):
                title = response.xpath("//ul[@id='m-song-module']//li//div/@title")[i].extract()
                id = handle.get_id_by_url(response.xpath("//ul[@id='m-song-module']//li//p//a/@href")[i].extract())
                list.append({"title": title, "id": id, "sid": sid})
            print(list)
            sl=sqlPool()
            list2 =sl.albumlistcheck(list)
            if(list2.__len__()>0):
                sl.savealbumList(list2)
            #nextlen = response.xpath("//div[@class='u-page']//a").__len__()
            hrefs = response.css(".u-page .znxt ::attr(href)")
            for h in hrefs:
                print()
                if ("javascript:void(0)".__eq__(h.extract())):
                    print("没有下一页")
                else:
                    nextp = "https://music.163.com" + h.extract()
                    time.sleep(2)
                    yield scrapy.Request(url=nextp, callback=self.parse,
                                         headers=handle.get_headers())


#!/usr/bin/env python
from pg_catalog.test import *

class TestCase(TestCase):
    def test(self):
        for r in self.db.query(
            pg_authid
        ).options(map(
            lambda c:undefer(c.key),
            pg_authid.__table__.columns
        )).all():
            is_(r,pg_authid)
            is_int(r.oid)
            is_text(r.rolname)
            is_bool(r.rolsuper)
            is_bool(r.rolinherit)
            is_bool(r.rolcreaterole)
            is_bool(r.rolcreatedb)
            is_bool(r.rolcatupdate)
            is_bool(r.rolcanlogin)
            is_bool(r.rolreplication)
            is_int(r.rolconnlimit)
            none_or_text(r.rolpassword)
            none_or_datetime(r.rolvaliduntil)

if __name__ == "__main__":
    main()


'''
Reading data from a csv file and then inserting all data into the database
using one line of code
'''
import csv
import sqlite3

employees_csv_data = csv.reader(open("employees.csv","r"))

with sqlite3.connect("new.db") as conn:

	c = conn.cursor()
	c.execute("CREATE TABLE employees(firstname TEXT, lastname TEXT)")
	c.executemany("INSERT INTO employees VALUES (?,?)",employees_csv_data)


#opdracht 2,1

letters= ('a','c','b','b','c','a','c','c','a','a','c')
a=letters.count('a')
b=letters.count ('b')
c=letters.count ('c')

list=[a,b,c]

list.sort()

print (list)


from zope.interface import implements
from zope.component import adapts
from AccessControl import getSecurityManager
from Products.CMFCore.utils import getToolByName
from Products.CMFCore.interfaces import IContentish
from plone.app.layout.nextprevious.interfaces import INextPreviousProvider
from plone.app.layout.navigation.interfaces import INavigationRoot
from plone.app.folder.folder import IATUnifiedFolder

class NextPrevious(object):
    """ adapter for acting as a next/previous provider """
    implements(INextPreviousProvider)
    adapts(IATUnifiedFolder)

    def __init__(self, context):
        self.context = context
        props = getToolByName(context, 'portal_properties').site_properties
        self.vat = props.getProperty('typesUseViewActionInListings', ())
        self.security = getSecurityManager()
        order = context.getOrdering()
        if not isinstance(order, list):
            order = order.idsInOrder()
        if not isinstance(order, list):
            order = None
        self.order = order

    @property
    def enabled(self):
        includeInNav = not self.context.getExcludeFromNav()
        nextPreviousEnabled = self.context.getNextPreviousEnabled()
        # only report 'enabled' True when both conditions are met
        return includeInNav and nextPreviousEnabled

    def getFirstItem(self):
        items = self.context.objectValues()[:]
        return items and items[0] or None

    def getLastItem(self):
        items = self.context.objectValues()[:]
        items.reverse()
        return items and items[0] or None

    def isFirstItem(self, obj):
        if obj is None:
            raise TypeError("Cannot compare 'None' to objects in container.")
        firstItem = self.getFirstItem()
        return obj == firstItem and True or False

    def isLastItem(self, obj):
        if obj is None:
            raise TypeError("Cannot compare 'None' to objects in container.")
        lastItem = self.getLastItem()
        return obj == lastItem and True or False

    def getNextItem(self, obj, camefrom=None):
        """ return info about the next item in the container """
        if not self.order:
            return None
        pos = self.context.getObjectPosition(obj.getId())
        for oid in self.order[pos+1:]:
            data = self.getData(self.context[oid])
            if data:
                return data
        # couldn't find one, let's see of our parent knows
        parent = INextPreviousProvider(self.context.aq_parent)
        if parent and parent.enabled:
            return parent.getNextItem(self.context, camefrom)
        return None

    def getPreviousItem(self, obj, camefrom=None):
        """ return info about the previous item in the container """
        if not self.order:
            return None
        order_reversed = list(reversed(self.order))
        pos = order_reversed.index(obj.getId())
        for oid in order_reversed[pos+1:]:
            data = self.getData(self.context[oid])
            if data:
                return data
        # couldn't find one, let's see of our parent knows
        if self.isFirstItem(obj) and INavigationRoot.providedBy(self.context):
            return None
        else:
            parent = INextPreviousProvider(self.context.aq_parent)
            if parent and parent.enabled:
                return parent.getPreviousItem(self.context, camefrom)
        return None

    def getData(self, obj):
        """ return the expected mapping, see `INextPreviousProvider` """
        if not self.security.checkPermission('View', obj):
            return None
        elif not IContentish.providedBy(obj):
            # do not return a not contentish object
            # such as a local workflow policy for example (#11234)
            return None
        # pay attention to the 'excludedFromNav' attribute itself too
        elif obj.getExcludeFromNav():
            return None

        portal_properties = getToolByName(self.context, 'portal_properties')
        navtree_properties = getattr(portal_properties, 'navtree_properties')
        if obj.portal_type in navtree_properties.getProperty(
            'metaTypesNotToList', ()):
            return None

        ptype = obj.portal_type
        url = obj.absolute_url()
        if ptype in self.vat:       # "use view action in listings"
            url += '/view'
        return dict(id=obj.getId(), url=url, title=obj.Title(),
            description=obj.Description(), portal_type=ptype)


print("Символ мат. операции '0' завершит работу программы"
        "\n'=' выведет результат")
z = 0
x = float(input("x = "))
while z != "=":
    z = input("Выберите символ мат.операции (+,-,*,/,**): ")
    if z == '0':
        break
    if z in ('+', '-', '*', '/', '**'):
        y = float(input("y = "))
        if z == '+':
            x += y
        elif z == '-':
            x -= y
        elif z == '*':
            x *= y
        elif z == '**':
            x **= y
        elif z == '/':
            if y != 0:
                x /= y
            else:
                print("Деление на 0")
    else:
        if z != "=":
            print("Неверный знак операции!")
print (x)


"""
This module deals with the prediction of sales for a year into the future.

This is done by finding the growth rates for each day in the csv file and multiplying
that to the latest data point for each beer over and over until all the growth rates have
been multiplied.
In addition, the module can plot past data and the prediction using
matplotlib and find the total predicted sale of a given time period.
"""
import os
from datetime import datetime, timedelta
from typing import List, Tuple, Dict
import logging
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from read_file import parse_data

ABS_PATH = os.path.abspath(__file__)
D_NAME = os.path.dirname(ABS_PATH)
os.chdir(D_NAME)

LOGGER = logging.getLogger("sales_predictions")
LOGGER.setLevel(logging.DEBUG)
F_HANDLER = logging.FileHandler('log_file.log')
F_FORMAT = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
F_HANDLER.setFormatter(F_FORMAT)
LOGGER.addHandler(F_HANDLER)

def calculate_growth(start_date_obj: datetime, end_date_obj: datetime,
                     x_list: List[datetime], y_list: List[int], days: int = 1) -> int:
    """
    This function calculates the growth % given two dates and the sales for those dates.

    This function can also calculate the growth rate between two periods.

    :param start_date_obj: First date.
    :param end_date_obj: Second date.
    :param x_list: List of dates.
    :param y_list: List of sales.
    :param days: Length of time period.

    :return: Growth % as a rounded integer.
    """
    x_index = x_list.index(start_date_obj)
    start_data = sum(y_list[x_index:x_index+days])  # Summing the sales values for the given period.
    if start_data == 0:
        # Setting a default replacement value for 0 so prediction division by 0 doesn't occur.
        LOGGER.debug("Start data changed to 1.1")
        start_data = 1.1
    x_index = x_list.index(end_date_obj)
    if x_index+days <= len(y_list):
        # Summing the sales values in the next given period.
        end_data = sum(y_list[x_index:x_index+days])
    else:
        end_data = sum(y_list[x_index:])  # If the end of the list is reached.
    growth_percent = round((end_data - start_data) / start_data, 5) * 100
    return growth_percent

def multiply_rate(value: int, percent_list: List[int],
                  index: int = 0, new_list: List = None) -> List[int]:
    """
    This function multiplies all the growth rates recursively.

    :param value: Value for the growth % to be applied to.
    :param percent_list: List of growth %.
    :param index: Index of the growth % to be applied.
    :param new_list: List of the new values after growth % was applied.

    :return: After recursion is finished, a list of the new values is returned.
    """
    if new_list is None:
        new_list = []

    if index >= len(percent_list):
        return new_list
    value += 1  # To avoid the prediction flat-lining.
    value *= ((percent_list[index]) / 100) + 1
    new_list.append(value)
    index += 1
    return multiply_rate(value, percent_list, index, new_list)

def plot_past_data(key_name: str = None) -> List[Line2D]:
    """
    This function plots the past data using matplotlib.

    The optional argument allows you to see the graph for only one beer type.

    :param key_name: A specific type of beer to be shown.
    :return: The plot.
    """
    LOGGER.info("Plotting past data")
    data_dict = parse_data()
    for key in data_dict['x']:
        if key_name is None or key == key_name:
            x_data = data_dict['x'][key]
            y_data = data_dict['y'][key]
            line_2d = plt.plot(x_data, y_data, label=key, marker=".", linewidth=0.5, markersize=1)

    plt.legend()
    return line_2d

def plot_growth_percent(days: int = 1, key_name: str = None, plot: bool = True,
                        start_date: datetime = None) -> Tuple[List[datetime], Dict[str, List[int]]]:
    """
    This function returns the growth rates for each beer.

    The growth can be calculated for a total of a given period or day by day. It can
    also be calculated for all the beers or just one specific beer.
    This module also has the capability to plot the grow rates using matplotlib.

    :param days: The period to sum the data.
    :param key_name: The name of the specific beer.
    :param plot: Whether to plot the graph or not.
    :param start_date: The date to start the growth rate list from.

    :return: A dictionary of the growth rates and the corresponding dates.
    """
    LOGGER.info("Calculating growth rates")
    data_dict = parse_data()
    growth_dict = {}

    for key in data_dict['x']:  # Iterating through each beer.
        if key_name is None or key_name == key:
            x_data, y_data = data_dict['x'][key], data_dict['y'][key]

            growth_rates = []
            dates = []

            # Iterating through the dates in required steps.
            for index in range(0, len(x_data)-days, days):
                date = x_data[index]
                if start_date is None or start_date <= date:
                    dates.append(date)
                    growth = calculate_growth(date, date + timedelta(days), x_data, y_data, days)
                    growth_rates.append(growth)
            LOGGER.debug("Data and date added")

            growth_dict[key] = growth_rates

            if plot:
                plt.plot(dates, growth_rates,
                         label=key + " growth % "+str(days),
                         linestyle='None', marker="D", markersize=2)

    if plot:
        plt.legend()
    return dates, growth_dict

def plot_next_year(days: int = 1, key_name: str = None, next_year: bool = True,
                   start_date: datetime = None, date_range: int = None)\
        -> Tuple[List[datetime], Dict[str, List[int]]]:
    """
    This module calculates the predictions for 1 year from the latest data in the csv file.

    The module has several options including calculating the data for just the given period.
    A prediction is made by calculating the growth rates per day in the csv file, and multiplying
    that to the latest sales made in the csv file.

    :param days:
    The period in which to calculate growth.
    Set this to values other than one to predict using time periods.
    :param key_name: Can be set to find the prediction for just one beer.
    :param next_year: Whether to adjust the dates for prediction.
    :param start_date: The date to start the prediction from.
    :param date_range: The number of days in the future the prediction should go on for.

    :return: A dictionary of predicted data and the corresponding dates.
    """
    LOGGER.info("Calculating next year")
    data_dict = parse_data()
    start_past_date = data_dict['x']['Organic Red Helles'][-1] - timedelta(days=364)
    dates, percent_dict = plot_growth_percent(days=days, key_name=key_name, plot=False,
                                              start_date=start_past_date)

    if dates is None:
        return None, None

    dates = [date + timedelta(days=days-1) for date in dates]
    prediction_dict = {}

    if next_year:
        dates = [date + timedelta(days=365) for date in dates]

    # Start date + date range is larger than date list
    if start_date is not None and start_date + timedelta(date_range) not in dates:
        return False, False

    for key, percent_list in percent_dict.items():
        start_sale = data_dict['y'][key][-1]

        LOGGER.debug("Multiplying rate")
        prediction_dict[key] = multiply_rate(start_sale, percent_list)

        if start_date is not None:
            index = dates.index(start_date)
            prediction_dict[key] = prediction_dict[key][index:]
        if date_range is not None:
            prediction_dict[key] = prediction_dict[key][:date_range]

    LOGGER.debug("All rates multiplied")
    if start_date is not None:
        dates = dates[index:]
    if date_range is not None:
        dates = dates[:date_range]

    return dates, prediction_dict

def get_total(start_date: datetime, date_range: datetime,
              data_tuple: Tuple[List[datetime], Dict[str, List[int]]]) -> Dict[str, int]:
    """
    This module gets the total sales in a given time period.

    :param start_date: The date to start counting the sales.
    :param date_range: The period in which to calculate the total.
    :param data_tuple: The list of dates and the dictionary which holds the sales data.

    :return:
    A dictionary containing the total for each beer.
    """
    LOGGER.info("Getting total from %s", str(start_date))
    dates, data = data_tuple
    return_dict = {}
    for key, batch in data.items():
        if start_date not in dates:
            LOGGER.warning("start date not in dates")
            return None

        index = dates.index(start_date)
        if index + date_range >= len(batch):
            LOGGER.warning("Date range out of range of batch list")
            return None

        return_dict[key] = sum(batch[index:index+date_range])
    return return_dict

if __name__ == "__main__":
    plot_past_data(key_name="Organic Pilsner")
    # plot_next_year(days=1, key_name="Organic Pilsner", next_year=False)
    # plot_growth_percent(days=7, key_name="Organic Pilsner")
    # plot_average_growths(days=3, key_name="Organic Pilsner")
    # dates, data = plot_next_year(plot=False)
    # print(get_total(datetime(2019, 12, 2), 7, dates, data))
    plt.show()


def collatz(num):
    """Recieves an integer as an attribute, if the number is even it divides it by two and
    returns the result. if the number is odd, it converts it to even and returns the result.
    """
    if num % 2 == 0:
        result = num / 2
        print(result)
    else:
        result = 3 * num + 1
        print(result)
    return result

def main_game():
    """Main game loop. it prompts the user to input a number wich is saved inside base_num,
    converts the number and checks if the input was actually an integer. if the input is
    indeed a number it loops through collatz until base_num reaches 1 and breaks the loop."""
    first_time_message = False
    while True:

        if not first_time_message:  # This makes sure the greet message shows up only one time.
            print("This algorithm will process any number you input until it reaches 1.")
            first_time_message = True

        print("Input a number:")

        try:
            base_num = int(input(""))

        except ValueError:
            print("Only numbers allowed")
            continue

        while base_num != 1:

            base_num = collatz(base_num)

main_game()


from enum import Enum
import math

class Vertex:
    """
    Graph vertex: A graph vertex (node) with data
    """
    def __init__(self, c = None, p = None,dist = None,n = None):
        """
        Vertex constructor
        @param color, parent, auxilary data1, auxilary data2
        """
        self.c = c
        self.p = p
        self.n = n
        self.dist = dist

class Graph:
    """
    Graph data: Any object which is used as a graph vertex data
    """
    def __init__(self, lv, le):
        """
        Data constructor
        @param A list of values assigned to object's attributes
        """
        self.lv = lv
        self.le = le

class Edge:
    """
    Graph data: Any object which is used as a graph vertex data
    """
    def __init__(self, src, dst, weight):
        """
        Data constructor
        @param A list of values assigned to object's attributes
        """
        self.src = src
        self.dst = dst
        self.weight = weight

class VertexColor(Enum):
        BLACK = 0
        GRAY = 127
        WHITE = 255

def makeGraph(lv,le):
	return Graph(lv,le)

def printGraph(G):
	for v in G.lv:
		print(v.n)
	for e in G.le:
		print(e.src.n + " " + e.dst.n + " - " + str(e.weight))

def getInDegrees(G):
	l = []
	for v in G.lv:
		cnt = 0
		for e in G.le:
			if e.dst.n == v.n:
				cnt = cnt + 1
		l.append(cnt)

	return l

def getOutDegrees(G):
	l = []
	for v in G.lv:
		cnt = 0
		for e in G.le:
			if e.src.n == v.n:
				cnt = cnt + 1
		l.append(cnt)

	return l

def initializeSingleSource(G,s):
	for v in G.lv:
		v.dist = math.inf
		v.p = None
	s.dist = 0

def relax(u,v,w):
	if v.dist > u.dist + w:
		v.dist = u.dist + w
		v.p = u

def bellmanFord(G,s):
	initializeSingleSource(G,s)
	for i in range(0,len(G.lv)):
		for e in G.le:
			relax(e.src, e.dst, e.weight)
	for e in G.le:
		if e.dst.dist > e.src.dist + e.weight:
			return False
	return True

def getEdge(G,u,v):
	for e in G.le:
		if e.src == u and e.dst == v:
			return e
	return None

def shortestPath(G,s,v):
	bellmanFord(G,s)
	l = []
	duzina = 0
	a = v
	while a is not None:
		l.append(a.n)
		if a.p != None:
			duzina = duzina + getEdge(G,a.p,a).weight
		a = a.p
	l.reverse()
	return l, duzina

def updateEdge(G,s,v,weight):
	edge = getEdge(G,s,v)
	if edge == None:
		e = Edge(s,v,weight)
		G.le.append(e)
	else:
		edge.weight = weight

#********************************************
a = Vertex(n = "a")
b = Vertex(n = "b")
c = Vertex(n = "c")
d = Vertex(n = "d")
e = Vertex(n = "e")
f = Vertex(n = "f")
g = Vertex(n = "g")
lv = [a,b,c,d,e,f,g]
ab = Edge(a,b,8)
ac = Edge(a,c,6)
bd = Edge(b,d,10)
cd = Edge(c,d,15)
ce = Edge(c,e,9)
de = Edge(d,e,14)
df = Edge(d,f,4)
ef = Edge(e,f,13)
eg = Edge(e,g,17)
fg = Edge(f,g,7)
le = [ab,ac,bd,cd,ce,de,df,ef,eg,fg]

G = makeGraph(lv,le)
printGraph(G)
l1 = getInDegrees(G)
l2 = getOutDegrees(G)

for i in l1:
	print(i)

print("\n")

for i in l2:
	print(i)

print("\n")
l,d = shortestPath(G,a,g)

print(d)
for i in l:
	print(i)

updateEdge(G,b,c,-4)
printGraph(G)


# -*- coding: utf-8 -*

# 将projects数据保存至时序数据库
def save_project(client, project):
    project_data = {}
    project_data['measurement'] = 'projects'
    project_data['time'] = project['created_at']
    project_data['tags'] = {
        "project_id": project['id'],
        "project_name": project['name']
    }
    project_data['fields'] = {
        "description": project['description'],
        "created_at": project['created_at'],
        "web_url": project['web_url'],
        "kind": project['namespace']['kind'],
        "groupid_or_userid": project['namespace']['id']
    }
    client.drop_series('projects', tags={'project_id': project['id']})
    return client.save_data([project_data])


import pytest
from unittest import mock
from truco_cord.models import Suit, CardValue, Card, Deck, Turn, Game, Round
from truco_cord.exceptions import GameException

@pytest.mark.parametrize(
    "suit, suit_value", [("diamonds", 0), ("spades", 1), ("hearts", 2), ("clubs", 3)]
)
def test_suit_create(suit, suit_value):
    obj = Suit(suit)
    assert obj
    assert obj.suit == suit_value

def test_suit_invalid_suit_raises_exception():
    with pytest.raises(ValueError):
        Suit("InvalidSuit")

@pytest.mark.parametrize("suit_name", ["diamonds", "spades", "hearts", "clubs"])
def test_suit_suit_name(suit_name):
    suit = Suit(suit_name)
    assert suit.suit_name() == suit_name

def test_suit_equal_special_method():
    obj = Suit("spades")
    same_value_obj = Suit("spades")
    different_value_obj = Suit("hearts")
    different_obj = object()
    assert obj == obj
    assert obj == same_value_obj
    assert obj != different_value_obj
    assert obj != different_obj

@pytest.mark.parametrize("value", "4567QJKA23")
def test_cardvalue_create(value):
    obj = CardValue(value)
    assert obj
    assert obj.value == value

def test_cardvalue_invalid_value_raises_exception():
    with pytest.raises(ValueError):
        CardValue("InvalidValue")

def test_card_value_equal_special_method():
    obj = CardValue("A")
    same_value_obj = CardValue("A")
    different_value_obj = CardValue("7")
    different_obj = object()
    assert obj == obj
    assert obj == same_value_obj
    assert obj != different_value_obj
    assert obj != different_obj

def test_card_create(suit, card_value):
    obj = Card(suit, card_value)
    assert obj
    assert obj.suit is suit
    assert obj.card_value is card_value

def test_card_create_method():
    obj = Card.create("spades", "A")
    assert isinstance(obj, Card)
    assert obj.card_value.value == "A"
    assert obj.suit.suit_name() == "spades"

def test_card_create_raises_exception_on_invalid_suit(card_value):
    invalid_suit = object()
    with pytest.raises(TypeError):
        Card(suit=invalid_suit, value=card_value)

def test_card_create_raises_exception_on_invalid_value(suit):
    invalid_value = object()
    with pytest.raises(TypeError):
        Card(suit=suit, value=invalid_value)

def test_card_equal_special_method():
    suit = Suit("spades")
    value = CardValue("A")
    obj = Card(suit, value)
    same_value_obj = Card(suit, value)
    different_value_obj = Card(Suit("spades"), CardValue("K"))
    different_obj = object()
    assert obj == obj
    assert obj == same_value_obj
    assert obj != different_value_obj
    assert obj != different_obj

def test_card_str(card):
    expected = "A of spades"
    assert str(card) == expected

def test_card_repr(card):
    expected = "<A of spades>"
    assert card.__repr__() == expected

@mock.patch("truco_cord.models.Deck.create_cards")
def test_deck_create(create_cards_mock, card):
    create_cards_mock.return_value = [card]
    obj = Deck()

    create_cards_mock.assert_called_once()
    assert obj
    assert obj.cards == [card]
    assert obj.shuffled == False

@mock.patch.multiple("truco_cord.models.CardValue", values=["A"])
@mock.patch.multiple("truco_cord.models.Suit", suits=["spades"])
def test_deck_create_cards_specific_card():
    cards = Deck.create_cards()
    assert len(cards) == 1
    assert cards[0].card_value.value == "A"
    assert cards[0].suit.suit_name() == "spades"

def test_deck_create_cards():
    cards = Deck.create_cards()
    assert len(cards) == 40

@mock.patch("random.shuffle")
def test_deck_shuffle(shuffle_mock, deck):
    deck.shuffle()

    shuffle_mock.assert_called_once_with(deck.cards)
    assert deck.shuffled == True

def test_deck_draw_card(deck):
    last_card = deck.cards[-1]
    original_length = len(deck.cards)
    card_drawn = deck.draw_card()

    assert last_card is card_drawn
    assert len(deck.cards) == (original_length - 1)

def test_game_create():
    handler = object()
    blue_players = [object() for _ in range(2)]
    red_players = [object() for _ in range(2)]
    game = Game(handler, blue_players, red_players)

    assert game
    assert game.handler is handler
    assert game.blue_players == blue_players
    assert game.red_players == red_players
    assert game.rounds == []
    assert game.score == (0, 0)

def test_game_new_round(game):
    result = game.new_round()

    assert game.rounds == [result]
    assert isinstance(result, Round)

def test_turn_create(card):
    player = object()
    turn = Turn(player=player, card=card)

    assert turn
    assert turn.player is player
    assert turn.card == card

def test_round_create(game):
    obj = Round(game)

    assert obj
    assert obj.game == game
    assert obj.turns == []

def test_round_player_turn(round, card):
    round.validate_turn = mock.Mock()
    player = object()
    result = round.player_turn(player, card)

    round.validate_turn.assert_called_once_with(card)
    assert isinstance(result, Turn)
    assert result.card == card
    assert result.player == player
    assert round.turns == [result]

def test_round_validate_turn_raises_exception_with_repeated_card(round, card):
    round.turns = [Turn(player=object(), card=card)]
    with pytest.raises(GameException):
        round.validate_turn(card)


import time
import threading

# 先定义一个全局变量
g_nums = [11,22]

def test1(temp):
	temp.append(33)
	print("---in test1 temp=%s" % str(temp))

# 获取全局变量，不用加global
def test2(temp):
	print("---in test2 temp=%s" % str(temp))

def main():
	# target指定将来这个线程会去哪个函数执行代码
	# args指定将来调用函数的时候，传递什么参数
	# 这里一定要注意，参数是个元组
	t1 = threading.Thread(target=test1, args=(g_nums,))
	t2 = threading.Thread(target=test2, args=(g_nums,))

	# 这里先进行t1线程
	t1.start()
	time.sleep(1)

	# 再进行t2
	t2.start()
	time.sleep(1)

	# 最后打印主线程中的值
	print("---in main Thread g_nums = %s ---" % str(g_nums))

if __name__ == "__main__":
	main()

08-多线程共享全局变量02.py


# -*- coding: utf-8 -*-
import random
import sys, pygame

from bonus import Bonus
from menu import Menu
from not_bug import NotBug
from player import Player
from bug import Bug
from results import Results
from timer import Timer
from suriken import Suriken
from pygame.image import load

pygame.init()
pygame.mouse.set_visible(False)
''' Вікно '''
size = width, height = 600, 630
window = pygame.display.set_mode(size)
''' Скріни '''
info_screen = pygame.Surface((600, 30))
screen = pygame.Surface((600, 600))
bg_image = load('images/bg.png')
'''Шрифти'''
pygame.font.init()
inf_font = pygame.font.Font(None, 27)
'''Меню'''
menu = Menu()
menu.menu(window)

player = Player()
player.name = "".join(menu.current_login)
left = right = False
sprite_group = pygame.sprite.Group()
sprite_group.add(player)

bug_army = []
bug_police = []
bonus_array = []
timer = Timer()
suriken_move = []
fps = pygame.time.Clock()

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                left = True
            if event.key == pygame.K_RIGHT:
                right = True

            if event.key == pygame.K_SPACE:
                if not suriken_move:
                    suriken = Suriken(x=player.rect.x, y=player.rect.y)
                    suriken_move.append(suriken)
                    sprite_group.add(suriken)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                left = False
            if event.key == pygame.K_RIGHT:
                right = False

            if event.key == pygame.K_ESCAPE:
                timer.pause_game()
                menu.menu(window)
                timer.unpause_game()

    '''Заливка'''
    screen.blit(bg_image, (0, 0))
    info_screen.fill((50, 50, 50))

    player.move(left, right)
    # Створюємо баги
    if len(bug_army) < 4:
        while len(bug_army) != 4:
            rand = random.randrange(10, 550)
            rand_speed = random.randrange(1, 5)
            bug = Bug(x=rand, speed=rand_speed)
            bug_army.append(bug)
            sprite_group.add(bug)
    # Створюємо не баги
    if len(bug_police) < 2:
        while len(bug_police) != 2:
            rand = random.randrange(10, 550)
            rand_speed = random.randrange(1, 5)
            notbug = NotBug(x=rand, speed=rand_speed)
            bug_police.append(notbug)
            sprite_group.add(notbug)

    if not bonus_array and int(timer.lost_time()) % 10 == 0:
            rand = random.randrange(10, 550)
            rand_speed = random.randrange(10, 11)
            bonus = Bonus(x=rand, speed=rand_speed)
            bonus_array.append(bonus)
            sprite_group.add(bonus)
    sprite_group.draw(screen)

    for b in bug_army:
        b.move(player, bug_army, suriken_move)
    for b in bug_police:
        b.move(player, bug_police, screen)
    for i in suriken_move:
        i.move(suriken_move)
    for i in bonus_array:
        i.move(player, bonus_array, timer)

    info_screen.blit(inf_font.render(u'Багов закрыто: '+str(player.bug_kill), 1, (212, 120, 49)), (10,5))
    info_screen.blit(inf_font.render(u'Время до релиза: ' + str(int(timer.lost_time())), 1, (212, 120, 49)), (190, 5))
    info_screen.blit(inf_font.render(u'Багов в релизе: ' + str(player.bug_miss), 1, (212, 120, 49)), (400, 5))

    if timer.lost_time() < 0 or player.bug_kill <= -1:
        # Після натискання Ретест обнуляємо всі елементи в грі
        res = Results(player)
        res.results(window, player)
        player.refresh()
        timer.start_game()
        for i in bug_army:
            i.remove(bug_army)
        for i in bug_police:
            i.remove(bug_police)

    window.blit(info_screen, (0, 0))
    window.blit(screen, (0, 30))

    pygame.display.flip()
    fps.tick(60)


import urllib2, urllib, datetime
from brown.models import Attempt
from brown.lib import utils

API_SSL_SERVER="https://www.google.com/recaptcha/api"
API_SERVER="http://www.google.com/recaptcha/api"
VERIFY_SERVER="www.google.com"

class RecaptchaResponse(object):
    def __init__(self, is_valid, error_code=None):
        self.is_valid = is_valid
        self.error_code = error_code

def display_html(public_key, use_ssl=False, error=None):
    """Gets the HTML to display for reCAPTCHA

    public_key -- The public api key
    use_ssl -- Should the request be sent over ssl?
    error -- An error message to display (from RecaptchaResponse.error_code)
    """
    error_param = ''
    if error:
        error_param = '&error=%s' % error

    if use_ssl:
        server = API_SSL_SERVER
    else:
        server = API_SERVER

    return """

  <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
  <input type='hidden' name='recaptcha_response_field' value='manual_challenge' />

""" % {
        'ApiServer': server,
        'PublicKey': public_key,
        'ErrorParam': error_param,
    }

def submit(recaptcha_challenge_field, recaptcha_response_field, private_key, remote_ip):
    """
    Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
    for the request

    recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form
    recaptcha_response_field -- The value of recaptcha_response_field from the form
    private_key -- your reCAPTCHA private key
    remote_ip -- the user's ip address
    """
    if not recaptcha_response_field or not recaptcha_challenge_field:
        return RecaptchaResponse(is_valid=False, error_code='incorrect-captcha-sol')

    def encode_if_necessary(s):
        if isinstance(s, unicode):
            return s.encode('utf-8')
        return s

    params = urllib.urlencode({
        'privatekey': private_key,
        'remoteip': remote_ip,
        'challenge': recaptcha_challenge_field,
        'response': recaptcha_response_field,
    })
    params = {key: encode_if_necessary(value) for key, value in params.iter_items()}

    request = urllib2.Request(
        url="http://%s/recaptcha/api/verify" % VERIFY_SERVER,
        data=params,
        headers={
            "Content-type": "application/x-www-form-urlencoded",
            "User-agent": "reCAPTCHA Python",
        }
    )

    httpresp = urllib2.urlopen(request)
    return_values = httpresp.read().splitlines()
    httpresp.close()

    return_code = return_values[0]

    if (return_code == "true"):
        return RecaptchaResponse(is_valid=True)
    else:
        return RecaptchaResponse(is_valid=False, error_code=return_values[1])

def check(request, attempt_type, config):
    """Check if the user should fill the captcha and if the captcha is valid."""
    time = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
    ip_long = utils.ip2long(request.remote_addr)

    fill_captcha = Attempt.query.filter(
        Attempt.ip==ip_long,
        Attempt.type==attempt_type,
        Attempt.date>time
    ).first() != None

    captcha_is_valid = not fill_captcha

    captcha_challenge = request.form.get('recaptcha_challenge_field')
    captcha_response = request.form.get('recaptcha_response_field')

    if fill_captcha and captcha_response and captcha_challenge:
        response = submit(
            captcha_challenge,
            captcha_response,
            config.get('CAPTCHA_PRIVATE_KEY'),
            request.remote_addr
        )
        captcha_is_valid = response.is_valid

    return fill_captcha, captcha_is_valid


import numpy as np
import pandas as pd
def regression(x,y):
	xMat=mat(x)
	yMat=mat(y).T
	xTx= xMat.T*xMat
	if linalg.det(xTx) == 0.0:
		print("this matrix is singular,cannot do inverse")
		return
	ws=xTx.T*(xMat.T*yMat)
	return ws


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

#'a test module'

__author__ = 'heyifeng'

import sys

def test():
    args = sys.argv  # argv参数至少存储了模块的文件名，
    # 运行python3 hello.py Michael获得的sys.argv就是['hello.py', 'Michael]。
    if len(args) == 1:
        print("hello_world")
    elif len(args) == 2:
        print('hello, %s' % args[1])
    else:
        print("Too many ")

# 当我们在命令行运行hello模块文件时，Python解释器把一个特殊变量__name__置为__main__，而如果在其他地方导入该hello模块时，
if __name__ == '__main__':
                                                        # if判断将失败，因此，这种if测试可以让一个模块通过命令行运行时执行一些额外的代码，最常见的就是运行测试。
    test()

def _private_1(name):
    return 'hello,%s' % name

def _private_2(name):
    return 'Hi,%s' % name

def greeting(name):
    if len(name) > 3:
        return _private_1(name)
    else:
        return _private_2(name)
s=input("your name is:")
print(greeting(s))


import random

class Manager(object):

    rand = [2, 2, 2, 4]
    before = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

    def __init__(self):
        self.add_rand(2)

    def add_rand(self, num=1):
        i = 0
        while i < num:
            x, y = random.randint(0, 3), random.randint(0, 3)
            if self.before[x][y] == 0:
                self.before[x][y] = random.choice(self.rand)
                i += 1

    def generate(self):
        ch = False
        for i in self.before:
            x = []
            last = 0
            for j in i:
                if j != 0:
                    if j == last:
                        x.append(x.pop() << 1)
                        last = 0
                    else:
                        x.append(j)
                        last = j
            x += [0] * (4 - len(x))
            if i != x:
                ch = True
                i[:] = x
        return ch

    def rotate(self, num):
        for i in range(num):
            self.before = [[self.before[i][j] for i in range(4)] for j in reversed(range(4))]

    def move(self, num):
        self.rotate(num)
        if self.generate():
            self.add_rand()
        self.rotate(4 - num)

    def left(self):
        self.move(0)

    def up(self):
        self.move(1)

    def right(self):
        self.move(2)

    def down(self):
        self.move(3)


import random
from hashlib import sha256

def make_key_pair(length):
    start = 1 << (length // 2 - 1)
    stop = 1 << (length // 2 + 1)

    if start >= stop:
        return []
    primes = [2]
    for n in range(3, stop + 1, 2):
        for p in primes:
            if n % p == 0:
                break
        else:
            primes.append(n)

    while primes and primes[0] < start:
        del primes[0]

    n_min = 1 << (length - 1)
    n_max = (1 << length) - 1
    while primes:
        p = random.choice(primes)
        primes.remove(p)
        q_candidates = [q for q in primes
                        if n_min <= p * q <= n_max]
        if q_candidates:
            q = random.choice(q_candidates)
            break
    return p, q

def co_prime(a, b):
    while b != 0:
        a, b = b, a % b
    return a

def mod_inv(aa, bb):
    remainder0, remainder = abs(aa), abs(bb)
    x, lastx = 0, 1
    while remainder:
        remainder0, (quotient, remainder) = remainder, divmod(remainder0, remainder)
        x, lastx = lastx - quotient * x, x
    return lastx * (-1 if aa < 0 else 1) % bb

def is_prime(num):
    if num == 2:
        return True
    if num < 2 or num % 2 == 0:
        return False
    for n in range(3, int(num ** 0.5) + 2, 2):
        if num % n == 0:
            return False
    return True

def generate_key_pair(p, q):
    n = p * q
    phi = (p - 1) * (q - 1)
    e = random.randrange(1, phi)
    g = co_prime(e, phi)

    while g != 1:
        e = random.randrange(1, phi)
        g = co_prime(e, phi)

    d = mod_inv(e, phi)
    return (e, n), (d, n)

def encrypt(private_key, plain_text):
    key, n = private_key
    return [pow(ord(char), key, n) for char in plain_text]

def decrypt(public_key, cipher_text):
    key, n = public_key
    plain = [chr(pow(char, key, n)) for char in cipher_text]
    return ''.join(plain)

def hash_function(message):
    return sha256(message.encode("UTF-8")).hexdigest()

if __name__ == '__main__':
    pub, priv = make_key_pair(10)
    pub, priv = generate_key_pair(pub, priv)

    text = 'qwerty12345678ytrewq'
    hashed = hash_function(text)
    enc_text = encrypt(priv, hashed)
    dec_text = decrypt(pub, enc_text)
    print(True if dec_text == hash_function(text) else False)


from django import forms
from models import *

class agregar_paciente_form(forms.Form):
    num_historia     = forms.IntegerField(
                            max_value=999999,
                            widget = forms.TextInput(attrs={'size': 6}))
    tipo_cedula      = forms.ChoiceField(
                            choices=TIPO_CEDULA,
                            widget=forms.RadioSelect())
    cedula           = forms.IntegerField(max_value=999999999)
    nombres          = forms.CharField(max_length=64)
    apellidos        = forms.CharField(max_length=64)
    sexo             = forms.ChoiceField(choices=SEXO)

    fecha_nacimiento          = forms.DateField(
                        label = "FECHA DE NACIMIENTO",
                        widget = forms.TextInput(attrs = {
                            'placeholder':'dd/mm/aaaa',
                            'data-format':'dd/mm/yyyy'
                            }))
    fecha_ingreso_institucion = forms.DateField(
                        label = "FECHA DE INGRESO A LA INSTITUCION",
                        widget = forms.TextInput(attrs = {
                            'placeholder':'dd/mm/aaaa',
                            'data-format':'dd/mm/yyyy'
                            }))


from models.kinematics import newtonian_model as nm
from models.em import em_model as em

print("\n\n--------------------------------------")
print("Welcome to the Physics Problem Solver!")
userFunc = ""

while userFunc != "exit":
    print("--------------------------------------")
    print("[function name]\t\t:\t[code]\t:\t[required parameters]\n"
          "distance\t\t\t:\tdis\t\t:\tinitial velocity, acceleration, time\n"
          "final velocity\t\t:\tfvd\t\t:\tinitial velocity, acceleration, distance\n"
          "final velocity\t\t:\tfvt\t\t:\tinitial velocity, acceleration, time\n"
          "*horizontal range\t:\thr\t\t:\tinitial velocity, angle, gravity\n"
          "*maximum height\t\t:\tmx\t\t:\tinitial velocity, angle, initial height, gravity\n"
          "coulomb force\t\t:\tcf\t\t:\tcharge 1, charge 2, distance r\n"
          "*electric field\t\t:\tef\t\t:\tcharge, distance r, x coordinate, y coordinate")
    print("--------------------------------------\n")

    userFunc = input("Enter a function code:\n")
    params = []

    # newtonian models
    if userFunc == "dis":
        for i in range(3):
            params.append(int(input("Enter parameter %d\t" % (i + 1))))
        nm.distance(params[0], params[1], params[2])

    if userFunc == "fvd":
        for i in range(3):
            params.append(int(input("Enter parameter %d\t" % (i + 1))))
        nm.vel_final_dist(params[0], params[1], params[2])

    if userFunc == "fvt":
        for i in range(3):
            params.append(int(input("Enter parameter %d\t" % (i + 1))))
        nm.vel_final_time(params[0], params[1], params[2])

    if userFunc == "hr":
        for i in range(3):
            params.append(int(input("Enter parameter %d\t" % (i + 1))))
        nm.horizontal_range(params[0], params[1], params[2])

    if userFunc == "mx":
        for i in range(4):
            params.append(int(input("Enter parameter %d\t" % (i + 1))))
        nm.maximum_height(params[0], params[1], params[2], params[3])

    # em models
    if userFunc == "cf":
        for i in range(3):
            params.append(input("Enter parameter %d\t" % (i + 1)))
        em.coulomb_force(float(params[0]), float(params[1]), float(params[2]))
        # remove this eventually, just to check function
        a = em.coulomb_force(float(params[0]), float(params[1]), float(params[2]))
        print("%.4g" % a)

    if userFunc == "ef":
        for i in range(4):
            params.append(int(input("Enter parameter %d\t" % (i + 1))))
        em.electric_field(params[0], params[1], params[2], params[3])


from .nodes.estimate_propensity import (
    bundle_train_and_test_data, impute_cols_features, schedule_propensity_scoring,
    treatment_fractions_, treatment_fractions_, fit_propensity, estimate_propensity,
    compute_cate, add_cate_to_df, recommend_by_cate, estimate_effect)

from .nodes.model_for_each import (
    model_for_treated_simulate_recommendation, model_for_untreated_simulate_recommendation,
    model_for_treated_fit, model_for_untreated_fit, bundle_treated_and_untreated_models,
    model_for_treated_predict_proba, model_for_untreated_predict_proba)

from .base_causal_lift import BaseCausalLift

class CausalLift(BaseCausalLift):

    def __init__(self, train_df, test_df, **kwargs):
        super(CausalLift, self).__init__(**kwargs)
        self.runner = None

        self.df = bundle_train_and_test_data(self.args_raw, train_df, test_df)
        self.args = impute_cols_features(self.args_raw, self.df)
        self.args = schedule_propensity_scoring(self.args, self.df)
        self.treatment_fractions = treatment_fractions_(self.args, self.df)
        if self.args.need_propensity_scoring:
            self.propensity_model = fit_propensity(self.args, self.df)
            self.df = estimate_propensity(self.args, self.df, self.propensity_model)

        self.treatment_fraction_train = self.treatment_fractions.train
        self.treatment_fraction_test = self.treatment_fractions.test

        self._separate_train_test()

    def estimate_cate_by_2_models(self):
        treated__model_dict = model_for_treated_fit(self.args, self.df)
        untreated__model_dict = model_for_untreated_fit(self.args, self.df)
        self.uplift_models_dict = bundle_treated_and_untreated_models(treated__model_dict, untreated__model_dict)

        self.treated__proba = model_for_treated_predict_proba(self.args, self.df, self.uplift_models_dict)
        self.untreated__proba = model_for_untreated_predict_proba(self.args, self.df, self.uplift_models_dict)
        self.cate_estimated = compute_cate(self.treated__proba, self.untreated__proba)
        self.df = add_cate_to_df(self.args, self.df, self.cate_estimated)

        return self._separate_train_test()

    def estimate_recommendation_impact(
        self, cate_estimated=None, treatment_fraction_train=None,
        treatment_fraction_test=None, verbose=None):

        super(CausalLift, self).estimate_recommendation_impact(
            cate_estimated,
            treatment_fraction_train,
            treatment_fraction_test,
            verbose
        )

        self.treatment_fractions.train = (treatment_fraction_train or self.treatment_fractions.train)
        self.treatment_fractions.test = (treatment_fraction_test or self.treatment_fractions.test)

        self.df = recommend_by_cate(self.args, self.df, self.treatment_fractions)
        self.treated__sim_eval_df = model_for_treated_simulate_recommendation(self.args, self.df, self.uplift_models_dict)
        self.untreated__sim_eval_df = model_for_untreated_simulate_recommendation(self.args, self.df, self.uplift_models_dict)
        self.estimated_effect_df = estimate_effect(self.treated__sim_eval_df, self.untreated__sim_eval_df)


from __future__ import absolute_import

from django.conf.urls import patterns, url
from django.views.generic import TemplateView

from contact_form.views import contact_form

from .forms import FoundationContactForm

urlpatterns = patterns('',
    url(
        regex=r'^foundation/$',
        view=contact_form,
        kwargs=dict(
            form_class=FoundationContactForm,
            template_name='contact/foundation.html',
        ),
        name='contact_foundation',
    ),
    url(
        regex=r'^sent/',
        view=TemplateView.as_view(template_name='contact/sent.html'),
        name='contact_form_sent',
    )
)


"""
Given the number k, return the minimum number of Fibonacci numbers whose sum is equal to k, whether a Fibonacci number could be used multiple times.

The Fibonacci numbers are defined as:

F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 , for n > 2.
It is guaranteed that for the given constraints we can always find such fibonacci numbers that sum k.

Example 1:
    Input: k = 7
    Output: 2
    Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
    For k = 7 we can use 2 + 5 = 7.

Example 2:
    Input: k = 10
    Output: 2
    Explanation: For k = 10 we can use 2 + 8 = 10.

Example 3:
    Input: k = 19
    Output: 3
    Explanation: For k = 19 we can use 1 + 5 + 13 = 19.

Constraints:
    1 <= k <= 10^9
"""

def findMinFibonacciNumbers(k):
    min = 0
    while k > 0:
        nums = [1, 1]
        while True:
            new_k = sum(nums[-2:])
            if new_k > k:
                break
            else:
                nums.append(new_k)
        k -= nums[-1]
        min += 1
        print(nums)
    return min

k1 = 7
k2 = 10
k3 = 19
print(findMinFibonacciNumbers(k3))

LeetCode-Python/1414 Find the Minimum Number of Fibonacci Numbers Whose Sum Is K.py


#Labsheet 2
#Question 5
hoursStr=input("How many hours?")
inpHours=int(hoursStr)
minutesStr=input("How many minutes?")
minutes=int(minutesStr)
currHours=inpHours
midi="in the morning."
periodHour=''
#-------------------------------------------------------------
#this bit checks if the user enters hours and minutes that are valid
if (minutes<0) or (minutes>59):
    print('The time you entered is invalid. Please try again!')
elif (inpHours<0) or (inpHours>23):
    print('The time you entered is invalid. Please try again!')
#-------------------------------------------------------------
else:
#three main variables that will form our final string:
    #  midi - tells us if it is morning or afternoon
    #  periodHour - tells us what period in an hour we are in(half past, quarter to etc)
    #  currHours - tells us at what hour we have to approximate the input

    if inpHours==12:
        midi="in the afternoon."
        currHours=inpHours
    elif inpHours>12:
        currHours=inpHours-12
        midi="in the afternoon."
    if (minutes>=53) and (minutes<=59):
        if (inpHours==12) or (inpHours==0):
            currHours=1
        else:
            currHours=currHours+1
            if inpHours==11:
                midi='in the afternoon.'
            elif inpHours==23:
                midi='in the morning.'
    elif (minutes>=38) and (minutes<=52):
        periodHour='quarter to '
        if (inpHours==12) or (inpHours==0):
            currHours=1

        else:
            currHours=currHours+1

    elif (minutes>=8) and (minutes<=22):
        periodHour='quarter past '
    elif (minutes>=23) and (minutes<=37):
        periodHour='half past '
#This bit transforms the integer currHours into the word representing the number
#It also prints the message
    numToWords=['twelve ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve']
    timeOfDay='The time is about ' + periodHour + numToWords[currHours] + midi
    print(timeOfDay)


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 22:57:12 2020

@author: Amber
"""

WIKIPEDIA_URL = "https://en.wikipedia.org"

WALK_OF_FAME_URL = ("https://en.wikipedia.org/wiki/"
                    + "List_of_actors_with_Hollywood_Walk_of_Fame_motion_picture_stars")

OUTPUT_PATH = ("C:\\Users\\Ladyj\\Documents\\GitHub\\"
               + "Walk-Of-Fame-Marriage-Analysis\\output")

STARS_OUTPUT = OUTPUT_PATH + "\\walk_of_fame_stars.csv"
FILLED_DATA_OUTPUT = OUTPUT_PATH + "\\filled_data.csv"

HTML_OUTPUT_PATH = OUTPUT_PATH + "\\star_html\\"


import requests
import urllib.request
import json
import time
import threading
import random, string

class PostThread(threading.Thread):
    def __init__(self, random_str):
        threading.Thread.__init__(self)
        self.id = random_str
        self.msg_count = 0
        self.start()

    def run(self):
        for i in range(1):
            random_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
            print(random_str)
            item = {
                "fromId": 101676,
                "fromType": "fromType",
                "model": 0,
                "msgBody": {
                    "msgContent": {
                        "arn": "arn",
                        "durationTime": 7,
                        "extras": "extras",
                        "fileSize": 2,
                        "format": "format",
                        "height": 5,
                        "mediaCrc32": "mediaCrc32",
                        "mediaId": "mediaId",
                        "text": "text",
                        "width": 5
                    },
                    "msgType": "text"
                },
                "msgType": "msgType",
                "targetId": 2,
                "targetType": "targetType",
                "version": 0,
                "time_stamp": time.time()
            }
            request_url = "http://127.0.0.1:5000/messages/public"
            r = requests.post(url=request_url, data=json.dumps(item), headers=header)
            # print(r)

if __name__ == "__main__":
    random_str = ''.join(random.sample(string.ascii_letters + string.digits, 32))
    # print(random_str)

    header = {"Accept": "application/json",
    # "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Content-Type": "application/json",
    "Host": "10.152.21.175:5000",
    "Origin": "http://10.152.21.175:5000",
    "Referer": "http://10.152.21.175:5000/ui/",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36"
        }

    # item = {"account": ["qiaoyuan", "tianxb", "heyx1"], "message": "test", "tag": 1, "title": "title", "extend": ""}
    # request_url = "https://cbazc8kgok.execute-api.cn-northwest-1.amazonaws.com.cn/test/"
    # r = requests.post(url=request_url, data=json.dumps(item))
    # print(r)

    for i in range(10):
        pt = PostThread(str(i))

    # class DataItem(object):
    #     """
    #     asdasdasd
    #     """
    #     # __slots__ = ['name', 'age', 'address']
    #     def __init__(self, name, age, address):
    #         self.name = name
    #         self.age = age
    #         self.address = address
    #
    #
    # def dump(obj):
    #     for attr in dir(obj):
    #         print("  obj.%s = %r" % (attr, getattr(obj, attr)))
    #
    #
    # test = DataItem('1', '2', '3')
    # dump(test)
    #
    # print(test.__dict__)
    #
    # print(test.__eq__())


from django.http import HttpResponse
from django.shortcuts import render
from . models import Gig

#waffle decorator for feature toggling
from waffle.decorators import waffle_switch

@waffle_switch('gig_global_features')
def index(request):
	gig_list = Gig.objects.order_by('-created_date')
	context = {
		'gig_list':gig_list,
	}
	return render(request, 'gigs/index.html', context)

@waffle_switch('gig_global_features')
def gig_detail(request, gig_pk):
	gig = Gig.objects.get(pk=gig_pk)
	context = {'gig': gig}
	return render(request, 'gigs/gig_detail.html', context)


'''
1.程序开始的时候提示用户输入学生年龄信息 格式如下：

Jack Green ,   21  ;  Mike Mos, 9;

我们假设 用户输入 上面的信息，必定会遵守下面的规则：
  学生信息之间用分号隔开（分号前后可能有不定数量的空格），
  每个学生信息里的 姓名和 年龄之间用 逗号隔开（逗号前后可能有不定数量的空格）

2. 程序随后将输入的学生信息分行显示，格式如下
Jack Green :   21;
Mike Mos   :   09;
学生的姓名要求左对齐，宽度为20， 年龄信息右对齐，宽度为2位，不足前面补零
'''

#输入学生姓名及年龄
inputstr = input('请输入学生姓名及年龄（多条数据以;间隔）:')
#以分号截取字符串信息
student =inputstr.split(';')
#循环遍历截取字符串数据
for one in student:
    #判断遍历的数据没有’,‘时跳过继续执行
    if ',' not in one:
        continue
    #定义两个变量接收以’,‘截取的遍历数据
    name = one.split(',')
    age = one.split(',')
    #去掉前后空格
    name = name[0].strip()
    age = age[1].strip()
    #判断年龄字符串中信息不是纯数字时跳过当前循环继续执行
    if not age.isdigit():
        print('您输入的学生年龄中含有非数字字符，请重新输入')
        continue
    age = int(age)#年龄转化为int类型
    print(f'{name:<20}:{age:0>2}')
'''
       11题总结:
    1-调用isdigit()方法时age.isdigit后面没加括号导致运行时报错
    2-代码逻辑思维能力不灵活，需要多练多敲

'''