Example #1
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 #2
1
    def __init__(self, verb, uri, regex, value, unit):
        """Initialize a new `Limit`.

        @param verb: HTTP verb (POST, PUT, etc.)
        @param uri: Human-readable URI
        @param regex: Regular expression format for this limit
        @param value: Integer number of requests which can be made
        @param unit: Unit of measure for the value parameter
        """
        self.verb = verb
        self.uri = uri
        self.regex = regex
        self.value = int(value)
        self.unit = unit
        self.unit_string = self.display_unit().lower()
        self.remaining = int(value)

        if value <= 0:
            raise ValueError("Limit value must be > 0")

        self.last_request = None
        self.next_request = None

        self.water_level = 0
        self.capacity = self.unit
        self.request_value = float(self.capacity) / float(self.value)
        msg = _("Only %(value)s %(verb)s request(s) can be " "made to %(uri)s every %(unit_string)s.") % {
            "value": self.value,
            "verb": self.verb,
            "uri": self.uri,
            "unit_string": self.unit_string,
        }
        self.error_message = msg
        def useImageMagick(screenshot):
            """ Using ImageMagick's utility 'identify'. Decide whether the screen shot is worth using.
            >>> useImageMagick('identify screenshot.jpg')
            >>> Example returned information "rose.jpg JPEG 640x480 DirectClass 87kb 0.050u 0:01"
            >>> u'' if the screenshot quality is too low 
            >>> screenshot if the quality is good enough to use
            """
            if not self.imagemagick:  # If imagemagick is not installed do not bother checking
                return u""

            width_height = re.compile(u"""^(.+?)[ ]\[?([0-9]+)x([0-9]+)[^\\/]*$""", re.UNICODE)
            p = subprocess.Popen(
                u'identify "%s"' % (screenshot),
                shell=True,
                bufsize=4096,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                close_fds=True,
            )

            response = p.stdout.readline()
            if response:
                match = width_height.match(response)
                if match:
                    dummy, width, height = match.groups()
                    width, height = int(width), int(height)
                    if width >= 320:
                        return screenshot
                return u""
            else:
                return u""
            return screenshot
Example #4
1
def processStudentsFile(fileIn):
    student = {}  # local dictionary.
    fileIn.readline()
    while True:  # read data and place into the data structure routine.
        line = fileIn.readline()
        if line == "":  # finish flag.
            break
        else:
            split = string.split(line[:-1], ",")  # data handling sequence.
            course = split[0]
            IDNumber = split[1]
            courseWork = int(split[2])
            exam = int(split[3])
            total = int(split[4])

            student[IDNumber] = {
                "course": course,
                "IDNumber": IDNumber,
                "coursework": courseWork,
                "exam": exam,
                "total": total,
            }

            if debug == 1:
                print student[IDNumber]
    return student
Example #5
1
def main():

    logger = get_root_logger()
    get_header(logger, "LOADING PROJECTIONS")

    client = APIClient()

    # grab dataframe shape from a trial run
    data = client.get_data("weekly-projections", "json", "QB")
    test_df = json_normalize(data["Projections"])

    # get DF structure from columns in test_df
    cols = test_df.columns
    df = DataFrame(columns=cols)

    # grab current week
    current_week = test_df.week.values[0]

    # loop through all weeks up to current week
    for wk in [str(x) for x in range(int(current_week))]:
        logger.info("Processing projections for week {0}".format(int(wk) + 1))
        # loop through all positions
        for pos in ["QB", "RB", "WR", "TE", "K", "DEF"]:
            tmp_data = client.get_data("weekly-projections", "json", pos, wk)
            tmp_df = json_normalize(tmp_data["Projections"])
            df = df.append(tmp_df)

    # import this df directly to PG DB
    conn = DBClient()
    conn.load(df, "projections", schema="raw", if_exists="replace")
