replaced more maps/filters with list comprehensions

master
idziubenko 3 years ago
parent b315b446dc
commit 4ec63ecbe9

@ -203,11 +203,8 @@ class iniParser(_error):
иначе - True
"""
if textIni.strip():
# if list(filter(lambda x: x.strip(),
# map(lambda x: x[0].split(";")[0],
# map(lambda x: x.split("#"),
# textIni.splitlines())))):
if [x for x in [y[0].split(";")[0] for y in [z.split("#") for z in textIni.splitlines()]] if x.strip()]:
if [x for x in [y[0].split(";")[0] for y in [z.split("#") for z
in textIni.splitlines()]] if x.strip()]:
return False
else:
return True

@ -236,7 +236,7 @@ class ldapUser(_error):
return self._dictData
file_name = "/etc/ldap.conf"
get_str_list = lambda x: reduce(lambda x, y: [x, y.upper()], ([x] * 2))
workdata = map(lambda x: (x[0], get_str_list(x[1]), len(x[1])), data)
workdata = [(x[0], get_str_list(x[1]), len(x[1])) for x in data]
dict_data = defaultdict(list)
delimeter = (" ", "\t")
try:

@ -473,9 +473,9 @@ class _terms(_error, _shareTermsFunction, _shareTemplate):
def fillSuffix(elemA, elemB, sA, svA, sB, svB):
if str(sA) or str(sB):
svA, svB = map(lambda x: [x] if x else ['0'], (svA, svB))
svA, svB = [[x] if x else ['0'] for x in (svA, svB)]
fillZero(svA, svB)
sA, sB = map(lambda x: x if x else 0, (sA, sB))
sA, sB = [x if x else 0 for x in (sA, sB)]
elemA.append(str(self._lenSuffixDict + sA))
elemA.extend(svA)
elemB.append(str(self._lenSuffixDict + sB))
@ -488,7 +488,7 @@ class _terms(_error, _shareTermsFunction, _shareTemplate):
elemB = vB.split(".")
fillZero(elemA, elemB)
if lA or lB:
lA, lB = map(lambda x: x if x else '0', (lA, lB))
lA, lB = [x if x else '0' for x in (lA, lB)]
elemA.append(lA)
elemB.append(lB)
@ -506,7 +506,7 @@ class _terms(_error, _shareTermsFunction, _shareTemplate):
fillSuffix(elemA, elemB, "", "", sB, svB)
if rvA or rvB:
rvA, rvB = map(lambda x: [x[1:]], (rvA, rvB))
rvA, rvB = [[x[1:]] for x in (rvA, rvB)]
fillZero(rvA, rvB)
elemA += rvA
elemB += rvB
@ -792,7 +792,7 @@ class _terms(_error, _shareTermsFunction, _shareTemplate):
"""
def splitQuote(listPar, quoteSymbol):
listTerm = map(lambda x: x + quoteSymbol, ("=", ">", "<"))
listTerm = [x + quoteSymbol for x in ("=", ">", "<")]
flagQ = False
mass = []
v = ""
@ -1944,7 +1944,7 @@ def template_function(lastall=False):
# число обязательных параметров
reqnum = varnum - defnum
if funArgv:
terms = map(lambda x: x.strip(), funArgv.split(","))
terms = [x.strip() for x in funArgv.split(",")]
else:
terms = []
@ -2075,13 +2075,12 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction,
if not self.templateFunction:
# префикс функций шаблона
pref = "func"
# cписок [(название функции, функция), ...]
dictFunc = filter(lambda x: x[0].startswith(pref) and \
hasattr(x[1], "__call__"),
self.__class__.__dict__.items())
# cписок [(название функции, функция), ...]
# удаляем у названия функции префикс и переводим остаток названия
# в нижний регистр
dictFunc = map(lambda x: (x[0][len(pref):].lower(), x[1]), dictFunc)
dictFunc = [(x[0][len(pref):].lower(), x[1]) for x
in self.__class__.__dict__.items()
if x[0].startswith(pref) and hasattr(x[1], "__call__")]
# Формируем словарь функций шаблона
self.templateFunction.update(dictFunc)
# Формируем список функций шаблона
@ -2391,7 +2390,7 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction,
если второй параметр root, то проверка осуществляется от корня.
"""
if funArgv.strip():
terms = map(lambda x: x.strip(), funArgv.split(","))
terms = [x.strip() for x in funArgv.split(",")]
if len(terms) > 2:
raise self.raiseErrTemplate()
fileName = terms[0]
@ -2480,8 +2479,7 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction,
if os.path.exists(fileName):
replace = readFile(fileName).strip()
if replace and lenTerms >= 2 and terms[0] == "empty":
replace = "\n".join(filter(lambda x: not self.reEmptyLoad.search(x),
replace.split("\n")))
replace = "\n".join((x for x in replace.split("\n") if not self.reEmptyLoad.search(x)))
if not replace and lenTerms >= 2 and terms[0] in ["ver", "num"]:
replace = "0"
textTemplateTmp = textTemplateTmp[:resS.start()] + replace + \
@ -3050,12 +3048,8 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction,
_("the first parameter must be the resolution"))
re_resol = re.compile(r".*?(\d+)x(\d+).*")
# res = list(map(lambda x: (int(x.group(1)), int(x.group(2)), x.group()),
# filter(None,
# map(re_resol.search,
# listDirectory(wpath)))))
res = [(int(x.group(1)), int(x.group(2)), x.group()) for x in
[re_resol.search(z) for z in listDirectory(wpath)] if x]
[re_resol.search(y) for y in listDirectory(wpath)] if x]
width = int(resol.group(1))
height = int(resol.group(2))
gep = sqrt(height ** 2 + width ** 2)
@ -3232,7 +3226,7 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction,
raise self.raiseErrTemplate()
return listArgv
terms = map(lambda x: x.strip(), funArgv.split(","))
terms = [x.strip() for x in funArgv.split(",")]
if len(terms) != 3:
raise self.raiseErrTemplate()
listArgv = getStrArgv(terms[:2])
@ -3325,7 +3319,7 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction,
"""Функция шаблона groups(),
проверяет нахождение пользователя в группах, если находится выдает '1'
"""
terms = map(lambda x: x.strip(), funArgv.split(","))
terms = [x.strip() for x in funArgv.split(",")]
groupNames = set(terms)
userGroups = set(self.groups)
replace = ""
@ -3768,11 +3762,9 @@ class ChangedFiles(object):
return self.pkgs
def getPkgFiles(self, pkg):
return map(lambda x: (x[0], x[1][0][1]),
filter(lambda x: x[1],
map(lambda x: (
x[0], filter(lambda x: x[0] == pkg, x[1])),
self.data.items())))
return [(x[0], x[1][0][1]) for x
in [(y[0], [z for z in y[1] if z[0] == pkg]) for y
in self.data.items()] if x[1]]
# modes work with configuration file
# T_ORIGIN - work with original config file
@ -4538,10 +4530,6 @@ gettext -d cl_template "$*"
filename = PkgContents.reCfg.sub("/", filename)
if not filename in self.cltObj.filterApplyTemplates:
self.cltObj.filterApplyTemplates[filename] = []
# pkgs = list(filter(
# lambda x: x not in
# self.cltObj.filterApplyTemplates[filename],
# list(map(lambda x: x[0], pkgs))))
pkgs = [x for x in [z[0] for z in pkgs]
if x not in self.cltObj.filterApplyTemplates[filename]]
self.cltObj.filterApplyTemplates[filename].extend(pkgs)
@ -4686,8 +4674,8 @@ gettext -d cl_template "$*"
elif action in (ChangedFiles.FILE_REMOVED,
ChangedFiles.DIR_REMOVED):
pkgContents.removeObject(filename)
files = set(map(lambda x: pathJoin(chrootPath, x),
pkgContents.content.keys()) + protected)
files = set([pathJoin(chrootPath, x) for x
in pkgContents.content.keys()] + protected)
if (self.objVar.Get('cl_dispatch_conf') != 'usenew' and
self.objVar.Get('cl_autoupdate_set') != "on"):
notUpdate = files - set(self.autoUpdateFiles)
@ -4844,8 +4832,8 @@ gettext -d cl_template "$*"
return False
nameFileConfig = path.partition(prefix)[2]
# файл в системе без условий
nameFileConfig = "/".join(map(lambda x: x.split("?")[0],
nameFileConfig.split("/")))
nameFileConfig = "/".join((x.split("?")[0] for x in nameFileConfig.split("/")))
# Записываем в переменную обрабатываемый файл
self.objVar.Set("cl_pass_file", os.path.basename(nameFileConfig))
self.headerParams = None
@ -4877,7 +4865,7 @@ gettext -d cl_template "$*"
return None
dirInfoFile = os.path.join(path, self.templDirNameFile)
newDir = pathJoin(self._baseDir, path.partition(prefix)[2])
newDir = "/".join(map(lambda x: x.split("?")[0], newDir.split("/")))
newDir = "/".join((x.split("?")[0]) for x in newDir.split("/"))
# Применяем шаблон
pathDir, objHeadDir, createdDirs = \
self.getApplyHeadDir(newDir, dirInfoFile, opt)
@ -5364,11 +5352,9 @@ gettext -d cl_template "$*"
passwdFile = os.path.join(self._baseDir, 'etc/passwd')
if os.path.exists(passwdFile):
with open(passwdFile, 'r') as f:
mapUid = dict(
filter(lambda x: x and len(x) > 1 and x[0] and x[1],
map(lambda x: x.split(':')[0:3:2],
filter(lambda x: not x.startswith('#'),
f))))
mapUid = dict([x for x in [y.split(':')[0:3:2] for y
in f if not y.startswith('#')]
if x and len(x) > 1 and x[0] and x[1]])
if strUid in mapUid:
return int(mapUid[strUid])
return None
@ -5378,11 +5364,9 @@ gettext -d cl_template "$*"
groupFile = os.path.join(self._baseDir, 'etc/group')
if os.path.exists(groupFile):
with open(groupFile, 'r') as f:
mapGid = dict(
filter(lambda x: x and len(x) > 1 and x[0] and x[1],
map(lambda x: x.split(':')[0:3:2],
filter(lambda x: not x.startswith('#'),
f))))
mapGid = dict([x for x in [y.split(':')[0:3:2] for y
in f if not y.startswith('#')]
if x and len(x) > 1 and x[0] and x[1]])
if strGid in mapGid:
return int(mapGid[strGid])
return None
@ -5393,14 +5377,8 @@ gettext -d cl_template "$*"
"""
# if file in PROTECT_MASK or not in PROTECT
chrootPath = self.objVar.Get('cl_chroot_path')
# if not list(filter(pathFile.startswith,
# map(lambda x: pathJoin(chrootPath, x),
# self.objVar.Get('cl_config_protect')))) or \
# list(filter(pathFile.startswith,
# map(lambda x: pathJoin(chrootPath, x),
# self.objVar.Get('cl_config_protect_mask')))):
if not [x for x in [pathJoin(chrootPath, y) for y in self.objVar.Get('cl_config_protect')] if pathFile.startswith(x)] or \
[x for x in [pathJoin(chrootPath, y) for y in self.objVar.Get('cl_config_protect_mask')] if pathFile.startswith(x)]:
[x for x in [pathJoin(chrootPath, y) for y in self.objVar.Get('cl_config_protect_mask')] if pathFile.startswith(x)]:
return pathFile
# if file was already modified by templates
if pathFile in self.changedFiles.data.keys():
@ -5916,7 +5894,7 @@ gettext -d cl_template "$*"
or HParams.Autoupdate in objHeadNew.params) and
not self.objVar.Get('cl_merge_pkg_pass')):
reCfg = re.compile(r"/._cfg\d{4}_", re.S)
self.autoUpdateFiles += map(lambda x: reCfg.sub('/', x), applyFiles)
self.autoUpdateFiles += [reCfg.sub('/', x) for x in applyFiles]
if pathOldFile not in self.dictProcessedTemplates:
self.dictProcessedTemplates[pathOldFile] = []
self.dictProcessedTemplates[pathOldFile].append(nameFileTemplate)
@ -6616,8 +6594,7 @@ class templateClt(scanDirectoryClt, Template):
origFileName = nameFileConfig
nameFileConfig = pathJoin(self._baseDir, nameFileConfig)
# файл в системе без условий
nameFileConfig = "/".join(map(lambda x: x.split("?")[0],
nameFileConfig.split("/")))
nameFileConfig = "/".join((x.split("?")[0] for x in nameFileConfig.split("/")))
# Записываем в переменную обрабатываемый файл
self.objVar.Set("cl_pass_file", os.path.basename(nameFileConfig))
self.headerParams = None

