예제 #1
0
    def update(self):
        output = ""
        with open("/proc/net/dev", "r") as f:
            output = f.read()
        listOfInterfaces = output.split('\n')
        del listOfInterfaces[0:2]  #remove headers
        self.timetag = datetime.datetime.now()
        collect = dict()
        for interfaceString in listOfInterfaces:
            if len(interfaceString) > 0:
                listOfStats = interfaceString.split()
                new_stats = self.getInterface(
                    listOfStats[0].strip(':')).update(listOfStats)
                collect = {
                    **collect,
                    **new_stats,
                    **{
                        k: op(collect[k], new_stats[k])
                        for k in new_stats.keys() & collect
                    }
                }

        time = dict({"time": [self.timetag]})
        collect = {
            **collect,
            **time,
            **{k: op(collect[k], time[k])
               for k in time.keys() & collect}
        }
        return collect
예제 #2
0
def calculate_time(time):
    '''
    calculates average, maximum and minimum time elapsed.
    Sends all these data to generate_report function
    :param time: dictionary of  commands as keys and elapsed time as values.

    '''
    total_time = 0
    for k, v in time.items():
        print(k, v)
        total_time = total_time + v  # calculate total time elapsed

    key_max = max(time.keys(), key=(lambda k: time[
        k]))  # find the command which took maximum amount of time to execute
    key_min = min(time.keys(), key=(lambda k: time[
        k]))  # find the command which took minimum amount of time to execute
    avg = total_time / 8  # Calculate average amount of time
    generate_report(time, key_max, key_min, avg, total_time)
def gettime_with_folders():
	time = {}
	res = all_comp_folders_from_db()
	other_folders = []
	for folder in res:
		all_files=get_all_files(folder) 
		time[folder] = gettime(all_files)
	tmp = 0
	result_folder = ''
	for item in time.items():
		if item[1] > tmp:
			tmp = item[1]
			result_folder = item[0]
	for item in time.keys():
		if item != result_folder:
			other_folders.append(item)
	return (result_folder, tmp, other_folders)
예제 #4
0
파일: craybot.py 프로젝트: mwaboff/Craybot
 def timeParser(self, timeamount):
     digits = ['1','2','3','4','5','6','7','8','9','0']
     time = {'h': [0], 'm': [0], 's': [0]}
     curdigits = ''
     for char in timeamount:
         if char in digits:
             curdigits += str(char)
         elif char in time.keys():
             time[char].append(int(curdigits))
             curdigits = ''
     try:
         extrasec = int(curdigits)
     except:
         extrasec = 0
     totalhour,totalmin,totalsec = 0,0,0
     for numb in time['h']:
         totalhour += numb
     for numb in time['m']:
         totalmin += numb
     for numb in time['s']:
         totalsec += numb
     final_count_in_seconds = (totalhour*3600) + (totalmin*60) + totalsec + extrasec
     return final_count_in_seconds
예제 #5
0
def gatherdata(trigger, time, stoptrigger, milliseconds=False, verbose = True):
    """Gathers data and returns a list of data and triggering events. The
    arguments trigger and stroptrigger are used to create event filters (using
    the function createeventfilter). 
    
    Events that pass the trigger filter they are used as starting points for 
    data gathering (the sample field of the event to be exact). How many sample 
    are gathered from that point is determined by the time argument. If time is 
    a number (int or float) it will simply gather that number of samples. If 
    time is a dict, it will use the type of the trigger event as a key to look 
    up the number of samples that need to be gathered in the dict.
    
    If an event passes the stopfilter the data gathering will stop handling
    new trigger events and return the data as soon as the remaining samples
    are gathered.
    
    If the argument milliseconds is true, it is assumed that the numbers in the 
    time argument express the number of samples that need to be gathered in 
    milliseconds rather than samples.
    
    Note that this function assumes that at least half a second of data is
    being stored in the buffer."""

    global fSample
    
    if isinstance(time, dict):
        for key in list(time.keys()):
            if milliseconds:
                time[key] = int(ceil((time[key]/1000.0)*fSample))
            elif isinstance(time[key],float):
                time[key] = int(ceil(time[key])) 
    else:
        if milliseconds:
            time = ceil((time/1000.0)*fSample)    
        elif isinstance(time,float):
            time = int(ceil(time))    
    
    gatherFilter = createeventfilter(trigger)
    stopFilter = createeventfilter(stoptrigger)
    
    global ftc
    nSamples, nEvents = ftc.poll()
    

    stillgathering = True;
    gather = []
    events = []
    data = []
    
    while True:
        nSamples, nEvents2 = ftc.wait(-1,nEvents, 500)    
        
        if nEvents != nEvents2:
            e = ftc.getEvents((nEvents, nEvents2 -1))
            nEvents = nEvents2            

            stopevents = stopFilter(e)            
            
            if stopevents:
                stillgathering = False
                if len(stopevents) == 1:
                    stopevents = stopevents[0]
                
            e = gatherFilter(e)
            
            for event in e:
                if not isinstance(time,dict):
                    endSample = event.sample + time
                else:
                    endSample = event.sample + time[event.type]
                
                gather.append((event, endSample))
                
        for point in gather:
            event,endSample = point
            if nSamples > endSample:
                events.append(event)
                data.append(ftc.getData((event.sample, endSample -1)))
                gather.remove(point)            
                if verbose:
                    print(("Gathering " + str(event.type) + " " + str(event.value) + " data from " + str(event.sample) + " to " +str(endSample)))
                
        if not stillgathering and not gather:
            break
            
    return (data,events, stopevents)
