def main():
    configure_logger()
    logging.info('Daemon started.')

    time.sleep(3)

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((HOST, PORT))
    sock.listen(0)
    logging.info('Listening on tcp://{}:{}'.format(HOST, PORT))

    try:
        next_id = 0
        while True:
            conn, addr = sock.accept()
            logging.info('Connection from {}'.format(addr))

            try:
                # Read only one request
                req = read(conn.recv)
                req['id'] = next_id
                next_id += 1

                send(req)

                resp = read()
                send(resp, conn.sendall)

            finally:
                conn.close()

    finally:
        sock.close()

    logging.info('Daemon exitting gracefully.')
def plotArea(city, area, df=None):
    if df is None:
        df = read(city)
    df = df.dropna(subset=['小区'])
    df = df.loc[df['小区'].str.contains(area)]
    if city == "北京":
        df = df.loc[df['成交价(元/平)'] > 10000]
    print(city, area, 'data count:', len(df))
    if len(df) == 0:
        return df
    gp = df.groupby(['成交时间'])['成交价(元/平)']
    res = pd.DataFrame({
        "volume": gp.size(),
        "median_price": gp.median(),
        "mean_price": gp.mean()
    })
    res = res.iloc[:len(res), :]
    city = 'default'
    MA = True
    start_date = None
    force = True
    keep_all = True
    for ma_length in [1, 30, 60, 90]:
        title = '%s-%d日均线' % (area, ma_length)
        plot(res, city, title, MA, ma_length, start_date, force, keep_all)
    return df
Exemplo n.º 3
0
def make_old_catalog_hash(file):
    old_catalog_hash = {}
    if os.path.isfile(file):
        print("There already is a {} catalog. It will be updated with new values.".format(file))
        old_catalog = read(file)
        for file_attrs in old_catalog:
            key = make_key(file_attrs)
            old_catalog_hash[key] = file_attrs
    return old_catalog_hash
Exemplo n.º 4
0
    def read(self, path, encoding=None):
        """
        Read the template at the given path, and return it as a unicode string.

        """
        b = common.read(path)

        if encoding is None:
            encoding = self.file_encoding

        return self.unicode(b, encoding)
Exemplo n.º 5
0
def main():
    req = json.load(sys.stdin)

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))

    send(req, sock.sendall)

    resp = read(sock.recv)

    print(json.dumps(resp, indent=4))
Exemplo n.º 6
0
def plotArea(city, area):
    cmd = 'python2.7 spider/chengJiaoSpider.py %s %s'%(city, area)
    os.system(cmd)
    df = read(area)
    gp = df.groupby(['成交时间'])['成交价(元/平)']
    res=pd.DataFrame({"volume":gp.size(),"median_price":gp.median(), "mean_price":gp.mean()})
    res = res.iloc[:len(res),:]
    city = 'default'
    MA = True
    start_date = None
    force = True
    keep_all = True
    for ma_length in [1, 30, 60, 90]:
        title = '%s-%d日均线'%(area, ma_length)
        plot(res, city, title, MA, ma_length, start_date, force, keep_all)
def plotAreas(city, areas):
    dfs = []
    df = read(city)
    for area in areas:
        dfs.append(plotArea(city, area, df))
    df = pd.concat(dfs)
    print('data count:', len(df))
    gp = df.groupby(['成交时间'])['成交价(元/平)']
    res=pd.DataFrame({"volume":gp.size(),"median_price":gp.median(), "mean_price":gp.mean()})
    res = res.iloc[:len(res),:]
    city = 'default'
    MA = True
    start_date = None
    force = True
    keep_all = True
    for ma_length in [1, 30, 60, 90]:
        title = '%s-%d日均线'%('前滩', ma_length)
        plot(res, city, title, MA, ma_length, start_date, force, keep_all)
Exemplo n.º 8
0
def plotArea(city, area):
    df = read(city)
    df = df.dropna(subset=['小区'])
    df = df.loc[df['小区'].str.contains(area)]
    gp = df.groupby(['成交时间'])['成交价(元/平)']
    res = pd.DataFrame({
        "volume": gp.size(),
        "median_price": gp.median(),
        "mean_price": gp.mean()
    })
    res = res.iloc[:len(res), :]
    city = 'default'
    MA = True
    start_date = None
    force = True
    keep_all = True
    for ma_length in [1, 30, 60, 90]:
        title = '%s-%d日均线' % (area, ma_length)
        plot(res, city, title, MA, ma_length, start_date, force, keep_all)