@ -709,7 +709,8 @@ class xmlDoc(object):
namesAreaComare = xpath.Evaluate(
"child::area/child::caption[child::name='%s']" % nameArea,
xmlArea)
return map(lambda x: x.getparent(), namesAreaComare)
return [x.getparent() for x in namesAreaComare]
def joinArea(self, baseNode, xmlNewArea):
"""Объединяет область c областью Body (xmlNewArea c baseNode)"""

@ -338,11 +338,8 @@ class Variable(VariableInterface):
"""
if "humanreadable" in kw:
hr = kw['humanreadable']
# return list(zip(*map(lambda x:self.Get(x, humanreadable=hr),
# argvVarNames)))
return list(zip(*[self.Get(x, humanreadable=hr) for x in argvVarNames]))
return list(zip(*(self.Get(x, humanreadable=hr) for x in argvVarNames)))
else:
# return list(zip(*map(self.Get, argvVarNames)))
return list(zip(*map(self.Get, argvVarNames)))
def _get_format_value(self):
@ -531,7 +528,7 @@ class Variable(VariableInterface):
if self.type == "bool":
value = "on" if self.isTrue(value) else "off"
if "bool" in self.type and "list" in self.type:
return map(convert, value)
return [convert(x) for x in value]
if "int" in self.type:
return str(value)
return value
@ -574,8 +571,6 @@ class Variable(VariableInterface):
if isinstance(choiceVal, GeneratorType):
choiceVal = tuple(choiceVal)
# tipChoice = map(lambda x: '"%s" [%s]' % (x[1], x[0]) \
# if type(x) in (list, tuple) else str(x), choiceVal)
tipChoice = ['"%s" [%s]' % (x[1], x[0]) if type(x) in (list, tuple) else str(x) for x in choiceVal]
if choiceVal and type(choiceVal[0]) in (tuple, list):
choiceVal = [x[0] for x in choiceVal]
@ -711,15 +706,9 @@ class TableVariable(Variable):
def get(self, hr=HumanReadable.No):
"""Get table data"""
for varname, value in filter(lambda x: type(x[1]) != list,
map(lambda x: (x, self.Get(x)),
self.source)):
for varname, value in (x for x in ((y, self.Get(y)) for y in self.source) if type(x[1]) != list):
raise VariableError(
_("Source variable %s does not contain a list") % varname)
# return list(map(list,
# zip_longest(
# *map(lambda x: self.Get(x, humanreadable=hr),
# self.source), fillvalue=''))) or [[]]
return [list(x) for x in zip_longest(*[self.Get(x, humanreadable=hr)
for x in self.source], fillvalue='')] or [[]]
@ -850,9 +839,7 @@ class TableVariable(Variable):
else:
oldvalue.update(newval)
oldvalValues = zip(*oldvalue.values())
# for col, vals in zip(map(lambda x: x[1], writeCols),
# oldvalValues):
for col, vals in zip([x[1] for x in writeCols],
for col, vals in zip((x[1] for x in writeCols),
oldvalValues):
try:
self.parent.Set(col, list(vals))
@ -918,16 +905,10 @@ class SourceReadonlyVariable(ReadonlyVariable):
indexField = ""
def get(self):
# return list(map(lambda x: x or "",
# map(self.getMap().get,
# self.Get(self.indexField))))
return [x or "" for x in map(self.getMap().get,
self.Get(self.indexField))]
def humanReadable(self):
# return list(map(lambda x: x or "",
# map(self.getMapHumanReadable().get,
# self.Get(self.indexField))))
return [x or "" for x in map(self.getMapHumanReadable().get,
self.Get(self.indexField))]
@ -1055,9 +1036,7 @@ class SimpleDataVars(object):
if "list" in varType:
return ",".join(map(fixEmpty, value))
elif "table" in varType:
# return ",".join(map(lambda x: ":".join(map(fixEmpty, x)),
# value))
return ",".join([":".join(map(fixEmpty, x)) for x in value])
return ",".join((":".join(map(fixEmpty, x)) for x in value))
return fixEmpty(value)
@staticmethod
@ -1072,7 +1051,6 @@ class SimpleDataVars(object):
val = str(val)
if val == "":
return []
# return list(map(fixEmpty, val.split(delimeter)))
return [fixEmpty(x) for x in val.split(delimeter)]
return wrapper
@ -1080,7 +1058,6 @@ class SimpleDataVars(object):
if "list" in varType:
return getList()(value)
if "table" in varType:
# return list(map(getList(':'), value.split(',')))
return [getList(':')(x) for x in value.split(',')]
# if (isinstance(value, bytes)):
# value = str(value, "UTF-8")
@ -1092,9 +1069,7 @@ class SimpleDataVars(object):
"""
if "humanreadable" in kw:
hr = kw['humanreadable']
# return list(zip(*map(lambda x:self.Get(x, humanreadable=hr),
# argvVarNames)))
return list(zip(*[self.Get(x, humanreadable=hr) for x in argvVarNames]))
return list(zip(*(self.Get(x, humanreadable=hr) for x in argvVarNames)))
else:
return list(zip(*map(self.Get, argvVarNames)))
@ -1194,15 +1169,11 @@ class SimpleDataVars(object):
if isinstance(selField, (tuple, list)):
count = len(selField) + woffset
mapFunc = lambda x: x[woffset:]
# res = list(filter(filterFunc,
# zipVars(*(where + selField))))
res = [x for x in zipVars(*(where + selField)) if filterFunc(x)]
else:
count = 1 + woffset
fields = where + [selField]
mapFunc = lambda x: x[woffset]
# res = list(filter(filterFunc,
# zipVars(*fields)))
res = [x for x in zipVars(*(fields)) if filterFunc(x)]
if sort:
if "/" in sort:
@ -1214,7 +1185,6 @@ class SimpleDataVars(object):
res = [[""] * count]
return mapFunc(res[0])
else:
# return list(map(mapFunc, res[:limit]))
return [mapFunc(x) for x in res[:limit]]
@ -1297,17 +1267,12 @@ class DataVars(SimpleDataVars):
section = varModule.section
else:
section = "main"
# for varMod in list(map(lambda x: getattr(varModule, x),
# filter(lambda x: (not x.startswith("_") and
# "Variable" not in x),
# dir(varModule)))) + [varModule]:
for varMod in [getattr(varModule, x) for x in dir(varModule)
if not x.startswith("_") and "Variable" not in x] + [varModule]:
for classname in filterfalse(
("ReadonlyVariable", "VariableInterface",
"Variable", "VariableError").__contains__,
filter(lambda x: x.startswith("Variable"),
dir(varMod))):
(x for x in dir(varMod) if x.startswith("Variable"))):
varObj = getattr(varMod, classname)
varName = varObj.getVariableName()
if not varName in self.allVars:
@ -1541,8 +1506,7 @@ class DataVars(SimpleDataVars):
# print("DEBUG2 in __GET")
# if for this variable already use Get method
if varObj.invalid and varObj in self.requestVariables:
varnames = "-".join(map(lambda x: x.name,
self.requestVariables + [varObj]))
varnames = "-".join((x.name for x in self.requestVariables + [varObj]))
raise DataVarsError(
_("Loop dependence of variables '%s'") % varnames)
# add this variable for list of requested variables
@ -1884,10 +1848,9 @@ class DataVars(SimpleDataVars):
val = list(zip_longest(*val, fillvalue=""))
for col, typecol in multiLists:
if col < len(val):
val[col] = map(
lambda x: x.split(',')
if type(x) in (str) else x,
val[col])
val[col] = [x.split(',')
if type(x) in (str) else x for x
in val[col]]
val = list(zip_longest(*val, fillvalue=""))
return val
@ -1938,10 +1901,8 @@ class DataVars(SimpleDataVars):
result = [x for x in choicedata if compare_choice(val, x[0], x[1])]
if len(result) > 1:
raise VariableError(
_("Ambiguous choice:%s") % formatListOr(map(
lambda x: ('"%s"(%s)' % (x[1], x[0])
if x[0] != x[1] else x[0]),
result)))
_("Ambiguous choice:%s") % formatListOr((('"%s"(%s)' % (x[1], x[0])
if x[0] != x[1] else x[0]) for x in result)))
elif result:
return result[0][0]
return val
@ -2037,8 +1998,7 @@ class DataVars(SimpleDataVars):
# assemble all variable errors
messages = e.message if type(e.message) == list \
else [e]
mess = "\n".join(
map(lambda x: str(x), self.plainList(*messages)))
mess = "\n".join((str(x) for x in self.plainList(*messages)))
mapError = {PasswordError: 'pwderror',
CommonVariableError: 'commonerror'}
for k, v in mapError.items():

