Exemplo n.º 1
0
def main():
    #challenge 9
    print 'Challenge 9 Results: '
    print Operations.padString('YELLOW SUBMARINE', 20, '\x04')

    #challenge 10
    data = FileConvert.FileConvert("10.txt")
    data.b64ToBinary()
    data.integrate()
    iv = Operations.padString('', 16, '\x00')
    AESCipher = AESImplementation.AESstuff('YELLOW SUBMARINE')
    print AESCipher.CBCEncrypt(iv, data.getContent())

    #challenge 11
    data11 = FileConvert.FileConvert("12.txt")
    data11.integrate()
    RandCipher = AESImplementation.AESstuff(Operations.randombytes(16))
    RandCipher.randKeyAndProtocol()
    if RandCipher.detectifECB() == 1:
        print "ECB Detected"
    else:
        print "CBC, Or something"

    #challenge 12
    data12 = FileConvert.FileConvert("12.txt")
    data12.b64ToBinary()
Exemplo n.º 2
0
    def getListVersions(self, values, package):

        # get all node versions
        versionsNode = list(NodeManager.nodeVersions.values())
        versionsNode.sort()
        versionsNode.reverse()

        # get the node version based in date
        values['node_on_date'] = NodeManager.getVersionOnDate(
            self.release.client_timestamp)

        # get only versions to execute
        posCurrentVersion = versionsNode.index(values['node_on_date'])
        versions = versionsNode[
            posCurrentVersion:]  # get only versions to execute

        # try get the version in package.json engines->node
        # if this versions doesn't exists in versions list, insert
        try:
            versionEngines = NodeManager.getVersionOnPackage(package)

            if not versions.__contains__(versionEngines):
                versions.insert(0, versionEngines)

        except (KeyError, AttributeError, TypeError):
            pass  # do nothing

        # try with the lattest
        if not versions.__contains__('10.12.0'):
            versions.insert(0, '10.12.0')

        op.printTableInfo('NodeJS versions to run in {0}: {1}'.format(
            self.client_name, str(versions)))
        return versions
Exemplo n.º 3
0
def AStar(initBoard, priority):
    startTime = time.time()
    output = {}
    visited = []
    openList = [Node(initBoard, 0, None, priority)]
    count = 0

    while (openList):
        if openList == []:
            return None
        # check if finish
        currentNode = openList[0]
        visited.append(currentNode.board)
        # print(currentNode.board)
        if (ops.isGoal(currentNode.board)):
            endTime = time.time()
            output["reachable"] = True
            output["iterations"] = count
            output["duration"] = endTime - startTime
            output["priority"] = priority
            output["nb_moves"] = openList[0].step
            return output, openList

        openList.pop(0)
        count += 1
        nextMoves = ops.moves(currentNode.board)
        for nextMove in nextMoves:
            if nextMove not in visited:
                openList.append(
                    Node(nextMove, currentNode.step + 1, currentNode,
                         priority))
        openList.sort(key=lambda x: x.value)
Exemplo n.º 4
0
def cron(request, db):
    blob_data = [blob.name for blob in bucket.list_blobs()]
    data = Operations.findall(db, collection, {'type': 'file'})
    dbfiles = [d['file_id'] for d in data]
    delete_files = list(set(blob_data) - set(dbfiles))
    dbdata = []
    blob_delete = []
    for d in data:
        if (d['file_id'].lower().endswith('.txt')):
            dbdata.append(d['_id'])
            blob_delete.append(d['file_id'])
    delete_files = delete_files + blob_delete
    db_delete_status = True
    blob_delete_status = True
    try:
        for blob in bucket.list_blobs():
            if blob.name in delete_files:
                blob.delete()
    except:
        blob_delete_status = False

    try:
        db_delete_status = Operations.deleteMany(db, collection,
                                                 {'_id': {
                                                     '$in': dbdata
                                                 }})
    except:
        db_delete_status = False
    return json.dumps(
        {
            'dbstatus': db_delete_status,
            'blob_status': blob_delete_status
        },
        default=str), 200, headers
def main():
    global session
    session = tf.Session()
    print("Creating network..")
    NC.create_network(FP.json_path)
    NC.define_cost()
    PM.initialize_performance_measures()
    Operations.train()
Exemplo n.º 6
0
 def __init__(self, *patterns):
     self.data = []
     item = [Base.asStream(p) for p in patterns]
     size = op.LCM(*[len(i) for i in item])
     for n in range(size):
         for i in item:
             self.data.append(op.modi(i, n))
     self.make()
Exemplo n.º 7
0
def main():
    if os.path.exists(DPATH):
        #R ootHash Login
        OPT.login(COLOR, FONT, SPATH)

    else:
        # When RootHash execute first time in a computer, this will run
        Root.first_time()
Exemplo n.º 8
0
 def __init__(self, inputBoard, step, parent, priority):
     self.board = inputBoard
     self.step = step
     if priority == "Hamming":
         self.value = ops.DistHamming(inputBoard) + self.step
     else:
         self.value = ops.DistManhattan(inputBoard) + self.step
     self.parent = parent
     self.priority = priority
Exemplo n.º 9
0
    def __init__(self,
                 string,
                 n,
                 no_measurment_qubits=1,
                 left_justified=False):
        """
        :param string: This should be a string of 1's and 0's where 1 is the |1> and
        0 is |0>
        :param n: The number of qubits in the system
        :param no_measurment_qubits:  The number of qubits that will be measured
        :return: Returns the

        Description of class variables
        state: This is the density matrix of the system
        classical_states: This is a dictionary of computational basis states that should have
        has its keys labels of computational basis states and values the corresponding
        probabilities
        projectors: This is a dictionary with keys being labels for the computational basis
        states and the values being the corresponding projectors for that particular
        computational basis state.
        no_measurement_qubits: The number of qubits you intend to measure
        classical_states_history: Has a key values all possible measurement syndromes and keeps a record of their
        probabilities
        """
        oper_dict = {'0': g.b1(), '1': g.b4(), '2': g.id()}

        self.state = op.superkron(oper_dict, val=1, string=string)
        self.n = n
        self.no_measurement_qubits = no_measurment_qubits
        self.measurement_string = op.createlabel(self.no_measurement_qubits, 2)
        for i in range(len(self.measurement_string)):
            if left_justified:
                self.measurement_string[i] = self.measurement_string[i].ljust(
                    self.n, '2')
            else:
                self.measurement_string[i] = self.measurement_string[i].rjust(
                    self.n, '2')
        self.projectors = {
            i.replace('2', ''): op.superkron(oper_dict, val=1, string=i)
            for i in self.measurement_string
        }
        self.classical_states = {
            i.replace('2', ''): 0
            for i in self.measurement_string
        }
        self.classical_states_history = {
            i.replace('2', ''): []
            for i in self.measurement_string
        }
        self.hamiltonian = None
        self.dt = None
        self.U = None
        self.xlabel = ''
        self.ylabel = ''
        self.T = None
        self.kraus_operators = []
Exemplo n.º 10
0
 def __init__(self, pat1, pat2, rule=lambda a, b: True):
     length = op.LCM(len(pat1), len(pat2))
     self.data = []
     i = 0
     while i < min(length, 32):
         a, b = op.modi(pat1,i), op.modi(pat2,i)
         if rule(a, b):
             self.data.append((a,b))
         i += 1
     self.make()