def play():
    # create a list of play options
    t = {1: "Kéo", 2: "Búa", 3: "Giấy"}

    # assign a random play to the computer
    computer = random.choice(list(t.keys()))

    # set player to False
    player = False

    chooselanguage = int(input("(1) - English\n(2) - Tiếng Việt\n"))
    if chooselanguage == 1:
        while player == False:
            # set player to True
            print("Choose your dicision...")
            player = int(input("(1) - Scissors\n(2) - Rock\n(3) - Paper\n"))
            # int(player)
            count(3)
            if player == computer:
                print("Tie!")
            elif player == 1:
                if computer == 2:
                    print("You lose...", "Rock", "smashed", "Scissors")
                else:
                    print("Chúc mừng bạn đã thắng!", "Scissors", "cut",
                          "Paper")
            elif player == 2:
                if computer == 3:
                    print("You lose...", "Paper", "covers", "Rock")
                else:
                    print("You win!", "Rock", "smashed", "Scissors")
            elif player == 3:
                if computer == 1:
                    print("You lose...", "Scissors", "cut", "Paper")
                else:
                    print("You win!", "Paper", "covers", "Rock")
            else:
                print("Oops, invalid, choose again...")
            # player was set to True, but we want it to be False so the loop continues
            player = False
            computer = random.choice(list(t.keys()))
            playOrNot("Again? Yes/No\n")
    elif chooselanguage == 2:
        while player == False:
            # set player to True
            print("Hãy chọn đi nào...")
            player = int(input("(1) - Kéo\n(2) - Búa\n(3) - Giấy\n"))
            # int(player)
            print("Oẳn tù tì ra cái gì ra cái này...\n")
            count(3)
            if player == computer:
                print("Bất phân thắng bại!")
            elif player == 1:
                if computer == 2:
                    print("Bạn đã thua!", "Búa", "đập cong", "Kéo")
                else:
                    print("Chúc mừng bạn đã thắng!", "Kéo", "cắt được", "Giấy")
            elif player == 2:
                if computer == 3:
                    print("Bạn đã thua!", "Giấy", "bọc được", "Búa")
                else:
                    print("Chúc mừng bạn đã thắng!", "Búa", "đập cong", "Kéo")
            elif player == 3:
                if computer == 1:
                    print("Bạn đã thua!", "Kéo", "cắt được", "Giấy")
                else:
                    print("Chúc mừng bạn đã thắng!", "Giấy", "bọc được", "Búa")
            else:
                print("Nhập sai rồi, nhập lại nha!")
            # player was set to True, but we want it to be False so the loop continues
            player = False
            computer = random.choice(list(t.keys()))
            playOrNot("Chơi lại nhé? Yes/No\n")
    else:
        print("Invalid")
