Example #1
1
    def subdivide_segment(self, A, B, C):
        """ Asuming [AB] is a segment (A.seg has B and B.seg has A),
        we insert C as an intermediate link [AC],[CB].
        This also adds C to self.points .
        Returns True, if subdivision was done. 
        Returns False, if [AB] was shorter than min_subdivide.
    """
        print >> sys.stderr, "subdivide_segment A,B,C: ", A, A.att(), B, B.att(), C, C.att()
        if dist_sq(A, B) < self.min_subdivide_sq:
            print >> sys.stderr, " ---- too short, nothing done."
            # should be caught earlier!
            sys.exit(0)

        a_seg_idx = None
        for n in range(0, len(A.seg)):
            if A.seg[n] == B.id:
                a_seg_idx = n
                break

        b_seg_idx = None
        for n in range(0, len(B.seg)):
            if B.seg[n] == A.id:
                b_seg_idx = n
                break
        if b_seg_idx is None or a_seg_idx is None:
            raise ValueError("A,B not linked???")
        C.sub = True
        C.id = len(self.points)
        self.points.append(C)
        A.seg[a_seg_idx] = C.id
        B.seg[b_seg_idx] = C.id
        C.seg = [A.id, B.id]
        return True
Example #2
1
def random_test():
    rand_periods = np.zeros(1000)
    periods = np.zeros(1000)
    for i in range(1000):
        rand_periods[i] = np.random.uniform(low=0.0, high=2.0)
        periods[i] = 10 ** rand_periods[i]

    true_periods = np.zeros(1000)
    for i in range(1000):
        data = np.genfromtxt("/Users/angusr/angusr/ACF/star_spot_sim/tests/sim_period%s.txt" % (i + 1))
        true_periods[i] = data

    p.close(4)
    p.figure(4)
    p.subplot(3, 1, 1)
    p.plot(rand_periods, "k.")
    p.subplot(3, 1, 2)
    p.plot(periods, "k.")
    p.subplot(3, 1, 3)
    p.plot(np.log10(true_periods), "k.")

    """ Plotting as close to original periods as I can"""
    p.close(10)
    p.figure(10)
    p.subplot(1, 2, 1)
    orig_periods = np.zeros(100)
    for i in range(100):
        data = np.genfromtxt("/Users/angusr/angusr/ACF/star_spot_sim/sim_period%s.txt" % (i + 1)).T
        p.axhline(np.log10(data[4]), color="k")
    p.subplot(1, 2, 2)
    for i in range(100):
        data = np.genfromtxt("/Users/angusr/angusr/ACF/star_spot_sim/grid/%sparams.txt" % (i + 1)).T
        p.axhline(np.log10(data[7]), color="k")
Example #3
1
def graph(s):
    f = open(s, "r")
    l = f.readlines()
    bases = [0] * (len(l) * 2)
    for i in range(len(l)):
        l[i] = l[i].split()
        l[i][0] = int(l[i][0])
        # bases[l[i][0]]=L[i][1]
        if len(l[i]) > 2:
            l[i][3] = int(l[i][3])
            # bases[l[i][3]]=l[i][2]

    print "L :"
    print l

    l = tri(l)
    for i in range(len(l)):
        bases[l[i][0]] = l[i][1]
        if len(l[i]) > 2:
            bases[l[i][3]] = l[i][2]

    print "L apres :"
    print l
    print "bases : "
    print bases
    print len(bases)
    return l, bases
Example #4
1
def gen_all_holds(hand):
    """
    Generate all possible choices of dice from hand to hold.

    hand: full yahtzee hand

    Returns a set of tuples, where each tuple is dice to hold
    """

    binary_mask = []
    dice = len(hand)

    # creating a binary mask
    for idx in range(2 ** dice):
        binary_mask.append(str(bin(idx))[2:].rjust(dice, "0"))

    # applying the binary mask to the hand
    all_holds = set([()])
    for mask in binary_mask:
        hold = []
        for die in range(dice):
            if mask[die] == "1":
                hold.append(hand[die])
            hold.sort()
            all_holds.add(tuple(hold))

    return all_holds
