예제 #1
0
def main():
    ctrl = True  # 标记是否退出系统
    while (ctrl):
        menu.menu()
        option = input("请选择:")
        option_str = re.sub('\D', '', option)  # 提取数字
        if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:
            option_int = int(option_str)
            if option_int == 0:
                print("您已退出学生管理系统!")
                ctrl = False
            elif option_int == 1:
                insert.insert()
            elif option_int == 2:
                search.search()
            elif option_int == 3:
                delete.delete()
            elif option_int == 4:
                modify.modify()
            elif option_int == 5:
                sort.sort()
            elif option_int == 6:
                total.total()
            elif option_int == 7:
                show.show()
예제 #2
0
def fetch_and_update(matches, teams, comp, standings):
    cursor = db.cursor()
    # call function to fill in data for matches
    get_season_data(matches, standings)

    # set up data frame object
    df = pd.DataFrame(standings)
    df = df.transpose()
    df.sort_values(by=['pts', 'gd', 'gs', 'ga'],
                   ascending=[0, 0, 0, 1],
                   inplace=True)
    df = df[[
        'gp', 'pts', 'gs', 'ga', 'gd', 'lead_time', 'trail_time', 'competition'
    ]]
    df = df.reset_index()
    df['lead_time_p90'] = df['lead_time'] / df['gp']
    df['trail_time_p90'] = df['trail_time'] / df['gp']
    df.columns = [
        'team', 'gp', 'pts', 'gs', 'ga', 'gd', 'lead_time', 'trail_time',
        'competition', 'lead_time_p90', 'trail_time_p90'
    ]
    df['pos'] = df.index + 1

    # create numpy array of data for the model
    X = np.asarray(df[['lead_time_p90', 'trail_time_p90', 'gs', 'ga']])
    df['top_four'] = model.top_four(comp, X)
    df['top_six'] = model.top_six(comp, X)
    df['relegation'] = model.relegation(comp, X)
    print(df)

    # convert df to dictionary and insert them into sql database
    data_dict = df.to_dict('records')
    for entry in data_dict:
        insert.insert(cursor, db, 'Competition_Summary', **entry)
def create_lead(cursor, db, match_id):
    cursor.execute("select minute, home_score, away_score \
                from scores where match_id = %s \
                order by minute;" % match_id)
    score_data = cursor.fetchall()

    insert_dict = {'match_id': match_id}
    for i in range(-1, len(score_data)):
        if i == -1:
            start = 0
            end = score_data[i + 1][0]
            hg = 0
            ag = 0
        elif score_data[i] is score_data[-1]:
            start = score_data[i][0]
            end = 91 if score_data[i][0] < 90 else score_data[i][0] + 2
            hg = score_data[i][1]
            ag = score_data[i][2]
        else:
            start = score_data[i][0]
            end = score_data[i + 1][0]
            hg = score_data[i][1]
            ag = score_data[i][2]

        for time in range(start, end):
            insert_dict['minute'] = time
            insert_dict['home_score'] = hg
            insert_dict['away_score'] = ag
            insert.insert(cursor, db, 'extended_scores', **insert_dict)
예제 #4
0
def update_metadata(match_id, cursor, db):
    """
    update weird metadata
    """
    session = HTMLSession()
    url = 'http://www.football-lineups.com/match/%s' % match_id
    r = session.get(url)
    r.html.encoding = 'ISO-8859-1'

    # HEIGHT #
    trs = r.html.find('tr')
    trs = [
        tr for tr in trs
        if 'align' in tr.attrs.keys() and tr.attrs['align'] == 'center'
    ]

    for i, tr in enumerate(trs):
        if 'Height Avg' in tr.text:
            home_height = tr.find('td')[0].text[:4]
            away_height = tr.find('td')[2].text[:4]
            break

    print(match_id, home_height, away_height)

    # INSERT #
    data_dict = {
        'match_id': match_id,
        'home_height': home_height,
        'away_height': away_height
    }
    insert.insert(cursor, db, 'match_metadata', **data_dict)
예제 #5
0
    def insert_league_records(self):
        lodicts = []
        data_dict = self.league_records
        for i, team in data_dict.items():
            for md in team['history']:
                lodicts.append(md)

        insert.insert('league_records', lodicts)
예제 #6
0
    def insert_player_data(self):
        lodicts = []
        data_dict = self.players
        for player in data_dict:
            player['competition'] = self.competition
            player['season'] = self.year
            lodicts.append(player)

        insert.insert('player_data', lodicts)
