class Authenticate(ntuple('Authenticate', 'username password')): def __repr__(self): return "{}(username='******', password='******')".format( self.__class__.__name__, *self) def __call__(self): return HTTPBasicAuth(self.username, self.password)
def __init__(self, csvFileName): global csv, codecs, icu import csv import codecs try: import icu # sudo apt-get install libicu && pip install pyicu self.icuOk = True except ImportError: self.icuOk = False self.csvFileName = csvFileName self.fileSize = os.path.getsize(self.csvFileName) self.sampleSize = 2048 if self.fileSize > 2048 else self.fileSize self.fileEncoding_ = self._get_encoding(self.csvFileName) self.csvfile = codecs.open(self.csvFileName, "r+", self.fileEncoding) self.data = self.mapfile(self.csvfile) self.dialect = self._get_dialect(self.csvFileName, self.fileEncoding) self.varNames_ = self._get_header(self.csvFileName, self.fileEncoding, self.dialect) self.Shape = ntuple("Shape", ["nrows", "ncols"]) self.lookup = list() self.lookup_done = False self.thread = threading.Thread(target=self._get_row_lookup, args=(open(self.csvFileName, "rb"), ), name="lookup maker thread") self.thread.start()
def _get_shape(self, xlsfile): nrows, ncols = [], [] for sheet in self.xlsfile.sheets(): nrows.append(sheet.nrows) for row in xrange(sheet.nrows): ncols.append(sheet.ncols + 1) # + 1 for the sheetname itself nrows, ncols = sum(nrows), max(ncols) return ntuple("Shape", ["nrows", "ncols"])(nrows, ncols)
class Retrys(ntuple('Retrys', 'retries backoff httpcodes')): def __repr__(self): return "{}(retries={}, backoff={}, httpcodes={})".format( self.__class__.__name__, *self) def __new__(cls, retries=3, backoff=0.3, httpcodes=(500, 502, 504)): return super().__new__(cls, retries, backoff, httpcodes) def __call__(self): retry = Retry(total=self.retries, read=self.retries, connect=self.retries, backoff_factor=self.backoff, status_forcelist=self.httpcodes) adapter = HTTPAdapter(max_retries=retry) return adapter
def execute_obj(conn, *args, **kwds): """ Run a query on the given connection or cursor and yield ntuples of the results. 'curs' can be either a Connection or a Cursor object. """ # Convert to a cursor if necessary. if re.search('Cursor', conn.__class__.__name__, re.I): curs = conn else: curs = conn.cursor() # Execute the query. execute_f(curs, *args, **kwds) # Yield all the results wrapped up in an ntuple. names = map(itemgetter(0), curs.description) TupleCls = ntuple('Row', ' '.join(names)) return starmap(TupleCls, imap(tuple, curs))
class WebLocator(ntuple('WebLocator', 'filtration attribute function')): def __init__(self, *args, **kwargs): pass def __call__(self, webcontent, *args, **kwargs): assert isinstance(webcontent, (WebContent, WebData)) located = webcontent for key in self.filtration: located = located.children[key] try: attribute = getattr(located, self.attribute) except EmptyWebDataError: return None if self.function: return attribute(*args, **kwargs) else: return attribute @classmethod def fromstr(cls, string): try: filtration, attribute = string.split(".") except ValueError: filtration, attribute = [], string if str(attribute).endswith("()"): attribute, function = str(attribute).replace("()", ""), True else: attribute, function = attribute, False if filtration: filtration = filtration.split("/") return cls(filtration, attribute, function)
def get_hash(fp): md5 = hashlib.md5() sha1 = hashlib.sha1() sha256 = hashlib.sha256() sha512 = hashlib.sha512() Hash = ntuple('hash', ['md5', 'sha1', 'sha256', 'sha512']) with open(fp, 'rb') as fb: while True: blk = fb.read(8192) # 8KB per block if not blk: break md5.update(blk) sha1.update(blk) sha256.update(blk) sha512.update(blk) return Hash(md5.hexdigest(), sha1.hexdigest(), sha256.hexdigest(), sha512.hexdigest())
class Realtor_Location(ntuple("Location", "state city neighborhood")): def __new__(cls, *args, **kwargs): if args: values = _padding( [arg for arg in args if not str(arg).endswith(" County")], 3, None) else: values = [kwargs.get(field, None) for field in cls._fields] return super().__new__(cls, *values) def __hash__(self): return hash(tuple(self)) def __str__(self): return "|".join([value for value in self if not _missing(value)]) def __repr__(self): return "{}({})".format( self.__class__.__name__, ", ".join( ["=".join([key, value]) for key, value in self._asdict()])) def keys(self): return self._asdict().keys() def values(self): return self._asdict().values() def items(self): return self._asdict().items() def todict(self): return self._asdict() @classmethod def fromstr(cls, string): return cls(*string.split("|"))
class Space(ntuple('Space', 'bed bath sqft lotsqft lotacre')): pattern = r"[\d,\.\-\+]+[a-z]+" delimiter = r"|" def __repr__(self): return "{}({})".format( self.__class__.__name__, ', '.join([ '='.join([key, value]) for key, value in self.todict().items() ])) def __str__(self): return self.delimiter.join([ " ".join([str(value), key]) for key, value in self.todict().items() if value is not None ]) def todict(self): return ODict([(field, getattr(self, field)) for field in self._fields]) def __new__(cls, items): assert isinstance(items, dict) bed = items.get( 'bed', items.get('beds', items.get('bds', items.get('bd', None)))) bath = items.get( 'bath', items.get('baths', items.get('bas', items.get('ba', None)))) sqft = items.get('sqft', None) lotsqft = items.get('lotsqft', items.get('sqftlot', None)) lotacre = items.get( 'lotacre', items.get( 'acrelot', items.get('acreslot', items.get('acre', items.get('acres', None))))) return super().__new__(cls, bed, bath, sqft, lotsqft, lotacre) @classmethod def fromstr(cls, string): if not string: return None if string is np.NaN: return None if not isinstance(string, str): raise TypeError("{}({})".format(type(string).__name__, string)) items = { key: value for strings in string.split(cls.delimiter) for key, value in strings.split(' ') } return cls(items) @classmethod def fromsearch(cls, string): if not string: return None if string is np.NaN: return None if not isinstance(string, str): raise TypeError("{}({})".format(type(string).__name__, string)) string = string.replace("\n", "").replace(" ", "").replace('Studio', '0') strings = re.findall(cls.pattern, string) content = { re.search("[a-z]+", string).group(): string.replace(re.search("[a-z]+", string).group(), '') for string in strings } content = { key: value for key, value in content.items() if value != '--' } return cls(content)
num_pos = obj_rem.end() num_pos1 = obj_rem.start() lst_ret.append(str_line_i[num_pos0:num_pos1]) else: if obj_rem is None: lst_ret.append(float(str_line_i[num_pos:])) break else: num_pos = obj_rem.end() num_pos1 = obj_rem.start() lst_ret.append(float(str_line_i[num_pos0:num_pos1])) return lst_ret TZbxEdge = ntuple('TZbxEdge', ['icon', 'edge_d']) TZbxShape = ntuple('TZbxShape', ['x', 'y', 'width', 'height']) TGraph = ntuple('TGraph', ['width', 'height', 'node_l', 'edge_l']) TGNode = ntuple('TGNode', ['name', 'xpoint', 'ypoint', 'width', 'height', 'label', 'zbx_hostid', 'zbx_edge']) TGEdge = ntuple('TGEdge', ['tail', 'head']) def input_parse(i_dct_opt: dict) -> object: dct_opt = i_dct_opt with open(dct_opt['file_json_path'], 'r+t') as rd_js: dct_cnn: dict = m_json.load(rd_js)
from collections import namedtuple as ntuple import pygame import math PixelSize = ntuple('PixelSize', 'w h') class Bullets(pygame.sprite.Group): def __init__(self,sprite=()): pygame.sprite.Group.__init__(self,sprite) def update(self,milliseconds): self.CheckSpriteCollisions() pygame.sprite.Group.update(self,milliseconds) def CheckSpriteCollisions(self): for sprite in self.sprites(): self.colliding = False for sprite1 in self.sprites(): for sprite2 in self.sprites(): if sprite1!=sprite2: diff_vec = AddVector(sprite1.pos,MultiplyVector(sprite2.pos,-1.)) r = Magnitude(diff_vec) if r<(float(sprite1.radius)+float(sprite2.radius)): sprite1.Collision(sprite2) else: continue else: continue class Bullet(pygame.sprite.Sprite): screen_size = PixelSize(640,480) speed = 0.5 size = PixelSize(10,10) def __init__(self, surface, origin_pos ,mouse_pos ): pygame.sprite.Sprite.__init__(self) self.image = surface
# Пользователь вводит данные о количестве предприятий, их наименования и прибыль # за 4 квартала (т.е. 4 отдельных числа) для каждого предприятия.. Программа # должна определить среднюю прибыль (за год для всех предприятий) и вывести # наименования предприятий, чья прибыль выше среднего и отдельно вывести # наименования предприятий, чья прибыль ниже среднего. from collections import namedtuple as ntuple Record = ntuple('Record', ['name', 'income']) # Префабы компаний c1 = Record("П. Шуйлер и сыновья", [15, 13, 10, 16]) c2 = Record("Umbrella", [16, 20, 4, 1]) c3 = Record("Камино", [4, 4, 4, 31]) sheet = [c1, c2, c3] # comp_count = int(input('Введите кол-во предприятий: ')) # sheet = [] # for i in range(comp_count): # input_str = input('Введите название предприятия и доход за 4 квартала: ').split() # comp_name = ' '.join(input_str[:-4]) # comp_income = list(map(float, input_str[-4:])) # sheet.append(Record(comp_name, comp_income)) medial = sum([sum(x.income) for x in sheet]) / len(sheet) print('Средняя прибыль за год для всех предприятий:', medial) print('Выше/равна среднего прибыль у компаний:') for x in filter(lambda x: sum(x.income) >= medial, sheet): print('\t', x.name)
from os.path import join as pathjoin, exists from pint import UnitRegistry from pprint import pprint as pp, pformat as pf from subprocess import Popen, PIPE from sys import stdout, exc_info try: from cPickle import dump, load except ImportError: from pickle import dump, load NL = '\n' TAB = '\t' quiet = False Bbox = ntuple('Bbox', 'x0 y0 x1 y1') def merge(bb1, bb2): return Bbox(min(bb1.x0, bb2.x0), min(bb1.y0, bb2.y0), max(bb1.x1, bb2.x1), max(bb1.y1, bb2.y1)) def numerify(s): try: return int(''.join(d for d in s if d.isdigit())) except ValueError: return s def compactify(multilineRegex):
import os, sys, pygame import time import math from collections import namedtuple as ntuple from Bullets import Bullets,Bullet,Magnitude #pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag pygame.init() # Set up some useful named tuples to hold data PixelPos = ntuple('PixelPos', 'x y') PixelSize = ntuple('PixelSize', 'w h') RGB = ntuple('RGB', 'r g b') # initialize some global varables with magic numbers SCREENSIZE = PixelSize(640, 480) #SCREENSIZE = PixelSize(200, 150) HEROSIZE = PixelSize(75,75) BULLETSIZE = PixelSize(20,20) CURSORRADIUS = BULLETSIZE.h/2 HEROORIGIN = PixelPos(SCREENSIZE.w/2,SCREENSIZE.h) BULLETORIGIN = PixelPos(HEROORIGIN.x,HEROORIGIN.y-BULLETSIZE.h/2) BKGCOLOUR = RGB(0, 0, 0) LINECOLOUR = RGB(20, 200, 20) CURSORCOLOUR = RGB(255, 0, 0) MAXFPS = 100 FONTSIZE = 16 BULLETSPEED = 0.2 STATS = False powerball = 2.5
nm_pos = ob_rem.end() nm_pos1 = ob_rem.start() cl_ret.append(i_tx_line[nm_pos0:nm_pos1]) else: if ob_rem is None: cl_ret.append(float(i_tx_line[nm_pos:])) break else: nm_pos = ob_rem.end() nm_pos1 = ob_rem.start() cl_ret.append(float(i_tx_line[nm_pos0:nm_pos1])) return cl_ret СZbxEdge = ntuple('TZbxEdge', ['icon', 'edge_d']) СZbxShape = ntuple('TZbxShape', ['x', 'y', 'width', 'height']) СGraph = ntuple('TGraph', ['width', 'height', 'node_l', 'edge_l']) СGNode = ntuple('TGNode', [ 'name', 'xpoint', 'ypoint', 'width', 'height', 'label', 'zbx_hostid', 'zbx_edge' ]) СGEdge = ntuple('TGEdge', ['tail', 'head']) def _input_parse(i_kv_opt: dict) -> object: kv_opt = i_kv_opt
"""" funkcje programu """ from collections import namedtuple as ntuple Person = ntuple('Person', 'fname lname age profession') Position = ntuple('Position', ['x', 'y', 'z']) def add_new_person(): """ asks for input data for each person :return: person """ fname = input('First name: ') lname = input('Last name: ') while True: if fname == '': age = '0' break try: age = int(input('Age: ')) age = str(age) break except ValueError: print('Try to type integer!') if fname != '': profession = input('Profession: ') else: profession = '' fname = fname.capitalize() # pierwsza litera wielka
from collections import namedtuple as ntuple from Bullets import Bullets, Bullet, Magnitude try: f = open("scores.txt", "r") scores = f.readlines() scores = [int(s) for s in scores] f.close() except: scores = [] #pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag pygame.init() # Set up some useful named tuples to hold data PixelPos = ntuple('PixelPos', 'x y') PixelSize = ntuple('PixelSize', 'w h') RGB = ntuple('RGB', 'r g b') # initialize some global varables with magic numbers SCREENSIZE = PixelSize(800, 600) #SCREENSIZE = PixelSize(200, 150) HEROSIZE = PixelSize(70, 70) BULLETSIZE = PixelSize(12, 12) CURSORRADIUS = BULLETSIZE.h / 1 HEROORIGIN = PixelPos(SCREENSIZE.w / 2, SCREENSIZE.h) BULLETORIGIN = PixelPos(HEROORIGIN.x, HEROORIGIN.y - BULLETSIZE.h / 2) BKGCOLOUR = RGB(0, 0, 0) LINECOLOUR = RGB(0, 255, 255) CURSORCOLOUR = RGB(255, 255, 0) MAXFPS = 100
class Location(ntuple('Location', 'state county city neighborhood')): formatting = "{state}, {county}, {city}, {neighborhood}" pattern = r"(?P<state>[a-zA-Z]+), (?P<county>[\-\&\d\w .]*), (?P<city>[\-\&\d\w .]*), (?P<neighborhood>[\-\&\d\w .\/]*)" def __repr__(self): return "{}({})".format( self.__class__.__name__, ', '.join([ '='.join([key, value]) for key, value in self.todict().items() ])) def __str__(self): return self.formatting.format(**{ key: (value if value else "") for key, value in self.todict().items() }).strip() def todict(self): return ODict([(field, getattr(self, field)) for field in self._fields]) def __new__(cls, items): if isinstance(items, (tuple, list)): return super().__new__(cls, *cls.__fromlist(*items)) elif isinstance(items, dict): return super().__new__(cls, *cls.__fromdict(**items)) else: raise ValueError(items) @classmethod def __fromlist(cls, *args): args = list(args) state = args.pop(0) state = STATES.get(state, state) if state not in STATES.values(): WebVariableError(cls.__name__, args) if str(args[0]).endswith(' County'): county = args.pop(0) else: county = None city = args.pop(0) try: neighborhood = args.pop(0) except IndexError: neighborhood = None return (state, county, city, neighborhood) @classmethod def __fromdict(cls, **kwargs): state = kwargs.get('state', None) state = STATES.get(state, state) if state not in STATES.values(): WebVariableError(cls.__name__, kwargs) county = kwargs.get('county', None) city = kwargs.get('city', None) neighborhood = kwargs.get('neighborhood', None) return (state, county, city, neighborhood) @classmethod def fromsearch(cls, string): if not string: return None if string is np.NaN: return None if not isinstance(string, str): raise TypeError("{}({})".format(type(string).__name__, string)) fixedstring = string.strip().replace('\n', ', ') content = re.search(cls.pattern, fixedstring) if content is None: raise WebVariableError(cls.__name__, string) content = content.groupdict() if not content: raise WebVariableError(cls.__name__, string) return cls(content)
class Address(ntuple('Address', 'name street city state zipcode')): formatting = "{name}| {street}, {city}, {state}, {zipcode}" pattern = r"(?P<name>[\-\&\d\w \#\.]*)| (?P<street>[\-\&\d\w \#\.]*), (?P<city>[\-\&\d\w #.]*), (?P<state>[A-Z]{2})(, | )(?P<zipcode>[0-9]{5})" def __repr__(self): return "{}({})".format( self.__class__.__name__, ', '.join([ '='.join([key, str(value)]) for key, value in self.todict().items() ])) def __str__(self): string = self.formatting.format(**{ key: (value if value else "") for key, value in self.todict().items() }).strip() string = re.sub("^\| ", "", string) string = re.sub("^\, ", "", string) return string def todict(self): return ODict([(field, getattr(self, field)) for field in self._fields]) def __new__(cls, items): assert isinstance(items, dict) name = items.get('name', None) street = items.get('street', None) city = items.get('city', None) state = items.get('state', None) zipcode = items.get('zipcode', None) zipcode = '{:05}'.format(int(zipcode)) if zipcode else None return super().__new__(cls, name, street, city, state, zipcode) @classmethod def fromstr(cls, string): if not string: return None if string is np.NaN: return None if not isinstance(string, str): raise TypeError("{}({})".format(type(string).__name__, string)) try: name, address = string.split("| ") except ValueError: name, address = None, string try: street, city, state, zipcode = address.split(", ") except ValueError: try: street, (city, state, zipcode) = None, address.split(", ") except ValueError: try: street, city, (state, zipcode) = None, None, address.split(", ") except ValueError: raise WebVariableError(cls.__name__, string) return cls({ 'name': str(name).strip(), 'street': str(street).strip(), 'city': str(city).strip(), 'state': str(state).strip(), 'zipcode': str(zipcode).strip() }) @classmethod def fromsearch(cls, string): if not string: return None if string is np.NaN: return None if not isinstance(string, str): raise TypeError("{}({})".format(type(string).__name__, string)) fixedstring = re.sub( " +", " ", string.strip().replace("\n", ", ").replace("\r", ", ")) fixedstring = re.sub(",+", ",", fixedstring) fixedstring = re.sub("(, )+", ", ", fixedstring) fixedstring = re.sub(" [^0-7a-zA-z,]+,", "", fixedstring) if not re.findall("[A-Z]{2},? [0-9]{5}", fixedstring): raise WebVariableError(cls.__name__, string) fixedstring = re.findall(".* [A-Z]{2},? [0-9]{5}", fixedstring)[0] state_zipcode = re.findall("[A-Z]{2},? [0-9]{5}", fixedstring)[-1] state, zipcode = re.split(",? ", state_zipcode) if not re.findall("[A-Z]{2}", state): raise WebVariableError(cls.__name__, string) if not re.findall("[0-9]{5}", zipcode): raise WebVariableError(cls.__name__, string) name_street_city = fixedstring.split(state_zipcode)[-2].split(",")[:-1] try: city = name_street_city.pop(-1).strip() except IndexError: return cls({ 'name': None, 'street': None, 'city': None, 'state': state, 'zipcode': zipcode }) try: street = name_street_city.pop(-1).strip() except IndexError: return cls({ 'name': None, 'street': None, 'city': city, 'state': state, 'zipcode': zipcode }) if not name_street_city: return cls({ 'name': None, 'street': street, 'city': city, 'state': state, 'zipcode': zipcode }) else: name = "-".join(name_street_city) return cls({ 'name': name, 'street': street, 'city': city, 'state': state, 'zipcode': zipcode })
class Price(ntuple('Price', 'lower upper')): pattern = r"\$(?P<lower>[\d\,]+)\-\$(?P<upper>[\d\,]+)[a-z \/]*|\$(?P<more>[\d\,]+)\+[a-z\/]*|\$(?P<state>[\d\,]+)[a-z\/]*" formatting = { 'range': '${lower:,.0f}|${upper:,.0f}', 'state': '${lower:,.0f}', 'more': '>${lower:,.0f}', 'less': '<${upper:,.0f}' } delimiter = '|' def __repr__(self): return "{}({})".format( self.__class__.__name__, ', '.join([ '='.join([key, value]) for key, value in self.todict().items() ])) def __str__(self): return self.formatting[self.direction].format(**self.todict()) def todict(self): return ODict([('lower', self.lower), ('upper', self.upper)]) @property def direction(self): if self.upper != None and self.lower != None: if self.upper == self.lower: return 'state' else: return 'range' elif self.lower != None: return 'more' elif self.upper != None: return 'less' else: raise ValueError(repr(self)) def __new__(cls, items): if isinstance(items, (tuple, list)): contents = cls.__fromlist(*items) elif isinstance(items, dict): contents = cls.__fromdict(**items) else: raise ValueError("{}.__new__({})".format(cls.__name__, items)) return super().__new__(cls, *contents) @classmethod def __fromlist(cls, *args): if len(args) == 0: raise WebVariableError(cls.__name__, args) elif len(args) == 1: return (args[0], args[0]) elif len(args) == 2: return (args[0], args[1]) else: raise WebVariableError(cls.__name__, args) @classmethod def __fromdict(cls, **kwargs): try: return (kwargs['lower'], kwargs['upper']) except KeyError: try: return (kwargs['state'], kwargs['state']) except KeyError: try: return (kwargs['more'], None) except KeyError: raise WebVariableError(cls.__name__, kwargs) @classmethod def fromstr(cls, string): if not string: return None if string is np.NaN: return None if not isinstance(string, str): raise TypeError("{}({})".format(type(string).__name__, string)) if '<' in string: contents = cls(parse(cls.formatting['less'], string).fixed) elif '>' in string: contents = cls(parse(cls.formatting['more'], string).fixed) elif cls.delimiter in string: contents = cls(parse(cls.formatting['range'], string).fixed) else: contents = cls(parse(cls.formatting['state'], string).fixed) return cls({ key: int(value.replace(',', '')) for key, value in contents.items() if value is not None }) @classmethod def fromsearch(cls, string): if not string: return None if string == np.NaN or string == np.nan: return None if str(string) == 'nan' or str(string) == 'NaN': return None if not isinstance(string, str): raise TypeError("{}({})".format(type(string).__name__, string)) if not str(string): return None if str(string).lower().strip() == 'price unavailable': return None if str(string).lower().strip() == 'contact for price': return None if str(string).lower().strip() == '---': return None if str(string).lower().strip() == '—': return None if str(string).lower().strip() == '-': return None if str(string).lower().strip() == 'n/a': return None if str(string).lower().strip() == 'price not available': return None if str(string).lower().strip() == 'call for rent': return None contents = re.search(cls.pattern, string) if contents is None: raise WebVariableError(cls.__name__, string) else: contents = contents.groupdict() if not contents: raise WebVariableError(cls.__name__, string) return cls({ key: int(value.replace(',', '')) for key, value in contents.items() if value is not None })
# Some named tuples and other small objects that will come in handy in many areas # and I don't want to keep defining them in many places from collections import namedtuple as ntuple rgb = ntuple('RGB', 'r g b') PixelSize = ntuple('PixelSize', 'w h') PixelPos = ntuple('PixelPos', 'x y') Coord = ntuple('Coord', 'x y')
from collections import namedtuple as ntuple import pygame import math PixelSize = ntuple('PixelSize', 'w h') class Bullets(pygame.sprite.Group): def __init__(self, sprite=()): pygame.sprite.Group.__init__(self, sprite) def update(self, milliseconds): self.CheckSpriteCollisions() pygame.sprite.Group.update(self, milliseconds) def CheckSpriteCollisions(self): for sprite in self.sprites(): self.colliding = False for sprite1 in self.sprites(): for sprite2 in self.sprites(): if sprite1 != sprite2: diff_vec = AddVector(sprite1.pos, MultiplyVector(sprite2.pos, -1.)) r = Magnitude(diff_vec) if r < (float(sprite1.radius) + float(sprite2.radius)): sprite1.Collision(sprite2) else: continue else: continue