Пример #1
0
    def _deriveSecrets(self, masterKey):
        """Derives session keys (AES keys, counter nonces, HMAC keys and magic
        values) from the given master secret. All key material is derived using
        HKDF-SHA256."""

        log.debug("Master key: 0x%s." % masterKey.encode("hex"))

        # We need key material for two magic values, symmetric keys, nonces and
        # HMACs. All of them are 32 bytes in size.
        hkdf = mycrypto.HKDF_SHA256(masterKey, "", 32 * 8)
        okm = hkdf.expand()

        # Set the symmetric AES keys.
        self.sendCrypter.setSessionKey(okm[0:32], okm[32:64])
        self.recvCrypter.setSessionKey(okm[64:96], okm[96:128])

        # Derive a magic value for the client as well as the server. They must
        # be distinct to prevent fingerprinting (e.g. look for two identical
        # 256-bit strings).
        self.sendMagic = okm[128:160]
        self.recvMagic = okm[160:192]

        # Set the HMAC keys.
        self.sendHMAC = okm[192:224]
        self.recvHMAC = okm[224:256]

        if self.weAreServer:
            self.sendHMAC, self.recvHMAC = util.swap(self.sendHMAC, self.recvHMAC)
            self.sendCrypter, self.recvCrypter = util.swap(self.sendCrypter, self.recvCrypter)
            self.sendMagic, self.recvMagic = util.swap(self.sendMagic, self.recvMagic)

        log.debug(
            "Magic values derived from session key: send=0x%s, "
            "recv=0x%s." % (self.sendMagic.encode("hex"), self.recvMagic.encode("hex"))
        )
Пример #2
0
def bubble_sort(lst):
    last_index = len(lst) - 1
    for _ in range(0, len(lst)):
        for i in range(0, last_index):
            if lst[i] > last_index:
                swap(lst, i, last_index)
        last_index -= 1
Пример #3
0
def sort(a):
	for i in range(len(a)):
		k = i
		for j in range(i+1, len(a)):
			if a[j] < a[k]:
				k = j
		util.swap(a, i, k)
Пример #4
0
    def deriveSecrets( self, masterKey ):
        """
        Derive various session keys from the given `masterKey'.

        The argument `masterKey' is used to derive two session keys and nonces
        for AES-CTR and two HMAC keys.  The derivation is done using
        HKDF-SHA256.
        """

        assert len(masterKey) == const.MASTER_KEY_LENGTH

        log.debug("Deriving session keys from %d-byte master key." %
                  len(masterKey))

        # We need key material for two symmetric AES-CTR keys, nonces and
        # HMACs.  In total, this equals 144 bytes of key material.
        hkdf = mycrypto.HKDF_SHA256(masterKey, "", (32 * 4) + (8 * 2))
        okm = hkdf.expand()
        assert len(okm) >= ((32 * 4) + (8 * 2))

        # Set AES-CTR keys and nonces for our two AES instances.
        self.sendCrypter.setSessionKey(okm[0:32],  okm[32:40])
        self.recvCrypter.setSessionKey(okm[40:72], okm[72:80])

        # Set the keys for the two HMACs protecting our data integrity.
        self.sendHMAC = okm[80:112]
        self.recvHMAC = okm[112:144]

        if self.weAreServer:
            self.sendHMAC, self.recvHMAC = util.swap(self.sendHMAC,
                                                     self.recvHMAC)
            self.sendCrypter, self.recvCrypter = util.swap(self.sendCrypter,
                                                           self.recvCrypter)