Exemplo n.º 11
0
def raw_harvest (year, game_num, away_acronym, home_acronym,
		away_roster, home_roster):
	"""
	Extract play-by-play information from a html file on the
	local machine (in the form of raw, unspeficied events).
	Returns list of unspecified event objects
	"""

	tree = Operations.germinate_report_seed(year,game_num,'PL','02')
	events = [] # empty list for holding unspecified events
	
	for item in tree.xpath('//table/tr[@class="evenColor"]'):
				
		event_raw = item.xpath('./td/text()')

		num = int(event_raw[0])
		per_num = int(event_raw[1])
		strength = unicode(event_raw[2])
		time = unicode(event_raw[3])
		event_type = unicode(event_raw[5])
		description = unicode(event_raw[6])
		try: # Zone not always indicated in event description
			# A bit redudant, done also before pruning events
			description_raw = description.split()
			zone_index = description_raw.index('Zone,') - 1
			zone = description_raw[zone_index]
		except ValueError:
			try: # Certain events have zone at end of description
				zone_index = description_raw.index('Zone') - 1
				zone = description_raw[zone_index]
			except ValueError:
				zone = None
		assert zone == 'Neu.' or zone == 'Off.' or zone == 'Def.' \
			or zone == None, "ERROR: Event zone(%s) invalid"%(zone)

		# Goals have an additional row in the description cell for assists
		if event_type == 'GOAL' and event_raw[7].find('Assist') != -1:
			description = unicode(" ".join(event_raw[6:8]))

		players_on_ice = item.xpath('./td/table')

		home_on_ice = []
		away_on_ice = []
			
		if len (players_on_ice) == 2: # Perhaps make this more robust?			
			away_on_ice = Operations.chop_on_ice_branch (
				players_on_ice[0], away_roster)
			home_on_ice = Operations.chop_on_ice_branch (
				players_on_ice[1], home_roster)

		event = Event(num, per_num, strength, time, event_type, zone, 
			description, away_acronym, home_acronym,
			away_on_ice, home_on_ice)		
		events.append (event)	    
	return events
Exemplo n.º 12
0
def analyseJUD(text, expression, count, flag, OP, c):
    """
    Analyse une opération de jointure entrée au clavier.
    Le paramètre OP spécifie le type de l'Opération à créer:
        1) OP = "J" => Join
        2) OP = "U" => Union
        ") OP = "D" => Diff 
    Syntaxe attendue : 
        -exemple1 : Join(Rel(name);Rel(name))
        -exemple2 : Join(*expr1*;*expre2*)
        -exemple3 : Union(*expr1*;*expre2*)
        -exemple4 : Diff(*expr1*;*expre2*)
        Note : expr1 et expr2 sont des expressions SPJRUD entrée au clavier en respectant la syntaxe.
    """
    flag.append(False)
    param1 = None
    param2 = None
    if(OP == "J"):
        currentExpression = o.Join(param1,param2, c)
    elif (OP == "U"):
        currentExpression = o.Union(param1,param2, c)
    elif (OP == "D"):
        currentExpression = o.Diff(param1,param2, c)
    #On analyse le param1
    count += 1
    if(text[count:count+3] == "Rel"):
        currentExpression.param1=(e.Relation(analyseRel(text, count), c))
        while(text[count] != ";"):
            count += 1
    else:
        tempExpr = None
        tempf = []
        #On effectue une seconde récursion pour déterminer le premier paramètre
        l = analyseLen(text, count)
        tempExpr = analyseInput(text, tempExpr, count, tempf, c)
        currentExpression.param1 = tempExpr
        #On calcule l'indice de début du param2
        count += l
    #On analyse le param2
    count += 1
    if(text[count:count+3] == "Rel"):
        flag[-1] = True
        currentExpression.param2=(e.Relation(analyseRel(text, count), c))
    else:
        flag[-1] = False
    
    if (expression != None):
        #Ce n'est pas la première opération de l'expression : On ajoute l'opération à l'expression existante
        expression.addExpr(currentExpression)
        return expression, flag, count
    else:
        #C'est la première opération de l'expression 
        expression = currentExpression
        return expression, flag, count
Exemplo n.º 13
0
async def ThirdFunction(time):
    print('Thread 3 started...')
    await asyncio.sleep(time)
    O = Obj.CreateVector(4, 3)
    P = Obj.CreateVector(4, 3)
    MS = Obj.CreateMatrix(4, 3)
    MT = Obj.CreateMatrix(4, 3)

    Result = Opr.SubtractVectors(
        Opr.MultiplyMatrixVector(Opr.SortMatrix(Opr.MultiplyMatrix(MS, MT)),
                                 O), P)
    print('\nFunction 3 result:\n' + str(Result))
Exemplo n.º 14
0
async def SecondFunction(time):
    print('Thread 2 started...')
    await asyncio.sleep(time)
    MG = Obj.CreateMatrix(4, 2)
    MH = Obj.CreateMatrix(4, 2)
    MK = Obj.CreateMatrix(4, 2)
    ML = Obj.CreateMatrix(4, 2)

    Result = Opr.MultiplyMatrix(Opr.MultiplyMatrix(MG, MH),
                                Opr.SumMatrix(MK, ML))

    prettyList = pprint.pformat(Result)
    print('\nFunction 2 result:\n' + prettyList)
Exemplo n.º 15
0
async def FirstFunction(time):
    print('Thread 1 started...')
    await asyncio.sleep(time)
    A = Obj.CreateVector(4, 1)
    B = Obj.CreateVector(4, 1)
    C = Obj.CreateVector(4, 1)
    MA = Obj.CreateMatrix(4, 1)
    ME = Obj.CreateMatrix(4, 1)
    #sleep
    Result = Opr.MultiplyVectors(B, C) + Opr.MultiplyVectors(
        A, B) + Opr.MultiplyVectors(
            Opr.MultiplyMatrixVector(Opr.MultiplyMatrix(MA, ME), B), C)
    print('\nFunction 1 result:\n' + str(Result))
Exemplo n.º 16
0
    def hsite(self):
        """
        :return: Returns the on site hamiltonian
        """

        labels = self.getlabels()
        operators = {'0': g.id(), '1': np.dot(g.b3(), g.b2())}
        ham = np.zeros((pow(2, self.n), pow(2, self.n)))

        for l in range(0, len(labels)):
            hamstring = op.generatetensorstring(self.n, l + 1)
            ham += op.superkron(operators, val=1, string=hamstring)
        return ham
Exemplo n.º 17
0
def AdminPanel(usrName, filename):
    print("Welcome to the software: " + usrName)
    operationAns = input("What action would you like to perform on the csv file: \n\n1.Add an account \n2.Delete an account \n3.Edit an account\n")

    if operationAns == '1':
        ops.Add(filename)
    elif operationAns == '2':
        ops.Delete(filename)
    elif operationAns == '3':
        ops.Edit(filename)
    else:
        print("Error: incorrect input, please enter with 1, 2 or 3 \n")
        AdminPanel(usrName, filename)
Exemplo n.º 18
0
def prune_block(event, description_raw, game_personnel):

	block_anchor = Operations.substring_index(description_raw, 'BLOCKED')[0]
	delim_index = Operations.substring_index(description_raw, ',')[0] + 1
	assert block_anchor != -1 and delim_index != 0, "ERROR - Anchor not found"
	assert 'Zone' in description_raw, "ERROR - 'Zone' not found"

	shot_type = description_raw[-3].strip(',')

	blocking_team = description_raw[block_anchor + 2]
	blocking_num = description_raw[block_anchor + 3].strip('#')
	blocking_name = (
		" ".join(description_raw[block_anchor + 4: delim_index])).strip (',')

	if blocking_team == event.home_acronym:
		shooting_on_ice = event.away_on_ice
		shooting_roster = game_personnel.away_roster
		blocking_on_ice = event.home_on_ice
		blocking_roster = game_personnel.home_roster
	elif blocking_team == event.away_acronym:
		shooting_on_ice = event.home_on_ice
		shooting_roster = game_personnel.home_roster
		blocking_on_ice = event.away_on_ice
		blocking_roster = game_personnel.away_roster
	else:
		assert False, 'ERROR: shooting_team(%s) doesnt match home (%s) or away\
			(%s) team'%(shooting_team, event.away_acronym, event.home_acronym)
		
	if block_anchor >= 3:
		shooting_name = " ".join(description_raw[2:block_anchor])
		shooting_team = description_raw[0]
		shooting_num = description_raw[1].strip('#')
		shooting_player =  clone_rosterplayer(
			shooting_num, shooting_name, shooting_roster)
	else: # NHL f****d up; loaded a blank shooter
		if blocking_team == event.away_acronym:
			shooting_team = event.home_acronym
		elif blocking_team == event.home_acronym:
			shooting_team = event.home_acronym
		shooting_player = Roster.return_null_player()

	blocking_player =  clone_rosterplayer(
		blocking_num, blocking_name, blocking_roster)

	return Block(
		event.num, event.period_num, event.strength, event.time,
		event.event_type, event.zone,	event.description, event.away_acronym,
		event.home_acronym, event.away_on_ice,
		event.home_on_ice, shot_type, shooting_player, blocking_player,
		shooting_team, blocking_team)