@ -285,8 +285,7 @@ class plasma(samba):
namesBlockList.append(namesBlock)
if findArea:
if len(namesBlock) > 1:
namesBlockView = map(lambda x: self.removeSymbolTerm(x),
namesBlock)
namesBlockView = (self.removeSymbolTerm(x) for x in namesBlock)
else:
namesBlockView = namesBlock
findArea.start = (indentionLeft + "[" +
@ -304,9 +303,7 @@ class plasma(samba):
areaNew.header = nameB
if lenNamesBlock == i:
if len(namesBlock) > 1:
namesBlockView = map(
lambda x: self.removeSymbolTerm(x),
namesBlock)
namesBlockView = (self.removeSymbolTerm(x) for x in namesBlock)
else:
namesBlockView = namesBlock
areaNew.start = (indentionLeft + "[" +
@ -482,7 +479,7 @@ class plasma(samba):
if not strHeader:
return ""
if type(strHeader) in (tuple, list):
outTxt = "".join(map(lambda x: "[" + x + "]", strHeader))
outTxt = "".join(("[" + x + "]" for x in strHeader))
if not outTxt:
return ""
outTxt += "\n"

@ -105,8 +105,8 @@ class xml_gconf_tree(xml_gconf):
if flagJoin:
listOldAttributes = list(nextOldNode.attrib.items())
if listOldAttributes:
listOldAttributes = filter(
lambda x: x[0] != "mtime", listOldAttributes)
listOldAttributes = [x for x
in listOldAttributes if x[0] != "mtime"]
# Замена содержимого
if xmlNode.tag == "entry":
replaceXmlNode = deepcopy(xmlNode)
@ -121,9 +121,8 @@ class xml_gconf_tree(xml_gconf):
childNodes = False
listNewAttributes = xmlNode.attrib.items()
if listNewAttributes:
listNewAttributes = filter(
lambda x: x[0] not in ("action", "mtime"),
listNewAttributes)
listNewAttributes = [x for x
in listNewAttributes if x[0] not in ("action", "mtime")]
if set(listNewAttributes) != set(listOldAttributes):
# Объединение аттрибутов
for attrName, attrValue in listNewAttributes:

@ -161,8 +161,7 @@ class ConsoleCodesConverter(BaseConverter):
"""Выполнить грамматику"""
if codes is None:
codes = SavableIterator([])
for gram in filter(lambda x: x.tryParse(code),
self.grams):
for gram in (x for x in self.grams if x.tryParse(code)):
return gram.parse(code, codes)
def transform(self, s):
@ -187,7 +186,7 @@ class ConsoleCodesConverter(BaseConverter):
yield self.output.outputText(txt)
yield self.output.endText()
return "".join(list(filter(None, generator())))
return "".join((x for x in generator() if x))
def detect(self, s):
"""
@ -288,7 +287,8 @@ class XmlConverter(BaseConverter):
self.__tagStack = []
self.parser.feed(s)
self.__outdata.append(self.output.endText())
return "".join(list(filter(None, self.__outdata)))
return "".join((x for x in self.__outdata if x))
def addResultToOutdata(f):
"""Добавить возвращаемый результат в список self.__outdata"""

@ -326,7 +326,6 @@ class ColorTerminalOutput(SaveAttrOutput):
"""
Создать ESC строку
"""
# attrs = list(map(str, ['%s[' % self.escSymb] + attrs + ['m']))
attrs = [str(x) for x in ['%s[' % self.escSymb] + attrs + ['m']]
return "%s%s%s" % (attrs[0], ";".join(attrs[1:-1]), attrs[-1])
@ -584,7 +583,7 @@ class XmlOutput(SaveAttrOutput):
yield self.escaper(root.text)
yield "</%s>" % root.tag
return "".join(filter(None, list(generator(xml))))
return "".join((x for x in generator(xml) if x))
def outputText(self, s):
if self.clear_state != self.current_state:

@ -89,7 +89,7 @@ class Print(object):
self.buffer.append(self.output.outputText(s))
self.buffer.append(self.output.endText())
try:
return self.printfunc("".join(_uu8(*filter(None, self.buffer))))
return self.printfunc("".join(_uu8(*[x for x in self.buffer if x])))
finally:
self.buffer = []
@ -114,6 +114,6 @@ class PrintClone(Print):
self.output.popState()
self.output.pushState()
try:
return self.printfunc("".join(filter(None, self.buffer)))
return self.printfunc("".join((x for x in self.buffer if x)))
finally:
self.buffer = []

@ -88,8 +88,7 @@ class _warning(object):
def genpassword(passlen=9, chars=string.ascii_letters + string.digits):
"""Return random charset specified lenght (passlen)"""
return ''.join(map(lambda x: choice(chars),
range(0, passlen)))
return ''.join((choice(chars) for i in range(0, passlen)))
def getpathenv():
@ -126,10 +125,6 @@ def getTupleVersion(ver):
"rc": -1}
def toTuple(v):
# return list(map(lambda x: suffix_value[x] if x in suffix_value else x,
# map(lambda x: int(x) if x.isdigit() else x,
# re.findall(r"r\d+$|\d+|[a-zA-Z+]+",
# v.replace('-SNAPSHOT', '')))))
return [suffix_value[x] if x in suffix_value else x for x
in [int(z) if z.isdigit() else z for z
in re.findall(r"r\d+$|\d+|[a-zA-Z+]+",v.replace('-SNAPSHOT', ''))]]
@ -166,9 +161,6 @@ def getDistfilesVideo(prefix="/"):
return None
return list(set([x for x in map(driver_by_fn, listDirectory(distFiles)) if x]))
# filter(None,
# map(driver_by_fn,
# listDirectory(distFiles)))))
def getAvailableVideo(prefix="/"):
@ -188,12 +180,7 @@ def getPasswdUsers(minId=1000, maxId=65000, prefix="/",
reNumb = re.compile(r"^\d+$")
lenData = 7
with open(fileName) as f:
# userData = list(filter(lambda x: len(x) == lenData,
# map(lambda x: x.rstrip().split(":"), f)))
userData = [z for z in map(lambda x: x.rstrip().split(":"), f) if len(z) == lenData]
# userData = list(filter(
# lambda x: reNumb.match(x[2]) and minId <= int(x[2]) <= maxId,
# userData))
userData = [x for x in (y.rstrip().split(":") for y in f) if len(x) == lenData]
userData = [x for x in userData if reNumb.match(x[2]) and minId <= int(x[2]) <= maxId]
sortUsers = [x[0] for x in userData]
sortUsers.sort()
@ -273,10 +260,7 @@ def getValueFromCmdLine(option, num=None):
if name is None:
return value.strip()
if ":" in value:
params = dict(
map(lambda x: x.partition(':')[0::2],
filter(lambda x: x,
value.split(','))))
params = dict((x.partition(':')[0::2] for x in value.split(',') if x))
return params.get(name, "").strip()
# old format
else:
@ -316,23 +300,16 @@ def getVideoFromXorgLog(prefix="/", available_drivers=()):
# Try analize Xorg.{DISPLAY}.log
display = os.environ.get('DISPLAY', ':0')
if display and available_drivers:
reDriver = re.compile('|'.join(map(lambda x: "%s_drv.so" % x,
available_drivers)))
reDriver = re.compile('|'.join(("%s_drv.so" % x for x in available_drivers)))
display_number = re.search(r':(\d+)(\..*)?', display)
reDriverName = re.compile(r'([^/]+)_drv.so')
if display_number:
xorg_log_file = path.join(prefix, 'var/log/Xorg.%s.log' %
display_number.group(1))
if path.exists(xorg_log_file):
# matchStrs = list(map(
# lambda x: x.group(1),
# filter(lambda x: x, map(
# reDriverName.search,
# filter(lambda x: "drv" in x and reDriver.search(x),
# readLinesFile(xorg_log_file))))))
matchStrs = [x.group(1) for x in [reDriverName.search(z)
for z in readLinesFile(xorg_log_file)
if "drv" in z and reDriver.search(z)] if x]
matchStrs = [x.group(1) for x in [reDriverName.search(y)
for y in readLinesFile(xorg_log_file)
if "drv" in y and reDriver.search(y)] if x]
if matchStrs:
reUnload = re.compile(r'UnloadModule: "(%s)"' %r'|'.join(x
for x in matchStrs))
@ -372,10 +349,6 @@ def getVideoFromCmdLine():
def getVideoFromModules():
# workedModules = list(map(lambda x: x[0],
# filter(lambda x: x[1].isdigit() and int(x[1]) > 0,
# map(lambda x: x.split()[:3:2],
# readLinesFile('/proc/modules')))))
workedModules = [x[0] for x in [z.split()[:3:2] for z
in readLinesFile('/proc/modules')]
if x[1].isdigit() and int(x[1]) > 0]
@ -466,10 +439,7 @@ def dict_by_columns(i, sep, key, value):
на колонки, key - номер колонки ключей, value номер колонки значений
"""
max_val = max(key, value)
return dict(
map(lambda x: (x[key], x[value]),
filter(lambda x: len(x) >= max_val,
map(lambda x: x.split(sep), i))))
return dict(((x[key], x[value]) for x in (y.split(sep) for y in i) if len(x) >= max_val))
from calculate.lib.utils.files import readLinesFile
@ -507,9 +477,6 @@ def getGroups(prefix="/"):
"""
Get groups from etc/group
"""
# return list(filter(None,
# map(lambda x: x.split(':')[0],
# readLinesFile(path.join(prefix, 'etc/group')))))
return [x for x in [z.split(':')[0] for z in readLinesFile(path.join(prefix, 'etc/group'))] if x]

@ -97,8 +97,8 @@ class PkgContents(ContentsFormat):
"""
Re-read contents
"""
self.content = dict(filter(None, map(self._identifyLine,
readLinesFile(self.contentFile))))
self.content = dict((x for x
in map(self._identifyLine, readLinesFile(self.contentFile) ) if x))
def writeContents(self):
"""
@ -192,10 +192,10 @@ def checkReserved(fileName, contentFile):
Check contents with newContent
"""
TYPE, FILENAME, MD5, MTIME = 0, 1, 2, 3
obj = filter(lambda x: x[1] == fileName,
map(lambda x: x.split(' '),
filter(lambda x: x.startswith('obj'),
readLinesFile(contentFile))))
obj = [x for x in [y.split(' ') for y
in readLinesFile(contentFile)
if y.startswith('obj')]
if x[1] == fileName]
# if pkg not content filename
if not obj:
return True
@ -222,10 +222,9 @@ def checkContents(pkg, fileName, prefix='/', reservedFile=None):
shortName = fileName
TYPE, FILENAME, MD5, MTIME = 0, 1, 2, 3
obj = filter(lambda x: x[1] == shortName,
map(lambda x: x.split(' '),
filter(lambda x: x.startswith('obj'),
readLinesFile(contentFile))))
obj = [x for x in (y.split(' ') for y
in readLinesFile(contentFile) if y.startswith('obj'))
if x[1] == shortName]
# if pkg not content filename
if not obj:
# for using reserved -CONTENTS file on postinst
@ -257,8 +256,8 @@ def getCfgFiles(protected_dirs=('/etc',), prefix='/'):
"-name", "._cfg????_*", "!", "-name", ".*~", "!", "-iname",
".*.bak", "-printf", r"%T@ %p\n"]
mapCfg = {}
for filetime, sep, filename in map(lambda x: x.partition(' '),
filter(None, process(*findParams))):
for filetime, sep, filename in (x.partition(' ') for x
in (y for y in process(*findParams) if y)):
origFilename = reCfg.sub(r'/', filename)
if not origFilename in mapCfg:
mapCfg[origFilename] = []
@ -277,7 +276,7 @@ def fillContents(allContent, protected, prefix='/'):
res = PkgContents.reObj.search(objFile.strip())
if res:
fn = res.groupdict()['filename']
if filter(lambda x: fn.startswith(x), protected):
if [x for x in protected if fn.startswith(x)]:
pkg = reVerSplit.search(os.path.dirname(contentFile))
if pkg:
pkg = "%s/%s" % (pkg.groups()[:2])

@ -198,11 +198,9 @@ def lspci(filtername=None, shortInfo=False):
lspciProg = files.checkUtils('/usr/sbin/lspci')
processLsPci = files.process(lspciProg, "-m")
retData = {}
for device in map(lambda x: x.groups(),
filter(lambda x: x,
map(reData.search,
filter(filterfunc,
processLsPci)))):
for device in (x.groups() for x
in (reData.search(y) for y
in processLsPci if filterfunc(y)) if x):
retData[device[0]] = {'type': sfunc(device[1]),
'vendor': sfunc(device[2]),
'name': sfunc(device[3])}

@ -442,11 +442,10 @@ class UnixUtilityFile:
MAGIC_MIME_TYPE: "--mime-type",
MAGIC_MIME_ENCODING: "--mime-encoding",
MAGIC_COMPRESS: "-z"}
appendParam = map(lambda x: paramdict[x],
filter(lambda x: flags & x,
sorted(paramdict.keys())))
appendParam = [paramdict[x] for x
in sorted(paramdict.keys()) if flags & x]
fileCmd = getProgPath('/usr/bin/file')
return [fileCmd, '-b'] + list(appendParam)
return [fileCmd, '-b'] + appendParam
def file(self, filename):
if path.exists(filename):
@ -747,10 +746,9 @@ def pathJoin(*paths):
"""Складывает пути, в отличии от os.path.join, складывает абсолютные пути"""
if len(paths) == 1:
return paths[0]
return reduce(path.join,
filter(lambda x: x and x != "/",
map(lambda x: x.startswith("/") and x[1:] or x,
paths[1:])), paths[0])
return reduce(path.join, (x for x
in (y.startswith("/") and y[1:] or y for y
in paths[1:]) if x and x != "/"), paths[0])
def listDirectory(directory, fullPath=False, onlyDir=False):
@ -959,8 +957,7 @@ def tarLinks(rootpath, archpath, skip=()):
tar = tarfile.open(archpath, "w:bz2")
# find links
if skip:
reSkip = re.compile(r"|".join(map(lambda x: x.replace("*", ".*"),
skip))).search
reSkip = re.compile(r"|".join((x.replace("*", ".*") for x in skip))).search
else:
reSkip = lambda x: False
for link in filterfalse(reSkip,
@ -1123,9 +1120,8 @@ def getMdRaidDevices():
Получить словарь: какой mdraid какие использует устройства
"""
reMdInfo = re.compile(r'^(\w+)\s+:\s+active.*?raid\d+\s+(.*)')
return dict(map(lambda x: (x[0], map(lambda x: x.partition('[')[0],
x[1].split())),
reSearch(reMdInfo, readLinesFile('/proc/mdstat'))))
return dict(((x[0], [y.partition('[')[0] for y in x[1].split()]) for x
in reSearch(reMdInfo, readLinesFile('/proc/mdstat'))))
class PercentProgress(processProgress):

@ -98,10 +98,9 @@ def checkNet(net):
return (strIpToIntIp(ip) & mask) == (strIpToIntIp(ip))
maskDigs = map(lambda x: str(x),
(0b10000000, 0b11000000, 0b11100000, 0b11110000,
0b11111000, 0b11111100, 0b11111110, 0b11111111))
maskDigs = [str(x) for x
in (0b10000000, 0b11000000, 0b11100000, 0b11110000,
0b11111000, 0b11111100, 0b11111110, 0b11111111)]
def checkMask(mask):
"""Check net"""
@ -177,14 +176,11 @@ def getIpNet(ip, mask=None, cidr=None):
def isIpInNet(checkip, *ipnets):
"""Check is ip in specified nets"""
return map(lambda x: x[0],
filter(lambda x: strIpToIntIp(checkip) & x[2] == strIpToIntIp(
x[1]) & x[2],
map(lambda x: (
x[0], x[1][0],
strIpToIntIp(cidrToMask(int(x[1][1])))),
map(lambda x: (x, x.partition('/')[0::2]),
ipnets))))
return [x[0] for x
in [(y[0], y[1][0], strIpToIntIp(cidrToMask(int(y[1][1])))) for y
in [(z, z.partition('/')[0::2]) for z
in ipnets]]
if strIpToIntIp(checkip) & x[2] == strIpToIntIp(x[1]) & x[2]]
def isUsingNetworkManager():
try:
@ -207,19 +203,16 @@ def isDhcpIp(interface="eth0"):
return True
commands = getRunCommands()
dhcpProgs = ("dhcpcd", "dhclient", "udhcpc")
if filter(lambda x: interface in x and any(prog in x for prog in dhcpProgs),
commands):
if [x for x in commands if interface in x and any(prog in x for prog in dhcpProgs)]:
return True
else:
# если запущен демон dhcpcd
if filter(lambda x: "dhcpcd\x00-q" in x, commands):
if [x for x in commands if "dhcpcd\x00-q" in x]:
curIp = getIp(interface)
dhcpcd = getProgPath('/sbin/dhcpcd')
leaseIp = \
map(lambda x: x.group(1),
filter(None,
map(re.compile(r'^ip_address=(.*)$').search,
process(dhcpcd, '-U', interface))))
leaseIp = [x.group(1) for x
in map(re.compile(r'^ip_address=(.*)$').search,
process(dhcpcd, '-U', interface)) if x]
if not curIp or leaseIp and leaseIp[0] == curIp:
return True
return False
@ -230,11 +223,11 @@ def getRouteTable(onlyIface=()):
ipProg = checkUtils('/sbin/ip')
routes = process(ipProg, "route")
if onlyIface:
filterRe = re.compile(r"|".join(map(lambda x: r"dev %s" % x, onlyIface)))
filterRe = re.compile(r"|".join((r"dev %s" % x for x in onlyIface)))
routes = filter(filterRe.search, routes)
for line in routes:
network, op, line = line.partition(" ")
routeParams = map(lambda x: x.strip(), line.split())
routeParams = [x.strip() for x in line.split()]
# (network,{'via':value,'dev':value})
if network:
yield (network, dict(zip(routeParams[0::2], routeParams[1::2])))

@ -103,10 +103,6 @@ class MountHelper(object):
def setlen(ar):
return ar[:6] + [""] * (6 - len(ar))
# self.cache = \
# list(map(lambda x: setlen(list(map(lambda y: y.strip(), x.split()))),
# filter(lambda x: x.strip() and not x.lstrip().startswith("#"),
# self._readdata().split('\n'))))
self.cache = [setlen([y.strip() for y in x.split()]) for x
in self._readdata().split('\n') if x.strip() and not x.lstrip().startswith("#")]
for data in self.cache:
@ -140,7 +136,7 @@ class MountHelper(object):
return list(zip(*reduce(lambda x, y: x + [self.rotateCache[y]], fields, [])))
def isReadonly(self, what=DIR, eq=None):
for data in filter(lambda x: x[what] == eq, self.cache):
for data in (x for x in self.cache if x[what] == eq):
opts = data[self.OPTS].split(',')
if "ro" in opts:
return True
@ -167,7 +163,7 @@ class MountHelper(object):
filterfunc = lambda x: x[what] == eq
else:
filterfunc = lambda x: x[what] != noteq
return bool(list(filter(filterfunc, self.cache)))
return bool([x for x in self.cache if filterfunc(x)])
class FStab(MountHelper):
@ -210,9 +206,7 @@ class DiskSpace(object):
def commonPath(*paths):
"""Return common path from list of paths"""
paths = map(lambda x: os.path.normpath(x).split('/'), paths)
# res = list(map(lambda x: x[0],
# filter(lambda x: filter(lambda y: x[0] == y, x[1:]), zip(*paths))))
paths = [os.path.normpath(x).split('/') for x in paths]
res = [x[0] for x in zip(*paths) if [y for y in x[1:] if x[0] == y]]
return "/".join(res)
@ -230,11 +224,8 @@ def childMounts(pathname):
return ""
with open(mtabFile) as f:
return reduce(lambda x, y: x + [y],
filter(lambda x: commonPath(absPath, x[0]) == absPath or \
commonPath(absPath, x[1]) == absPath,
map(lambda x: [x[0], x[1]],
map(lambda x: x.split(" "), f))),
[])
(x for x in ([y[0], y[1]] for y in (z.split(" ") for z in f))
if commonPath(absPath, x[0]) == absPath or commonPath(absPath, x[1]) == absPath), [])
class MountError(Exception):
pass

@ -94,14 +94,10 @@ def getPkgUses(fullpkg, version=None, prefix="/"):
_pkgCategory = '{0}/{1}'.format(VDB_PATH, category)
pkgCategory = path.join(prefix, _pkgCategory)
if version is None:
# packages = list(filter(lambda x: x['PN'] == pkg,
# map(reVerSplitToPV,
# filter(lambda x: x,
# map(lambda x: reVerSplit.search(x),
# listDirectory(pkgCategory))))))
packages = [x for x in [reVerSplitToPV(y)
for y in [reVerSplit.search(z)
for z in listDirectory(pkgCategory)] if y] if x['PN'] == pkg]
packages = [x for x
in [reVerSplitToPV(y) for y
in [reVerSplit.search(z) for z
in listDirectory(pkgCategory)] if y] if x['PN'] == pkg]
if not packages:
return None
usePath = path.join(pkgCategory, packages[-1]['PF'], "USE")
@ -111,12 +107,6 @@ def getPkgUses(fullpkg, version=None, prefix="/"):
iusePath = path.join(pkgCategory, "%s-%s" % (pkg, version), "IUSE")
iuse = readFile(iusePath).strip().split()
use = readFile(usePath).strip().split()
# return (list(map(lambda x: x[1:] if x.startswith("+") else x,
# filter(lambda x: x,
# use))),
# list(map(lambda x: x[1:] if x.startswith("+") else x,
# filter(lambda x: x,
# iuse))))
return ([x[1:] if x.startswith("+") else x for x in use if x],
[x[1:] if x.startswith("+") else x for x in iuse if x])
@ -939,8 +929,7 @@ class EixFullnameParserBestVersion(EixFullnameParser):
"""
def get_versions(self, et):
ret = None
for ver in filter(lambda x: x.find('mask') is None,
et.iterfind('version')):
for ver in (x for x in et.iterfind('version') if x.find('mask') is None):
ret = ver.attrib['id']
yield ret
@ -1341,10 +1330,9 @@ def get_remove_list(directory, filelist, depth=1):
"""
directory = path.normpath(directory)
l = len(directory) + 1
for fn in filter(lambda x: not x[l:] in filelist,
find(directory,
onefilesystem=True,
fullpath=True, depth=depth)):
for fn in (x for x
in find(directory,onefilesystem=True,fullpath=True, depth=depth)
if not x[l:] in filelist):
if path.isfile(fn):
yield fn

@ -48,11 +48,11 @@ def columnMatrix(*cols):
else:
yield part
return zip_longest(
return list(zip_longest(
*starmap(splitter,
zip_longest(islice(cols, 0, None, 2),
islice(cols, 1, None, 2))),
fillvalue="")
fillvalue=""))
def columnStr(*cols):
@ -70,8 +70,7 @@ def columnStr(*cols):
def generateStrings(*cols):
colWidth = list(islice(cols, 1, None, 2))
for line in map(lambda x: zip_longest(colWidth, x),
columnMatrix(*cols)):
for line in (zip_longest(colWidth, x) for x in columnMatrix(*cols)):
yield " ".join(("{0:%d}" % (width or 1)).format(s) for \
width, s in line)
@ -124,9 +123,9 @@ class tableReport(object):
# elements list for first table row
self.headerList = headerList
# row list (each row is list)
self.dataList = map(lambda x: map(lambda y: str(y).expandtabs(),
map(lambda y: y or "", x)),
dataList)
self.dataList = [[str(y).expandtabs() for y
in [z or "" for z in x]] for x in dataList]
# calculate columns list
self.columnsWidth = self.getColumsnWidth()
self.vertChar = colSpan * " " + "|" + colSpan * " "
@ -145,13 +144,11 @@ class tableReport(object):
spanSize = self.colSpan * 2 + 1
if colNum < 0:
colNum += len(self.columnsWidth)
currentSize = sum(map(lambda x: x + spanSize, self.columnsWidth)) + 1
currentSize = sum((x + spanSize for x in self.columnsWidth)) + 1
if currentSize < maxSize and not forceMax:
return
excludeSize = sum(map(lambda x: x[1] + spanSize,
filter(lambda x: x[0] != colNum,
enumerate(
self.columnsWidth)))) + spanSize + 1
excludeSize = sum((x[1] + spanSize for x
in enumerate(self.columnsWidth) if x[0] != colNum)) + spanSize + 1
if maxSize - excludeSize > 5:
self.columnsWidth[colNum] = maxSize - excludeSize
@ -186,8 +183,7 @@ class tableReport(object):
def createFormatStr(self, listStr, offset=0):
"""Создает список (текст, ширина ...)"""
return chain(*zip_longest(listStr,
map(lambda x:x-offset, self.columnsWidth),
fillvalue=""))
[x-offset for x in self.columnsWidth], fillvalue=""))
def printFunc(self, s):
"""
@ -390,12 +386,8 @@ def convertStrListDict(val):
def formatListOr(lst):
"""Convert list to string like this: [1,2,3] -> 1,2 or 3"""
lststr = map(lambda x: str(x), lst)
return (" %s " % _("or")).join(filter(lambda x: x,
[", ".join(map(lambda x: x or "''",
lststr[:-1])),
"".join(lststr[-1:])]))
lststr = [str(x) for x in lst]
return (" %s " % _("or")).join((x for x in [", ".join((y or "''" for y in lststr[:-1])),"".join(lststr[-1:])] if x))
def get_term_size(fd=sys.stdout.fileno()):
"""
@ -428,8 +420,7 @@ def simplify_profiles(profiles, drop_words=("amd64", "x86")):
"""
if len(profiles) < 2:
if len(profiles) == 1:
return ["/".join(filter(lambda x: x not in drop_words,
profiles[0].split('/')))]
return ["/".join((x for x in profiles[0].split('/') if x not in drop_words))]
return profiles
matrix = [x.split('/') for x in profiles]
# удаляем одинаковые начальные и конечные поля
@ -438,4 +429,4 @@ def simplify_profiles(profiles, drop_words=("amd64", "x86")):
lambda x: x.count(x[0]) == len(x),
zip_longest(*matrix,
fillvalue="")))))))))
return ["/".join(filter(None, x)) for x in matrix]
return ["/".join((y for y in x if y)) for x in matrix]