Exemplo n.º 9
0
from common import read
data1 = read('北京')
x=data1.groupby(['成交时间']).size()
x.index
date = list(x.index)
date.sort()
print(date[-10:])
Exemplo n.º 10
0
def read(filename):
    return common.read(filename)
Exemplo n.º 11
0
        for w in widths:
            position = self.position + w.dot(self.rotation)
            if not self.visitedLocationTwice:
                self.__is_position_bookmarked(position)
            self.bookmarks.append(np.copy(position))
        self.position = self.bookmarks[-1]

    def __is_position_bookmarked(self, position):
        if any((position == p).all() for p in self.bookmarks):
            self.firstVisitedTwice = np.copy(position)
            self.visitedLocationTwice = True

    @staticmethod
    def get_manhattan_distance(point):
        return sum(map(abs, point))


#### Main part.

instructions = [
    m.groups() for m in map(INSTRUCTION_REGEX.match,
                            read(__file__).split(', '))
]

path = Path()
for instruction in instructions:
    path.update_position(*instruction)

print_results(Path.get_manhattan_distance(path.position),
              Path.get_manhattan_distance(path.firstVisitedTwice))
Exemplo n.º 12
0
    all_ingredients = flatten([ings for ings, allerg in parsed])
    ingredient_set = set(all_ingredients)
    possble_allergen_names = possible_allerggens(parsed)
    allergen_set = set.union(*possble_allergen_names.values())
    non_allergens = ingredient_set - allergen_set
    return sum(all_ingredients.count(allrg) for allrg in non_allergens)

def mapped_allergens(parsed):
    possible_allergen_names = possible_allerggens(parsed)
    mapped = {}
    allergen_keys = set(possible_allergen_names.keys())
    while allergen_keys:
        for allergen in allergen_keys.copy():
            unidentified = list(filter(lambda ingr: ingr not in mapped.values(), possible_allergen_names[allergen]))
            if len(unidentified) == 1:
                mapped[allergen] = unidentified[0]
                allergen_keys.remove(allergen)
    return ','.join([ing for _, ing in sorted(mapped.items())])

inp = read('21.txt').strip()

print(possible_names(s))
print('---')
print(possible_names(inp))

print('--- part b --- ')
print(mapped_allergens(parse(s)))
print('---')
print(mapped_allergens(parse(inp)))

Exemplo n.º 13
0

def B(lst):
    return sum([len(set.intersection(*[set(findall('\w', g))\
            for g in group.split('\n')])) for group in lst.strip().split('\n\n')])


s1 = """abc

a
b
c

ab
ac

a
a
a
a

b
"""

assert A(s1) == 11
assert B(s1) == 6

if __name__ == "__main__":
    print(A(read('6.txt')))
    print(B(read('6.txt')))
Exemplo n.º 14
0
#!/usr/bin/env python3

import sys
import os
from common import read, write, Const, append_suffix

if len(sys.argv) != 3:
    print("Use ./prune.py <dir-to-catalog> <catalog_file.csv>")
    exit(1)

catalog_directory = sys.argv[1]
catalog_file_name = sys.argv[2]

print("Reading {}/{}".format(os.getcwd(), catalog_file_name))

catalog = read(catalog_file_name)
catalog_pruned = []

for file in catalog:
    full_path = os.path.join(catalog_directory, file["path"],
                             file["file_name"])
    if os.path.exists(full_path):
        catalog_pruned.append(file)
    else:
        print(full_path + " was pruned")

catalog_pruned_file_name = append_suffix(catalog_file_name, Const.pruned)
write(catalog_pruned_file_name, catalog_pruned)
Exemplo n.º 15
0
import json
import re

from common import print_results, read

NUMBER_REGEX = re.compile(r'-?\d+')

json_string = read(__file__)

# Part One
count_1 = sum(int(s) for s in NUMBER_REGEX.findall(json_string))