Exemplo n.º 19
0
def Resolve_Signal(Sig_Index, kernel):          #(Make sure you put driving count = 0 after resolving values)

    final_val = M.VALUE_Z
    for i in range(0,kernel.Signal[Sig_Index]['Driving_Count']):

        final_val = OP.Resolve_Value(final_val, kernel.Driver[kernel.Signal[Sig_Index]['Driver_Head'] + i])
    
    if(final_val != kernel.Signal[Sig_Index]['Eff_Val']):

        kernel.Signal[Sig_Index]['Eff_Val'] = final_val

        OP.Trigger_Sensitive_Processes(Sig_Index,kernel)

    kernel.Signal[Sig_Index]['Driving_Count'] = 0
Exemplo n.º 20
0
def echo_message(message):
    bot.send_chat_action(message.chat.id, 'typing')
    text = op.strip_accents(message.text)
    if op.validar_mensaje(text):
        bot.send_message(
            message.chat.id,
            "Debes seguir esta estructura:\n\nNombres ApellidoMaterno ApellidoPaterno Materia",
            parse_mode="MARKDOWN")
        with open('Images/giphy.gif', 'rb') as gif:
            bot.send_sticker(message.chat.id, gif)
    else:
        # La materia son las ultimas dos palabras
        materia = ' '.join(text.split(' ')[-2:])
        archivo = op.regresa_archivo(materia)
        if archivo == None:
            bot.send_message(
                message.chat.id,
                f"La materia: ___{materia}___ no existe, prueba cambiando el numero a romano o viceversa",
                parse_mode="MARKDOWN")
            with open('Images/fallout.webp', 'rb') as gif:
                bot.send_sticker(message.chat.id, gif)
        else:
            nombre = text.split(' ')[:-2]
            alumno = op.bitacora_alumno(archivo, nombre)
            if alumno == None:
                bot.send_message(
                    message.chat.id,
                    f"El nombre: ___{' '.join(nombre)}___ no esta en mi base de datos",
                    parse_mode="MARKDOWN")
                with open('Images/mario.webp', 'rb') as gif:
                    bot.send_sticker(message.chat.id, gif)
            else:
                try:
                    bot.send_message(message.chat.id,
                                     f"```{alumno.get_table()}```",
                                     parse_mode="MARKDOWN")
                except telebot.apihelper.ApiTelegramException as ex:
                    if ex.error_code == 400:
                        with open('temp.html', 'w', encoding="UTF-8") as f:
                            f.write(f"{alumno.nombre}\n\n{alumno.get_html()}")
                        with open('temp.html', 'rb') as f:
                            bot.send_document(message.chat.id, f)
                bot.send_message(
                    message.chat.id,
                    f"___{alumno.nombre} - {materia.upper()}___ [👨🏼‍🎓]\n\nTienes {alumno.promedio} [📝]\n\nDado tu puntaje eres el numero {alumno.ranking} [🌟]",
                    parse_mode="MARKDOWN")
                with open('log.txt', 'a', encoding="UTF-8") as f:
                    f.write(
                        f"{message.from_user.username} | {alumno.nombre} | {materia} | {datetime.datetime.now()}\n"
                    )
Exemplo n.º 21
0
    def noaction_operators(self):
        operators = {'0': g.id(), '1': g.b1()}
        perceptnum = len(self.perceptlabels())
        actuatorlist = self.actuatorlabels()
        list_op = {}
        actlist = range(0, len(actuatorlist))

        for a_1, a_2 in zip(actlist, actuatorlist):
            opstring = op.generatetensorstring(self.n, perceptnum + a_1 + 1)
            list_op['n' + a_2] = op.superkron(operators,
                                              val=1,
                                              string=opstring)

        return list_op
Exemplo n.º 22
0
 def generate(p):
     if is_atom(p):
         return values[p]
     elif len(p) == 2:
         if p[0] == "!":
             return op.negate(generate(p[1]))
     elif len(p) == 3:
         if p[1] == "&":
             return op.conjuction(generate(p[0]), generate(p[2]))
         if p[1] == "|":
             return op.disjunction(generate(p[0]), generate(p[2]))
         if p[1] == ">":
             return op.implies(generate(p[0]), generate(p[2]))
         if p[1] == "=":
             return op.equivalence(generate(p[0]), generate(p[2]))
Exemplo n.º 23
0
def prune_give_take(event, description_raw, game_personnel):

	givetake_team = description_raw[0]
	givetake_num = description_raw[3].strip('#')

	delim_anchor = Operations.substring_index(description_raw, ',')[0] + 1

	assert delim_anchor != 0, "ERROR - Anchor not found"

	givetake_name = (" ".join(description_raw[4:delim_anchor])).strip(',')

	if givetake_team == event.away_acronym:
		givetake_on_ice = event.away_on_ice
		givetake_roster = game_personnel.away_roster	
	elif givetake_team == event.home_acronym:
		givetake_on_ice = event.home_on_ice
		givetake_roster = game_personnel.home_roster	
	else:
		assert False, "ERROR: Which team(%s) gave/took away??"%(givetake_team)
		
	givetake_player = clone_rosterplayer(
		givetake_num, givetake_name, givetake_roster)

	if event.event_type == 'GIVE':
		return Give(
			event.num, event.period_num, event.strength, event.time,
			event.event_type, event.zone, event.description, event.away_acronym,
			event.home_acronym, event.away_on_ice, event.home_on_ice, 
			givetake_player, givetake_team)
	elif event.event_type == 'TAKE':
		return Take(
			event.num, event.period_num, event.strength, event.time,
			event.event_type, event.zone, event.description, event.away_acronym,
			event.home_acronym, event.away_on_ice, event.home_on_ice, 
			givetake_player, givetake_team)
Exemplo n.º 24
0
def pauli_group(n, full=False, normalize=True):
    """
    :param n: number of qubits
    :param full: If true returns the full pauli group for n qubits including group elements that differ by center
    of the group
    :param normalize: If true returns pauli group elements so that group are normalized
    :return: Returns a dictionary of unitary representation of the single qubit pauli group
    """
    if normalize:
        pauli_matrix = {
            'I': id() / sqrt(2),
            'X': x() / sqrt(2),
            'Y': y() / sqrt(2),
            'Z': z() / sqrt(2)
        }
    else:
        pauli_matrix = {'I': id(), 'X': x(), 'Y': y(), 'Z': z()}
    center = {'i': 1j, '-i': -1j, '1': 1, '-1': -1}
    pauli_labels = [''.join(i) for i in product('IXYZ', repeat=n)]
    qubit_group = {}
    pauli_dict = {}
    if full is False:
        for pl in pauli_labels:
            pauli_dict[pl] = op.superkron(pauli_matrix, val=1, string=pl)
    else:
        for i in center:
            for p in pauli_dict:
                qubit_group[str(i) + str(p)] = dot(center[i], pauli_dict[p])

    return pauli_dict