@ -71,7 +71,7 @@ class VariableOsX11Resolution(Variable):
reXorgLogParser = re.compile(re_pat, re.S)
resXorgLogParser = reXorgLogParser.search(logdata)
if resXorgLogParser:
tmp = list(filter(lambda x: x, resXorgLogParser.groups()))
tmp = [x for x in resXorgLogParser.groups() if x]
return "%sx%s" % tuple(tmp[:2])
# get resolution from xorg.conf
@ -80,9 +80,9 @@ class VariableOsX11Resolution(Variable):
re.S)
reModes = re.compile(r'Modes\s+"(\d+x\d+)')
if os.access(xorgconf, os.R_OK):
sectionsScreen = filter(lambda x: "Modes" in x,
reScreenSections.findall(
readFile('/etc/X11/xorg.conf')))
sectionsScreen = [x for x
in reScreenSections.findall(readFile('/etc/X11/xorg.conf'))
if "Modes" in x]
modes = [x.groups()[0] for x in map(reModes.search, sectionsScreen) if x]
if modes:
return max(modes, key=lambda x: int(x.partition('x')[0]))

@ -50,9 +50,8 @@ class VariableAcCustomName(Variable):
self.parent.Set('cl_action', old_action, force=True)
self.parent.Set('ac_custom_name', old_name, force=True)
cl_templ.closeFiles()
return list(set(map(lambda x: x[1],
filter(lambda x: x[0] == 'ac_custom_name',
self.Get('cl_used_action')))))
return list(set((x[1] for x
in self.Get('cl_used_action') if x[0] == 'ac_custom_name')))
def check(self, value):
if value == '':