Example #6
1
def do_padding(img, padding):
    if not padding:
        return img
    try:
        padding = float(padding)*2.0
        if padding > .9:
            padding = .9
        if padding <= 0.0:
            return img
    except ValueError:
        return

    iw, ih = img.size

    img.thumbnail(
        (
            int( round( float(img.size[0]) * (1.0 - padding) ) ),
            int( round( float(img.size[1]) * (1.0 - padding) ) )
        ),
        pil.ANTIALIAS
        )

    img = do_fill(img, "ffffff00", iw, ih)

    return img
Example #7
1
    def pct(self, so_far, total=None):
        percentage = str(int(self.percentage * 100)) + "%"
        if self.num_files_left > 1:
            message = _("Uploading %(number)d files to %(service)s") % {
                "number": self.num_files_left,
                "service": '"' + service["name"] + '"',
            }
            title = _("%(percentage)s of %(number)d files - Uploading to %(service)s") % {
                "percentage": percentage,
                "number": self.num_files_left,
                "service": '"' + service["name"] + '"',
            }
        else:
            message = _("Uploading 1 file to %(service)s") % {"service": '"' + service["name"] + '"'}
            title = _("%(percentage)s of 1 file - Uploading to %(service)s") % {
                "percentage": percentage,
                "service": '"' + service["name"] + '"',
            }

        self.percentage = float(self.size_so_far) / float(self.total_size)
        Gdk.threads_enter()
        try:
            self.progressbar.set_fraction(self.percentage)
            self.progressbar.set_text(str(int(self.percentage * 100)) + "%")
            self.builder.get_object("upload_label").set_text(message)
            self.builder.get_object("main_window").set_title(title)
        finally:
            Gdk.threads_leave()
        pass
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 __init__(
     self,
     WorkerFactory=Worker,
     threads=1,
     max_items=0,
     name="<AnonymouseWorkerPool>",
     target=None,
     generator=None,
     batch_size=0,
     batch_timeout=1,
     batch_target=None,
     **kwargs
 ):
     self.name = name
     self.queue = Queue(max_items)
     self.threads = []
     self.workers = []
     self.worker_factory = WorkerFactory
     self.batch_size = int(batch_size)
     self.batch_timeout = float(batch_timeout)
     self.thread_num = int(threads)
     if self.thread_num < 1:
         self.thread_num = 1
     self.isopen = False
     self.next = None
     self.prev = None
     self.target = target
     self.generator = generator
     self.batch_target = batch_target
     self.data = None
     self.open_time = 0
     self.statistics_data = defaultdict(lambda: 0)
     self.barrier = Barrier(self.thread_num)
     self.kwargs = kwargs
Example #10
1
    def test_resize_server_revert(self):
        # The server's RAM and disk space should return to its original
        # values after a resize is reverted

        previous_flavor_ref, new_flavor_ref = self._detect_server_image_flavor(self.server_id)

        resp, server = self.client.resize(self.server_id, new_flavor_ref)
        self.assertEqual(202, resp.status)
        self.client.wait_for_server_status(self.server_id, "VERIFY_RESIZE")

        self.client.revert_resize(self.server_id)
        self.client.wait_for_server_status(self.server_id, "ACTIVE")

        # Need to poll for the id change until lp#924371 is fixed
        resp, server = self.client.get_server(self.server_id)
        start = int(time.time())

        while server["flavor"]["id"] != previous_flavor_ref:
            time.sleep(self.build_interval)
            resp, server = self.client.get_server(self.server_id)

            if int(time.time()) - start >= self.build_timeout:
                message = (
                    "Server %s failed to revert resize within the \
                required time (%s s)."
                    % (self.server_id, self.build_timeout)
                )
                raise exceptions.TimeoutException(message)
Example #11
1
 def draw_scanline_indicator(self):
     cos_ang = math.cos(self.current_angle)
     sin_ang = math.sin(self.current_angle)
     r = 2 * self.radius
     x = int(self.center_x + r * sin_ang)
     y = self.height - int(self.center_y + r * cos_ang) - 1
     self.radar_canvas.coords(self.scanline_indicator, self.center_x, self.center_y, x, y)
    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 #13