Exemplo n.º 25
0
    def create_filter(self, filter_set, repoman):
        filter = None
        name = filter_set.pop(0)
        if filter_set.pop(0) == "And":
            filter = Filter.Filter(name, Filter.And)
        else:
            filter = Filter.Filter(name, Filter.Or)

        # Get rid of 'begin items' and 'end items' strings
        filter_set.pop(0)
        filter_set.pop()

        while len(filter_set) > 0:
            filter_type = filter_set.pop(0)
            if filter_type == "BEGIN ITEM":
                key = filter_set.pop(0)
                op = Operations.opForName(filter_set.pop(0))
                value = eval(filter_set.pop(0))
                filter.add_item(FilterItem(key, op, value))
            elif filter_type == "BEGIN GROUP":
                group = filter_set.pop(0)
                isMember = eval(filter_set.pop(0))
                filter.add_item(FilterGroup(group, isMember, repoman))
            else:
                target = self.get(filter_set.pop(0))
                value = eval(filter_set.pop(0))
                filter.add_item(FilterFilter(target, value))
            # Get rid of 'end item', 'end group' or 'end filterfilter' strings
            filter_set.pop(0)

        return filter
def fullHamDist(List, Blocksize):
    subLists = []
    for i in range(0, len(List), Blocksize):
        subLists.append(List[i:i + Blocksize])
    Average = 0
    num = 0
    for i in range(0, len(subLists)):
        for j in range(1, len(subLists)):
            Average += op.binhamdist(subLists[i], subLists[j])
            num += 1
    Average /= float(num)
    return Average


# file = open("FIND_ECB","r")
# hexStr = ""
# BinaryList = []
# for line in file:
#     hexStr = line
#     binStr = binascii.a2b_hex(hexStr.strip("\n"))
#     BinaryList.append(binStr)
# file.close()
#
# Distances = []
# Index = 1
# for list in BinaryList:
#     avgDist = fullHamDist(list,16)
#     Distances.append((avgDist,Index))
#     Index += 1
#
# Minimum, Index = op.indexOfMinimum(Distances)
# print Distances[Index-1]
# print Index
Exemplo n.º 27
0
def kraus_ad(n, t, t1):
    """
      Produces the kraus matrices for the amplitude damping channel
        :param n: number of qubit
        :param t: time step for evolution
        :param t1: relaxation time
        :return: returns a 3 dimensinal array of amplitude damping kraus matrices
      """

    A = np.zeros((pow(2, n), pow(2, n), pow(2, n)),
                 dtype=complex)  # 3 dimensional array to store kraus matrices
    gamma = 1 - np.exp(-t / t1)
    adOperators = {
        "0": np.array([[1, 0], [0, np.sqrt(1 - gamma)]]),
        "1": np.array([[0, np.sqrt(gamma)], [0, 0]])
    }

    labels = op.createlabel(n, 2)

    for i in range(len(labels)):
        temp = 1
        for digit in labels[i]:
            temp = np.kron(temp, adOperators[digit])
        A[i] = temp
    return A
Exemplo n.º 28
0
def kraus_pta(n, t, t1, t2):
    """
    Produces the kraus matrices for the pta channel
    :param n: number of qubit
    :param t: time step for evolution
    :param t1: relaxation time
    :param t2: dephasing time
    :return: returns a 3 dimensinal array of pta kraus matrices
    """
    gamma = 1 - np.exp(-t / t1)
    t_phi = Decimal(1 / t2) - Decimal(1 / (2 * t1))
    # lambda1 = np.exp(-t/t1)*(1-np.exp(-2*(t/t_phi)))
    px = py = gamma / 4.0
    pz = 1.0 / 2.0 - py - np.exp(-t / (2 * t1)) * np.exp(-(t / t_phi)) / 2
    pi = 1 - (px + py + pz)
    print('px: ', py, 'pz: ', pz, 'pi: ', pi)
    A = np.zeros((pow(4, n), pow(2, n), pow(2, n)),
                 dtype=complex)  # 3 dimensional array to store kraus matrices
    ptaOperators = {
        '0': np.sqrt(pi) * g.id(),
        '1': np.sqrt(px) * g.x(),
        '2': np.sqrt(py) * g.y(),
        '3': np.sqrt(pz) * g.z()
    }

    # get labels
    labels = op.createlabel(n, 4)

    for i in range(len(labels)):
        temp = 1
        for digit in labels[i]:
            temp = np.kron(temp, ptaOperators[digit])
        A[i] = temp
    return A
Exemplo n.º 29
0
def pta_ad(n, t, t1):
    """
    Produces the kraus matrices for the pta channel
    :param n: number of qubit
    :param t: time step for evolution
    :param t1: relaxation time
    :return: returns a 3 dimensinal array of pta kraus matrices
    """
    gamma = 1 - np.exp(-t / t1)
    px = py = gamma / 4.0
    pz = 1.0 / 2.0 - py - np.sqrt(1 - gamma) / 2
    pi = 1 - (px + py + pz)
    A = np.zeros((pow(4, n), pow(2, n), pow(2, n)),
                 dtype=complex)  # 3 dimensional array to store kraus matrices
    ptaOperators = {
        '0': np.sqrt(pi) * g.id(),
        '1': np.sqrt(px) * g.x(),
        '2': np.sqrt(py) * g.y(),
        '3': np.sqrt(pz) * g.z()
    }

    # get labels
    labels = op.createlabel(n, 4)

    for i in range(len(labels)):
        temp = 1
        for digit in labels[i]:
            temp = np.kron(temp, ptaOperators[digit])
        A[i] = temp
    return A
Exemplo n.º 30
0
    def __init__(self, s, dur=0.5):

        self.data = []

        chars = PSeq().fromString(s)

        for i, char in chars.items():

            dur = op.modi(dur, i)

            if char == " ":
                self.data[-1] += dur

            else:

                if len(char) > 1:

                    div = float(len(char))

                    this_dur = PRhythm(str(char), dur / div).list()
                    self.data += this_dur

                else:

                    self.data.append(dur)
Exemplo n.º 31
0
def Execute_Time_Events(kernel):

    for ele in kernel.Event_List[0][1:]:

        if( ele[0] < 0):                                 # Delayed Signal

            OP.Insert_Driving_Value(ele[1],ele[2],kernel)                 # ele[1] = Sig_Index , ele[2] = Value
        
        else:

            Execute_Process(ele, kernel)                                  # process and kernel sent

    kernel.Event_List.pop(0)                                              # Removes already happed time events

    for i in range(1,kernel.Signal_Update_Event[0]+1):

        Resolve_Signal(kernel.Signal_Update_Event[i], kernel)            # Signal_index and kernel sent

    
    kernel.Signal_Update_Event[0] = 0                                    # Resets the Signal Update Head

    while(bool(kernel.Process_Trigger_Event[0])):             # if Some process trigering is registered, then entered in while

        for i in range(1,kernel.Process_Trigger_Event[0]+1):

            Execute_Process(kernel.Signal_Triggered_Process[kernel.Process_Trigger_Event[i]], kernel)
            kernel.Signal_Triggered_Process[kernel.Process_Trigger_Event[i]]['Triggered_Bit'] = 0         # Resets. Now it can again be registered for Trigering

        kernel.Process_Trigger_Event[0] = 0                             # Resets the Process Trigger Head

        for i in range(1,kernel.Signal_Update_Event[0]+1):
            
            Resolve_Signal(kernel.Signal_Update_Event[i], kernel)            # Signal_index and kernel sent
            
        kernel.Signal_Update_Event[0] = 0                                    # Resets the Signal Update Head
Exemplo n.º 32
0
 def __init__(self, *pats):
     l, p = [], []
     for pat in pats:
         p.append(Base.asStream(pat))
         l.append(len(p[-1]))
     length = op.LCM(*l)
     self.data = zip(*[p[i].stretch(length) for i in range(len(p))])
Exemplo n.º 33
0
    def __init__(self, s, dur=0.5):

        self.data = []
        
        chars = PSeq().fromString(s)
        
        for i, char in chars.items():

            dur = op.modi(dur, i)

            if char == " ":
                self.data[-1] += dur

            else:

                if len(char) > 1:

                    div = float(len(char))

                    this_dur = PRhythm(str(char), dur / div).list()
                    self.data += this_dur
                    
                else:

                    self.data.append(dur)