예제 #7
0
def gatherdata(trigger,
               time,
               stoptrigger=[],
               pending=[],
               stopondata=False,
               milliseconds=False,
               verbose=True):
    """Gathers data and returns a list of data and triggering events. The
    arguments trigger and stroptrigger are used to create event filters (using
    the function createeventfilter). 
    
    Events that pass the trigger filter they are used as starting points for 
    data gathering (the sample field of the event to be exact). How many sample 
    are gathered from that point is determined by the time argument. If time is 
    a number (int or float) it will simply gather that number of samples. If 
    time is a dict, it will use the type of the trigger event as a key to look 
    up the number of samples that need to be gathered in the dict.
    
    If an event passes the stopfilter the data gathering will stop handling
    new trigger events and return the data as soon as the remaining samples
    are gathered.
    
    If the argument milliseconds is true, it is assumed that the numbers in the 
    time argument express the number of samples that need to be gathered in 
    milliseconds rather than samples.
    
    Note that this function assumes that at least half a second of data is
    being stored in the buffer.
    
    Inputs: 
     trigger    - [] set of triggers to start recording data
     time       - [] length of data to record, in samples if Milliseconds=False, in milliseconds if Milliseconds=true
     stoptrigger- [] set of triggers to stop gathering data.  
                     **return immeadiately data is available if stoptrigger is *not* set**
     pending    - [] set of previously identified events to get data from who do not have all the data yet
     
     stopondata - [boolean] if set then stop gathering as soon as we have some data to return, i.e. trigger-event happened and sufficient samples available.
    Outputs:
     data       - [[nSamp x nCh] x nEvent] list of lists of numpy-arrays of [nSamp x nCh] for each trigger
     events     - [event] list of trigger events
     stopevents - [event] list of events which caused us to stop gathering
     state      - [struct] internal state of this function to track pending events which have not got complete data yet

    Example Usage:
      # gather data for trigger events, and return when 'stimulus.end' event is recieved
      data,devents,stopevents=bufhelp.gatherdata('stimulus.epoch',100,'stimulus.end)

      # wait for trigger event and return data as soon as it's ready 
      pending=[]
      while true:
         data,devents,stopevents,pending=bufhelp.gatherdata('stimulus.epoch',100,[],pending,stopondata=true)
         print('Got %d new events'%(len(data),len(devents)))

      # wait for trigger event and return data OR when "stimulus.end"
      pending=[]
      while true:
         data,devents,stopevents,pending=bufhelp.gatherdata('stimulus.epoch',100,'stimulus.end',pending,stopondata=true)
         print('Got %d new events'%(len(data),len(devents)))
"""

    global fSample

    if isinstance(time, dict):
        for key in list(time.keys()):
            if milliseconds:
                time[key] = int(ceil((time[key] / 1000.0) * fSample))
            elif isinstance(time[key], float):
                time[key] = int(ceil(time[key]))
    else:
        if milliseconds:
            time = ceil((time / 1000.0) * fSample)
        elif isinstance(time, float):
            time = int(ceil(time))

    gatherFilter = createeventfilter(trigger)
    if stoptrigger:
        stopFilter = createeventfilter(stoptrigger)
    else:
        if verbose: print("Stopping when data available")
        stopondata = True

    global ftc
    nSamples, nEvents = ftc.poll()

    stillgathering = True
    events = []
    data = []
    stopevents = []

    while True:
        nSamples, nEvents2 = ftc.wait(-1, nEvents, 500)

        if nEvents != nEvents2:
            e = ftc.getEvents((nEvents, nEvents2 - 1))
            nEvents = nEvents2

            if stoptrigger:
                stopevents = stopFilter(e)

                if stopevents:
                    stillgathering = False

            e = gatherFilter(e)

            for event in e:
                if verbose:
                    print("Recording event:" + str(event))
                if not isinstance(time, dict):
                    endSample = event.sample + time
                else:
                    endSample = event.sample + time[event.type]

                pending.append((event, endSample))

        for point in pending:
            event, endSample = point
            if nSamples > endSample:
                events.append(event)
                data.append(ftc.getData(
                    (event.sample, endSample - 1)))  # [ nSamples x nChannels ]
                pending.remove(point)
                if stopondata:  # stop gathering if should return first time data is available
                    stillgathering = False
                if verbose:
                    print(("Saving event :" + str(event) + " data from " +
                           str(event.sample) + " to " + str(endSample)))

        if not stillgathering:
            break

    return (data, events, stopevents, pending)