0
def create_pool(event_id):
    """The method that creates a pool of contestants."""
    # Use a double ended queue structured list for the pool
    pool_deque = deque([])

    # Get the list of all attendees for an event; only -> "checked_in": true
    eventbrite = Eventbrite(EVENTBRITE_OAUTH_TOKEN)
    this_event = eventbrite.get("/events/" + event_id + "/attendees")

    # Add all attendee IDs to a deque as many times as the ID
    # has chances to win

    for each_attendee in this_event["attendees"]:
        pool_deque.append(each_attendee["id"])

        # Match each attendee to their number entries in the database

    current_page = int(this_event["pagination"]["page_number"])
    last_page = int(this_event["pagination"]["page_count"])

    if current_page != last_page:
        while current_page <= last_page:
            this_event = eventbrite.get("/events/" + event_id + "/attendees?page=" + str(current_page + 1))

            current_page = this_event["pagination"]["page_number"]
            last_page = this_event["pagination"]["page_count"]

    return pool_deque
def convert_to_rgb(minval, maxval, val, colors):
    max_index = len(colors) - 1
    v = float(val - minval) / float(maxval - minval) * max_index
    i1, i2 = int(v), min(int(v) + 1, max_index)
    (r1, g1, b1), (r2, g2, b2) = colors[i1], colors[i2]
    f = v - i1
    return int(r1 + f * (r2 - r1)), int(g1 + f * (g2 - g1)), int(b1 + f * (b2 - b1))
Example #15
0
    def test_get_roles(self):
        header = httplib2.Http(".cache")
        url = "%sroles" % (utils.URL)
        # test for Content-Type = application/json
        resp, content = header.request(
            url, "GET", body="{}", headers={"Content-Type": "application/json", "X-Auth-Token": self.auth_token}
        )
        if int(resp["status"]) == 500:
            self.fail("Identity Fault")
        elif int(resp["status"]) == 503:
            self.fail("Service Not Available")
        self.assertEqual(200, int(resp["status"]))

        # verify content
        obj = json.loads(content)
        if not "roles" in obj:
            raise self.fail("Expecting Roles")
        roles = obj["roles"]["values"]
        if len(roles) != 1:
            self.fail("Roles not of required length.")

        role = roles[0]
        if not "id" in role:
            role_id = None
        else:
            role_id = role["id"]
        if role_id != "Admin":
            self.fail("Not the expected Role")
Example #16
0
    def __init__(self, server, path):
        self.path = path

        match = server.path_expr.match(path)
        if not match:
            raise ValueError(path)

        self.bundle = match.group("bundle")
        if self.bundle not in server.bundles:
            raise ValueError(path)

        self.resource = match.group("resource")
        resource_path = [self.resource]

        self.subject = match.group("subject")
        if self.subject:
            resource_path.append("id")

        self.tail = match.group("tail")
        if self.tail:
            resource_path.append(self.tail)

        self.format = match.group("format")
        if self.format is not None and self.format not in server.formats:
            raise ValueError(path)

        self.version = (int(match.group("major")), int(match.group("minor")))
        self.resource_path = "/".join(resource_path)
Example #17
0
 def restore(self, node):
     name = str(node.getAttribute("name"))
     if name == "":
         return
     connects = []
     other = OtherDomainInfo()
     for c in node.childNodes:
         if c.nodeType == c.ELEMENT_NODE:
             if c.nodeName == "connection":
                 attrhash = {}
                 for i in range(0, c.attributes.length):
                     attr = c.attributes.item(i)
                     attrhash[attr.nodeName] = attr.nodeValue
                     pass
                 connects.append(attrhash)
                 pass
             elif c.nodeName == "IPMB_rescan_time":
                 try:
                     other.ipmb_rescan_time = int(c.getAttribute("time"))
                 except:
                     _oi_logging.error("Error restoring IPMB rescan time" + " in a domain")
                     pass
                 pass
             elif c.nodeName == "SEL_rescan_time":
                 try:
                     other.sel_rescan_time = int(c.getAttribute("time"))
                 except:
                     _oi_logging.error("Error restoring SEL rescan time" + " in a domain")
                     pass
                 pass
             pass
         pass
     defaultDomains.append([name, connects, other])
     return