@ -353,10 +353,8 @@ class VariableClWsdlAvailable(ReadonlyVariable):
if (x.endswith('site-packages') and
x.startswith('/usr/lib'))]
ret_list = []
for module, modDir in chain(
*map(lambda x: map(lambda y: (path.basename(y), y),
listDirectory(x, True, True)),
site_packages)):
for module, modDir in chain(*[((path.basename(y), y) for y
in listDirectory(x, True, True)) for x in site_packages]):
if path.exists(path.join(modDir, "wsdl_%s.py" % module)):
if not "calculate-%s" % module in ret_list:
ret_list.append("calculate-%s" % module)
@ -466,8 +464,7 @@ class VariableClPkgdir(ReadonlyVariable):
return emerge_config['PKGDIR']
else:
emerge_info = self.Get('cl_emerge_info')
for line in filter(lambda x: x.startswith("PKGDIR="),
emerge_info):
for line in (x for x in emerge_info if x.startswith("PKGDIR=")):
return line.partition("=")[2].strip('\n"\'')
return ""
@ -485,8 +482,7 @@ class VariableClFeatures(ReadonlyVariable):
return [x for x in emerge_config['FEATURES'].split() if x]
else:
emerge_info = self.Get('cl_emerge_info')
for line in filter(lambda x: x.startswith("FEATURES="),
emerge_info):
for line in (x for x in emerge_info if x.startswith("FEATURES=")):
return [x for x in line.partition("=")[2].strip('\n"\'').split() if x]
return ""
@ -522,13 +518,11 @@ class VariableClRepositoryData(ReadonlyTableVariable):
return re_block.findall(text)
def from_portdir_vars(self, info):
for line in filter(lambda x: x.startswith("PORTDIR="),
info):
for line in (x for x in info if x.startswith("PORTDIR=")):
yield ["gentoo", line.partition("=")[2].strip('\n"\'')]
self.Get('cl_emerge_info')
for line in filter(lambda x: x.startswith("PORTDIR_OVERLAY="),
info):
for line in (x for x in info if x.startswith("PORTDIR_OVERLAY=")):
for i in ([path.basename(x), x]
for x in line.partition("=")[2].strip('\n"\'').split(' ')
if x):
@ -692,8 +686,7 @@ class VariableClEmergeDefaultOpts(ReadonlyVariable):
return emerge_config['EMERGE_DEFAULT_OPTS']
else:
emerge_info = self.Get('cl_emerge_info')
for line in filter(lambda x: x.startswith("EMERGE_DEFAULT_OPTS="),
emerge_info):
for line in (x for x in emerge_info if x.startswith("EMERGE_DEFAULT_OPTS=")):
key, op, value = line.partition('=')
for quote in ("'", '"'):
if value.startswith(quote):