예제 #8
0
def gatherdata(trigger, time, stoptrigger, milliseconds=False, verbose=True):
    """Gathers data and returns a list of data and triggering events. The
    arguments trigger and stroptrigger are used to create event filters (using
    the function createeventfilter). 
    
    Events that pass the trigger filter they are used as starting points for 
    data gathering (the sample field of the event to be exact). How many sample 
    are gathered from that point is determined by the time argument. If time is 
    a number (int or float) it will simply gather that number of samples. If 
    time is a dict, it will use the type of the trigger event as a key to look 
    up the number of samples that need to be gathered in the dict.
    
    If an event passes the stopfilter the data gathering will stop handling
    new trigger events and return the data as soon as the remaining samples
    are gathered.
    
    If the argument milliseconds is true, it is assumed that the numbers in the 
    time argument express the number of samples that need to be gathered in 
    milliseconds rather than samples.
    
    Note that this function assumes that at least half a second of data is
    being stored in the buffer."""

    global fSample

    if isinstance(time, dict):
        for key in time.keys():
            if milliseconds:
                time[key] = int(ceil((time[key] / 1000.0) * fSample))
            elif isinstance(time[key], float):
                time[key] = int(ceil(time[key]))
    else:
        if milliseconds:
            time = ceil((time / 1000.0) * fSample)
        elif isinstance(time, float):
            time = int(ceil(time))

    gatherFilter = createeventfilter(trigger)
    stopFilter = createeventfilter(stoptrigger)

    global ftc
    nSamples, nEvents = ftc.poll()

    stillgathering = True
    gather = []
    events = []
    data = []

    while True:
        nSamples, nEvents2 = ftc.wait(-1, nEvents, 500)

        if nEvents != nEvents2:
            e = ftc.getEvents((nEvents, nEvents2 - 1))
            nEvents = nEvents2

            stopevents = stopFilter(e)

            if stopevents:
                stillgathering = False
                if len(stopevents) == 1:
                    stopevents = stopevents[0]

            e = gatherFilter(e)

            for event in e:
                if not isinstance(time, dict):
                    endSample = event.sample + time
                else:
                    endSample = event.sample + time[event.type]

                gather.append((event, endSample))

        for point in gather:
            event, endSample = point
            if nSamples > endSample:
                events.append(event)
                data.append(ftc.getData((event.sample, endSample - 1)))
                gather.remove(point)
                if verbose:
                    print "Gathering " + str(event.type) + " " + str(
                        event.value) + " data from " + str(
                            event.sample) + " to " + str(endSample)

        if not stillgathering and not gather:
            break

    return (data, events, stopevents)
