Esempio n. 1
0
def read_input():
    global bags

    # input = lib.readfile('inputs/07-input-sample.txt')
    # input = lib.readfile('inputs/07-input-sample2.txt')
    input = lib.readfile('inputs/07-input.txt')
    m = re.compile(r"(\d+)\s+(.*)")

    # sanitize input: clean plural forms (bags -> bag), remove sentence chars.
    # then split and create Bag objects
    for line in input:
        # sanitize:
        line = line.replace('bags', 'bag').replace('.','')
        # split name from contents:
        spl = line.split('contain')
        bag = spl[0].strip()
        contents = spl[1].split(',')

        # create bag objects (aka graph nodes):
        bag_obj = Bag()
        bag_obj.name = bag
        bag_obj.bag_list = []

        # create a bag list (aka node list): name -> object
        bags[bag] = bag_obj

        # create a child node list for each bag, including bag count (weights)
        for c in contents:
            c = c.strip()
            g = m.match(c)
            if g:
                (nr, name) = g.group(1, 2)
                bag_obj.bag_list.append((nr, name))

    return bags
Esempio n. 2
0
def problem1():
    lines = [
        math.floor(int(nr) / 3) - 2
        for nr in lib.readfile('inputs/00-input.txt')
    ]
    sum_energy = functools.reduce(lambda a, b: a + b, lines)

    print("Solution 1: The sum is {}".format(sum_energy))
Esempio n. 3
0
 def wpconfig_backup(self):
     path = realpath(__file__).split('modules')[0]
     path += "db/backupfile.wpseku"
     for ext in readfile(path):
         url = Path(self.url, "wp-config.php" + ext.decode('utf-8'))
         resp = self.send(url=url, method="GET")
         if resp.status_code == 200 and resp.content != ("" or None):
             if resp.url == url:
                 plus('wp-config.php backup was found at: %s' % (resp.url))
Esempio n. 4
0
	def run(self):
		if self.kwargs['verbose'] is True:
			info('Checking directory listing...')
		path  = realpath(__file__).split('modules')[0]
		path += "db/dirlisting.wpseku"
		for dir_ in readfile(path):
			url = Path(self.url,dir_.decode('utf-8'))
			resp = self.send(url=url,method="GET")
			if search(decode('<title>Index of /'),resp.content,I):
				plus('Dir "%s" listing enable at: %s'%(dir_.decode('utf-8'),resp.url))
Esempio n. 5
0
	def run(self):
		if self.kwargs['verbose'] is True:
			info('Checking common files...')
		path  = realpath(__file__).split('modules')[0]
		path += "db/commonfile.wpseku"
		for file in readfile(path):
			url = Path(self.url,file.decode('utf-8'))
			resp = self.send(url=url,method="GET")
			if resp.status_code == 200 and resp.content != ("" or None):
				if resp.url == url:
					plus('%s file was found at: %s'%(file.decode('utf-8'),resp.url))
Esempio n. 6
0
def read_input():
    input = lib.remove_empty(lib.readfile('inputs/22-input.txt'))
    # input = lib.remove_empty(lib.readfile('inputs/22-input-sample.txt'))

    players = [deque(),deque()]
    p = -1
    for line in input:
        if re.match(r"Player", line):
            p += 1
        else:
            players[p].append(int(line))
    return players
def read_input():
    input = lib.readfile('inputs/19-input.txt')
    # input = lib.readfile('inputs/19-input-sample.txt')
    # input = lib.readfile('inputs/19-input-sample-2.txt')
    rules = []
    messages = []
    for l in input:
        if re.match(r"\d+:.*", l):
            rules.append(l)
        elif len(l.strip()):
            messages.append(l)

    return (rules, messages)
Esempio n. 8
0
def read_input():
    # input = lib.readfile('inputs/08-input-sample.txt')
    input = lib.readfile('inputs/08-input.txt')
    m = re.compile(r"(\w+)\s+([+-]\d+)+")

    mem = []
    for line in input:
        g = m.match(line)
        if g:
            instr = [g.group(1), int(g.group(2)), 0]
            mem.append(instr)

    return CPU(mem)
Esempio n. 9
0
def read_input():
    # return list(lib.remove_empty(lib.readfile('inputs/12-input-sample.txt')))

    # input = list(lib.remove_empty(lib.readfile('inputs/13-input-sample.txt')))
    input = list(lib.remove_empty(lib.readfile('inputs/13-input.txt')))
    depart = int(input[0])
    buses = input[1].split(',')
    final_buses = []
    for b in buses:
        if b == 'x':
            final_buses.append(b)
        else:
            final_buses.append(int(b))
    return (depart, final_buses)