@ -75,8 +75,7 @@ class VariableHrCpuNum(ReadonlyVariable):
def get(self):
cpuinfo_file = "/proc/cpuinfo"
return str(len(list(filter(lambda x: x.startswith("processor"),
readLinesFile(cpuinfo_file)))) or 1)
return str(len([x for x in readLinesFile(cpuinfo_file) if x.startswith("processor")]) or 1)
class VariableHrCpuName(ReadonlyVariable):
def get(self):

@ -81,10 +81,10 @@ class Linux(VariableInterface):
if path.exists(inifile):
with open(inifile) as f:
data = f.readlins()
short_name_list = list(filter(
None, map(lambda x: (len(x.split("=")) == 2 and
x.split("=")[0] == "calculate" and
x.split("=")[1].strip()), data)))
short_name_list = [x for x
in [len(y.split("=")) == 2 and
y.split("=")[0] == "calculate" and
y.split("=")[1].strip() for y in data] if x]
if short_name_list:
return short_name_list[0]
@ -93,8 +93,7 @@ class Linux(VariableInterface):
gentoo_file = path.join(systemroot, "etc/gentoo-release")
if path.exists(gentoo_file):
return "Gentoo"
if all(map(lambda x: path.lexists(path.join(systemroot, x)),
['bin', 'var', 'lib', 'etc'])):
if all([path.lexists(path.join(systemroot, x)) for x in ['bin', 'var', 'lib', 'etc']]):
return "Linux"
return None
@ -121,14 +120,13 @@ class Linux(VariableInterface):
if path.exists(pathname):
with open(pathname) as f:
data = f.readlines()
ver_list = list(filter(
None, map(lambda x:
(len(x.split("=")) == 2 and
x.split("=")[0] == "linuxver" and
x.split("=")[1].strip()), data)))
ver_list = [x for x
in [len(y.split("=")) == 2 and
y.split("=")[0] == "linuxver" and
y.split("=")[1].strip() for y in data] if x]
if not ver_list:
re_ver = re.compile(r"^(\d+\.)*\d$", re.S)
re_res = list(filter(re_ver.search, ver_list))
re_res = [x for x in ver_list if re_ver.search(x)]
if re_res:
return re_res[0]
@ -139,8 +137,7 @@ class Linux(VariableInterface):
if path.exists(gentoo_file):
gentoo_link = self.Get('cl_make_profile')
if path.islink(gentoo_link):
vers = list(filter(re_ver.search,
os.readlink(gentoo_link).split('/')))
vers = [x for x in os.readlink(gentoo_link).split('/') if re_ver.search(x)]
if vers:
return vers[-1]
@ -262,8 +259,7 @@ class VariableOsLinuxPkglist(Variable):
def get(self):
make_profile = self.Get('cl_make_profile')
if path.exists(make_profile):
return list(unique(filter(None,
self.generate_shortnames(make_profile))))
return list(unique((x for x in self.generate_shortnames(make_profile) if x)))
else:
return []