Example #18
0
 def drop(self):
     """Remove me from the list of running bot processes."""
     # drop all throttles with this process's pid, regardless of site
     self.checktime = 0
     processes = []
     try:
         f = open(self.ctrlfilename, "r")
     except IOError:
         return
     else:
         now = time.time()
         for line in f.readlines():
             try:
                 line = line.split(" ")
                 this_pid = int(line[0])
                 ptime = int(line[1].split(".")[0])
                 this_site = line[2].rstrip()
             except (IndexError, ValueError):
                 # Sometimes the file gets corrupted ignore that line
                 continue
             if now - ptime <= self.releasepid and this_pid != pid:
                 processes.append({"pid": this_pid, "time": ptime, "site": this_site})
     processes.sort(key=lambda p: p["pid"])
     try:
         f = open(self.ctrlfilename, "w")
         for p in processes:
             f.write("%(pid)s %(time)s %(site)s\n" % p)
     except IOError:
         return
     f.close()
Example #19
0
 def __repr__(self):
     return "<TwistedCheckerError type=%s line=%d indent=%d, text=%r>" % (
         self.type,
         int(self.line),
         int(self.indent),
         self.text,
     )
Example #20
0
 def cal_dimension(self, ids, context={}):
     all_vals = {}
     dbname = database.get_active_db()
     for obj in self.browse(ids):
         master_img = obj.product_id.image
         master_path = os.path.join("static/db/", dbname, "files", master_img)
         frame = int(obj.get("rotate_frame"))
         column = int(obj.get("rotate_footage"))
         row = 1
         if frame and column:
             row = frame / column
         vals = {}
         im_path = obj.image
         if im_path and frame and column:
             filename = os.path.join("static/db/", dbname, "files", im_path)
             img = Image.open(filename)
             (width, height) = img.size
             swidth = math.floor(width / column)
             sheight = math.floor(height / row)
             vals["rotate_width"] = swidth
             vals["rotate_height"] = sheight
             vals["master_image"] = master_path
             all_vals[obj.id] = vals
         else:
             print("Not enough arguments given")
     return all_vals
Example #21
0
    def test_get_roles_xml(self):
        header = httplib2.Http(".cache")
        url = "%sroles" % (utils.URL)
        # test for Content-Type = application/json
        resp, content = header.request(
            url,
            "GET",
            body="",
            headers={"Content-Type": "application/xml", "X-Auth-Token": self.auth_token, "ACCEPT": "application/xml"},
        )
        if int(resp["status"]) == 500:
            self.fail("Identity Fault")
        elif int(resp["status"]) == 503:
            self.fail("Service Not Available")
        self.assertEqual(200, int(resp["status"]))

        # Validate Returned Content
        dom = etree.Element("root")
        dom.append(etree.fromstring(content))
        roles = dom.find("{http://docs.openstack.org/identity/api/v2.0}" "roles")
        if roles == None:
            self.fail("Expecting Roles")
        roles = roles.findall("{http://docs.openstack.org/identity/api/v2.0}" "role")
        if len(roles) != 1:
            self.fail("Not the expected Role count")
        for role in roles:
            if role.get("id") != "Admin":
                self.fail("Not the expected Role")