예제 #7
0
    def insert_rosters(self):
        lodicts = []
        for k, team in self.rosters.items():
            for j, player in team.items():
                player['competition'] = self.match_info['league']
                player['season'] = self.match_info['season']
                player['position_order'] = player.pop('positionOrder')
                player['match_id'] = self.match_info['id']
                lodicts.append(player)

        insert.insert('roster_data', lodicts)
예제 #8
0
    def insert_shot_data(self):
        lodicts = []
        for k, team in self.shot_data.items():
            for shot in team:
                shot['last_action'] = shot.pop('lastAction')
                shot['shot_type'] = shot.pop('shotType')
                shot['team'] = shot['h_team'] if shot['h_a'] == 'h' else \
                    shot['a_team']
                shot['competition'] = self.match_info['league']
                lodicts.append(shot)

        insert.insert('shot_data', lodicts)
예제 #9
0
 def insert_team_data(self):
     # changing so i can edit stuff
     data_dict = self.team_data
     for category, v in data_dict.items():
         lodicts = []
         for meta_category, vi in v.items():
             vi['category'] = category
             vi['meta_category'] = meta_category
             vi['team'] = ' '.join(self.name.split('_'))
             vi['competition'] = self.competition
             vi['season'] = self.year
             lodicts.append(vi)
         insert.insert('team_data', lodicts)
예제 #10
0
def newUser(msg=[]):
    print(msg)
    db = pymysql.connect('localhost', 'server', '[removed for security]',
                         'thegrind')
    cursor = db.cursor()
    sql = "SELECT * FROM userinfo"
    try:
        cursor.execute(sql)
        results = cursor.fetchall()
        print(results)
        idnum = 0
        uname = 1
        email = 2
        pw = 3
        achiev = '00000000'
        users = []
        emails = []
        pws = []
        for idx in results:
            print(idx[idnum])
        for idx in results:
            users.append(idx[uname])
        for idx in results:
            emails.append(idx[email])
        for idx in results:
            pws.append(idx[pw])
        print(users, '\n', emails, '\n', pws)
        if msg[0] != msg[1]:  #if uname and confirmUname dont match
            print('Uname error')
            return 1
        if msg[2] != msg[3]:  #if emails dont match
            print('Email error')
            return 2
        if msg[4] != msg[5]:  #is passwords dont match
            print('Password error')
            return 3
        if msg[0] in users:  #if user in table
            print('Invalid Uname')
            return 4
        if msg[2] in emails:  #if email in table
            print('Invalid Email')
            return 5
        if msg[4] in pws:  #if password in table
            print('Invalid Pass')
            return 6
        insert.insert(msg[0], msg[2], msg[4], achiev)
    except:
        pass
    db.close()
    return 0  #successful entry into table
예제 #11
0
 def menu(self):
     while self.dato:
         selection = input(
             '\nSelect 1 to insert, 2 to update, 3 to read, 4 to delete \n')
         if selection == '1':
             insert.insert()
         elif selection == '2':
             update.update()
         elif selection == '3':
             read.read()
         elif selection == '4':
             delete.delete()
         else:
             print('\n Invalid selection \n')
예제 #12
0
    def menu(self):

        while self.dato:
            selecction = input("\n Selecciona una de las opciones del menu \n 1.- Insertar \n 2.- Leer \n 3.-Actualizar \n 4.-Borrar \n\n")
            if selecction=='1':
                insert.insert()
            elif selecction=='2':
                read.read()
            elif selecction=='3':
                update.update()
            elif selecction=='4':
                delete.delete()
            else:
                print("Instruccion invalida")
예제 #13
0
def upload(data):

    counter = 0

    while counter < 5:
        try:
            insert(data)
            counter += 6

        except RuntimeError as error:
            print(error.args[0])

        time.sleep(2.0)
        counter += 1
예제 #14
0
def upload(data):

    counter = 0

    while counter < 5:
        try:
            insert(data)
            counter += 6

        except RuntimeError as error:
            print(error.args[0])
            logging.error('RuntimeError@upload:', exc_info=error)

        time.sleep(2.0)
        counter += 1
예제 #15
0
    def menu(self):
        while self.dato:
            selection = input(
                '\nSelecciona 1 para insertar, 2 para actualizar, 3 para leer, 4 para borrar.\n'
            )

            if selection == '1':
                insert.insert()
            elif selection == '2':
                update.update()
            elif selection == '3':
                read.read()
            elif selection == '4':
                delete.delete()
            else:
                print('\nSelección inválida.')