Пример #5
0
def evaluate(inp, client, l, DBlocation):
    inp = inp.split(' ')
    status = client.status()

    if len(inp) > 1 and not str(inp[1]):
        inp.pop()

    if inp[0] == 'p' or 'play' == (inp[0]):
        try:
            if not status['state'] == 'stop':
                if len(inp) == 1:
                    util.pause(client)
                else:
                    util.play(client, int(inp[1]))
            else:
                if len(inp) == 1:
                    util.play(client, 0)
                else:
                    util.play(client, int(inp[1]))
        except:
            print('mpd error: bad song index')
    elif inp[0] == 'pause':
        util.pause(client)
    elif inp[0] == 'next' or inp[0] == 'n':
        util.next(client)
    elif inp[0] == 'previous' or inp[0] == 'ps':
        util.previous(client)
    elif inp[0] == 'stop':
        util.stop(client)
    elif inp[0] == 'pl' or inp[0] == 'playlist':
        util.print_playlist(client)
    elif inp[0] == 'update' or inp[0] == 'u':
        util.update(client)
    elif inp[0] == 'clear':
        util.clear(client)
    elif inp[0] == 'random':
        util.mpdrandom(client, inp[1])
    elif inp[0] == 'shuffle':
        util.shuffle(client)
    elif inp[0] == 'consume':
        util.consume(client, inp[1])
    elif inp[0] == 'swap':
        util.swap(client, int(inp[1]) - 1, int(inp[2]) - 1)
    elif inp[0] == 'single':
        util.single(client, inp[1])
    elif inp[0] == 'search' or inp[0] == 's':
        if '-f' in inp or '--filter' in inp:
            l = util.mpdsearch(inp[1], inp, DBlocation, True)
        else:
            l = util.mpdsearch(inp[1], inp, DBlocation, False)
    elif inp[0] == 'a' or inp[0] == 'add':
        if l:
            for line in l:
                client.add(line)
        else:
            print('You have to search first!')
    elif inp[0] == 'q' or inp[0] == 'quit':
        quit()
    return l
Пример #6
0
 def _move_win(self, direction):
     if self.cur is not None:
         try:
             index = util.clamp2(self.cur + direction.num, self.n_items())
             util.swap(self.windows, self.cur, index)
             self.cur = index
         except IndexError:
             util.debug("Bad index for moving window")
Пример #7
0
def insert_sort(array):
    n = len(array)
    for i in range(n - 1):
        j = i + 1
        while (j >= 1):
            if array[j] < array[j - 1]:
                util.swap(array, j, j - 1)
            j = j - 1
Пример #8
0
def select_sort(array):
    n = len(array)
    for i in range(n - 1):
        min = i
        for j in range(i + 1, n):
            if array[min] > array[j]:
                min = j
        util.swap(array, i, min)
Пример #9
0
 def _move_win(self, direction):
     if self.cur is not None:
         try:
             index = util.clamp2(self.cur + direction.num, self.n_items())
             util.swap(self.windows, self.cur, index)
             self.cur = index
         except IndexError:
             util.debug("Bad index for moving window")