Exemplo n.º 34
0
class TestOperationsMethods(unittest.TestCase):
    def setUp(self):
        self.operations = Operations()

    def test_operations(self):
        self.assertEqual("Running app 'app1' in namespace 'dev' nice",
                         self.operations.runningInfo("app1", "dev"))
Exemplo n.º 35
0
def Execute_Process(process, kernel):

    suspend = 0  # if 1, then process should be suspended

    if (process['Current_Instruction_Index'] >=
            process['Instruction_End_Index']):  #Exceded own region

        process['Current_Instruction_Index'] = process[
            'Instruction_Start_Index']  # resets

    while (not (bool(suspend))):

        if (process['Current_Instruction_Index'] >=
                process['Instruction_End_Index']):

            process['Current_Instruction_Index'] = process[
                'Instruction_Start_Index']

            suspend = 1

            if (len(process) == 3):  # Time Sensitive Process

                OP.Schedule_Time_Event(
                    process, 0,
                    kernel)  # Schedules process event in the next timestrap

        else:

            suspend = Execute_Instruction(
                process, kernel
            )  # Executes the Instruction pointed by  process['Current_Instruction_Index']
Exemplo n.º 36
0
def delete(request, db):
    try:
        document_id = request.args.get('docid')
        status = Operations.deleteOne(db, collection, document_id)
        return json.dumps({'status': status}, default=str), 200, headers
    except:
        return "Invalid JSON"
def fullHamDist(List, Blocksize):
    subLists = []
    for i in range(0,len(List),Blocksize):
        subLists.append(List[i:i + Blocksize])
    Average = 0
    num = 0
    for i in range(0,len(subLists)):
        for j in range(1,len(subLists)):
            Average += op.binhamdist(subLists[i], subLists[j])
            num += 1
    Average /= float(num)
    return Average

# file = open("FIND_ECB","r")
# hexStr = ""
# BinaryList = []
# for line in file:
#     hexStr = line
#     binStr = binascii.a2b_hex(hexStr.strip("\n"))
#     BinaryList.append(binStr)
# file.close()
#  
# Distances = []
# Index = 1
# for list in BinaryList:
#     avgDist = fullHamDist(list,16)
#     Distances.append((avgDist,Index))
#     Index += 1
#  
# Minimum, Index = op.indexOfMinimum(Distances)
# print Distances[Index-1]
# print Index
Exemplo n.º 38
0
def playbyplay_extractor (year, game_num):
	"""
	Extract play-by-play information from a html file on the
	local machine (in the form of events)
	"""

	tree = Operations.germinate_report_seed(year,game_num,'PL','02')

	events = [] # empty list for holding unspecified events
	
	for item in tree.xpath('//table/tr[@class="evenColor"]'):
	#for x in range (116, 120):
	#   item = tree.xpath('//table/tr[@class="evenColor"]') [x]
					
		event_raw = item.xpath('./td/text()')

		num = unicode(event_raw[0])
		per_num = unicode(event_raw[1])
		strength = unicode(event_raw[2])
		time = unicode(event_raw[3])
		event_type = unicode(event_raw[5])
		description = unicode(event_raw[6])

		# Goals have an additional row in the description cell for assists
		if event_type == 'GOAL' and event_raw[7].find('Assist') != -1:
			description = unicode(" ".join(event_raw[6:8]))

		players_on_ice = item.xpath('./td/table')

		home_on_ice = []
		away_on_ice = []
			
		if len (players_on_ice) == 2:

			away_players_raw = players_on_ice[0].xpath ('.//font')
			for away_player in away_players_raw:
				position_name = away_player.xpath ('./@title')
				number = away_player.xpath ('./text()') [0]

				position, name = position_name[0].split(' - ')

				away_on_ice.append ([position, name, number])
			
			home_players_raw = players_on_ice[1].xpath ('.//font')
			for home_player in home_players_raw:
				position_name = home_player.xpath ('./@title')
				number = home_player.xpath ('./text()') [0]

				position, name = position_name[0].split(' - ')

				home_on_ice.append ([position, name, number])

		event = Objects.Event(
			num, per_num, strength, time, event_type, description,\
			away_on_ice, home_on_ice
			)
		
		events.append (event)	    
	return events
Exemplo n.º 39
0
 def __init__(self, *patterns):
     self.data = []
     item = [asStream(p) for p in patterns]
     size = op.LCM(*[len(i) for i in item])
     for n in range(size):
         for i in item:
             self.data.append(op.modi(i,n))
     self.make()
Exemplo n.º 40
0
    def __init__(self, data, n=1):

        n = P(n)

        lrg = max(len(data), len(n))

        self.data = []

        for i in range(lrg):
            for j in range(op.modi(n,i)):
                self.data.append(op.modi(data,i))

##        for i, item in enumerate(data):
##            for j in range(op.modi(n,i)):
##                self.data.append( item )

        self.make()
Exemplo n.º 41
0
 def description(self):
     value = None
     if type(self.value) == int:
         value = "%d" % self.value
     elif type(self.value) == float:
         value = "%.2f" % self.value
     else:
         value = "%s" % self.value
     return self.key + " " + Operations.nameForOp(self.op) + " " + value
Exemplo n.º 42
0
    def __init__(self, data, n=1):

        self.data = []

        for i, item in enumerate(data):
            for j in range(op.modi(n,i)):
                self.data.append( item )

        self.make()
Exemplo n.º 43
0
 def save(self, f):
     f.write('BEGIN ITEM')
     f.write(os.linesep)
     f.write(self.key)
     f.write(os.linesep)
     f.write(Operations.nameForOp(self.op))
     f.write(os.linesep)
     f.write(repr(self.value))
     f.write(os.linesep)
     f.write('END ITEM')
     f.write(os.linesep)
Exemplo n.º 44
0
def prune_stop(event, description_raw, event_index, event_list, game_personnel):

	stopping_player = Roster.return_null_player()
	stopping_team = None
	zone = None
	tv_timeout = 0
	timeout_caller = None

	description_raw = re.split('\W+', event.description)
	description_parsed = " ".join(description_raw)
	
	# Parse out 'TV TIMEOUT if not only item
	if 'TV' in description_raw:
		tv_timeout = 1
		if len(description_raw) != 2:
			index = description_raw.index("TV")
			description_raw.pop (index)
			description_raw.pop (index)
			description_parsed = " ".join(description_raw)

	if 'HOME' in description_raw:
		timeout_caller = game_personnel.home_coach.full_name()
	elif 'VISITOR' in description_raw:
		timeout_caller = game_personnel.away_coach.full_name()
	
	if "GOALIE" in description_raw or 'FROZEN' in description_raw:		
		stopping_team, stopping_on_ice = Operations.team_responsible(
			event_index, event_list)
		for player in stopping_on_ice:
			if player.pos == 'Goalie':
				stopping_player = player
	elif "ICING" in description_raw:
		stopping_team, stopping_on_ice = Operations.team_responsible(
			event_index, event_list)

	return Stop(
		event.num, event.period_num, event.strength, event.time,
		event.event_type, zone,	event.description, event.away_acronym,
		event.home_acronym, event.away_on_ice,
		event.home_on_ice, description_parsed, stopping_player,
		stopping_team, tv_timeout, timeout_caller)
Exemplo n.º 45
0
def test_all():
	year = '20142015'
	report_type = 'PL'
	game_type = '02'

	for x in range (750,1150):
		game_num = Operations.pad_game_num(x)
		game_info = GameHeader.harvest(year, game_num, report_type, game_type)
		game_personnel = Roster.harvest(year, game_num)
		game_summary = GameSummary.harvest(year, game_num, game_info, game_personnel)
	
		yield check_refs, game_personnel, game_summary