Example #22
0
 def test_delete_roleref_using_invalid_token(self):
     header = httplib2.Http(".cache")
     utils.add_user_json(self.tenant, self.user, self.auth_token)
     resp, content = utils.create_role_ref(self.user, "Admin", self.tenant, str(self.auth_token))
     resp_val = int(resp["status"])
     self.assertEqual(201, resp_val)
     obj = json.loads(content)
     if not "roleRef" in obj:
         raise fault.BadRequestFault("Expecting RoleRef")
     roleRef = obj["roleRef"]
     if not "id" in roleRef:
         role_ref_id = None
     else:
         role_ref_id = roleRef["id"]
     if role_ref_id is None:
         raise fault.BadRequestFault("Expecting RoleRefId")
     url = "%susers/%s/roleRefs/%s" % (URL, self.user, role_ref_id)
     resp, content = header.request(
         url,
         "DELETE",
         body="",
         headers={"Content-Type": "application/json", "X-Auth-Token": str(self.invalid_token)},
     )
     resp_val = int(resp["status"])
     self.assertEqual(404, resp_val)
Example #23
0
def _dosave(request, viewName):
    profile = getProfile(request)
    # First find our View
    log.info("Saving view '%s' under profile '%s'" % (viewName, profile.user.username))
    try:
        view = profile.view_set.get(name=viewName)
    except ObjectDoesNotExist:
        view = View(profile=profile, name=viewName)
        view.save()
    # Now re-associate the view with the correct Windows
    view.window_set.all().delete()
    for windowName, encodedString in request.GET.items():
        try:
            if windowName in ("_", "commandInput"):
                continue
            paramString = urllib.unquote_plus(encodedString)
            queryParams = cgi.parse_qs(paramString)
            modelParams = {}
            for key, value in queryParams.items():  # Clean up the window params
                key = str(key)
                value = str(value[0])
                if key in ("top", "left"):
                    value = int(float(value.replace("px", "")))
                if key in ("width", "height", "interval"):
                    value = int(float(value))
                modelParams[key] = value
            if "interval" not in modelParams:
                modelParams["interval"] = None
            win = Window(view=view, name=windowName, **modelParams)
            win.save()
        except:
            log.exception("Failed to process parameters for window '%s'" % windowName)
    return stdout("Saved view %s" % viewName)
Example #24
0
 def test_get_rolerefs_xml(self):
     header = httplib2.Http(".cache")
     utils.add_user_json(self.tenant, self.user, self.auth_token)
     resp, content = utils.create_role_ref(self.user, "Admin", self.tenant, str(self.auth_token))
     url = "%susers/%s/roleRefs" % (URL, self.user)
     # test for Content-Type = application/xml
     resp, content = header.request(
         url,
         "GET",
         body="{}",
         headers={
             "Content-Type": "application/xml",
             "X-Auth-Token": str(self.auth_token),
             "ACCEPT": "application/xml",
         },
     )
     if int(resp["status"]) == 500:
         self.fail("Identity Fault")
     elif int(resp["status"]) == 503:
         self.fail("Service Not Available")
     self.assertEqual(200, int(resp["status"]))
     # verify content
     dom = etree.Element("root")
     dom.append(etree.fromstring(content))
     roles = dom.find("{http://docs.openstack.org/identity/api/v2.0}" "roleRefs")
     if roles == None:
         self.fail("Expecting Role Refs")
Example #25
0
def find_contour(img, draw=False):
    objects = []
    copy = np.zeros_like(img)  # output image
    np.copyto(copy, img)

    _, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if contours is not None and len(contours) > 0:
        num_objects = len(contours)
        # print("objects = %d" % numObjects )
        if num_objects < 1024:
            for i in range(0, len(contours)):
                moment = cv2.moments(contours[i])
                area = moment["m00"]
                if area > DEF.AREA:
                    # print("area = %d" % area)
                    object = Gauge()
                    object.area = area
                    object.x = int(moment["m10"] / area)
                    object.y = int(moment["m01"] / area)
                    object.position = i
                    objects.append(object)
                    # print len(objects)
                    # print "area is greater than .."
                    objectFound = True
                    # else: objectFound = False

    if draw:
        assert len(objects) <= len(contours), "objects: %d, contours: %d" % (len(objects), len(contours))
        while len(objects) > 0:
            this_contour = objects.pop()
            # epsilon = 0.001*cv2.arcLength(contours[this_contour.position],False)
            # contours[this_contour.position] = cv2.approxPolyDP(contours[this_contour.position],epsilon,False)
            # contours[this_contour.position] = cv2.convexHull(contours[this_contour.position], returnPoints = True)
            cv2.drawContours(img, contours, this_contour.position, DEF.WHITE, 3, 2)
    return img