예제 #16
0
def store_metrics(request):
    if 'metric' in request.params and 'value' in request.params and 'ID' in request.params:
        print request.params['metric']
        print request.params['value']
        print request.params['ID']
        metric = request.params['metric']
        value = int(request.params['value'])
        ID = int(request.params['ID'])
        insert.insert(value, metric, ID)
        return Response(body="Stored to database",
                        content_type=CONTENT_TYPE_LATEST)
    else:
        print "NO"
        return Response(body="Not stored to database")

    return Response(status="OK")
예제 #17
0
def saving():
    jsonData = request.get_json(cache=False)
    user=jsonData["userName"]
    type = "Goal"
    if request.method =='GET':
        getData = access(graph, type, user, user)
    elif request.method=='POST':
        postData = [jsonData["userName"], jsonData["savingsName"], jsonData["amount"], jsonData["downpay"],jsonData["term"],jsonData["description"]]
        insert(graph,type,postData)
    elif request.method=='PUT':
        current=["currentItem"]
        mod = jsonData["modItem"]
        modify(graph,type,user,current,mod)
    elif request.method=='DELETE':
        delItem=jsonData["delItem"]
		delete(graph,type,user,delItem)
예제 #18
0
def transaction():
    jsonData = request.get_json(cache=False)
    user=jsonData["userName"]
    type = "Transaction"
    if request.method =='GET':
        getData = access(graph, type, user, user)
    elif request.method=='POST':
        postData = [jsonData["userName"], jsonData["transName"], jsonData["transDate"], jsonData["transLocation"],jsonData["transAmount"]]
        insert(graph,type,postData)
    elif request.method=='PUT':
        current=["currentItem"]
        mod = jsonData["modItem"]
        modify(graph,type,user,current,mod)
    elif request.method=='DELETE':
        delItem=jsonData["delItem"]
		delete(graph,type,user,delItem)
예제 #19
0
def menuLista():
    global listaPila
    while True:
        print("Seleccione una opción:\n")
        print("1)Insert")
        print("2)Delete")
        print("3)Salir")
        opc = int(input())
        if opc == 3:
            break
        else:
            if opc == 1:
                insert.insert(lista)
            elif opc == 2:
                datoBorrado = (lista)
            mostrarLista.mostrarLista(lista)
예제 #20
0
파일: app.py 프로젝트: lbedoyas/Python
    def menu(self):

        while self.dato:
            # chossing option to do CRUD operations
            selection = input(
                '\nSelect 1 to insert, 2 to update, 3 to read, 4 to delete\n')

            if selection == '1':
                insert.insert()
            elif selection == '2':
                update.update()
            elif selection == '3':
                read.read()
            elif selection == '4':
                delete.delete()
            else:
                print('\n INVALID SELECTION \n')
예제 #21
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-e", "--env", help="get db.conf")
    args = parser.parse_args()
    if len(sys.argv) == 1:
        get.get_pdf()
        v1 = parse01.parse_pdf01("./pdf/")
        v2 = parse02.parse_pdf02("./pdf/")
        insert.insert(v1, v2, 'test')
    elif len(sys.argv) == 3:
        get.get_pdf()
        v1 = parse01.parse_pdf01("./pdf/")
        v2 = parse02.parse_pdf02("./pdf/")
        insert.insert(v1, v2, args.env)
    else:
        print("error param!")
        sys.exit(1)
예제 #22
0
def switch(cursor, mysqldb, option, table_name):

    switchDic = {
        "1": sel.mysqlsel(cursor, mysqldb, table_name),
        "2": ins.insert(cursor, mysqldb, table_name),
        "3": up.update(cursor, mysqldb, table_name),
        "4": de.delete(cursor, mysqldb, table_name)
    }
    return switchDic.get(option, switchDefault())
 def menu(self):
     while self.dato:
         print('\nSelect: ')
         print('\n 1 to Insert ')
         print('\n 2 to Update ')
         print('\n 3 to Read ')
         print('\n 4 to Delete ')
         selection = input('\nChoose your option: ')
         if selection == '1':
             insert.insert()
         elif selection == '2':
             update.update()
         elif selection == '3':
             read.read()
         elif selection == '4':
             delete.delete()
         else:
             print('\n INVALID SELECTION \n')