# Part Two
red = lambda x: {} if 'red' in x.values() else x
json_string = json.dumps(json.loads(json_string, object_hook=red))
count_2 = sum(int(s) for s in NUMBER_REGEX.findall(json_string))

print_results(count_1, count_2)
Exemplo n.º 16
0
from common import print_results, read


def is_triangle(possible_triangle):
    a, b, c = sorted(possible_triangle)
    return a + b > c


#### Main part.

sides = list(map(int, read(__file__).split()))

row_triangles = [sides[i:i + 3] for i in range(0, len(sides), 3)]

column_triangles = [
    sides[i + j:i + j + 7:3] for i in range(0, len(sides), 9) for j in range(3)
]

print_results(sum(is_triangle(triangle) for triangle in row_triangles),
              sum(is_triangle(triangle) for triangle in column_triangles))
Exemplo n.º 17
0
Arquivo: 4.py Projeto: bkachinthay/aoc
def passports(fname):
    return read(fname).split('\n\n')
Exemplo n.º 18
0
    return res


import os
MA = True
ma_length = 30
start_date = '2015-01-01'

#cityList = ['北京', '上海','深圳']
#cityList = ['北京']
data = {}
res = {}
districtRes = {}
for city in cityList:
    print(city)
    df = read(city)
    data[city] = df
    res[city] = plotCity(df, city)
    districtRes[city] = plotAllDistrict(df, city)
#计算城市排名
if not os.path.exists('fig/allcity'):
    os.makedirs('fig/allcity')
os.system('rm fig/allcity/*')


def makeTable(res, cityLevel='城市', cityName=None):
    print('compute change of', cityName)
    median = {}
    mean = {}
    yearChange = {}
    change = {}
Exemplo n.º 19
0
    # print(t, buses)
    mint, minb = min([(b - t % b, b) for b in buses])
    return mint * minb


def B(inp):
    t, buses = inp.strip().split('\n')
    buses = buses.strip().split(',')
    n = 0
    inc = 1
    # conditions = []
    for b, bi in zip(buses, range(len(buses))):
        if b != 'x':
            b = int(b)
            # conditions.append((b, bi))
            # while  any([(n % b1) != ((b1 - b1i) % b1) for b1, b1i in conditions]):
            while (n % b) != ((b - bi) % b):
                n += inc
            inc *= b
    return n


s1 = """939
7,13,x,x,59,x,31,19"""
assert A(s1) == 295
assert B(s1) == 1068781

if __name__ == '__main__':
    print(A(read('13.txt')))
    print(B(read('13.txt')))
Exemplo n.º 20
0
from common import print_results, read


def get_message(function, messages):
    return ''.join(map(lambda x: function(x, key=x.count), messages))


#### Main part.

flipped_messages = list(zip(*read(__file__).split()))

print_results(get_message(max, flipped_messages),
              get_message(min, flipped_messages))
Exemplo n.º 21
0
abbbbbabbbaaaababbaabbbbabababbbabbbbbbabaaaa
bbabbbbaabaabba
babbbbaabbbbbabbbbbbaabaaabaaa
aaabbbbbbaaaabaababaabababbabaaabbababababaaa
bbbbbbbaaaabbbbaaabbabaaa
bbbababbbbaaaaaaaabbababaaababaabab
ababaaaaaabaaab
ababaaaaabbbaba
baabbaaaabbaaaababbaababb
abbbbabbbbaaaababbbbbbaaaababb
aaaaabbaabaaaaababaa
aaaabbaaaabbaaa
aaaabbaabbaaaaaaabbbabbbaaabbaabaaa
babaaabbbaaabaababbaabababaaab
aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba"""

    # '8': [ '42', '42 42' ],
    # '11': [ '42 31', '42 42 31 31' ],
    # '8': [ '42' ],
    # '11': [ '42 31' ],
    # '42': 'a',
    # '31': 'b',

if __name__ == '__main__':
    t = time()
    # print('19', A(read('19.txt')))
    print('B : ', B(read('19.txt')))
    # print('B : ', B(s2))
    print('time : ', time() - t)
Exemplo n.º 22
0
Arquivo: 7.py Projeto: bkachinthay/aoc
            for bag, bc in content.items():
                frontier.append((bag, int(bc) * cf))
                bags_contained += int(bc) * cf
    return bags_contained


s1 = """light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
dark olive bags contain 3 faded blue bags, 4 dotted black bags.
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
faded blue bags contain no other bags.
dotted black bags contain no other bags."""

s2 = """shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags."""

assert A(s1, 'shinygold') == 4
assert B(s2, 'shinygold') == 126

if __name__ == '__main__':
    print(A(read('7.txt'), 'shinygold'))
    print(B(read('7.txt'), 'shinygold'))
Exemplo n.º 23
0
seat: 13-40 or 45-50

your ticket:
7,1,14

nearby tickets:
7,3,47
40,4,50
55,2,20
38,6,12"""