Example #26
0
File: htm.py Project: kikoval/pyHTM
    def _get_train_patterns(self, level, all_patterns=True):
        """Get an image from the sensor and either extracts one pattern or all
        of them.

        Args:
            level: level number
            all_patterns: A boolean indicating whether all patterns (image
                          patches) should be used

        Returns:
            A list of pattern(s).
        """
        data = self.sensor.compute()
        sensor_im, is_reset = data["data"], data["is_reset"]
        if not isinstance(self.sensor, ImageSensor):
            return sensor_im, is_reset

        # if level.level_no == 0:
        #     visualize.show_image(sensor_im)

        # if level.level_no == 0 and level.node_cloning:
        if not all_patterns:
            # TODO how to pick a good spot?
            # central patch
            f = int(self.sensor.width / 2 - self.patch_size[0] / 2)
            t = int(self.sensor.width / 2 + (self.patch_size[0] - self.patch_size[0] / 2))
            pattern = sensor_im[f:t, f:t].reshape(np.prod(self.patch_size), 1)

            patterns = [pattern]  # * np.prod(self.levels[0].size)
        else:
            patterns = utils.extract_patches(sensor_im, self.patch_size, self.levels[0].overlap)

        return patterns, is_reset
Example #27
0
 def get(self, *args, **kwargs):
     network_id = int(self.get_argument("network_id"))
     domain_id = int(self.get_cookie("domain_id"))
     resp = yield tornado.gen.Task(task.get_monitored_devices_task.apply_async, args=[network_id, domain_id])
     mntdevs = resp.result
     respJson = json.dumps(mntdevs)
     self.write(respJson)
Example #28
0
    def _iprange_to_glob(lb, ub):
        #   Internal function to process individual IP globs.
        t1 = [int(_) for _ in str(lb).split(".")]
        t2 = [int(_) for _ in str(ub).split(".")]

        tokens = []

        seen_hyphen = False
        seen_asterisk = False

        for i in range(4):
            if t1[i] == t2[i]:
                #   A normal octet.
                tokens.append(str(t1[i]))
            elif (t1[i] == 0) and (t2[i] == 255):
                #   An asterisk octet.
                tokens.append("*")
                seen_asterisk = True
            else:
                #   Create a hyphenated octet - only one allowed per IP glob.
                if not seen_asterisk:
                    if not seen_hyphen:
                        tokens.append("%s-%s" % (t1[i], t2[i]))
                        seen_hyphen = True
                    else:
                        raise AddrConversionError("only 1 hyphenated octet" " per IP glob allowed!")
                else:
                    raise AddrConversionError(
                        "asterisks are not allowed' \
                        ' before hyphenated octets!"
                    )

        return ".".join(tokens)
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 svg2boundedPDF(filename, outfilename):
    """
    convert filename to pdf file outputfilename. We make no assumptions
    file extensions. 

    """

    (fidin, fidout) = os.popen4(
        "inkscape --without-gui --file=%s  --print='| ps2eps - > /tmp/svg2boundedPDF.eps'" % (filename)
    )

    res = fidout.read()

    # new attempt to extract outut boundingbox
    fid = file("/tmp/svg2boundedPDF.eps")
    res = fid.read()
    bbre = re.compile("%%BoundingBox: (\d+) (\d+) (\d+) (\d+)")

    m = bbre.search(res)

    if m:
        (x1, y1, x2, y2) = m.groups()
        x1 = int(x1)
        x2 = int(x2)
        y1 = int(y1)
        y2 = int(y2)

        os.popen("ps2pdf -dEPSCrop /tmp/svg2boundedPDF.eps  %s" % (outfilename))