Esempio n. 10
0
def read_input():
    global prgs

    # input = lib.readfile('inputs/13-input-sample.txt')
    input = lib.readfile('inputs/13-input.txt')
    m = re.compile(r"^(\d+):\s+(\d+)")
    lines = []

    for line in input:
        g = m.match(line)
        if g:
            # tuples of: ( depth, range )
            lines.append((int(g.group(1)), int(g.group(2))))

    return lines
Esempio n. 11
0
 def run(self):
     plus('Bruteforcing Login via XML-RPC...')
     if self.kwargs['verbose'] is True:
         info('Setting user: %s' % (self.user))
     self.check()
     q = queue.Queue(self.max_thread)
     t = []
     for x in range(self.max_thread):
         thread = ThreadBrute(Path(self.url, 'xmlrpc.php'), q, self,
                              self.user)
         thread.daemon = True
         t.append(thread)
         thread.start()
     for passwd in readfile(self.wordlist):
         q.put(passwd.decode('utf-8'))
Esempio n. 12
0
	def testFile(self,file):
		res = []
		code = readfile(file)
		res += self.csrf(code)
		res += self.ope(code)
		res += self.pce(code)
		res += self.com(code)
		res += self.auth(code)
		res += self.php(code)
		res += self.fin(code)
		res += self.fid(code)
		res += self.sql(code)
		res += self.xss(code)
		if res != []:
			print(format_pretty_table(res,self.table))
		else: plus('Not found vulnerabilities')
Esempio n. 13
0
def DoAnchor(href, base, text, cursor):

	""" Default anchor selection handler """

	url = urlparse.urljoin(base, href)
	scheme, net, path = urlparse.urlparse(url)[:3]
	error = "%s\n- %s is not supported yet." % (url, scheme)
	if scheme == 'file':
		data = readfile(path)
		if data:
			text['cursor'] = cursor
			HTML2TextClean(text)
			HTML2Text(data, text)
			return
		error = "%s\n- could not read %s." % (url, path)
	elif scheme in ('http', 'https', 'ftp'):
		if not globals.AllowHREFURLQueries:
			url = urlparse.urlunparse((scheme, net, path) + ('',)*3)
		command = globals.OpenURLCmd % url
		Debug(1, 'command')
		text['cursor'] = 'watch'
		text.update_idletasks()
		import os; os.system(command)
		text['cursor'] = cursor
		return
	elif scheme == 'mailto':
		try:
			import Compose
			text['cursor'] = 'watch'
			text.update_idletasks()
			Compose.Compose()(path)
			text['cursor'] = cursor
			return
		except ImportError: pass
	elif not scheme and url[0] == '#':
		tag = 'name_%s' % string.replace(url[1:], ' ', '_')
		Debug(1, '''"See tag %s => %s" % (tag, `text.tag_ranges(tag)`)''')
		try:
			text.yview(text.tag_ranges(tag)[0])
		except IndexError:
			pass	# Hmmm. Tk bug?
		return

	Debug(1, '''"url=%s, scheme=%s, net=%s, path=%s" % (url, scheme, net, path)''')
	import TopLevel
	TopLevel.MessageTextBox('URL reference error')(error)
Esempio n. 14
0
def read_input():
    # lines = lib.readfile('inputs/04-input-sample.txt')
    lines = lib.readfile('inputs/04-input.txt')

    act_pass = dict()
    for line in lines:
        if len(line.strip()) == 0:
            passports.append(act_pass)
            act_pass = dict()
        else:
            pieces = line.split(' ')
            for piece in pieces:
                key_val = piece.split(':')
                act_pass[key_val[0]] = key_val[1]

    passports.append(act_pass)
    return lines
def read_input():
    global prgs

    # input = lib.readfile('inputs/12-input-sample.txt')
    input = lib.readfile('inputs/12-input.txt')
    m = re.compile(r"^(\d+)\s+<->\s+(.*)")

    for line in input:
        g = m.match(line)
        if g:
            (prg, conn_list) = g.group(1, 2)
            conn_list = [s.strip() for s in conn_list.split(',')]
            prg_obj = Prg()
            prg_obj.name = prg
            prg_obj.conn_list = conn_list
            prgs[prg] = prg_obj

    return prgs