s2 = """class: 0-1 or 4-19
row: 0-5 or 8-19
seat: 0-13 or 16-19

your ticket:
11,12,13

nearby tickets:
3,9,18
15,1,5
5,14,9"""

assert (A(*parse(s1))) == 71

if __name__ == "__main__":
    # print(A(*parse(read('16.txt'))))
    print(B(*parse(read('16.txt'))))
    # print(B(*parse(s2)))
    # print(B(*parse(s1)))
Exemplo n.º 24
0
            d2 = deck2.pop(0)
        else:
            cache_deck1.add(join(deck1))
            cache_deck2.add(join(deck2))
            d1 = deck1.pop(0)
            d2 = deck2.pop(0)
            if d1 <= len(deck1) and d2 <= len(deck2):
                new_deck1, new_deck2 = _part2(deck1[:d1], deck2[:d2])
                if new_deck1:
                    winner = 1
                else:
                    winner = 2
            elif d1 > d2:
                winner = 1
            else:
                winner = 2
        if winner == 1:
            deck1 += [d1, d2]
        else:
            deck2 += [d2, d1]


inp = read('22.txt').strip()
print(part1(s))
print(part1(inp))
print('--- part 2 ---')
t = time()
# print(part2(s))
print(part2(inp))
print('time took ', time() - t)
Exemplo n.º 25
0
swweswneswnenwsewnwneneseenw
eesenwseswswnenwswnwnwsewwnwsene
sewnenenenesenwsewnenwwwse
wenwwweseeeweswwwnwwe
wsweesenenewnwwnwsenewsenwwsesesenwne
neeswseenwwswnwswswnw
nenwswwsewswnenenewsenwsenwnesesenew
enewnwewneswsewnwswenweswnenwsenwsw
sweneswneswneneenwnewenewwneswswnese
swwesenesewenwneswnwwneseswwne
enesenwswwswneneswsenwnewswseenwsese
wnwnesenesenenwwnenwsewesewsesesew
nenewswnwewswnenesenwnesewesw
eneswnwswnwsenenwnwnwwseeswneewsenese
neswnwewnwnwseenwseesewsenwsweewe
wseweeenwnesenwwwswnew""".strip()

inp = read('24.txt').strip()

# print(len([short_path(s) for s in ss.split('\n')]))
# print(([short_path(s) for s in ss.split('\n')]))
# print(key_cnt([short_path(s) for s in inp.split('\n')]))

# part 1
# print(black_tile_cnt(inp))

# part 2
t = time()
print(len(iterate(inp, 100)))
print('time : ', time()-t)
Exemplo n.º 26
0
def points(patched):
    return [(p[0], p[-1]) for p in patched]

def prod(nums):
    pr = 1
    for n in nums:
        pr *= int(n)
    return pr

# part A

# tiles = [parse_tile(t) for t in s.split('\n\n')]
# print(get_pos([tiles[5][0], tiles[5][1], 0, [0, 0]], tiles[2]))

tiles = [parse_tile(t) for t in read('20.txt').split('\n\n')]
# print(len(tiles), patch(tiles))
# t = time()
# t2 = time()
# print(prod(corners(points(patch(tiles)))))
# t3 = time()
# print('time took A: ', t3 - t)

def grange(rng):
    a,b = rng
    return range(a,b+1)

def patch_dict(patched):
    return {p[0]: p for p in patched}

def get_id(mapped, coord):