예제 #24
0
def main():

    quit = "y"
    while (quit == 'y' or quit == 'Y'):
        
        x = PrettyTable(["A R A B I D O P S I S  T H A L I A N A  D A T A B A S E"])
        x.align["A R A B I D O P S I S  T H A L I A N A  D A T A B A S E"] = "l" 
        x.padding_width = 1
        x.add_row(["1. Create the Genes table"]) 
        x.add_row(["2. Display the Genes"])
        x.add_row(["3. Insert a new Gene"])
        x.add_row(["4. Delete a Gene"])
        x.add_row(["5. Blast a Gene"])
        print x 
    
        ## Get input ###
        choice = raw_input('Enter your choice [1-5] : ')
    
        ### Convert string to int type ##
        choice = int(choice)
 
        ### Take action as per selected menu-option ###
        if choice == 1:
            create.create() #this will create the tables and popululate the data
            
        elif choice == 2:
            display.display() # display both the tables from the database
            
        elif choice == 3:
            insert.insert() # insert a new gene record in the database
            
        elif choice == 4:
           delete.delete() # delete a gene record from the database
           
        elif choice == 5:
            name = raw_input("Please enter the name of the gene to perform blast: ")
            Blast.fn(name) # Calls the BLAST module
            Blast.show()   # Calls the module that prints image downloaded from Google Search
            
           
               
        else:    ## default ##
            print ("Invalid input. Please enter the correct input...")
        quit = raw_input('Do you wanna Continue : ')
예제 #25
0
def check_sort():
    result = {
        'insert': {},
        'select': {},
        'bubble': {},
    }
    array_insert = get_array('up')
    array_select = array_insert.copy()
    array_bubble = array_insert.copy()
    result['insert']['up'] = insert(array_insert, len(array_insert))
    result['select']['up'] = select(array_select)
    result['bubble']['up'] = bubble(array_bubble)

    array_insert = get_array('down')
    array_select = array_insert.copy()
    array_bubble = array_insert.copy()
    result['insert']['down'] = insert(array_insert, len(array_insert))
    result['select']['down'] = select(array_select)
    result['bubble']['down'] = bubble(array_bubble)

    avg = {'insert': [0, 0], 'select': [0, 0], 'bubble': [0, 0]}
    for i in range(400):
        array_insert = get_array('rand')
        array_select = array_insert.copy()
        array_bubble = array_insert.copy()

        sort_result = insert(array_insert, len(array_insert))
        avg['insert'][0] += sort_result[0]
        avg['insert'][1] += sort_result[1]

        sort_result = select(array_select)
        avg['select'][0] += sort_result[0]
        avg['select'][1] += sort_result[1]

        sort_result = bubble(array_bubble)
        avg['bubble'][0] += sort_result[0]
        avg['bubble'][1] += sort_result[1]

    result['insert']['rand'] = [avg['insert'][0] / 400, avg['insert'][1] / 400]
    result['select']['rand'] = [avg['select'][0] / 400, avg['select'][1] / 400]
    result['bubble']['rand'] = [avg['bubble'][0] / 400, avg['bubble'][1] / 400]

    return result
예제 #26
0
def parse_html(html):
    soup = bs4.BeautifulSoup(html, 'html.parser')
    trs = soup.select('tr')
    for tr in trs[3:]:
                a = tr.contents[3].contents[1].attrs['href']
                id = a[23:47]
                href = a[50:-3]
                url1 = 'http://tzxm.hbzwfw.gov.cn/sbglweb/xminfo?xmdm='+id+'&sxid='+href+'&xzqh=130000'

                html1 = requests.get(url1, headers=headers1,proxies={"http": "http://{}".format(proxy)}, timeout=50)
                if html1.status_code == 200:
                    # print('点击页面获取成功')
                    html1 = html1.text
                    soup1 = bs4.BeautifulSoup(html1, 'html.parser')
                    tables = soup1.select('td')
                    j = 3
                    k = 3
                    sql = ''
                    sql1 = ''
                    sql2 = ''
                    for table  in  tables[3:]:
                        if j%2 ==1 and  j<10 :
                            # print(table.text)
                            sql = sql + "N'"+table.text.replace("\r\n",'').replace("\t",'').replace(u'\xa0','')+"',"
                        if  j > 16 and  j <22:
                            # print(table.text)
                            sql1 = sql1 + "N'"+table.text.replace("\r\n",'').replace("\t",'').replace(u'\xa0','')+"',"
                            if k == 21:
                                fullsql = " insert into [dbo].[邯郸投资平台数据_Crawler] VALUES ("+sql+sql1[:-1]+');commit;'
                                insert(fullsql)
                        if  j > 28:
                            # print(table.text)
                            sql2 = sql2 + "N'" + table.text.replace("\r\n",'').replace("\t",'').replace(u'\xa0','') + "',"
                            if  k==33 or k==38 or k==43 or k==48 or k==53 or k==58 or k==63   or k==68 or k==73 or k==78 or k==83 or k==88 or k==93:
                                fullsql1 = " insert into [dbo].[邯郸投资平台数据_Crawler] VALUES (" + sql + sql2[:-1] + ');commit;'
                                insert(fullsql1)
                                sql2 = ''
                        j+=1
                        k+=1
                else:
                    print('ERROR', html.status_code)
                    html.close()