Exemplo n.º 46
0
def prune_hit(event, description_raw, game_personnel):

	hit_anchor = description_raw.index('HIT')
	delim_anchors = Operations.substring_index(description_raw, ',') 
	assert hit_anchor != -1, "ERROR - Anchor not found"

	if delim_anchors == []: # No zone entered in nhl report
		hit_name = (" ".join(
			description_raw[hit_anchor + 3:])).strip (',')
	else:
		name_anchor = delim_anchors[0] + 1
		hit_name = (" ".join(
			description_raw[hit_anchor + 3: name_anchor])).strip (',')

	hit_team = description_raw[hit_anchor + 1]
	hit_num = description_raw[hit_anchor + 2].strip('#')
	
	if hit_team == event.home_acronym:
		hitting_on_ice = event.away_on_ice
		hitting_roster = game_personnel.away_roster
		hit_on_ice = event.home_on_ice
		hit_roster = game_personnel.home_roster
	elif hit_team == event.away_acronym:
		hitting_on_ice = event.home_on_ice
		hitting_roster = game_personnel.home_roster
		hit_on_ice = event.away_on_ice
		hit_roster = game_personnel.away_roster
	else:
		assert False, 'ERROR: hit_team(%s) doesnt match home (%s) or away\
			(%s) team'%(hit_team, event.away_acronym, event.home_acronym)

	if hit_anchor >= 3:
		hitting_team = description_raw[0]
		hitting_num = description_raw[1].strip('#')
		hitting_name = " ".join(description_raw[2:hit_anchor])
		hitting_player = clone_rosterplayer(
			hitting_num, hitting_name, hitting_roster)
	else:# NHL f****d up; loaded a blank hitter
		if hit_team == event.away_acronym:
			hitting_team = event.home_acronym
		elif hit_team == event.home_acronym:
			hitting_team = event.home_acronym
		hitting_player = Roster.return_null_player()

	hit_player = clone_rosterplayer(hit_num, hit_name, hit_roster)

	return Hit(
		event.num, event.period_num, event.strength, event.time,
		event.event_type, event.zone, event.description, event.away_acronym,
		event.home_acronym, event.away_on_ice,
		event.home_on_ice, hitting_player, hit_player, hitting_team,
		hit_team)
Exemplo n.º 47
0
def prune_miss(event, description_raw, game_personnel):

	delim_anchors = Operations.substring_index(description_raw, ',')
	delim_anchor = delim_anchors[0] + 1	
	assert delim_anchor != 0, "ERROR - Anchor not found"
	
	if len(delim_anchors) < 4: # Part of info is missing-usually shot/miss type
		shot_type = None
		miss_type = None
	else:
		shot_type = description_raw[-8].strip(',')
		miss_type = (" ".join(description_raw[delim_anchor + 1:-4])).strip(',')

	distance = description_raw[-2]
	shooting_team = description_raw[0]
	shooting_num = description_raw[1].strip('#')

	shooting_name = (" ".join(description_raw[2:delim_anchor])).strip(',')
	shooting_player = (shooting_num, shooting_name)

	if shooting_team == event.away_acronym:
		shooting_on_ice = event.away_on_ice
		shooting_roster = game_personnel.away_roster
		blocking_on_ice = event.home_on_ice
		blocking_team = event.home_acronym
		blocking_roster = game_personnel.home_roster
	elif shooting_team == event.home_acronym:
		shooting_on_ice = event.home_on_ice
		shooting_roster = game_personnel.home_roster
		blocking_on_ice = event.away_on_ice
		blocking_team = event.away_acronym
		blocking_roster = game_personnel.away_roster
	else:
		assert False, 'ERROR: shooting_team doesnt match home or away team'
	
	for player in blocking_on_ice:
		blocking_player = Roster.return_null_player()
		if player.pos == 'G':
			blocking_player = player

	shooting_player =  clone_rosterplayer(
		shooting_num, shooting_name, shooting_roster)
	
	return Miss(
		event.num, event.period_num, event.strength, event.time,
		event.event_type, event.zone, event.description, event.away_acronym,
		event.home_acronym, event.away_on_ice,
		event.home_on_ice, shot_type, miss_type, distance, shooting_player,
		blocking_player, shooting_team, blocking_team)
Exemplo n.º 48
0
	def __init__(
			self, name, SA, rt_cnts, sht_cnts, rt_wght, gfact,
			load_time, elut_ends, raw_cpms, elut_cpms):
		"""Constructor of Run objects

		@type self: Run
		@type name: str
			Name of run, used for identification purposes
		@type SA: float
			The specific activity of the loading solution used for the CATE
				run/replicate; radioactivity(counts per min)/volume (mL).
		@type rt_cnts: float
			Radioactivity of the roots of the plant used (cpm).
		@type sht_cnts: float
			Radioactivity of the shoots of the plant used (cpm).
		@type rt_wght: float
			Weight of the roots of the plant used (grams).
		@type gfact: float
			Instrument-specific correction factor. Used to account of idiosyncrasies
				of the detecting equipment.
		@type load_time: float
			Amount of time plant used was placed in loading solution for (minutes).
		@type elut_ends: list[float]
			Time points that eluates were removed from plants (vs added to plants)
		@type raw_cpms: list[float]
			Eluate radioactivities as measured by detecting equipment.
		@type elut_cpms: list[float]
			raw_cpms with blank values ('') replaced with 0s

		@rtype: None
		"""       
		self.name = name  # Text identifier extracted from col header in excel
		self.SA = SA
		self.rt_cnts = rt_cnts
		self.sht_cnts = sht_cnts
		self.rt_wght = rt_wght
		self.gfact = gfact
		self.load_time = load_time
		self.elut_ends = elut_ends
		self.raw_cpms = raw_cpms
		self.elut_cpms = elut_cpms  # = raw_cpms with blanks('') replaced w/0
		self.elut_starts = [0.0] + elut_ends[:-1]
		self.elut_cpms_gfact, self.elut_cpms_gRFW, \
			self.elut_cpms_log, self.elut_ends_parsed = \
			Operations.basic_run_calcs(
				rt_wght, gfact, self.elut_starts, elut_ends, elut_cpms)       
		# x and y data for graphing ('numpy-fied')
		self.x = numpy.array(self.elut_ends_parsed)
		self.y = numpy.array(self.elut_cpms_log)
def findKeySize(hexStr):
    dec = int(hexStr,16)
    binaryStr = bin(dec)
    Distances = []
    for keySize in range(2,40):
        firstPart = binaryStr[0:keySize * 8]
        secondPart = binaryStr[keySize * 8: keySize * 8 * 2]
        Distances.append(((op.binhamdist(firstPart, secondPart) / 1.0 / keySize),keySize))
           
    min = 2
    val = Distances[0][0]
    for num, key in Distances:
        if num < val:
            val = num
            min = key
#     print numpy.array(Distances)
#     exit()
    return min
Exemplo n.º 50
0
 def findKeySize(self, workingData=None, keymin=2, keymax=40):
     if workingData is None:
         workingData = self.data
     minHamming = 99999
     bestKey = 0
     for key in range(keymin, keymax):
         hammingSum = float(0)
         compares = 0
         for endblock in range(1, 4):
             for startBlock in range(0, endblock - 1):
                 hammingSum += Operations.binaryHamming(workingData[startBlock * key:(startBlock + 1) * key],
                                                        workingData[endblock * key:(endblock + 1) * key])
                 compares += 1
         hammingSum = hammingSum / key / compares
         if hammingSum < minHamming:
             minHamming = hammingSum
             bestKey = key
     return bestKey
Exemplo n.º 51
0
    def __init__(self, s, dur=0.5):

        self.chars = []
        self.data  = []

        if type(s) is str:
            s = P().fromString(s)
            
        dur = s.dur(dur)
        self.data = []
        
        for i, char in s.items():
            # Recursively get rhythms
            val = op.modi(dur,i)
            if isinstance(char, Base.PGroup):
                dur_group = self.__class__(char, val)
                self.chars += list(dur_group.chars)
                self.data  += list(dur_group.data)
            else:
                self.chars.append(char)
                self.data.append(val)
