Beispiel #1
0
    def resolveAddresses(self, args):
        # r = common.getResolver()
        self.resolveMap = {}
        multipleUnresolved = False
        for address in args.addresses:
            if not common.isIPAddress(address):
                if common.isHostname(address):
                    # TODO: Use twisted.names.client's getHostByName without removing
                    #       the hostfile resolver from the resolverchain.
                    #       (Right now, the standard behavior of using the resolverchain
                    #       hostsresolver -> cacheresolver -> resolver triggers an error when
                    #       you try to look up a domain that matches an IP address defined
                    #       in the hosts file--"noneType has no function stopListening" in
                    #       the passthrough.)

                    # d = r.getHostByName(address)
                    # self.resolveMap[address] = d

                    # Blocking, but it's ok. We'd be waiting anyway.
                    import socket
                    if not multipleUnresolved:
                        print(
                            colorize(" @Y*@x {0:51} @B[---]@x".format(
                                "Resolving hostnames...")))
                        multipleUnresolved = True
                    sys.stdout.write(
                        colorize("   @y-@x {0:28} ".format(address)))
                    sys.stdout.flush()
                    try:
                        new = socket.getaddrinfo(address, 80, 0, 0,
                                                 socket.SOL_TCP)[0][4][0]
                    except (socket.error, socket.herror, socket.gaierror,
                            socket.timeout):
                        self.resolveMap[address] = Failure()
                        print(
                            colorize(
                                "{0:<20} @B[@R!!!@B]@x".format("Not found")))
                        continue
                    print(colorize("{0:<20} @B[ @G- @B]@x".format(new)))
                    self.resolveMap[address] = new
                else:
                    raise TypeError(
                        "Please specify only IP addresses or hostnames in --address; {0} is invalid."
                        .format(address))
        # deferreds = self.resolveMap.values()
        # dl = (defer.DeferredList(deferreds)
        #       .addCallback(self._cbResolveAddresses, args))
        # return dl
        return self._cbResolveAddresses(None, args)
Beispiel #2
0
 def dispatch(self, msg, trail=True):
     if trail:
         msg = '{0}\n\r'.format(msg)
     if self.ansi:
         msg = color.colorize(msg)
     else:
         msg = color.decolorize(msg)
     self.outbuf = '{0}{1}'.format(self.outbuf, msg)
Beispiel #3
0
 def formatResult(self, result, sub=False):
     if result.extra:
         extra = colorize('@B--@x ') + result.extra
     else:
         extra = ''
     if not result.status:
         last = colorize('@B[@R!!!@B]@x')
     elif config.warningsOnly:
         return
     elif result.status == CHECK_NOT_APPLICABLE:
         last = '@B[@D - @B]@x'
     elif result.status == CHECK_RESULT_HIDDEN:
         last = ''
     elif result.status == CHECK_RESULT_SUB:
         last = colorize('@B[---]@x')
     elif result.status == CHECK_RESULT_UNCERTAIN:
         last = colorize('@B[@Y ? @B]@x')
     else:
         last = colorize('@B[ @G- @B]@x')
     if sub:
         output = colorize("   @y-@x {0:49} {1}{2}".format(
             result.text, last, extra))
     else:
         output = colorize(" @Y*@x {0:51} {1}{2}".format(
             result.text, last, extra))
     return output
Beispiel #4
0
 async def dispatch(self, msg, trail=True):
     if self.state['connected']:
         if trail:
             msg = f'{msg}\n\r'
         if self.ansi:
             msg = color.colorize(f'{msg}{{x')
         else:
             msg = color.decolorize(msg)
         await self.out_buf.put((msg, "false"))
Beispiel #5
0
 def dispatch(self, msg, trail=True):
     if trail:
         msg = f"{msg}\n\r"
     if self.ansi:
         msg = color.colorize(msg)
     else:
         msg = color.decolorize(msg)
     self.outbuf = f"{self.outbuf}{msg}"
     if hasattr(self.owner,
                "snooped_by") and len(self.owner.snooped_by) > 0:
         for each_person in self.owner.snooped_by:
             each_person.write(self.outbuf)