def bound_SISO_wi(w_start, w_end, vec, G, Gp, steps):

    w = np.logspace(w_start, w_end, steps)

    #    Gp_i = np.zeros((vec.shape[0], len(w), 1))
    Gp_i_max = np.zeros((len(w)))

    # Plotting the multiplicative relative uncertianty as a function of w

    # Calculate sequences to plot all perturbations
    #    for i in range(vec.shape[0]):
    #        Gp_i = [(Gp(w_i * 1j, vec, i) - G(w_i * 1j)) / (G(w_i * 1j))
    #                for w_i in w]
    #        plt.loglog(w, np.abs(Gp_i), 'b+')
    #        plt.ylabel('Deviation due to uncertainty')
    #        plt.xlabel('Frequency (rad/min)')
    #
    # Calculate the vales by frequency and store the highest
    # value at each frequency
    # Plotting only the maximum value evaluated at each frequency

    for k in range(len(w)):
        w_i = w[k]
        Gp_i = [(Gp(w_i * 1j, vec, i) - G(w_i * 1j)) / (G(w_i * 1j)) for i in range(vec.shape[0])]
        Gp_i_max[k] = np.max(np.abs(Gp_i))

    #    plt.loglog(w, Gp_i_max, 'b+')
    return Gp_i_max
 def clip_warning(self):
     for row_index in range(CLIP_GRID_Y):
         row = self._parent._button_rows[row_index]
         for button_index in range(CLIP_GRID_X):
             button = row[button_index]
             # Passing True to send_value forces it to happen even when the button in question is MIDI mapped
             button.send_value(LED_RED, True)
Example #7
1
   def delete(cls, client, resource):
       """ Use this API to delete capolicy.
	"""
       try:
           if type(resource) is not list:
               deleteresource = capolicy()
               if type(resource) != type(deleteresource):
                   deleteresource.name = resource
               else:
                   deleteresource.name = resource.name
               return deleteresource.delete_resource(client)
           else:
               if type(resource[0]) != cls:
                   if resource and len(resource) > 0:
                       deleteresources = [capolicy() for _ in range(len(resource))]
                       for i in range(len(resource)):
                           deleteresources[i].name = resource[i]
               else:
                   if resource and len(resource) > 0:
                       deleteresources = [capolicy() for _ in range(len(resource))]
                       for i in range(len(resource)):
                           deleteresources[i].name = resource[i].name
               result = cls.delete_bulk_request(client, deleteresources)
           return result
       except Exception as e:
           raise e
Example #8
1
File: htm.py Project: kikoval/pyHTM
    def create_network(self, params):
        """Create network based on the provided parameters.

        Args:
            params: list of dicts sorted starting from the bottom level
        """
        if params is None:
            raise ValueError("Parameter 'params' should not be empty.")

        if self.verbose:
            print("Creating network...")

        for level_no in range(len(params)):

            if level_no == 0:
                # assuming rectangular arrangement of nodes
                if self.is_image_sensor:
                    self.patch_size = [
                        int(self.sensor.width / params[0]["size"][0]),
                        int(self.sensor.height / params[0]["size"][1]),
                    ]
                    if self.verbose:
                        print("Patch size is set to %s." % self.patch_size)
                prev_level_size = params[0]["size"]
            else:
                prev_level_size = params[level_no - 1]["size"]

            level = HTMLevel(level_no, params=params[level_no], debug=self.debug, previous_level_size=prev_level_size)
            self.add_level(level)

        for level_no in range(len(self.levels) - 1):
            self.levels[level_no].above_links = self.levels[level_no + 1].links

        if self.verbose:
            print("=" * 40)
Example #9
1
def singleBasis6():
    f = plt.figure()
    sb = f.add_subplot(111)
    sb.set_xticklabels([i for i in range(1, len(gridpoints) + 1)])
    # sb.set_yticklabels([])
    plt.axis([start, end, -1, 1])
    plt.xticks([(1 / 8.0) * g for g in gridpoints])

    # function
    # plt.plot(xval, yval, color="red")

    # basis fun
    ys_a = []
    for g in gridpoints:
        point = (1 / 8.0) * g
        alpha = fun(point)
        ys_a.append([alpha * hatfun(x, 3, g) for x in xval])

    # sum
    ys_sum = [0 for i in ys_a[0]]
    for ys_i in ys_a:
        for i in range(len(ys_i)):
            ys_sum[i] += ys_i[i]
    plt.plot(xval, ys_sum, color="blue", linewidth=2)

    plt.savefig(savedir + "singlebasis_6.png", bbox_inches="tight")
    plt.show()