예제 #27
0
 def menu(self):
     while self.dato:
         menu = '''
         1._Insertar
         2._Actualizar
         3._Eliminar
         4._Consultar
         5._ Salir'''
         print(menu)
         selection = input("Ingrese Opcion : ")
         if selection == '1':
             insert.insert()
         elif selection == '2':
             update.update()
         elif selection == '3':
             delete.delete()
         elif selection == '4':
             read.read()
         elif selection == '5':
             exit()
         else:
             print("Opcion Invalida")
예제 #28
0
def recon_f(sinogram, thetas):
    n0, n1 = sinogram.shape

    x, y = np.mgrid[0:n0, 0:n0]
    x -= n0 // 2
    y -= n1 // 2
    r = np.sqrt(x * x + y * y)

    fil = np.fft.ifftshift(np.where(r < n0 / 3, 1, 0))
    # fil = 1 #np.abs(np.fft.fftfreq(n0)).reshape((-1, 1))
    ft_sino = np.fft.fftshift(np.fft.fft(sinogram, axis=0), axes=0)
    slices_real = np.real(ft_sino).T
    slices_imag = np.imag(ft_sino).T

    model_real = insert(slices_real, thetas)
    model_imag = insert(slices_imag, thetas)

    model = model_real + 1j * model_imag
    # model *= fil

    recon = np.fft.ifft2(np.fft.ifftshift(model)).real

    return model, recon
예제 #29
0
def word_combi(word):

    split_set = [(word[:letter], word[letter:])
                 for letter in range(len(word) + 1)]
    subset_of_delete = [
        leftside_set + rightside_set[1:]
        for leftside_set, rightside_set in split_set if rightside_set
    ]
    transposes = [
        leftside_set + rightside_set[1] + rightside_set[0] + rightside_set[2:]
        for leftside_set, rightside_set in split_set if len(rightside_set) > 1
    ]
    replaces = replace.replace(word)
    inserts = insert.insert(word)

    return list(set(subset_of_delete + transposes + replaces + inserts))
def traverse_tree(node, point, max_nodes_per_quad):
    if node.TopLeftChild is None and node.TopRightChild is None and node.BottomLeftChild is None and node.BottomRightChild is None:  # Is leaf node
        node.points.append(point)
        if len(
                node.points
        ) > max_nodes_per_quad:  # Spilt child if points are hight that max point per quad
            print(node.points)
            return insert.insert(node, max_nodes_per_quad)
    cross_x = node.x
    cross_y = node.y
    # Check for the suitable child
    if point[0] <= cross_x and point[1] >= cross_y:
        traverse_tree(node.TopLeftChild, point, max_nodes_per_quad)
    else:
        if cross_x <= point[0] and point[1] <= cross_y:
            traverse_tree(node.BottomRightChild, point, max_nodes_per_quad)
    if cross_x < point[0] and point[1] > cross_y:
        traverse_tree(node.TopRightChild, point, max_nodes_per_quad)
    if point[0] < cross_x and point[1] < cross_y:
        traverse_tree(node.BottomLeftChild, point, max_nodes_per_quad)
예제 #31
0
def run():
	# Login and save the html file to gen
	logging.info('Login and saving notice board html to gen')
	tpo = TpoSession()
	tpo.login()

	# From the html file, extract and save the notices
	logging.info('Extracting notice from notice board html.')
	num = insert.insert()
	if num is None:
		logging.error("Error encountered during extraction. Exiting.")
		exit()
	logging.info("Inserted %d notices.", num)

	# Update the json files to include the notice details and attachments
	logging.info('Updating json files')
	update.update()

	# Send the unsent notices
	logging.info('Sending unsent notices.')
	send.send_unsent()

	logging.info("Finished running script.")