Beispiel #6
0
    def resolveAddresses(self, args):
        # r = common.getResolver()
        self.resolveMap = {}
        multipleUnresolved = False
        for address in args.addresses:
            if not common.isIPAddress(address):
                if common.isHostname(address):
                    # TODO: Use twisted.names.client's getHostByName without removing
                    #       the hostfile resolver from the resolverchain.
                    #       (Right now, the standard behavior of using the resolverchain
                    #       hostsresolver -> cacheresolver -> resolver triggers an error when
                    #       you try to look up a domain that matches an IP address defined
                    #       in the hosts file--"noneType has no function stopListening" in
                    #       the passthrough.)

                    # d = r.getHostByName(address)
                    # self.resolveMap[address] = d

                    # Blocking, but it's ok. We'd be waiting anyway.
                    import socket
                    if not multipleUnresolved:
                        print(colorize(" @Y*@x {0:51} @B[---]@x".format("Resolving hostnames...")))
                        multipleUnresolved = True
                    sys.stdout.write(colorize("   @y-@x {0:28} ".format(address)))
                    sys.stdout.flush()
                    try:
                        new = socket.getaddrinfo(address, 80, 0, 0, socket.SOL_TCP)[0][4][0]
                    except (socket.error, socket.herror, socket.gaierror, socket.timeout):
                        self.resolveMap[address] = Failure()
                        print(colorize("{0:<20} @B[@R!!!@B]@x".format("Not found")))
                        continue
                    print(colorize("{0:<20} @B[ @G- @B]@x".format(new)))
                    self.resolveMap[address] = new
                else:
                    raise TypeError("Please specify only IP addresses or hostnames in --address; {0} is invalid.".format(address))
        # deferreds = self.resolveMap.values()
        # dl = (defer.DeferredList(deferreds)
        #       .addCallback(self._cbResolveAddresses, args))
        # return dl
        return self._cbResolveAddresses(None, args)
Beispiel #7
0
    def getRandomPhoto(self):
        randomId = random.choice(self.photoIds)
        res = self.graph.get_object(randomId)
        data = requests.get(res['source']).content
        original = PIL.Image.open(io.BytesIO(data)).convert("RGBA")
        (colorized, levels) = color.colorize(original)

        return {
            "id": randomId,
            "levels": levels,
            "original": imageToBase64String(original),
            "colorized": imageToBase64String(colorized),
        }
Beispiel #8
0
def show_video():
    kinect.process_frame()
    color.colorize(kinect.image, kinect.constants, kinect.colors)
    for ball in kinect.balls:
        cv.Circle(
            cv.fromarray(kinect.image),
            (int(ball["col"][0] + 0.5), int(ball["row"][0] + 0.5)),
            int(1.5 + np.sqrt(ball["size"] / 3.14)),
            (0, 0, 255),
        )
    for wall in kinect.yellow_walls:
        cx, wx = wall["col"][0], width(wall["col"][1]) / 2
        cy, wy = wall["row"][0], width(wall["row"][1]) / 2
        cv.Rectangle(
            cv.fromarray(kinect.image),
            (int(cx - wx + 0.5), int(cy - wy + 0.5)),
            (int(cx + wx + 0.5), int(cy + wy + 0.5)),
            (0, 0, 255),
        )
    cv.CvtColor(cv.fromarray(kinect.image), cv.fromarray(kinect.image), cv.CV_HSV2BGR)
    cv.ShowImage("Video", cv.fromarray(kinect.image))
    cv.ShowImage("Depth", cv.fromarray(kinect.depth << 5))
Beispiel #9
0
    async def send_prompt(self):
        if self.state['logged in']:
            if hasattr(self.owner, "editing"):
                await self.out_buf.put(">")
                return

            log.info(
                f'in send_prompt: is_paginating is {self.owner.oocflags["is_paginating"]}'
            )
            log.info(f'page_buf is {self.page_buf}')
            if self.promptable and not self.owner.oocflags["is_paginating"]:
                if self.owner.oocflags["afk"]:
                    pretext = '{W[{RAFK{W]{x '
                else:
                    pretext = ''
                output = color.colorize(f'{pretext}{self.owner.prompt}{{x')
                await self.out_buf.put((output, "true"))
            else:
                output = color.colorize(
                    'Paginating output: {Genter{x to continue, {Gq{x to exit paginate display\n\r'
                )
                await self.out_buf.put((output, "true"))
Beispiel #10
0
 async def write(self):
     if self.state['logged in']:
         log.info('Writing something')
         if hasattr(self.owner, "editing"):
             asyncio.create_task(self.out_buf.put(">"))
         elif self.promptable:
             if self.owner.oocflags["afk"]:
                 pretext = "{W[{RAFK{W]{x "
             else:
                 pretext = ""
             output = color.colorize(
                 f"\n\r{pretext}{self.owner.prompt}\n\r")
             asyncio.create_task(self.out_buf.put(output),
                                 name=self.session)