def read_input():
    m = re.compile(
        r"(\w+)\s+(\w+)\s+([0-9-]+)\s+if\s+(\w+)\s+(<|>|<=|>=|==|!=)\s+([0-9-]+)"
    )
    # read all nodes, create each without processing childs:
    for line in lib.readfile('inputs/08-input.txt'):
        g = m.match(line)
        if g:
            (reg, op, val, cond_reg, cond_op,
             cond_val) = g.group(1, 2, 3, 4, 5, 6)
            instr = Instruction()
            instr.reg = reg
            instr.op = op
            instr.val = int(val)
            instr.cond_reg = cond_reg
            instr.cond_op = cond_op
            instr.cond_val = int(cond_val)
            instructions.append(instr)
Esempio n. 17
0
def read_input():
    input = lib.readfile('inputs/21-input.txt')
    # input = lib.remove_empty(lib.readfile('inputs/21-input-sample.txt'))
    foods = []
    ingredients = dict()
    allergens = set()
    m = re.compile(r"(.*)\s+\(contains (.*)\)")
    for l in input:
        g = m.match(l)
        if g:
            ingr = g.group(1).split(' ')
            allergs = g.group(2).split(', ')
            foods.append((ingr, allergs))
            for i in ingr:
                ingredients[i] = set()
            for a in allergs:
                allergens.add(a)
    return (foods, ingredients, allergens)
Esempio n. 18
0
def read_input():
    # ops = list(map(lambda line:line.split(' '), lib.remove_empty(lib.readfile('inputs/18-input-sample.txt'))))
    # ops = list(map(lambda line:line.split(' '), lib.remove_empty(lib.readfile('inputs/18-input-sample2.txt'))))
    ops = list(
        map(lambda line: line.split(' '),
            lib.remove_empty(lib.readfile('inputs/18-input.txt'))))
    for i in range(0, len(ops)):
        try:
            nr = int(ops[i][1])
            ops[i][1] = nr
        except Exception:
            pass
        try:
            nr = int(ops[i][2])
            ops[i][2] = nr
        except Exception:
            pass
    return ops
Esempio n. 19
0
def read_input():
    # lines = lib.readfile('inputs/20-input-sample.txt')
    # lines = lib.readfile('inputs/20-input-sample2.txt')
    lines = lib.readfile('inputs/20-input.txt')
    particles = []
    m = re.compile(
        r"p=<([0-9-]+),([0-9-]+),([0-9-]+)>,v=<([0-9-]+),([0-9-]+),([0-9-]+)>,a=<([0-9-]+),([0-9-]+),([0-9-]+)>"
    )
    index = 0
    for line in lines:
        line = line.strip().replace(' ', '')
        g = m.match(line)
        if g:
            p = Particle()
            p.index = index
            p.coords = list(map(int, g.group(1, 2, 3)))
            p.v = list(map(int, g.group(4, 5, 6)))
            p.a = list(map(int, g.group(7, 8, 9)))
            particles.append(p)
            index += 1
    return particles
def read_input():
    input = lib.readfile('inputs/20-input.txt')
    # input = lib.readfile('inputs/20-input-sample.txt')

    tiles = []
    act_tile = None
    m = re.compile(r'Tile (\d+):')
    for l in input:
        if len(l.strip()):
            g = m.match(l)
            if g:
                if act_tile:
                    tiles.append(act_tile)
                act_tile = Tile()
                act_tile.nr = int(g.group(1))
            else:
                act_tile.pixels.append(list(l))
    tiles.append(act_tile)
    for t in tiles:
        t.calc_versions()
    return tiles
import time
import lib
import functools
import math
import re

# lines = list(filter(lambda l: len(l.strip()) > 0, lib.readfile('inputs/03-input-sample.txt')))
lines = list(
    filter(lambda l: len(l.strip()) > 0, lib.readfile('inputs/03-input.txt')))


def slope_down(dx, dy):
    """
    sleigh down the hill: for each step, move act pos + dy/dy
    and check if it's a tree or not
    return the number of trees encountered until the end is reached
    """
    trees = 0
    x = 0
    y = 0
    while y < len(lines):
        actLine = lines[y]
        if actLine[x] == '#':
            trees = trees + 1
        y = y + dy
        x = (x + dx) % len(actLine)
    return trees


def problem1():
    trees = slope_down(3, 1)
Esempio n. 22
0
import time
import lib
import functools
import math

numbers = lib.readfile('inputs/02-input.txt', "\t")


def problem1():
    sum = 0
    for line in numbers:
        line = [int(nr) for nr in line]
        sum += (max(line) - min(line))

    print("Solution 1: The sum is {}".format(sum))


def problem2():
    sum = 0
    for line in numbers:
        line = [int(nr) for nr in line]
        stop = False
        for first in range(0, len(line) - 1):
            for second in range(first + 1, len(line)):
                small = min(line[first], line[second])
                large = max(line[first], line[second])
                if small == 0 or large == 0:
                    break
                if large % small == 0:
                    sum += large // small
                    stop = True