Exemplo n.º 52
0
def harvest(year, game_num):
    """
	Extract roster information from a html file on the
	local machine and create database entries
	"""

    game_info = GameHeader.harvest(year, game_num, "RO", "02")

    tree = Operations.germinate_report_seed(year, game_num, "RO", "02")

    tables = tree.xpath("//table//table//table//table")

    away_roster = chop_ind_roster_branch(tables, "away", game_info, year)
    home_roster = chop_ind_roster_branch(tables, "home", game_info, year)

    away_coach, home_coach = chop_coach_branch(tables)
    away_coach.team = game_info.away_team
    home_coach.team = game_info.home_team

    referees, linesmen = chop_officials_branch(tables)

    return GamePersonnel(away_roster, home_roster, away_coach, home_coach, referees, linesmen)
Exemplo n.º 53
0
def prune_roster_parts(tree, scratch, team, years, roster_objects):
    """
	Given xml tree of a part of a roster (either scratched or nonscratched 
	list as tree), construct and add R_Player objects to roster_objects list
	"""
    iter_roster = iter(tree)
    next(iter_roster)

    for item in iter_roster:

        captaincy = None
        num = item.xpath("./td/text()")[0]
        position = item.xpath("./td/text()")[1]

        temp_starting = item.xpath("./td/@class")[0]
        starting = 0
        if "bold" in temp_starting:
            starting = 1

        temp_name_raw = item.xpath("./td/text()")[2]
        temp_name_raw_split = temp_name_raw.split()
        first_name = temp_name_raw_split[0]

        if "(A)" in temp_name_raw_split:
            captaincy = "A"
            temp_name_raw_split.pop(-1)
        elif "(C)" in temp_name_raw_split:
            captaincy = "C"
            temp_name_raw_split.pop(-1)

        last_name = " ".join(temp_name_raw_split[1:])

        playerid = Operations.get_playerid(first_name, last_name, team, years, position)

        roster_objects.append(
            R_Player(team, num, position, first_name, last_name, captaincy, starting, scratch, playerid)
        )
Exemplo n.º 54
0
def prune_shot(event, description_raw, game_personnel):
	
	distance = description_raw[-2]
	shot_type = description_raw[-5].strip(',')
	shooting_team = description_raw[0]
	shooting_num = description_raw[3].strip('#')

	delim_anchor = Operations.substring_index(description_raw, ',')[0] + 1

	assert delim_anchor != 0, "ERROR - Anchor not found"

	shooting_name = (" ".join(description_raw[4:delim_anchor])).strip(',')

	if shooting_team == event.away_acronym:
		shooting_on_ice = event.away_on_ice
		shooting_roster = game_personnel.away_roster
		blocking_on_ice = event.home_on_ice
		blocking_team = event.home_acronym
	elif shooting_team == event.home_acronym:
		shooting_on_ice = event.home_on_ice
		shooting_roster = game_personnel.home_roster
		blocking_on_ice = event.away_on_ice
		blocking_team = event.away_acronym
		
	for player in blocking_on_ice:
		if player.pos == 'G':
			blocking_player = player

	shooting_player = clone_rosterplayer(
		shooting_num, shooting_name, shooting_roster)
	
	return Shot(
		event.num, event.period_num, event.strength, event.time, 
		event.event_type, event.zone, event.description, event.away_acronym,
		event.home_acronym, event.away_on_ice,
		event.home_on_ice, shot_type, distance, shooting_player, 
		blocking_player, shooting_team, blocking_team)
Exemplo n.º 55
0
def harvest(year, game_num):

	game_info = GameHeader.harvest (year, game_num, 'RO', '02')
	away_full_name = Operations.team_acronym_to_uppercase(
		game_info.away_team)
	home_full_name = Operations.team_acronym_to_uppercase(
		game_info.home_team)

	tree = Operations.germinate_report_seed (year, game_num, "ES", '02')

	tables = tree.xpath('//table[@class="tablewidth" and @align="center"]/tr/td/table[@width="100%"]')
	rows = tables[3].xpath('./tr')

	roster = []
	team_acronym = game_info.away_team
	
	for item in rows:
		if item.xpath('./td/text()')[0] == home_full_name:
			away_roster = roster
			roster = []
			team_acronym = game_info.home_team
		elif item.get('class') == 'evenColor' or\
				item.get('class') == 'oddColor':
			fields = item.xpath('./td/text()')
			for index, field in enumerate(fields):
				if field == u'\xa0':
					field = '0'

				if index == 0:
					number = field
				elif index == 1:
					position = field
				elif index == 2:
					name_raw = field.split(', ')
					first_name = name_raw[1]
					last_name = name_raw[0]
				elif index == 3:
					goals = field					
				elif index == 4:
					assists = field
				elif index == 5:
					points = field
				elif index == 6:
					plus_minus = field
				elif index == 7:
					num_penalties = field
				elif index == 8:
					pim = field
				elif index == 9:
					total_minutes = field
				elif index == 10:
					num_shifts = field
				elif index == 11:
					avg_shift_length = field
				elif index == 12:
					powerplay_minutes = field
				elif index == 13:
					shorthanded_minutes = field
				elif index == 14:
					evenstrength_minutes = field
				elif index == 15:
					shots = field
				elif index == 16:
					attempts_blocked = field
				elif index == 17:
					missed_shots = field
				elif index == 18:
					hits = field
				elif index == 19:
					give_aways = field
				elif index == 20:
					take_aways = field
				elif index == 21:
					blocked_shots = field
				elif index == 22:
					faceoff_wins = field
				elif index == 23:
					faceoff_losses = field
				elif index == 24:
					faceoff_percentage = field

			playerid = Operations.get_playerid(first_name, last_name, 
				team_acronym, year,	position)
			
			roster.append (ES_Player(team_acronym, number, position,
				first_name, last_name, goals, assists, points, plus_minus,
				num_penalties, pim, total_minutes, num_shifts,
				avg_shift_length, powerplay_minutes, shorthanded_minutes,
				evenstrength_minutes, shots, attempts_blocked, missed_shots,
				hits, give_aways, take_aways, blocked_shots, faceoff_wins,
				faceoff_losses, faceoff_percentage, playerid))

		home_roster = roster

	return away_roster, home_roster
Exemplo n.º 56
0

def harvest(year, game_num):
    """
	Extract roster information from a html file on the
	local machine and create database entries
	"""

    game_info = GameHeader.harvest(year, game_num, "RO", "02")

    tree = Operations.germinate_report_seed(year, game_num, "RO", "02")

    tables = tree.xpath("//table//table//table//table")

    away_roster = chop_ind_roster_branch(tables, "away", game_info, year)
    home_roster = chop_ind_roster_branch(tables, "home", game_info, year)

    away_coach, home_coach = chop_coach_branch(tables)
    away_coach.team = game_info.away_team
    home_coach.team = game_info.home_team

    referees, linesmen = chop_officials_branch(tables)

    return GamePersonnel(away_roster, home_roster, away_coach, home_coach, referees, linesmen)


if __name__ == "__main__":
    for x in range(1, 100):
        game_num = Operations.pad_game_num(x)
        print harvest("20142015", game_num)