예제 #9
0
def gatherdata(trigger, time, stoptrigger=[], pending=[], state=True, stopondata=False, milliseconds=False, verbose = True):
    """Gathers data and returns a list of data and triggering events. The
    arguments trigger and stroptrigger are used to create event filters (using
    the function createeventfilter). 
    
    Events that pass the trigger filter they are used as starting points for 
    data gathering (the sample field of the event to be exact). How many sample 
    are gathered from that point is determined by the time argument. If time is 
    a number (int or float) it will simply gather that number of samples. If 
    time is a dict, it will use the type of the trigger event as a key to look 
    up the number of samples that need to be gathered in the dict.
    
    If an event passes the stopfilter the data gathering will stop handling
    new trigger events and return the data as soon as the remaining samples
    are gathered.
    
    If the argument milliseconds is true, it is assumed that the numbers in the 
    time argument express the number of samples that need to be gathered in 
    milliseconds rather than samples.
    
    Note that this function assumes that at least half a second of data is
    being stored in the buffer.
    
    Inputs: 
     trigger    - [] set of triggers to start recording data
     time       - [] length of data to record, in samples if Milliseconds=False, in milliseconds if Milliseconds=true
     stoptrigger- [] set of triggers to stop gathering data.  
                     **return immeadiately data is available if stoptrigger is *not* set**
     pending    - [] set of previously identified events to get data from who do not have all the data yet
     
     stopondata - [boolean] if set then stop gathering as soon as we have some data to return, i.e. trigger-event happened and sufficient samples available.
    Outputs:
     data       - [[nSamp x nCh] x nEvent] list of lists of numpy-arrays of [nSamp x nCh] for each trigger
     events     - [event] list of trigger events
     stopevents - [event] list of events which caused us to stop gathering
     pending      - [struct] internal state of this function to track pending events which have not got complete data yet
     state      - internal state recording events processed so far        (True=global-state)
                   use state=None to reset all history, i.e. ignore any events/samples before the current time
                   use state=True to use a single shared global state over all calls
    Example Usage:
      # gather data for trigger events, and return when 'stimulus.end' event is recieved
      data,devents,stopevents=bufhelp.gatherdata('stimulus.epoch',100,'stimulus.end)

      # wait for trigger event and return data as soon as it's ready 
      pending=[]
      while true:
         data,devents,stopevents,pending=bufhelp.gatherdata('stimulus.epoch',100,[],pending,stopondata=true)
         print('Got %d new events'%(len(data),len(devents)))

      # wait for trigger event and return data OR when "stimulus.end"
      pending=[]
      while true:
         data,devents,stopevents,pending=bufhelp.gatherdata('stimulus.epoch',100,'stimulus.end',pending,stopondata=true)
         print('Got %d new events'%(len(data),len(devents)))
"""

    global fSample
    
    if isinstance(time, dict):
        for key in list(time.keys()):
            if milliseconds:
                time[key] = int(ceil((time[key]/1000.0)*fSample))
            elif isinstance(time[key],float):
                time[key] = int(ceil(time[key])) 
    else:
        if milliseconds:
            time = ceil((time/1000.0)*fSample)    
        elif isinstance(time,float):
            time = int(ceil(time))    
    
    gatherFilter = createeventfilter(trigger)
    if stoptrigger :        
        stopFilter = createeventfilter(stoptrigger)
    else:
        if verbose: print("Stopping when data available")
        stopondata=True
        
    global ftc
    global globalstate # cursor for how much data processed in previous calls 
    useglobal=False
    if state==True : # use a single global state
        useglobal=True
        if globalstate is None:
            globalstate = ftc.poll()
        state = globalstate
    else : 
        if not state : # init if not already set
            state = ftc.poll()
    nSamples=state[0]
    nEvents =state[1]
            
    stillgathering = True;
    events = []
    data = []
    stopevents=[]
    
    while True:
        nSamples, nEvents2 = ftc.wait(-1,nEvents, 500)    
        
        if nEvents != nEvents2:
            e = ftc.getEvents((nEvents, nEvents2 -1))
            nEvents = nEvents2            

            if stoptrigger :
                stopevents = stopFilter(e)            
            
                if stopevents:
                    stillgathering = False                
                
            e = gatherFilter(e)
            
            for event in e:
                if verbose:
                    print("Recording event:"+str(event))
                if not isinstance(time,dict):
                    endSample = event.sample + time
                else:
                    endSample = event.sample + time[event.type]
                
                pending.append((event, endSample))
                
        for point in pending:
            event,endSample = point
            if nSamples > endSample:
                events.append(event)
                data.append(ftc.getData((event.sample, endSample -1))) # [ nSamples x nChannels ]
                pending.remove(point)            
                if stopondata : # stop gathering if should return first time data is available
                    stillgathering = False
                if verbose:
                    print(("Saving event :" + str(event) + " data from " + str(event.sample) + " to " +str(endSample)))
                
        if not stillgathering:
            break
            
    # update record of which events we have processed so far
    state=(nSamples,nEvents)
    globalstate=state

    return (data, events, stopevents, pending)