Пример #10
0
def sort(a):
	n = len(a)
	a.insert(0, 0)
	for i in range(n//2, 0, -1):
		sink(a, i, n)
	for i in range(1, n+1):
		util.swap(a, 1, n-i+1)
		sink(a, 1, n-i)
	a.pop(0)
Пример #11
0
def sort(a):
	for i in range(len(a)):
		swapped = False
		for j in range(len(a)-1, i, -1):
			if a[j] < a[j-1]:
				util.swap(a, j, j-1)
				swapped = True
		if not swapped:
			break
Пример #12
0
def partition(lst, low, high):
	pivot = lst[high]
	wall_index = low - 1
	for i in range(low, high):
		if lst[i] < pivot:
			wall_index += 1
			swap(lst, i, wall_index)
	swap(lst, wall_index + 1, high)
	return wall_index + 1
Пример #13
0
def sort(a):
    for i in range(len(a)):
        swapped = False
        for j in range(len(a) - 1, i, -1):
            if a[j] < a[j - 1]:
                util.swap(a, j, j - 1)
                swapped = True
        if not swapped:
            break
def bubble_sort(arr):
    for i in range(len(arr) - 1):
        swapped = False
        for j in range(0, len(arr) - 1 - i):
            if arr[j] > arr[j + 1]:
                swap(arr, j, j + 1)
                swapped = True
        if not swapped:
            return arr
    return arr
Пример #15
0
    def extract_max(self):
        if self._size == 0:
            raise Exception("Extracting from empty heap")

        _result = self._items[1]
        self._size -= 1
        if self._size > 0:
            swap(self._items, 1, self._size + 1)
            self._shuffle_down(1)
        return _result
Пример #16
0
def bubble_sort(arr):
	if len(arr) <= 1:
		return

	for i in range(len(arr)):
		index1 = len(arr) - 2
		index2 = len(arr) - 1
		while index1 >= i:
			if arr[index1] > arr[index2]:
				util.swap(arr, index1, index2)
			index1 -= 1
			index2 -= 1
def insertion_sort1(lst):
    #For each element in the list
    for i in range(len(lst)):
        #Start at element i
        j = i
        #Check if element j-1 is greater than j
        while j > 0 and lst[j-1] > lst[j]:
            #If so, swap them to the correct order
            swap(lst, j, j-1)
            #Go down one element and repeat
            j-=1
    return lst
Пример #18
0
def par(_a, _pivot=0):
    last = len(_a) - 1
    i = 1
    while i <= last:
        if _a[i] <= _a[i - 1]:
            swap(_a, i - 1, i)
            i += 1
        elif i != last:
            swap(_a, i, last)
            last -= 1
        else:
            break
Пример #19
0
    def _shuffle_down(self, idx):
        _item_key = self._key(self._items[idx])

        _left_idx = idx * 2
        if _left_idx > self._size:
            return
        _left_key = self._key(self._items[_left_idx])
        _right_key = self._key(None) if _left_idx + 1 > self._size else self._key(self._items[_left_idx + 1])
        if _left_key >= _right_key and _left_key > _item_key:
            swap(self._items, idx, _left_idx)
            self._shuffle_down(_left_idx)
        elif _right_key > _item_key:
            swap(self._items, idx, _left_idx + 1)
            self._shuffle_down(_left_idx + 1)
Пример #20
0
def quick_sort(array):
	if len(array) <= 1:
		return array
	else:
		pivot = array[len(array) - 1]
		wall = 0
		for i in range(len(array) - 1):
			if array[i] < pivot:
				array = util.swap(array, i, wall)
				wall += 1
		array = util.swap(array, len(array)-1, wall)
		subarray = quick_sort(array[:wall])
		subarray2 = quick_sort(array[wall+1:])
		array = subarray + [array[wall]] + subarray2
		return array
Пример #21
0
def medianSort(A, left, right):
    if left < right:
        #find media value A[me] in A[left,rigth]
        me = find_Media_Value(A,left, right)
        print("ponto médio :i %d valor : %d" %(me,A[me]))
        mid = (right + left)//2
        A[mid],A[me] = swap(A[mid],A[me])
        for i in range(left,mid):
            if A[i] > A[mid]:
                #find A[k]<= A[mid] where k > mid
                k = find_k(A, mid, right)
                print('VALOR K: IND: %d valor %d' %(k , A[k]))
                A[i],A[k] = swap(A[i],A[k])
        print(A)        
        medianSort(A,left, mid -1)
        medianSort(A,mid + 1, right )
Пример #22
0
def sink(a, i, n):
	lc = 2*i
	if lc > n:
		return
	rc = lc+1
	mc = 0
	if rc > n:
		mc = lc
	elif a[lc] > a[rc]:
		mc = lc
	else:
		mc = rc
	if a[i] >= a[mc]:
		return
	util.swap(a, i, mc)
	sink(a, mc, n)
Пример #23
0
def selection_sort(array):
    for i in range(len(array)):
        smallest = i
        for j in range(i + 1, len(array)):
            if array[smallest] > array[j]:
                smallest = j
        array = util.swap(array, i, smallest)
    return array
Пример #24
0
def _quick_sort(arr, i, j):
    if j - i <= 1:
        return arr

    pivot = arr[j - 1]
    lpointer, rpointer = i, j - 2
    while True:
        while lpointer <= rpointer and arr[lpointer] <= pivot:
            lpointer += 1
        while lpointer <= rpointer and arr[rpointer] >= pivot:
            rpointer -= 1
        if lpointer <= rpointer:
            swap(arr, lpointer, rpointer)
        else:
            break
    swap(arr, lpointer, j - 1)
    _quick_sort(arr, i, lpointer)
    _quick_sort(arr, lpointer + 1, j)
    return arr
Пример #25
0
 def maxHeapify(self,i):
     l = self.Left(i)
     r = self.Right(i)
     if l <= self.heapsize and self._heap[l] > self._heap[i]:
         largest = l;
     else:
         largest = i;
     if r <= self.heapsize and self._heap[r] > self._heap[largest]:
         largest = r;
     if largest != i:
         self._heap[i],self._heap[largest] = util.swap(self._heap[i],self._heap[largest])
         self.maxHeapify(largest)
Пример #26
0
def heapify(ar, idx, max):
    left = 2 * idx + 1
    right = 2 * idx + 2
    largest = 0
    if left < max and my_cmp(ar[left], ar[idx]) > 0:
        largest = left
    else:
        largest = idx
    if (right < max and my_cmp(ar[right], ar[largest]) > 0):
        largest = right
    if largest != idx:
        ar[idx], ar[largest] = swap(ar[idx], ar[largest])
        heapify(ar, largest, max)
Пример #27
0
    def _deriveSecrets(self, masterKey):
        """Derives session keys (AES keys, counter nonces, HMAC keys and magic
        values) from the given master secret. All key material is derived using
        HKDF-SHA256."""

        log.debug("Master key: 0x%s." % masterKey.encode('hex'))

        # We need key material for two magic values, symmetric keys, nonces and
        # HMACs. All of them are 32 bytes in size.
        hkdf = mycrypto.HKDF_SHA256(masterKey, "", 32 * 8)
        okm = hkdf.expand()

        # Set the symmetric AES keys.
        self.sendCrypter.setSessionKey(okm[0:32], okm[32:64])
        self.recvCrypter.setSessionKey(okm[64:96], okm[96:128])

        # Derive a magic value for the client as well as the server. They must
        # be distinct to prevent fingerprinting (e.g. look for two identical
        # 256-bit strings).
        self.sendMagic = okm[128:160]
        self.recvMagic = okm[160:192]

        # Set the HMAC keys.
        self.sendHMAC = okm[192:224]
        self.recvHMAC = okm[224:256]

        if self.weAreServer:
            self.sendHMAC, self.recvHMAC = util.swap(self.sendHMAC,
                                                     self.recvHMAC)
            self.sendCrypter, self.recvCrypter = util.swap(self.sendCrypter, \
                    self.recvCrypter)
            self.sendMagic, self.recvMagic = util.swap(self.sendMagic, \
                    self.recvMagic)

        log.debug("Magic values derived from session key: send=0x%s, " \
                "recv=0x%s." % (self.sendMagic.encode('hex'), \
                self.recvMagic.encode('hex')))
Пример #28
0
def _sort(a, l, n):
	if n <= 1:
		return
	util.swap(a, l, l+random.randint(0, n-1))
	k = l
	for i in range(l+1, l+n):
		if a[i] < a[l]:
			util.swap(a, ++k, i)
	util.swap(a, l, k)
	_sort(a, l, k-l)
	_sort(a, k+1, l+n-k-1)
Пример #29
0
def _sort(a, l, n):
    if n <= 1:
        return
    util.swap(a, l, l + random.randint(0, n - 1))
    k = l
    for i in range(l + 1, l + n):
        if a[i] < a[l]:
            util.swap(a, ++k, i)
    util.swap(a, l, k)
    _sort(a, l, k - l)
    _sort(a, k + 1, l + n - k - 1)
Пример #30
0
def main(num, file_name):
    count = 0
    with open(file_name, 'w') as g:
        for s in seeds[500 * num:(num + 1) * 500]:
            s = int(s)
            ### be ware of scaling, training and testing must be consistent
            g.write('%d:' % s)

            if (s in G.nodes()):
                ### predict the people using ind_model
                sub = train[train['s'] == s]
                cand = sub[sub['label'] == 0]
                cand_num = cand['n']
                cand_arr = cand[features].values
                #cand_scale = scaler.transform(cand[features])
                rank = []
                for i in range(30):
                    rank.append([-100, -1])
                for c in range(len(cand)):
                    score = model.predict_proba(cand_arr[c])[:, 1][0]
                    n = cand_num[c + cand_num.index[0]]
                    n = int(n)
                    if (c49[s] == 0) and (c49[n] == 0):
                        continue

                    ### insert the score
                    if score > rank[n_top - 1][0]:
                        rank[n_top - 1] = [score, n]
                        for i in range(n_top - 1, 0, -1):
                            if rank[i][0] > rank[i - 1][0]:
                                (rank[i], rank[i - 1]) = util.swap(
                                    rank[i], rank[i - 1])

                ### write the file!!!
                for i in range(len(rank)):
                    if (i == (len(rank) - 1)):
                        g.write('%d' % rank[i][1])
                    else:
                        g.write('%d,' % rank[i][1])
                g.write('\n')
            else:
                ### fill the content of fill file
                g.write(fill[s])
            if (count % 10) == 0:
                print count
            count += 1
def insertion(to_sort):
    """
    Perform insertion sort.

    Args:
        to_sort (list):     list to sort.

    Returns:
        list
    """

    for i in xrange(1, len(to_sort)):
        j = i
        while j > 0 and to_sort[j - 1] > to_sort[j]:
            to_sort = swap(to_sort, j, j - 1)
            j -= 1

    return to_sort
Пример #32
0
def bubble_sort(to_sort):
    """
    Implement Bubble Sort.

    Args:
        to_sort (list):     List to sort.
    """

    list_length = len(to_sort) - 1
    for i in xrange(0, len(to_sort), 1):
        for j in xrange(0, len(to_sort) - i, 1):
            if j + 1 > list_length:
                break

            if to_sort[j] > to_sort[j + 1]:
                to_sort = swap(to_sort, j, j + 1)

    return to_sort
Пример #33
0
def selection(to_sort):
    """
    Perform selection sort.

    Args:
        to_sort (list):     List to Sort,
    """

    list_length = len(to_sort)
    for i in xrange(0, list_length):
        min_index = i
        for j in xrange(i, list_length):
            if to_sort[j] < to_sort[min_index]:
                min_index = j

        if min_index != i:
            to_sort = swap(to_sort, i, min_index)

    return to_sort
Пример #34
0
def _sort(a, l, n):
	if n <= 1:
		return
	util.swap(a, l+n-1, l+random.randint(0, n-1))
	i = l
	k = l
	p = l+n
	while i < p:
		if a[i] < a[l+n-1]:
			util.swap(a, i, k)
			i += 1
			k += 1
		elif a[i] == a[l+n-1]:
			p -= 1
			util.swap(a, i, p)
		else:
			i += 1
	m = min(p-k, l+n-p+1)
	for i in range(0, m-1):
		util.swap(a, k+i, l+n-m+1+i)
	_sort(a, l, k-l)
	_sort(a, k+1, l+n-k-1)
Пример #35
0
def _sort(a, l, n):
    if n <= 1:
        return
    util.swap(a, l + n - 1, l + random.randint(0, n - 1))
    i = l
    k = l
    p = l + n
    while i < p:
        if a[i] < a[l + n - 1]:
            util.swap(a, i, k)
            i += 1
            k += 1
        elif a[i] == a[l + n - 1]:
            p -= 1
            util.swap(a, i, p)
        else:
            i += 1
    m = min(p - k, l + n - p + 1)
    for i in range(0, m - 1):
        util.swap(a, k + i, l + n - m + 1 + i)
    _sort(a, l, k - l)
    _sort(a, k + 1, l + n - k - 1)
Пример #36
0
def par3(_a, _pivot = 0):
    _last = len(_a) - 1
    _i = 1
    _q = -1
    while _i <= _last:
        if _a[_i] == _a[_i - 1]:
            if _q == -1:
                _q = _i - 1
            _i += 1
        elif _a[_i] < _a[_i - 1]:
            if _q == -1:
                swap(_a, _i - 1, _i)
            else:
                swap(_a, _q, _i)
                _q += 1
            _i += 1
        elif _i != _last:
            swap(_a, _i, _last)
            _last -= 1
        else:
            break
Пример #37
0
def selection_sort(lst):
    for i in range(0, len(lst)):
        minimum_index = min_index(lst, i, len(lst))
        swap(lst, i, minimum_index)
Пример #38
0
 def right(self, blankIndex):
     pos = blankIndex - 1
     if (pos >= 0) and (pos < State.size) and (pos % State.n !=
                                               State.n - 1):
         return swap(self.seq, pos, blankIndex)
     return None
Пример #39
0
 def left(self, blankIndex):
     pos = blankIndex + 1
     if (pos >= 0) and (pos < State.size) and (pos % State.n != 0):
         return swap(self.seq, pos, blankIndex)
     return None
Пример #40
0
 def down(self, blankIndex):
     pos = blankIndex - State.n
     if (pos >= 0) and (pos < State.size):
         return swap(self.seq, pos, blankIndex)
     return None
Пример #41
0
def _insertion(a, l, n):
	for i in range(l+2, l+n):
		for k in range(i, l, -1):
			if a[k] >= a[k-1]:
				break
			util.swap(a, k, k-1)
Пример #42
0
def selection_sort(arr):
	for i in range(len(arr)):
		smallest_index = util.find_smallest_index(arr, i, len(arr))
		util.swap(arr, i, smallest_index)
Пример #43
0
def heapSort(ar, n):
    i = 0
    buildHeap(ar, n)
    for i in range(n - 1, 0, -1):
        ar[0], ar[i] = swap(ar[0], ar[i])
        heapify(ar, 0, i)
Пример #44
0
 def _shuffle_up(self, idx):
     while (idx >> 1) > 0:
         p = idx >> 1
         if self.key(self.items[p]) > self.key(self.items[idx]):
             swap(self.items, p, idx)
         idx = p
Пример #45
0
 def _shuffle_up(self, idx):
     while (idx >> 1) > 0:
         p = idx >> 1
         if self._items[p] < self._items[idx]:
             swap(self._items, p, idx)
         idx = p