Beispiel #11
0
 def dispatch(self, msg, trail=True):
     if self.state['connected']:
         log.info('Dispatching something')
         if trail:
             msg = f'{msg}\n\r'
         if self.ansi:
             msg = color.colorize(msg)
         else:
             msg = color.decolorize(msg)
         asyncio.create_task(self.out_buf.put(msg), name=self.session)
     elif self.state['connected'] and self.state['logged in']:
         log.info('Writing something')
         if hasattr(self.owner, "editing"):
             asyncio.create_task(self.out_buf.put(">"))
         elif self.promptable:
             if self.owner.oocflags["afk"]:
                 pretext = "{W[{RAFK{W]{x "
             else:
                 pretext = ""
             output = color.colorize(
                 f"\n\r{pretext}{self.owner.prompt}\n\r")
             asyncio.create_task(self.out_buf.put(output),
                                 name=self.session)
Beispiel #12
0
 def handle_write(self):
     try:
         self.send(self.outbuf.encode("utf8"))
         self.outbuf = ''
         if hasattr(self.owner, 'editing'):
             output = ">"
             self.send(output.encode("utf8"))
         elif self.promptable == True:
             if self.owner.oocflags['afk'] == True:
                 pretext = "{W[{RAFK{W]{x "
             else:
                 pretext = ""
             output = color.colorize('\n\r{}{} '.format(pretext, self.owner.prompt))
             self.send(output.encode("utf8"))
     except Exception as err:
         print("Error in handle_write:server.py - {0}".format(err))
Beispiel #13
0
def report(worklog, config):
    lines = []
    total = timedelta(seconds=0)
    rollup = dict()
    lines.append('{} {}'.format(
        color.bold('Worklog Report for'),
        color.purple(worklog.when.strftime('%F'), bold=True)))
    if len(worklog) == 0:
        lines.append('	no entries')
    else:
        for task, next_task in worklog.pairwise():
            if isinstance(task, GoHome):
                continue
            if isinstance(next_task, DummyRightNow):
                colorize_end_time = color.yellow
            else:
                colorize_end_time = color.green
            delta = next_task.start - task.start
            if task.include_in_rollup():
                total += delta
                if task.description not in rollup:
                    rollup[task.description] = delta
                else:
                    rollup[task.description] += delta
            if delta > timedelta():
                if not task.logged:
                    task.logged = False
                lines.append('	{:5s} {} {:5s} {}{!s:>7}{} {} {}  {}'.format(
                    color.green(task.start.strftime('%H:%M')),
                    color.black('-', intense=True),
                    colorize_end_time(next_task.start.strftime('%H:%M')),
                    color.black('(', intense=True),
                    Duration(delta).colorized(),
                    color.black(')', intense=True), {
                        True: color.green('*'),
                        False: color.red('*')
                    }[task.logged], task.ticket, task.description))

        lines.append('\n	{!s:>7}  {}'.format(
            Duration(total).colorized(underline=True),
            color.colorize('TOTAL', bold=True, underline=True)))
        for key in sorted(rollup.keys()):
            lines.append('	{!s:>7}  {}'.format(
                Duration(rollup[key]).colorized(), color.bold(key)))
        print('\n'.join(lines))
Beispiel #14
0
    def handle_write(self):
        try:
            self.send(self.outbuf.encode("utf8"))
            self.outbuf = ""
            if hasattr(self.owner, "editing"):
                output = ">"
                self.send(output.encode("utf8"))
            elif self.promptable:
                if self.owner.oocflags["afk"]:
                    pretext = "{W[{RAFK{W]{x "
                else:
                    pretext = ""

                output = color.colorize(f"\n\r{pretext}{self.owner.prompt}")
                self.send(output.encode("utf8"))
        except Exception as err:
            self.handle_close()
            log.error(f"handle_write : {err}")
Beispiel #15
0
 def showResults(self):
     if not self.runningResults:
         if config.warningsOnly:
             hasWarning = False
             for scan in self.scans:
                 if not scan.result.status:
                     hasWarning = True
                 for subresult in scan.subresults:
                     if not subresult.status:
                         hasWarning = True
             if not hasWarning:
                 return
         print("")
         print(colorize("@W{0}@x".format(self.title)))
         print(config.bar)
         for scan in self.scans:
             self.showResult(scan.result)
         print("")