Example #10
1
 def submitMissingTasks(stage):
     myPending = pendingTasks.setdefault(stage, set())
     tasks = []
     have_prefer = True
     if stage == finalStage:
         for i in range(numOutputParts):
             if not finished[i]:
                 part = outputParts[i]
                 if have_prefer:
                     locs = self.getPreferredLocs(finalRdd, part)
                     if not locs:
                         have_prefer = False
                 else:
                     locs = []
                 tasks.append(ResultTask(finalStage.id, finalRdd, func, part, locs, i))
     else:
         for p in range(stage.numPartitions):
             if not stage.outputLocs[p]:
                 if have_prefer:
                     locs = self.getPreferredLocs(stage.rdd, p)
                     if not locs:
                         have_prefer = False
                 else:
                     locs = []
                 tasks.append(ShuffleMapTask(stage.id, stage.rdd, stage.shuffleDep, p, locs))
     logger.debug("add to pending %s tasks", len(tasks))
     myPending |= set(t.id for t in tasks)
     self.submitTasks(tasks)
def evolve(
    pc, popsize, rankfunction, maxgen=500, mutationrate=0.1, breedingrate=0.4, pexp=0.7, pnew=0.05, previouswinner=0
):
    def selectindex():
        return int(log(random()) / log(pexp))

    population = [makerandomtree(pc) for i in range(popsize)]
    if previouswinner != 0:
        population.pop()
        population.append(previouswinner)

    for i in range(maxgen):
        scores = rankfunction(population)
        print scores[0][0]
        if scores[0][0] == 0:
            break

        newpop = [scores[0][1], scores[1][1]]

        while len(newpop) < popsize:
            if random() > pnew:
                newpop.append(
                    mutate(
                        crossover(scores[selectindex()][1], scores[selectindex()][1], probswap=breedingrate),
                        pc,
                        probchange=mutationrate,
                    )
                )
            else:
                newpop.append(makerandomtree(pc))

        population = newpop
    scores[0][1].display()
    return scores[0][1]
Example #12
0
   def unset(cls, client, resource, args):
       """ Use this API to unset the properties of capolicy resource.
	Properties that need to be unset are specified in args array.
	"""
       try:
           if type(resource) is not list:
               unsetresource = capolicy()
               if type(resource) != type(unsetresource):
                   unsetresource.name = resource
               else:
                   unsetresource.name = resource.name
               return unsetresource.unset_resource(client, args)
           else:
               if type(resource[0]) != cls:
                   if resource and len(resource) > 0:
                       unsetresources = [capolicy() for _ in range(len(resource))]
                       for i in range(len(resource)):
                           unsetresources[i].name = resource[i]
               else:
                   if resource and len(resource) > 0:
                       unsetresources = [capolicy() for _ in range(len(resource))]
                       for i in range(len(resource)):
                           unsetresources[i].name = resource[i].name
               result = cls.unset_bulk_request(client, unsetresources, args)
           return result
       except Exception as e:
           raise e
Example #13
0
   def update(cls, client, resource):
       """ Use this API to update capolicy.
	"""
       try:
           if type(resource) is not list:
               updateresource = capolicy()
               updateresource.name = resource.name
               updateresource.rule = resource.rule
               updateresource.action = resource.action
               updateresource.comment = resource.comment
               updateresource.logaction = resource.logaction
               updateresource.undefaction = resource.undefaction
               return updateresource.update_resource(client)
           else:
               if resource and len(resource) > 0:
                   updateresources = [capolicy() for _ in range(len(resource))]
                   for i in range(len(resource)):
                       updateresources[i].name = resource[i].name
                       updateresources[i].rule = resource[i].rule
                       updateresources[i].action = resource[i].action
                       updateresources[i].comment = resource[i].comment
                       updateresources[i].logaction = resource[i].logaction
                       updateresources[i].undefaction = resource[i].undefaction
               result = cls.update_bulk_request(client, updateresources)
           return result
       except Exception as e:
           raise e