def run():

    kOffset_a = 24
    kOffset_b = 8

    clk = 0
    arr = []

    isNextTrainA = True

    offset = kOffset_a

    for clk in range(0, 8192 * 4):
        if int(clk % (8192)) == 0:
            if isNextTrainA:
                offset = kOffset_a
                isNextTrainA = False
            else:
                offset = kOffset_b
                isNextTrainA = True

                # The Bluetooth clock is a 28-bit counter with a clock cycle of 312.5µs.
                # Bluetooth communication at the Baseband level is organised into time slots.
                # Each slot has a length of two clock cycles, i.e. 625µs.
        clk_bits = op.dec2bin(clk, 32)  # change clock to 32 bits

        # ---------------------------
        # 			Find X

        # 0 index is right most one
        # 4-0 would actually mean -> indices 27, 28, 29 , 30, 31

        # Similarly take clock's 16-12
        # +1 because python does not include b if a:b
        clk_16_12 = op.bin2dec(clk_bits[31 - 16 : 31 - 12 + 1])
        clk_4_2_0 = op.bin2dec(clk_bits[31 - 4 : 31 - 2 + 1] + clk_bits[31 - 0])

        #################################################
        sub_clk = 0
        """if clk_16_12 > clk_4_2_0:
			sub_clk = clk_16_12 - clk_4_2_0
		else:
			sub_clk = clk_4_2_0 - clk_16_12
		"""
        # clk_4_2_0 is always a pattern like 0101 2323 ... 12131213, 14151415. (32 tics)
        # clk_16_12 is 0 for 4096 tics and 1 for next 4096 then 2 so on
        # subtraction doesn't make sense
        sub_clk = clk_4_2_0 - clk_16_12
        temp_clk = sub_clk % 16  # in decimal

        Xi = op.dec2bin((clk_16_12 + offset + temp_clk) % 32, 32)
        X = Xi[31 - 4 : 31 - 0 + 1]
        # print(">>> " + X)
        # print("X: "+str(temp_clk))
        # ---------------------------

        # 0000 1001 1110 1000
        # address = [ 4-LSBs-of-DCI(0x00), GIAC LAP (0x9E8B33)]
        address = op.hex2bin("09E8B33")  # this return 32 bits

        ###########################
        ## we can flip the address

        address = address[4:]  # Get 28 bits

        # print("Address:" + address)

        A = address[27 - 27 : 27 - 23 + 1]
        B = address[27 - 22 : 27 - 19 + 1]
        C = "".join((address[27 - 8], address[27 - 6], address[27 - 4], address[27 - 2], address[27 - 0]))
        D = address[27 - 18 : 27 - 10 + 1]
        E = "".join(
            (
                address[27 - 13],
                address[27 - 11],
                address[27 - 9],
                address[27 - 7],
                address[27 - 5],
                address[27 - 3],
                address[27 - 1],
            )
        )
        F = "0"

        # print('clock [1]: ' + clk_bits[31-1])
        Y1 = clk_bits[31 - 1] * 5  # in binary
        # Y1 = clk_bits[31-2]

        if clk_bits[31 - 1] == "0":
            Y2 = "000000"
        else:
            Y2 = "100000"
            # Y2 will either be 100000 or 000000
            # Y2 = op.dec2bin(32 * op.bin2dec(clk_bits[31-1]), 32) # in binary

            # Y1 = '0'
        Y2 = "0"

        add_1 = "{0:05b}".format((op.bin2dec(A) + op.bin2dec(X)) % 32)
        xor_1 = "{0:05b}".format(op.bin2dec(add_1) ^ op.bin2dec(B))
        xor_2 = "{0:05b}".format(op.bin2dec(C) ^ op.bin2dec(Y1))
        perm_1 = op.perm5(xor_1, xor_2, D)
        add_2 = op.bin_add(E, F, perm_1, Y2)
        freq = op.bin2dec(add_2) % 79
        arr.append(freq)
    return arr
Exemplo n.º 58
0
 def singleByteXor(self, cipher, workingData=None):
     if workingData is None:
         workingData = self.data
     return Operations.xorAgainst(workingData, cipher)
Exemplo n.º 59
0
 def repeatingXORKeyKnown(self, key):
     decrypted = Operations.xor(self.data, key)
     return decrypted
Exemplo n.º 60
0
	def analyze(self):
		"""Implement analysis based on settings from attributes.

		Parameters are defined based on the phase limits that have been provided
		The 'engine' of the analysis if you will.

		@type self: Analysis
		@rtype: None
		"""
		# Implement objective analysis. Note that objective analysis just uses a
		#    set algorithm to set phase limits. After this if block the process
		#    is the same of both objective and subjective analyses. A subjective
		#    just allows the user to directly set the phase limits.
		if self.kind == 'obj':
			self.obj_x_start = self.run.x[-self.obj_num_pts:]
			self.obj_y_start = self.run.y[-self.obj_num_pts:]
			self.xs_p3, self.r2s, self.ms, self.bs = Operations.get_obj_phase3(
				obj_num_pts=self.obj_num_pts,
				elut_ends_parsed=self.run.elut_ends_parsed,
				elut_cpms_log=self.run.elut_cpms_log)
			self.xs_p2, self.xs_p1, self.p12_r2_max = Operations.get_obj_phase12(
				xs_p3=self.xs_p3, 
				elut_ends_parsed=self.run.elut_ends_parsed,
				elut_cpms_log=self.run.elut_cpms_log,
				elut_ends=self.run.elut_ends)
		# From here analysis is same for both objective and subjective analyses
		if self.xs_p3 != ('', ''):
			self.phase3 = Operations.extract_phase(
				xs=self.xs_p3, 
				x_series=self.run.elut_ends_parsed, 
				y_series=self.run.elut_cpms_log,
				elut_ends=self.run.elut_ends,
				SA=self.run.SA, load_time=self.run.load_time)
			Operations.advanced_run_calcs(analysis=self)
			if self.xs_p2 != ('', '') and self.phase3.xs != ('', ''):
				# Set series' to be curve-stripped
				end_p12_index = Operations.x_to_index(
					x_value=self.xs_p2[1], boundary_type='end',
					x_series=self.run.elut_ends_parsed,
					larger_x=self.run.elut_ends)
				self.x_p12 = self.run.x[: end_p12_index+1]
				self.y_p12 = self.run.y[: end_p12_index+1]
				# Curve strip phase 1 + 2 data of phase 3
				# From here on data series potentially have 'holes' from
				# omitting negative log operations during curvestripping
				self.x_p12_curvestrip_p3, self.y_p12_curvestrip_p3 = \
					Operations.curvestrip(
						x_series=self.x_p12, y_series=self.y_p12, 
						slope=self.phase3.slope,
						intercept=self.phase3.intercept)
				self.phase2 = Operations.extract_phase(
					xs=self.xs_p2, 
					x_series=self.x_p12_curvestrip_p3,
					y_series=self.y_p12_curvestrip_p3,
					elut_ends=self.run.elut_ends,
					SA=self.run.SA, load_time=self.run.load_time)
				if self.xs_p1 != ('', '') and self.phase2.xs != ('', ''):
					start_p1_index = Operations.x_to_index(
						x_value=self.xs_p1[0], boundary_type='start',
						x_series=self.run.elut_ends_parsed,
						larger_x=self.run.elut_ends)
					end_p1_index = Operations.x_to_index(
						x_value=self.xs_p1[1], boundary_type='end',
						x_series=self.run.elut_ends,
						larger_x=self.run.elut_ends)
					self.x_p1 = self.run.x[start_p1_index : end_p1_index+1]
					self.y_p1 = self.run.y[start_p1_index : end_p1_index+1]
					# Getting phase 1 data that has been already stripped of
					# phase 3 data
					self.x_p1_curvestrip_p3 =\
						self.x_p12_curvestrip_p3[start_p1_index: end_p1_index+1]
					self.y_p1_curvestrip_p3 =\
						self.y_p12_curvestrip_p3[start_p1_index: end_p1_index+1]
					# Curve-strip phase 2 data from phase 1
					self.x_p1_curvestrip_p23, self.y_p1_curvestrip_p23 = \
						Operations.curvestrip(
							x_series=self.x_p1_curvestrip_p3,
							y_series=self.y_p1_curvestrip_p3, 
							slope=self.phase2.slope,
							intercept=self.phase2.intercept)
					self.phase1 = Operations.extract_phase(
						xs=self.xs_p1, 
						x_series=self.x_p1_curvestrip_p23,
						y_series=self.y_p1_curvestrip_p23,
						elut_ends=self.run.elut_ends,
						SA=self.run.SA, load_time=self.run.load_time)