Beispiel #16
0
 def showResults(self):
     if not self.runningResults:
         if config.warningsOnly:
             hasWarning = False
             for scan in self.scans:
                 if not scan.result.status:
                     hasWarning = True
                 for subresult in scan.subresults:
                     if not subresult.status:
                         hasWarning = True
             if not hasWarning:
                 return
         print("")
         print(colorize("@W{0}@x".format(self.title)))
         print(config.bar)
         for scan in self.scans:
             self.showResult(scan.result)
         print("")
Beispiel #17
0
    def run(self):
        if self.runningResults:
            print("")
            print(colorize("@W{0}@x".format(self.title)))
            print(config.bar)
        for check in self.checks:
            c = check(self.target)

            # "lambda x: c, x" takes the (same) c in scope each loop; we have to do
            # manual assignment to get the current c.
            def checkFinishedTrigger(value, c=c):
                self.checkFinished(c)

            d = (c.run()
                 .addBoth(checkFinishedTrigger))
            c.deferred = d
            self.scans.append(c)
        dl = (defer.DeferredList([c.deferred for c in self.scans])
              .addCallback(lambda x: self.showResults())
              .addErrback(log.err)) # Uncaught error
        return dl
Beispiel #18
0
    def run(self):
        if self.runningResults:
            print("")
            print(colorize("@W{0}@x".format(self.title)))
            print(config.bar)
        for check in self.checks:
            c = check(self.target)

            # "lambda x: c, x" takes the (same) c in scope each loop; we have to do
            # manual assignment to get the current c.
            def checkFinishedTrigger(value, c=c):
                self.checkFinished(c)

            d = (c.run().addBoth(checkFinishedTrigger))
            c.deferred = d
            self.scans.append(c)
        dl = (defer.DeferredList([
            c.deferred for c in self.scans
        ]).addCallback(lambda x: self.showResults()).addErrback(log.err)
              )  # Uncaught error
        return dl
Beispiel #19
0
 def formatResult(self, result, sub=False):
     if result.extra:
         extra = colorize('@B--@x ') + result.extra
     else:
         extra = ''
     if not result.status:
         last = colorize('@B[@R!!!@B]@x')
     elif config.warningsOnly:
         return
     elif result.status == CHECK_NOT_APPLICABLE:
         last = '@B[@D - @B]@x'
     elif result.status == CHECK_RESULT_HIDDEN:
         last = ''
     elif result.status == CHECK_RESULT_SUB:
         last = colorize('@B[---]@x')
     elif result.status == CHECK_RESULT_UNCERTAIN:
         last = colorize('@B[@Y ? @B]@x')
     else:
         last = colorize('@B[ @G- @B]@x')
     if sub:
         output = colorize("   @y-@x {0:49} {1}{2}".format(result.text, last, extra))
     else:
         output = colorize(" @Y*@x {0:51} {1}{2}".format(result.text, last, extra))
     return output
Beispiel #20
0
def _notify(ok, title, message):
    status = color.colorize('OK', color.green) if ok else color.colorize('FAIL', color.red)
    return '%s: %s | %s' % (
        trail_spaces(color.colorize(title.title(), color.blue), 15),
        status,
        message)