def get_score_info_v2(corridate, label):
    # print(label)
    scores = {}
    score_index = 0
    time = {}
    time_index = 0
    team_name = {}
    quarter_dict = {}
    remainder_attack_time = {}
    remainder_attack_time_index = 0

    if int(len(corridate) / 4) == len(label):
        for i in range(len(label)):
            # corridate_label_center[label[i]] = [(int(corridate[4 * int(i) + 0]) + int(corridate[4 * int(i) + 2])) / 2,
            #                                     (int(corridate[4 * int(i) + 1]) + int(corridate[4 * int(i) + 3])) / 2]
            if label[i] in all_team:
                team_name[label[i]] = [(int(corridate[4 * int(i) + 0]) +
                                        int(corridate[4 * int(i) + 2])) / 2,
                                       (int(corridate[4 * int(i) + 1]) +
                                        int(corridate[4 * int(i) + 3])) / 2]
            if label[i] in quarter:
                quarter_dict[label[i]] = [(int(corridate[4 * int(i) + 0]) +
                                           int(corridate[4 * int(i) + 2])) / 2,
                                          (int(corridate[4 * int(i) + 1]) +
                                           int(corridate[4 * int(i) + 3])) / 2]
            if label[i].isdigit():
                scores[label[i] + "_" + str(score_index)] = [
                    (int(corridate[4 * int(i) + 0]) +
                     int(corridate[4 * int(i) + 2])) / 2,
                    (int(corridate[4 * int(i) + 1]) +
                     int(corridate[4 * int(i) + 3])) / 2
                ]
                score_index += 1
            if ":" in label[i]:
                time[label[i] + "_" + str(time_index)] = [
                    (int(corridate[4 * int(i) + 0]) +
                     int(corridate[4 * int(i) + 2])) / 2,
                    (int(corridate[4 * int(i) + 1]) +
                     int(corridate[4 * int(i) + 3])) / 2
                ]
                time_index += 1
            if "." in label[i] and ":" not in label[i]:
                remainder_attack_time[label[i] + "_" +
                                      str(remainder_attack_time_index)] = [
                                          (int(corridate[4 * int(i) + 0]) +
                                           int(corridate[4 * int(i) + 2])) / 2,
                                          (int(corridate[4 * int(i) + 1]) +
                                           int(corridate[4 * int(i) + 3])) / 2
                                      ]
                remainder_attack_time_index += 1

    # if len(team_name.keys())!=0 and len(team_name.keys())!=2:
    #     print("wrong len(team_name)={}".format(len(team_name)))
    #     return  None
    # if len(quarter_dict.keys())>1:
    #     print("wrong len(quarter_list)={}".format(len(quarter_dict)))
    #     return None

    if len(remainder_attack_time.keys()) == 2:
        # print(remainder_attack_time)
        time_res = left_up(remainder_attack_time)
        return content_sort(team_name, scores, quarter_dict, time_res["guest"],
                            time_res["host"])
        # return remainder_attack_time["host"]

    elif len(time.keys()) == 2:
        # print(time)
        time_res = left_up(time)
        return content_sort(team_name, scores, quarter_dict, time_res["guest"],
                            time_res["host"])
        # time_temp=time["host"]
        # if time_temp.startswith(":") and float(time_temp.split("_")[0].split(":")[1])<=24:
        #     return time_temp
        # return None

    elif len(remainder_attack_time.keys()) == 1 and len(time.keys()) == 1:

        return content_sort(team_name, scores, quarter_dict,
                            list(time.keys())[0],
                            list(remainder_attack_time.keys())[0])
        # return  list(remainder_attack_time.keys())[0] if float(list(remainder_attack_time.keys())[0])<=24 else None
        # if len(time.keys())==2:
    #     time_keys=list(time.keys())
    #     time1=time_keys[0]
    #     time2=time_keys[1]
    #     if not time1.startswith(":") and time2.startswith(":"):
    #         remainder_time[time1]=time[time1]
    #     elif time1.startswith(":") and not time2.startswith(":"):
    #         remainder_time[time2]=time[time2]
    #     elif time1.startswith(":") and time2.startswith(":"):
    #         if time1.split("_")[0]==time2.split("_")[0]:
    #             # print(time)
    #             remainder_time[time1]=time[time2]
    # if score_big==2 or len(scores.keys())==2:
    #     return scores
    elif (len(scores.keys())==3 and len(time.keys())==1)\
            or (len(scores.keys()) == 3 and len(remainder_attack_time.keys()) == 1):
        big_score = {}
        small_score = ""
        remainder_attack_time_temp = list(time.keys())[0] if len(
            time.keys()) == 1 else list(remainder_attack_time.keys())[0]
        for key in scores.keys():
            if int(key.split("_")[0]) > 24:
                big_score[key] = scores[key]
            else:
                small_score = key
        if len(big_score) == 2:
            # print(scores,big_score)
            score_stay = remove_key(scores, small_score)
            return content_sort(team_name, score_stay, quarter_dict,
                                remainder_attack_time_temp, small_score)
            # return small_score

        else:
            if len(time.keys()) == 1:  #find remain time
                time_key = list(time.keys())[0]
                time_stay = time
            else:
                time_key = list(remainder_attack_time.keys())[0]
                time_stay = remainder_attack_time
            right_key = []
            for key in scores.keys():
                if scores[key][0] > time_stay[time_key][0]:
                    right_key.append(key)
            if len(right_key) == 1:
                res_score = remove_key(scores, right_key[0])
                return content_sort(team_name, res_score, quarter_dict,
                                    remainder_attack_time_temp, right_key[0])
                # return right_key[0] if int(right_key[0].split("_")[0])<=24 else None
            elif len(right_key) == 0:
                #print(label)
                print("right key is null")
            elif len(right_key) == 2:
                right1 = right_key[0]
                right2 = right_key[1]
                distance_dic = {}
                distance1 = math.pow(
                    scores[right1][1] - time_stay[time_key][1], 2)
                distance_dic[right1] = distance1
                distance2 = math.pow(
                    scores[right2][1] - time_stay[time_key][1], 2)
                distance_dic[right2] = distance2
                # print(distance_dic)
                distance_sort = sorted(distance_dic.items(),
                                       key=lambda item: item[1])
                if distance_sort[-1][-1] < 30:
                    distance_dic2 = {}
                    distance1 = math.pow(
                        scores[right1][0] - time_stay[time_key][0], 2)
                    distance_dic2[right1] = distance1
                    distance2 = math.pow(
                        scores[right2][0] - time_stay[time_key][0], 2)
                    distance_dic2[right2] = distance2
                    min_right = sorted(distance_dic2.items(),
                                       key=lambda item: item[1])[0][0]
                    res_score = remove_key(scores, min_right)
                else:
                    min_right = distance_sort[0][0]
                    res_score = remove_key(scores, min_right)

                return content_sort(team_name, res_score, quarter_dict,
                                    remainder_attack_time_temp, min_right)
                #                 # if label[-1] != min_right.split("_")[0]:
                #     # print(scores,time_stay)
                #     # print(distance1, distance2)
                #     # print(time_key)
                #     print(("_").join(label), min_right)
                #     pass
            else:
                right1 = right_key[0]
                right2 = right_key[1]
                right3 = right_key[2]
                distance_dic = {}
                distance1 = math.pow(
                    scores[right1][1] - time_stay[time_key][1], 2)
                distance_dic[right1] = distance1
                distance2 = math.pow(
                    scores[right2][1] - time_stay[time_key][1], 2)
                distance_dic[right2] = distance2
                distance3 = math.pow(
                    scores[right3][1] - time_stay[time_key][1], 2)
                distance_dic[right3] = distance3
                min_right = sorted(distance_dic.items(),
                                   key=lambda item: item[1])[0][0]
                res_score = remove_key(scores, min_right)

                return content_sort(team_name, res_score, quarter_dict,
                                    remainder_attack_time_temp, min_right)
                # if label[-1] != min_right.split("_")[0]:
                #     # print(scores,time_stay)
                #     # print(distance1, distance2)
                #     # print(time_key)
                #     print(("_").join(label), min_right)
                #     pass
    elif (len(remainder_attack_time.keys()) == 1 and len(time.keys()) == 0):
        # return list(remainder_attack_time.keys())[0]
        return content_sort(team_name, scores, quarter_dict,
                            list(remainder_attack_time.keys())[0], None)
    elif len(remainder_attack_time.keys()) == 0 and len(time.keys()) == 1:
        return content_sort(team_name, scores, quarter_dict,
                            list(time.keys())[0], None)
        # if list(time.keys())[0].startswith(":"):
        #     return list(time.keys())[0]
        # else:
        #     return None
    elif len(remainder_attack_time.keys()) == 0 and len(
            time.keys()) == 0 and len(scores.keys()) == 2:
        return content_sort(team_name, scores, quarter_dict, None, None)
    else:
        # print(label)
        return None
예제 #11
0
try:  ##Get this idea from Harrison Grubb who dropped this code to Slack
    parsed_response['Time Series (Daily)']
except:
    print('Oh no, something is wrong. Can we start over?')
    print('Shutting program down...')
    exit()

##3. INFO OUTPUT
#print(parsed_response.keys())
request_time = time.strftime("%Y-%m-%d %H:%M %p", time.localtime())

last_refreshed = parsed_response["Meta Data"]["3. Last Refreshed"]

time = parsed_response["Time Series (Daily)"]
dates = list(time.keys())

latest_day = dates[0]
latest_close = time[latest_day]["4. close"]

high_prices = []
for date in dates:
    high_price = time[date]["2. high"]
    high_prices.append(float(high_price))
recent_high = max(high_prices)

low_prices = []
for date in dates:
    low_price = time[date]["3. low"]
    low_prices.append(float(low_price))
recent_low = min(low_prices)