Example #14
0
   def add(cls, client, resource):
       """ Use this API to add capolicy.
	"""
       try:
           if type(resource) is not list:
               addresource = capolicy()
               addresource.name = resource.name
               addresource.rule = resource.rule
               addresource.action = resource.action
               addresource.undefaction = resource.undefaction
               addresource.comment = resource.comment
               addresource.logaction = resource.logaction
               return addresource.add_resource(client)
           else:
               if resource and len(resource) > 0:
                   addresources = [capolicy() for _ in range(len(resource))]
                   for i in range(len(resource)):
                       addresources[i].name = resource[i].name
                       addresources[i].rule = resource[i].rule
                       addresources[i].action = resource[i].action
                       addresources[i].undefaction = resource[i].undefaction
                       addresources[i].comment = resource[i].comment
                       addresources[i].logaction = resource[i].logaction
               result = cls.add_bulk_request(client, addresources)
           return result
       except Exception as e:
           raise e
def combine_cycles(lists_of_cycles):
    """
	Takes in a list of lists of all cycles and prints a 
	cycle that indicates any instance when there was a hit
	amongst the cycles.
	"""

    combined_cycle = ["-" for i in range(len(lists_of_cycles[0]))]

    for cycle in lists_of_cycles:

        for i in range(len(cycle)):

            if cycle[i] == "|":

                combined_cycle[i] = "|"

            elif cycle[i] == "X":

                combined_cycle[i] = "X"

    combined_c = ""

    for i in combined_cycle:

        combined_c += i

    print "Combined Cycle:"

    print combined_c

    return None
Example #16
0
def fill_wave(pulses_buffer, direction):
    for i in range(0, 4):
        pulses_buffer.append(pigpio.pulse(1 << GPIO, 0, 1500))
        pulses_buffer.append(pigpio.pulse(0, 1 << GPIO, 500))
    for i in range(0, signals[direction]):
        pulses_buffer.append(pigpio.pulse(1 << GPIO, 0, 500))
        pulses_buffer.append(pigpio.pulse(0, 1 << GPIO, 500))
Example #17
0
    def update_tank_table(self):
        # ustalenie krotek agregacji
        aggregate_count = 5
        if self.ui.radioButton_5.isChecked():
            aggregate_count = 5
        elif self.ui.radioButton_15.isChecked():
            aggregate_count = 15
        elif self.ui.radioButton_30.isChecked():
            aggregate_count = 30
        elif self.ui.radioButton_60.isChecked():
            aggregate_count = 60

        # aktualizacja tabeli gui
        self.ui.tableWidget_tank_aggregate.setColumnCount(4)
        self.ui.tableWidget_tank_aggregate.setHorizontalHeaderLabels(
            ["datetime", "avr(volume_brutto)", "avr(volume_netto)", "avr(temp)"]
        )
        self.ui.tableWidget_tank_aggregate.setRowCount(len(self.aggregate_dict[aggregate_count]))
        for i in range(len(self.aggregate_dict[aggregate_count])):
            for j in range(len(self.aggregate_dict[aggregate_count][i])):
                self.ui.tableWidget_tank_aggregate.setItem(
                    i, j, QTableWidgetItem(str(self.aggregate_dict[aggregate_count][i][j]))
                )

        # autoprzewijanie tabel
        if self.ui.checkBox_autoscroll.isChecked():
            self.ui.tableWidget_tank_aggregate.scrollToBottom()
Example #18
0
    def parse(self, data):
        self.shares = {}
        pos = 0

        self.user, pos = self.unpack_pos_string(data, pos)
        dirs, pos = self.unpack_pos_uint(data, pos)
        for i in range(dirs):
            dir, pos = self.unpack_pos_string(data, pos)

            self.shares[dir] = {}

            files, pos = self.unpack_pos_uint(data, pos)

            for j in range(files):
                filename, pos = self.unpack_pos_string(data, pos)
                size, pos = self.unpack_pos_off(data, pos)
                extension, pos = self.unpack_pos_string(data, pos)
                attrs, pos = self.unpack_pos_uint(data, pos)
                attributes = []
                for k in range(attrs):
                    a, pos = self.unpack_pos_uint(data, pos)
                    attributes.append(a)

                self.shares[dir][filename] = [size, extension, attributes]
        return self