Beispiel #21
0
def gen_rgbbase_and_normal(seed=69, rot=0):
    im_rgbref_base = np.zeros((res, res, multi_sampling, multi_sampling, 4))
    normal_base = np.zeros((res, res, multi_sampling, multi_sampling, 3))
    cloud_map = np.zeros((res, res, multi_sampling, multi_sampling))

    for i in tqdm(range(res)):
        for d1 in range(multi_sampling):
            for d2 in range(multi_sampling):

                z2 = radius**2 - (x[i, :] + dx[d1, d2])**2 - (y[i, :] +
                                                              dy[d1, d2])**2
                ok = z2 >= 0

                if np.any(ok):
                    x1, y1, z1 = (x[i, ok] +
                                  dx[d1, d2]), (y[i, ok] +
                                                dy[d1, d2]), np.sqrt(z2[ok])

                    ox1, oz1 = x1, z1

                    x1, z1, = x1 * np.cos(rot) - z1 * np.sin(rot), x1 * np.sin(
                        rot) + z1 * np.cos(rot)

                    h = double_perlin3D(x1, y1, z1, seed=seed)

                    vT = double_perlin3D(x1,
                                         y1,
                                         z1,
                                         a=20,
                                         persistance=0.8,
                                         seed=seed + 132)
                    vH = double_perlin3D(x1,
                                         y1,
                                         z1,
                                         a=20,
                                         persistance=0.8,
                                         seed=seed + 463)

                    c = double_perlin3D(x1,
                                        y1,
                                        z1,
                                        a=5,
                                        d=5,
                                        persistance=0.6,
                                        seed=seed + 212)

                    c = .6 * c + .4 * double_perlin3D(x1,
                                                      y1,
                                                      z1,
                                                      a=20,
                                                      d=10,
                                                      persistance=0.8,
                                                      seed=seed + 213)

                    cloud_map[i, ok, d1, d2] = c

                    rgbref = colorize(x1, y1, z1, h, vT, vH)

                    dhdx = np.zeros_like(h)
                    dhdy = np.zeros_like(h)
                    dhdz = np.zeros_like(h)

                    dhdx[h > 0.5] = (double_perlin3D(
                        x1[h > 0.5] + eps, y1[h > 0.5], z1[h > 0.5], seed=seed)
                                     - h[h > 0.5]) / eps
                    dhdy[h > 0.5] = (double_perlin3D(
                        x1[h > 0.5], y1[h > 0.5] + eps, z1[h > 0.5], seed=seed)
                                     - h[h > 0.5]) / eps
                    dhdz[h > 0.5] = (double_perlin3D(
                        x1[h > 0.5], y1[h > 0.5], z1[h > 0.5] + eps, seed=seed)
                                     - h[h > 0.5]) / eps

                    norm = normal(ox1, y1, oz1, h, dhdx, dhdy, dhdz, A=0.05)

                    i_var = np.ones_like(h)

                    i_var[h > 0.5] = (0.5 + double_perlin3D(x1[h > 0.5],
                                                            y1[h > 0.5],
                                                            z1[h > 0.5],
                                                            a=20,
                                                            d=5,
                                                            persistance=0.8,
                                                            seed=seed + 214))

                    im_rgbref_base[i, ok, d1, d2, 0] = rgbref[:, 0] * i_var
                    im_rgbref_base[i, ok, d1, d2, 1] = rgbref[:, 1] * i_var
                    im_rgbref_base[i, ok, d1, d2, 2] = rgbref[:, 2] * i_var
                    im_rgbref_base[i, ok, d1, d2, 3] = rgbref[:, 3]

                    normal_base[i, ok, d1, d2, 0] = norm[0]
                    normal_base[i, ok, d1, d2, 1] = norm[1]
                    normal_base[i, ok, d1, d2, 2] = norm[2]

                im_rgbref_base[i, ~ok, d1, d2,
                               0] = background(x[i, ~ok], y[i, ~ok])[0, :]
                im_rgbref_base[i, ~ok, d1, d2,
                               1] = background(x[i, ~ok], y[i, ~ok])[1, :]
                im_rgbref_base[i, ~ok, d1, d2,
                               2] = background(x[i, ~ok], y[i, ~ok])[2, :]

    return im_rgbref_base, normal_base, cloud_map
Beispiel #22
0
phi, theta = np.meshgrid(phi, theta)

x1 = radius * np.cos(theta) * np.cos(phi)
z1 = radius * np.cos(theta) * np.sin(phi)
y1 = radius * np.sin(theta)

x1 = x1.flatten()
y1 = y1.flatten()
z1 = z1.flatten()

h = double_perlin3D(x1, y1, z1, seed=seed)
vT = double_perlin3D(x1, y1, z1, a=20, persistance=0.8, seed=seed + 132)
vH = double_perlin3D(x1, y1, z1, a=20, persistance=0.8, seed=seed + 463)

rgbref = colorize(x1, y1, z1, h, vT, vH)

i_var = np.ones_like(h)

i_var[h > 0.5] = (0.5 + double_perlin3D(x1[h > 0.5],
                                        y1[h > 0.5],
                                        z1[h > 0.5],
                                        a=20,
                                        d=5,
                                        persistance=0.8,
                                        seed=seed + 214))

rgbref[:, 0] = rgbref[:, 0] * i_var
rgbref[:, 1] = rgbref[:, 1] * i_var
rgbref[:, 2] = rgbref[:, 2] * i_var
rgbref[:, 3] = rgbref[:, 3]
Beispiel #23
0
def log(msg, indent=0):
    msg = indentString(msg, indent)
    file_manager.append('app-cache/log-html.txt', color.colorizeHtml(msg))
    # The rest of the files will take normal ASCII colors
    msg = color.colorize(msg)
    print(msg)  # This should be the only print statement in the entire bot
Beispiel #24
0
def main():
    pep8_check.pep8_all()
    data_integrity_check.verify_all()
    coverage_check.coverage_test_all()
    print color.colorize("OK", color.green)