def read_input():
    # input = lib.remove_empty(lib.readfile('inputs/18-input-sample.txt'))
    input = lib.remove_empty(lib.readfile('inputs/18-input.txt'))
    return input
def read_input():
    lines = lib.readfile('inputs/15-input.txt')
    return [int(re.sub(r'[^0-9]','',lines[0])), int(re.sub(r'[^0-9]','',lines[1]))]
def read_input():
    return lib.readfile('inputs/06-input.txt')
Esempio n. 26
0
def read_input():
    # read all nodes, create each without processing childs:
    # input = "".join(lib.readfile('inputs/09-input-sample4.txt'))
    input="".join(lib.readfile('inputs/09-input.txt'))
    return input
def read_input():
    # return [int(i) for i in (lib.readfile('inputs/06-input-sample.txt', "\t")[0])]
    return [int(i) for i in (lib.readfile('inputs/06-input.txt', "\t")[0])]
Esempio n. 28
0
	res = [None]*len(d)

	for i in range(0, len(tkdesc), 2):
		index = d.get(tkdesc[i])
		if index is not None:
			res[index] = tkdesc[i+1]
		
	return tuple(res)



if __debug__:
    if __name__ == '__main__':

	html = readfile('test.html')
	if not html:
		html = '''
<HTML><BODY BGCOLOR="white">
<CENTER>
<H1>An H1 title</H1>
</CENTER>
<H3>An H3 heading</H3>
A short line containing three non-breaking-spaces here &gt;&nbsp;&nbsp;&nbsp;&lt;.
Check out <A HREF="#here">this local reference</A>
<H5>An H5 heading</H5>
<P>A few short lines of text containing an underlined <U>word</U>
that I hope are properly formatted,
with a reference to
<A HREF="http://www.cs.su.oz.au/~piers/">my homepage</A>.</P>
<H6>An H6 heading</H6>
Esempio n. 29
0
import time
import lib
import functools
import math

numbers = [int(nr.strip()) for nr in lib.readfile('inputs/01-input.txt')]


def problem1():
    prod = 0
    for outer in range(0, len(numbers) - 1):
        outnr = numbers[outer]
        for inner in range(outer + 1, len(numbers)):
            innr = numbers[inner]
            if outnr + innr == 2020:
                prod = outnr * innr
                print("Numbers: {} and {}".format(outnr, innr))
                break

    print("Solution 1: The product is {}".format(prod))


def prod():
    for i in range(0, len(numbers) - 2):
        n1 = numbers[i]
        for j in range(i + 1, len(numbers) - 1):
            n2 = numbers[j]
            for k in range(j + 1, len(numbers)):
                n3 = numbers[k]
                if n1 + n2 + n3 == 2020:
                    print("Numbers: {}, {} and {}".format(n1, n2, n3))
Esempio n. 30
0
import time
import lib
import functools
import math

digits = lib.readfile('inputs/01-input.txt')[0]
count = len(digits)


def problem1():
    sum = 0
    for i in range(0, count):
        if digits[(i + 1) % count] == digits[i]:
            sum += int(digits[i])

    print("Solution 1: The sum is {}".format(sum))


def problem2():
    sum = 0
    for i in range(0, count):
        if digits[(i + (count // 2)) % count] == digits[i]:
            sum += int(digits[i])

    print("Solution 2: The sum is {}".format(sum))


def main():
    title = "Advent of Code 2017!"
    print("{title}\n{line}\n\n".format(title=title, line="=" * len(title)))
def read_input():
    # return list(map(list, lib.readfile('inputs/19-input-sample.txt', strip=False)))
    return list(map(list, lib.readfile('inputs/19-input.txt', strip=False)))
Esempio n. 32
0
import time
import lib
import functools
import math
import re

# inputs = lib.readfile('inputs/02-input-sample.txt')
inputs = lib.readfile('inputs/02-input.txt')


def problem1():
    valid = 0
    for line in inputs:
        # find format: '(nr)-(nr) (char): (*)'
        m = re.compile("(\d+)-(\d+)\s+(.):\s+(.*)")
        g = m.match(line)
        if g:
            nrMin = int(g.group(1))
            nrMax = int(g.group(2))
            letter = str(g.group(3))
            pw = str(g.group(4))
            countNr = pw.count(letter)
            if countNr >= nrMin and countNr <= nrMax:
                valid = valid + 1
    print("Solution 1: Valid passwords: {}".format(valid))


def problem2():
    valid = 0
    for line in inputs:
        # find format: '(nr)-(nr) (char): (*)'