Example #19
0
def copyInto(smallPicture, bigPicture, startX, startY):
    # like copyInto(butterfly, jungle, 20,20)
    if not smallPicture.__class__ == Picture:
        print "copyInto(smallPicture, bigPicture, startX, startY): smallPicture must be a picture"
        raise ValueError
    if not bigPicture.__class__ == Picture:
        print "copyInto(smallPicture, bigPicture, startX, startY): bigPicture must be a picture"
        raise ValueError
    if (startX < Picture._PictureIndexOffset) or (startX > getWidth(bigPicture) - 1 + Picture._PictureIndexOffset):
        print "copyInto(smallPicture, bigPicture, startX, startY): startX must be within the bigPicture"
        raise ValueError
    if (startY < Picture._PictureIndexOffset) or (startY > getHeight(bigPicture) - 1 + Picture._PictureIndexOffset):
        print "copyInto(smallPicture, bigPicture, startX, startY): startY must be within the bigPicture"
        raise ValueError
    if (startX + getWidth(smallPicture) - 1) > (getWidth(bigPicture) - 1 + Picture._PictureIndexOffset) or (
        startY + getHeight(smallPicture) - 1
    ) > (getHeight(bigPicture) - 1 + Picture._PictureIndexOffset):
        print "copyInto(smallPicture, bigPicture, startX, startY): smallPicture won't fit into bigPicture"
        raise ValueError

    xOffset = startX - Picture._PictureIndexOffset
    yOffset = startY - Picture._PictureIndexOffset

    for x in range(0, getWidth(smallPicture)):
        for y in range(0, getHeight(smallPicture)):
            bigPicture.setBasicPixel(x + xOffset, y + yOffset, smallPicture.getBasicPixel(x, y))

    return bigPicture
Example #20
0
    def parse(self, data):
        self.users = {}
        pos = 0
        self.room, pos = self.unpack_pos_string(data, pos)
        n, pos = self.unpack_pos_uint(data, pos)
        for i in range(n):
            user, pos = self.unpack_pos_string(data, pos)
            status, pos = self.unpack_pos_uint(data, pos)
            avgspeed, pos = self.unpack_pos_uint(data, pos)
            downloadnum, pos = self.unpack_pos_uint(data, pos)
            files, pos = self.unpack_pos_uint(data, pos)
            dirs, pos = self.unpack_pos_uint(data, pos)

            free = ord(data[pos])
            pos += 1
            self.users[user] = [status, avgspeed, downloadnum, files, dirs, free]
        self.private = False
        self.owner = ""
        self.operators = []
        if len(data) > 0:
            self.private = True
            self.owner, pos = self.unpack_pos_string(data, pos)
            no, pos = self.unpack_pos_uint(data, pos)
            for i in range(no):
                operator, pos = self.unpack_pos_string(data, pos)
                self.operators.append(operator)
        return self
def tournament(pl, game):
    """
	Stages a tournament in which each player competes with every other player.

	Takes a list of players, and the desired game to be played, and returns a
	zipped list of each player and their score.
	
	'game' syntax: 
		Parameters: List of players
		return: 0 if pl[0] wins
				1 if pl[1] wins
				-1 if tie
	"""
    losses = [0 for p in pl]
    for i in range(len(pl)):
        for j in range(len(pl)):
            if i == j:
                continue
            winner = game([pl[i], pl[j]])

            if winner == 0:
                losses[j] += 2
            elif winner == 1:
                losses[i] += 2
            elif winner == -1:
                losses[i] += 1
                losses[j] += 1
                pass
    z = zip(losses, pl)
    z.sort()
    return z