예제 #32
0
def run():
    # Login and save the html file to gen
    logging.info('Login and saving notice board html to gen')
    tpo = TpoSession()
    tpo.login()

    # From the html file, extract and save the notices
    logging.info('Extracting notice from notice board html.')
    num = insert.insert()
    if num is None:
        logging.error("Error encountered during extraction. Exiting.")
        exit()
    logging.info("Inserted %d notices.", num)

    # Update the json files to include the notice details and attachments
    logging.info('Updating json files')
    update.update()

    # Send the unsent notices
    logging.info('Sending unsent notices.')
    send.send_unsent()

    logging.info("Finished running script.")
예제 #33
0
root = os.path.abspath(os.path.dirname(__file__))
path = root + "/gen"

if os.path.isdir(path):
	logging.info("Found gen folder. Cleaning it up.")
	shutil.rmtree(path)

# Login and save the html file to gen
logging.info('Login and save html file to gen')
tpo = TpoSession()
tpo.login()

# From the html file, extract and save the notices
logging.info('From the html file, extract and save the notices')
num = insert.insert()
if num is None:
	logging.error("Error encountered during extraction. Exiting.")
	exit()
logging.info("Inserted %d notices.", num)

# Update the json files to include the notice details and attachments
logging.info('Updating the json files.')
update.update()

# Do not send redundant pushes on first run
logging.info('Setting the sent property to false.')
sent_false()

# Finally, insert the cron jobs to enable automatic updates
#logging.info('Inserting cron jobs.')
예제 #34
0
cns.constants("quests_merge", "tables/quests_constants.j", "quest_struct", ["header", "insert", "msg"])

#creates library for reward constants--integer to integer
cns.constants("reward_merge", "tables/reward_constants.j", "reward_struct", ["header", "insert"], "", "_REWARD")

#creates library for story constants--integer to integer
cns.constants("story_merge", "tables/story_constants.j", "jass", ["header", "insert", "msg"], "", "")

#creates library for story constants--integer to integer
cns.constants("events_merge", "tables/events_constants.j", "event_struct", ["header", "insert", "msg"], "", "")

#insert scripts
#creates lua/jass files that allow "global" values

#creates lua file for villagers
ins.insert("villagers_header.j", "villagers", "villagers_insert.j", "lua", "//insert", ["decrep", "header", "insert"])

#creates lua file for npcs
#ins.insert("npcs_header.j", "npcs", "npcs_insert.j", "lua", "//insert", ["decrep", "header", "insert"])

#replacement for npc calls
ins.insert("npc_units_header.j", "npc_units", "npc_units_insert.j", "npc_units", "//insert", ["decrep", "header", "insert"], True)
ins.insert("npc_heroes_header.j", "npc_heroes", "npc_heroes_insert.j", "npc_heroes", "//insert", ["decrep", "header", "insert"], True)

#creates lua file for monsters
ins.insert("monsters_header.j", "monsters", "monsters_insert.j", "lua", "//insert", ["decrep", "header", "insert"])

#creates lua file for warps
#ins.insert("warps_header.j", "warps", "warps_insert.j", "lua", "//insert", ["decrep", "header", "insert"])
ins.insert("warps_header.j", "warps_merge", "warps_insert.j", "warps", "//insert", ["decrep", "header", "insert"], True)
예제 #35
0
# file_path = "chain"

block_head_format = struct.Struct('20s d 16s I 11s I')
block_head = namedtuple('Block_Head',
                        'hash timestamp case_id item_id state length')
block_data = namedtuple('Block_Data', 'data')
prev_hash = b''

# Initialise necessary arguements
if action not in ["init", "verify"]:

    if action == "add":
        arguements["case_id"] = args.c
        arguements["item_id"] = args.i
        if arguements["case_id"] and arguements["item_id"]:
            insert(arguements["case_id"], arguements["item_id"], file_path)
        else:
            Arguement_Error()
    elif action == "checkout" or action == "checkin":
        arguements["item_id"] = args.i
        if action == "checkout":
            checkout(arguements["item_id"], file_path)
        else:
            checkin(arguements["item_id"], file_path)
    elif action == "log":
        arguements["reverse"] = args.reverse
        arguements["number"] = args.n
        arguements["case_id"] = args.c
        arguements["item_id"] = args.i
        log(arguements["reverse"], arguements["number"], arguements["case_id"],
            arguements["item_id"], file_path)