Could someone help me out with what is going wrong and what I can do to fix it?
File "C:/Users/rawaa/raw/untitled2.py", line 246, in disp_message
str02= str02 + str01[single]
IndexError: string index out of range
def disp_message(val01, file_name):
f = open(file_name,'r')
data = f.readlines()
f.close()
str01 = str(data[0])
str02 = ' '
for each in val01:
#print each
for single in each:
#print single
str02= str02 + str01[single]
str02 = str02 + ' '
print("the hidden message in the data is:")
print(str02)
print("\n\npress 1. to see hidden data visualisation or ctrl+c to terminate")
cho = raw_input()
if cho == '1':
print(show_data(str01,1,val01))
you didn't specify the range of length of each, you should do maybe :
for each in val01:
#print each
for single in range (len(each)):
#print single
str02= str02 + str01[single]
str02 = str02 + ' '
here my function . I have to do lower what ever coming in newfilename..i.e newfilename.lower()
def my_function(start, end):
sheetname = 'my-sheet'
filepath = "/myxl.xlsx"
try:
work_book=xlrd.open_workbook(filepath)
except:
print 'error'
try:
worksheet = work_book.sheet_by_name(sheetname)
except:
print 'error'
rows=worksheet.nrows
cols=worksheet.ncols
success = []
fail = []
for row in xrange(start,end):
print "row no. : ",row
state = '/home/myfolder/'
if os.path.exists(state):
print "state folder exits"
else:
os.makedirs(state)
district = state + worksheet.cell_value(row,0) + '/'
if os.path.exists(district):
print "district folder exits"
else:
os.makedirs(district)
city = district + worksheet.cell_value(row,2) + '/'
if os.path.exists(city):
print "city folder exits"
else:
os.makedirs(city)
newfilename = city + worksheet.cell_value(row,4).replace (" ", "-") + '.png'
if worksheet.cell_value(row,5) !="":
oldfilename = worksheet.cell_value(row,5)
else:
oldfilename="no-image"
newfullpath = newfilename
oldfullpath = '/home/old/folder/' + oldfilename
try:
os.rename(oldfullpath,newfullpath)
success.append(row)
except Exception as e:
fail.append(row)
print "Error",e
print 'renaming done for row #' ,row , ' file ', oldfilename , ' to ', newfilename
print 'SUCCESS ', success
print 'FAIL ', fail
newfilename.lower() not working
here when I am going to use unicode error coming...
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 72: ordinal not in range(128)
def isAlpha(c):
return (ord(c) >= 65 and ord(c) <= 95) or \
(ord(c) >= 97 and ord(c) <= 122)
# testing first function
print isAlpha("D")
print isAlpha("z")
print isAlpha("!")
s = "AEIOUaeiou"
def isVowel(c):
return s.find(c) > -1
# testing second function
print isVowel("A")
print isVowel("B")
print isVowel("c")
print isVowel(" ")
print isVowel("a")
def convPigLatin_word(word):
if isVowel(word[0]):
word += "way"
while not isVowel(word[0]):
word = word[1:] + word[0]
if isVowel(word[0]):
word += "ay"
return word
# testing third function
print convPigLatin_word("This")
print convPigLatin_word("ayyyyyylmao")
def translate(phrase):
final = ""
while phrase.find(" ") != -1:
n = phrase.find(" ")
final += convPigLatin_word(phrase[0:n]) + " "
phrase = phrase[n+1:]
if phrase.find(" ") == -1:
final += convPigLatin_word(phrase)
return final
print translate("Hello, this is team Number Juan") #Should be "elloHay, isthay isway eamtay umberNay uanJay"
I tried to create a code that transform a string into pig latin. But I got stuck on the non-alphanumeric character. The while loop only works up to the comma. How can I resolve that? I don't know where to implement the isAlpha code to check for non alphanumeric character. Any advice is helpful.
You can iterate through the words of a phrase by using .split(' '). Then you can test them for special characters using .isalpha()
pigLatin = lambda word: word[1:]+ word[0]+"ay"
def testChars(word):
text = ""
for char in list(word):
if char.isalpha():
text += char
else:
return pigLatin(text)+ char
def testWords(lis):
words = []
lis = lis.split(' ')
for word in lis:
if not word.isalpha():
words.append( testChars(word) )
else:
words.append(pigLatin(word))
return (' ').join(words)
phrase = "I, have, lots of! special> characters;"
print testWords(phrase)
Is there a easy way to identify and clean unused informatica artifacts?
Context: In one of the projects, there are lot of zombie sessions / mappings etc, the creators have long gone.
I want to do the following:
List/Delete all sessions that are not associated with a workflow.
List/Delete all mappings that are not used in any session/wf.
List/Delete all source/target that were not used in any mapping.
List/Delete all workflows that were not run in the past one year.
Someone mentioned about using : Designer > Tools > Queries . I can't express the above 1/2/3/4 with the option given, can anyone shed some light?
Note:
I’m not looking for click one by one and find dependencies.
I’m not looking for download the whole plant as xml and search dependencies
one by one
As this is not easily achievable with PowerCenter itself, I tried to come up with some simple tool to solve it. For the full description and download link please go to this page.
Below you'll find the code published as requested in comments: Find and later delete zombie informatica objects
Feel free to use, share and improve :) Any code review will be also much appreciated.
import subprocess
import os
from subprocess import *
import platform
import sys
import getpass
import configparser
#global variables declarations
currentDir=''
pmrepPath=''
domainFile=''
def connect_to_repo(Repository,Domain,User,Host,Port, UserSecurityDomain):
#password = raw_input("Enter password for Repository: " + Repository + ", User: " + User)
password = getpass.getpass()
print "\nConnecting..."
if Domain != '':
RepoCommand="pmrep connect -r "+Repository+" -d "+Domain+" -n "+User + " -x " + password #+" -X DOMAIN_PWD"
else:
RepoCommand="pmrep connect -r "+Repository+" -n "+User + " -x " + password + " -h " + Host + " -o " + Port
if UserSecurityDomain != '':
RepoCommand += " -s " + UserSecurityDomain
RepoCommand=RepoCommand.rstrip()
p=subprocess.Popen(RepoCommand,stderr=subprocess.PIPE,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
out,err=p.communicate()
if p.returncode or err:
print "Connection Failed"
print err.strip()
print out.strip()
sys.stdout.flush()
sys.stdin.flush()
else:
print "Connection Successful"
sys.stdout.flush()
sys.stdin.flush()
return p.returncode
def execute_pmrep_command(command, output_file_name, start_line, end_line, line_prefix):
if len(line_prefix)>0: line_prefix+=' '
out=open(output_file_name,'a')
return_code=subprocess.Popen(command,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
output,error=return_code.communicate()
for line in output.split('\r\n')[start_line:end_line]:
out.writelines(line_prefix + line + '\n')
out.close()
return
def check_platform():
global domainFile
global currentDir
global pmrepPath
global platForm
platForm=platform.system()
print "Platform recognized : "+platForm
## if not os.getenv('INFA_HOME', 'C:\\Informatica\\9.5.1'):
## print "INFA_HOME env_variable not set in your "+platForm+" platform."
## print "Please set INFA_HOME and continue."
## raw_input()
## sys.exit(0)
if not os.getenv('INFA_DOMAINS_FILE'):
print "INFA_DOMAINS_FILE env_variable not set in your "+platForm+" platform."
print "Please set INFA_DOMAINS_FILE and continue."
raw_input()
sys.exit(0)
## elif not os.getenv('DOMAIN_PWD', 'vic'):
## print "DOMAIN_PWD env variable not set in your "+platForm+" platform."
## print "Please set DOMAIN_PWD and continue."
## raw_input()
## sys.exit(0)
## else:
## if platForm == 'Windows':
## pmrepPath=os.getenv('INFA_HOME').strip()+"\clients\PowerCenterClient\client\\bin"
## elif platForm == 'Linux':
## pmrepPath=os.getenv('INFA_HOME').strip()+"/server/bin"
## currentDir=os.getcwd()
## domainFile=os.getenv('INFA_DOMAINS_FILE','C:\\Informatica\\9.5.1\\domains.infa').strip()
config = configparser.RawConfigParser()
config.optionxform = lambda option: option
config.read('InfaRepo_ListUnusedObjects.cfg')
infaDir = config.get('Common', 'infaDir').strip()
Repository = config.get('Common', 'Repository').strip()
Domain = config.get('Common', 'Domain').strip()
Host = config.get('Common', 'Host').strip()
Port = config.get('Common', 'Port').strip()
Folder = config.get('Common', 'Folder').strip()
User = config.get('Common', 'User').strip()
UserSecurityDomain = config.get('Common', 'UserSecurityDomain').strip()
objectTypeList = config.get('Common', 'objectTypeList').split(',')
if Domain != '':
print 'Domain provided, will be used to connect.'
else:
print 'Domain not provided, Host and Port will be used to connect.'
for i in range(len(objectTypeList)):
objectTypeList[i]=objectTypeList[i].strip()
currentDir=os.getcwd()
outputDir=currentDir+'\\UnusedObjectsReport'
###objectTypeList = ['mapplet', 'mapping', 'session', 'source', 'target', 'worklet']
##
##objectTypeList = ['target']
pmrepPath=infaDir.strip()+"\clients\PowerCenterClient\client\\bin"
os.chdir(pmrepPath)
outFile = outputDir + "\ListOfUnusedObjects.txt"
if not os.path.exists(os.path.dirname(outFile)):
os.makedirs(os.path.dirname(outFile))
print 'Output file: ' + outFile
open(outFile,'w').writelines("Domain : "+Domain+"\nRepository : "+Repository+"\nUserName : "+User+"\n")
open(outFile,'a').writelines("***************************"+"\n")
open(outFile,'a').writelines("LIST OF UNUSED OBJECTS:\n")
outBatchFile = outputDir + "\DeleteUnusedObjects.bat"
tempDir = outputDir + "\\temp"
if not os.path.exists(outputDir):
os.makedirs(outputDir)
if not os.path.exists(tempDir):
os.makedirs(tempDir)
for tempFile in os.listdir(tempDir):
os.remove(os.path.join(tempDir, tempFile))
print 'Output batch file: ' + outBatchFile
if Domain != '':
RepoCommand="pmrep connect -r "+Repository+" -d "+Domain+" -n "+User
else:
RepoCommand="pmrep connect -r "+Repository+" -n "+User + " -h " + Host + " -o " + Port
if UserSecurityDomain != '':
RepoCommand += " -s " + UserSecurityDomain
open(outBatchFile,'w').writelines(pmrepPath+"\\"+RepoCommand+"\n")
objectTypeCounter=0
return_code=connect_to_repo(Repository,Domain,User,Host,Port,UserSecurityDomain)
objDepDict={}
error = False
errorList = []
#check if repository connection is successfull
if return_code==0:
for objectType in objectTypeList:
objectTypeCounter+=1
print "Step {0} of {1}: {2}".format(objectTypeCounter, len(objectTypeList), objectType)
objectFile = tempDir + "\\" + objectType + ".txt"
open(objectFile,'w').writelines("")
objectDepFile = tempDir + "\\" + objectType + "_dep.txt"
open(objectDepFile,'w').writelines("")
execute_pmrep_command("pmrep listobjects -f " + Folder + " -o " + objectType, objectFile, 8, -4, '')
objectList=open(objectFile).readlines()
objectCounter=0
if len(objectList) == 0:
print '\tNo {0}s found'.format(objectType)
elif objectList[0][:3] == ' [[':
error=True
for line in objectList:
errorList += [line.replace('\n','')]
break
for line in objectList:
objectCounter+=1
fields=line.split(' ')
if len(fields) == 2:
objectType=fields[0]
objectName=fields[1][:-1]
else:
objectType=fields[0]
objectName=fields[2][:-1]
#if the object is non-reusable, it obviously is in some workflow, so skipp it
if fields[1] == 'non-reusable':
print "\t{0} {1} of {2}: {3} is not a reusable {4} - skipping".format(objectType, objectCounter, len(objectList), objectName, objectType)
continue
command = "pmrep listobjectdependencies -f " + Folder + " -n " + objectName + " -o " + objectType + " -p parents"
#print "Getting object dependencies for " + objectType + " " + objectName
print "\t{0} {1} of {2}: {3}".format(objectType, objectCounter, len(objectList), objectName)
execute_pmrep_command(command, objectDepFile, 8, -6, objectName)
#find unused objects
for fileLine in open(objectDepFile,'r').readlines():
line = fileLine.split(' ')
if len(line) == 3:
Name = line[0]
ParentType = line[1]
ParentName = line[2]
else:
Name = line[0]
ParentType = line[1]
ParentName = line[3]
try:
objDepDict[objectType + ': ' + Name]+=[ParentType + ' ' + ParentName]
except:
objDepDict[objectType + ': ' + Name]=[ParentType + ' ' + ParentName]
found = False
for objectKey in objDepDict.iterkeys():
objectType, objName = objectKey.replace(' ','').split(':')
if len(objDepDict[objectKey]) <= 1:
if not found:
print '\n'
print 'Following unused objects have been found:'
found = True
print '\t{0}: {1}'.format(objectType, objName)
open(outFile,'a').writelines('{0}: {1}\n'.format(objectType, objName))
open(outBatchFile,'a').writelines("rem {0}\\pmrep deleteobject -f {1} -o {2} -n {3}\n".format(pmrepPath, Folder, objectType, objName))
execute_pmrep_command('pmrep cleanup', 'log.txt', 0, 0, '')
open(outBatchFile,'a').writelines(pmrepPath+'\\pmrep cleanup' + '\n')
if not error:
if not found:
print 'No unused objects found.'
print '\nDone.'
print 'Output file: ' + outFile
print 'Output batch file: ' + outBatchFile
else:
print 'Following errors occured:'
for e in errorList:
print '\t', e
#wait for key press
print '\nHit Enter to quit...'
raw_input()
#End of program
I'm new to python (2.7.3) and I am experimenting with lists. Say I have a list that is defined as:
my_list = ['name1', 'name2', 'name3']
I can print it with:
print 'the names in your list are: ' + ', '.join(my_list) + '.'
Which would print:
the names in your list are: name1, name2, name3.
How do i print:
the names in your list are: name1, name2 and name3.
Thank you.
Update:
I am trying logic suggested below but the following is throwing errors:
my_list = ['name1', 'name2', 'name3']
if len(my_list) > 1:
# keep the last value as is
my_list[-1] = my_list[-1]
# change the second last value to be appended with 'and '
my_list[-2] = my_list[-2] + 'and '
# make all values until the second last value (exclusive) be appended with a comma
my_list[0:-3] = my_list[0:-3] + ', '
print 'The names in your list are:' .join(my_list) + '.'
Try this:
my_list = ['name1', 'name2', 'name3']
print 'The names in your list are: %s, %s and %s.' % (my_list[0], my_list[1], my_list[2])
The result is:
The names in your list are: name1, name2, and name3.
The %s is string formatting.
If the length of my_list was unknown:
my_list = ['name1', 'name2', 'name3']
if len(my_list) > 1: # If it was one, then the print statement would come out odd
my_list[-1] = 'and ' + my_list[-1]
print 'The names in your list are:', ', '.join(my_list[:-1]), my_list[-1] + '.'
My two cents:
def comma_and(a_list):
return ' and '.join([', '.join(a_list[:-1]), a_list[-1]] if len(a_list) > 1 else a_list)
Seems to work in all cases:
>>> comma_and(["11", "22", "33", "44"])
'11, 22, 33 and 44'
>>> comma_and(["11", "22", "33"])
'11, 22 and 33'
>>> comma_and(["11", "22"])
'11 and 22'
>>> comma_and(["11"])
'11'
>>> comma_and([])
''