Example #22
0
def computeE():
    l = []
    for i in range(N):
        for j in range(i + 1, N):
            l.append((i, j))
    pool = mp.Pool(2)
    pool.map(E_computer, l)
    def encode(self, number):
        result = ""

        if len(number) < 12 or len(number) > 13 or not number.isdigit():
            sys.stderr.write("Can not encode '" + number + "' into EAN13 Barcode, Size must be 12 numbers only\n")
            return

        if len(number) == 12:
            number = number + self.getChecksum(number)
        else:
            if not self.varifyChecksum(number):
                sys.stderr.write(
                    "EAN13 Checksum not correct for this barcode, omit last charicter to generate new checksum.\n"
                )
                return

        result = result + guardBar
        family = mapFaimly[int(number[0])]

        i = 0
        for i in range(0, 6):
            mapLeft = mapLeftFaimly[int(family[i])]
            result += mapLeft[int(number[i + 1])]

        result += centerBar

        for i in range(7, 13):
            result += mapRight[int(number[i])]

        result = result + guardBar

        self.label = number[0] + "    " + number[1:7] + "    " + number[7:] + "       "
        self.inclabel = self.label
        return result
Example #24
0
def dofilehorz(filename):
    print filename
    out = open(filename.replace(".csv", ".trunc.csv"), "w")
    outcsv = UnicodeWriter(out)
    # do preparse
    with open(filename, "r") as f:
        for i, row in enumerate(UnicodeReader(f)):
            if i == 0:
                header = row
                headers = Counter(row)
                continue
            for c, cell in enumerate(row):
                size = (len(cell) / MAX_SIZE) + 1  # integer division is horrid.
                headers[header[c]] = max(headers[header[c]], size)
    # pass 2
    with open(filename, "r") as f:
        for i, row in enumerate(UnicodeReader(f)):
            if i == 0:
                newrow = []
                for c, cell in enumerate(header):
                    newrow.extend(["%s_%d" % (cell, r) for r in range(headers[cell])])
                outcsv.writerow(newrow)
                continue
            # populate dictionary
            d = OrderedDict()
            for c, cell in enumerate(row):
                for r in range(headers[header[c]]):
                    d["%s_%d" % (header[c], r)] = cell[MAX_SIZE * r : MAX_SIZE * (r + 1)]
            outcsv.writerow(d.values())
    out.close()
Example #25
0
def bound_MIMO_wi(w_start, w_end, vec, G, Gp, steps):

    w = np.logspace(w_start, w_end, steps)

    #    Gp_i = np.zeros((vec.shape[0], len(w), 1))
    Gp_i_max = np.zeros((len(w)))

    # Plotting the multiplicative output relative uncertianty
    # as a function of w

    # Calculate the vales by frequency and store the highest
    # value at each frequency
    # Plotting only the maximum value evaluated at each frequency

    for k in range(len(w)):
        w_i = w[k]
        # Calculate all perturbations at a specific frequency
        Gp_i = [
            np.linalg.svd((Gp(w_i * 1j, vec, i) - G(w_i * 1j)) * np.linalg.pinv(G(w_i * 1j)), compute_uv=False)[0]
            for i in range(vec.shape[0])
        ]
        # Calculate the maximum of the maximum singular values
        # at each frequency
        Gp_i_max[k] = np.max(Gp_i)
    #    plt.loglog(w, Gp_i_max, 'b+')
    return Gp_i_max
Example #26
0
def check_dims_values(python_obj, h2o_frame, rows, cols):
    """
    Check that the dimensions and values of the python object and H2OFrame are equivalent. Assumes that the python object
    conforms to the rules specified in the h2o frame documentation.

    :param python_obj: a (nested) list, tuple, dictionary, numpy.ndarray, ,or pandas.DataFrame
    :param h2o_frame: an H2OFrame
    :param rows: number of rows
    :param cols: number of columns
    :return: None
    """
    h2o_rows, h2o_cols = h2o_frame.dim
    assert (
        h2o_rows == rows and h2o_cols == cols
    ), "failed dim check! h2o_rows:{0} rows:{1} h2o_cols:{2} cols:{3}" "".format(h2o_rows, rows, h2o_cols, cols)
    if isinstance(python_obj, (list, tuple)):
        for c in range(cols):
            for r in range(rows):
                pval = python_obj[c][r] if cols > 1 else python_obj[r]
                hval = h2o_frame[r, c]
                assert pval == hval, (
                    "expected H2OFrame to have the same values as the python object for row {0} and column "
                    "{1}, but h2o got {2} and python got {3}.".format(r, c, hval, pval)
                )
    elif isinstance(python_obj, dict):
        for r in range(rows):
            for k in python_obj.keys():
                pval = python_obj[k][r] if hasattr(python_obj[k], "__iter__") else python_obj[k]
                hval = h2o_frame[r, k]
                assert pval == hval, (
                    "expected H2OFrame to have the same values as the python object for row {0} and column "
                    "{1}, but h2o got {2} and python got {3}.".format(r, k, hval, pval)
                )