@ -499,8 +499,8 @@ class Locale(object):
return lang in self.langData.keys()
def isValueInFieldExists(self, field, value):
return value in map(lambda x: self.langData[x][field],
self.langData.keys())
return value in (self.langData[x][field] for x in self.langData.keys())
def getFields(self, field):
return [l[1][field] for l in self.langData.items()]

@ -66,7 +66,7 @@ class VariableOsNetAllow(ReadonlyVariable):
ipaddr, mask = ip.getIp(iface), ip.cidrToMask(ip.getMask(iface))
if ipaddr and mask:
networks.append(ip.getIpNet(ipaddr, mask))
return ",".join(list(set(filter(lambda x: x, networks))))
return ",".join(list(set((x for x in networks if x))))
class VariableOsNetIp(ReadonlyVariable):

@ -112,8 +112,7 @@ class VariableOsMapperRootDev(ReadonlyVariable):
dev_links = device.udev.get_device_info(
name=rootdev).get("DEVLINKS", "")
if dev_links:
mapper_name = list(filter(lambda x: "/dev/mapper" in x,
dev_links.split()))
mapper_name = [x for x in dev_links.split() if "/dev/mapper" in x]
if mapper_name:
return mapper_name[0]
return rootdev
@ -244,11 +243,9 @@ class VariableOsRootTypeExt(ReadonlyVariable):
return RootType.Value.NetBoot
return RootType.Value.LiveCD
id_dict = dict(map(link2pair,
filter(lambda x: path.islink(x),
map(lambda x: path.join('/dev/disk/by-id',
x),
listDirectory('/dev/disk/by-id')))))
id_dict = dict([link2pair(x) for x
in [path.join('/dev/disk/by-id', y) for y
in listDirectory('/dev/disk/by-id')] if path.islink(x)])
if "usb-" in id_dict.get(root_dev, ""):
return RootType.Value.USB_HDD
return RootType.Value.HDD

Loading…
Cancel
Save