Example #27
0
    def X_test(self):
        class X(Structure):
            _fields_ = [("p", POINTER(c_char_p))]

        x = X()
        i = c_char_p("abc def")
        from sys import getrefcount as grc

        print "2?", grc(i)
        x.p = pointer(i)
        print "3?", grc(i)
        for i in range(320):
            c_int(99)
            x.p[0]

        print x.p[0]
        import gc

        gc.collect()
        for i in range(320):
            c_int(99)
            x.p[0]

        print x.p[0]
        print x.p.contents
        x.p[0] = "spam spam"
        print "+" * 42
        print x._objects
def f(n):
    dict = {}
    for i in range(n):
        s = int("".join(raw_input().split()))
        if s in dict:
            dict[s] += 1
        else:
            dict[s] = 1
    k = raw_input()
    # print dict
    l = dict.keys()
    l.sort()
    # print l
    for i in l:
        temp = str(i)
        count = 26 - len(temp)
        for j in range(count):
            temp = "0" + temp
        temp = list(temp)
        temp.insert(2, " ")
        temp.insert(11, " ")
        temp.insert(16, " ")
        temp.insert(21, " ")
        temp.insert(26, " ")
        temp = "".join(temp)
        temp = temp + " " + str(dict[i])
        print temp
Example #29
0
def make_video(events, t0=0.0, t1=None, dt_frame=0.01, tau=0.01):
    if t1 is None:
        t1 = events["t"].max()

    ts = events["t"]
    dt = 1e-3
    nt = int((t1 - t0) / dt) + 1
    # nt = min(nt, 1000)  # cap at 1000 for now

    image = np.zeros((128, 128))
    images = np.zeros((nt, 128, 128))

    for i in range(nt):
        # --- decay image
        image *= np.exp(-dt / tau) if tau > 0 else 0
        # image *= 0

        # --- add events
        ti = t0 + i * dt
        add_to_image(image, events[close(ts, ti)])

        images[i] = image

    # --- average in frames
    nt_frame = int(dt_frame / dt)
    nt_video = int(nt / nt_frame)

    video = np.zeros((nt_video, 128, 128))
    for i in range(nt_video):
        slicei = slice(i * nt_frame, (i + 1) * nt_frame)
        video[i] = np.sum(images[slicei], axis=0)

    return video
Example #30
0
    def unlink_segment(s, A, B):
        """Remove the segment [AB] from the s.points list. 
       The segment is removed, by replacing its slot with a negative number.
       The endpoints are marked with seen=True so that in case of a sharp turn, 
       we know we can no longer start there.
       If now A or B are without other active segments, A and/or B are dropped
       entirely from s.points .

       process_simple_barrier() and process_pyramids_barrier() ignore points and segments 
       that have already been done. This asserts progress in the algorithms.
    """
        A.seen = True
        B.seen = True
        iA = A.id
        iB = B.id
        a_seg_todo = False
        b_seg_todo = False
        for iS in range(len(A.seg)):
            if A.seg[iS] == iB:
                A.seg[iS] = -iB or -sys.maxsize
            if A.seg[iS] >= 0:
                a_seg_todo = True
        for iS in range(len(B.seg)):
            if B.seg[iS] == iA:
                B.seg[iS] = -iA or -sys.maxsize
            if B.seg[iS] >= 0:
                b_seg_todo = True

        # CAUTION: is this really helpful?:
        ## it prevents points from a slice to go into process_simple_barrier()'s segment list,
        ## but it also hides information....
        if not a_seg_todo:
            s.points[iA] = None
        if not b_seg_todo:
            s.points[iB] = None