Related
I have a long string, and I've extracted the substrings I wanted. I am looking for a method which uses less lines of code to get my output. I'm after all the sub strings which start with CN=., and removing everything else up-to the semi-colon..
example list output (see picture)
The script I'm currently using is below
import re
import fnmatch
import os
# System call
os.system("")
# Class of different styles
class style():
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
CNString = "CN=User2,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User4,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User56,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User9,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=Jane45 user,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User-Donna,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=User76 smith,OU=blurb,OU=Test4,DC=Test,DC=Testal;CN=Pink Panther,OU=blurb,OU=Test,DC=Testing,DC=Testal;CN=Testuser78,OU=blurb,OU=Tester,DC=Test,DC=Testal;CN=great Scott,OU=blurb,OU=Test,DC=Test,DC=Local;CN=Leah Human,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=Alan Desai,OU=blurb,OU=Test,DC=Test,DC=Testal;CN=Duff Beer,OU=Groups,OU=Test,DC=Test,DC=Testal;CN=Jane Doe,OU=Users,OU=Test76,DC=Test,DC=Testal;CN=simple user67,OU=Users,OU=Test,DC=Test,DC=Testal;CN=test O'Lord,OU=Users,OU=Test,DC=Concero,DC=Testal"
newstring1 = CNString.replace(';','];')
print(newstring1)
newstring2 = newstring1.replace(',OU=',',[OU=')
print(newstring2)
newstring3 = newstring2.replace(',[OU','],[OU')
print(newstring3)
newstring4 = newstring3.replace('],[OU',',[OU')
print(newstring4)
newstring5 = newstring4.replace('];',']];')
print(newstring5)
endstring = "]]"
newstring6 = newstring5 + endstring
print(newstring6)
newstring7 = re.sub("\[.*?\]","()",newstring6)
print(newstring7)
print(style.YELLOW + "Line Break")
newstring8 = newstring7.replace(',()]','')
print(style.RESET + newstring8)
newstring9 = newstring8.split(';')
for cnname in newstring9:
print(style.GREEN + cnname)
Not sure why your code is juggling with those square brackets. Wouldn't this do it?
names = re.findall(r"\bCN=[^,;]*", CNString)
cn_list = [elem.split(",")[0] for elem in CNString.split(";") if elem.startswith("CN=")]
If I print cn_list I obtain:
['CN=User2', 'CN=User4', 'CN=User56', 'CN=User9', 'CN=Jane45 user', 'CN=User-Donna', 'CN=User76 smith', 'CN=Pink Panther', 'CN=Testuser78', 'CN=great Scott', 'CN=Leah Human', 'CN=Alan Desai', 'CN=Duff Beer', 'CN=Jane Doe', 'CN=simple user67', "CN=test O'Lord"]
I am trying to generate PDF files from generated image. The generated PDF file has high level of pixelation on zooming in which is creating shadows during printing.
Image of zoomed in qrcode from PDF
Showing gray zone around qrcode modules and pixels (gray) which should be white otherwise. It does not matter if the desired_resolution matches or is lower than the resolution in which the original image was created.
What could be the issue and possible fixes?
qr_size_mm = 8
MM2PX_FACTOR = 94.48 # 2400 dpi
def create_code(prefix, number, postfix=None):
message = prefix + str(number)
message += postfix if postfix is not None else ""
series_qrcode = pyqrcode.create(message, error='H', version=3, mode='binary')
# print(series_qrcode.get_png_size())
binary = BytesIO()
desired_scale = int(qr_size_px / series_qrcode.get_png_size())
series_qrcode.png(binary, scale=desired_scale, module_color=(0, 0, 0),
background=(255, 255, 255), quiet_zone=3)
tmpIm = Image.open(binary).convert('RGB')
qr_dim = tmpIm.getbbox()
# print(qr_dim)
return tmpIm, qr_dim
qr_size_px = int(qr_size_mm * MM2PX_FACTOR)
# create A4 canvas
paper_width_mm = 210
paper_height_mm = 297
start_offset_mm = 10
start_offset_px = start_offset_mm * MM2PX_FACTOR
canvas_width_px = int(paper_width_mm * MM2PX_FACTOR)
canvas_height_px = int(paper_height_mm * MM2PX_FACTOR)
pil_paper_canvas = Image.new('RGB', (canvas_width_px, canvas_height_px), (255, 255, 255))
# desired pixels for 1200 dpi print
required_resolution_px = 94.48 # 47.244 # 23.622
required_resolution = 2400
print("Page dimension {page_width} {page_height} offset {offset}".format(page_width=canvas_width_px, page_height=canvas_height_px, offset=start_offset_px))
start_range = 10000100000000
for n in range(0, 5):
print("Generating ", start_range+n)
qr_image, qr_box = create_code("TLTR", number=start_range+n)
# qr_image.show()
print("qr_box ", qr_box)
qr_x = int(start_offset_px + ((n+1) * qr_box[2]))
qr_y = int(start_offset_px)
print("pasting at ", qr_x, qr_y)
pil_paper_canvas.paste(qr_image, (qr_x, qr_y))
# create a canvas just for current qrcode
one_qr_canvas = Image.new('RGB', (int(10*MM2PX_FACTOR), int(10*MM2PX_FACTOR)), (255, 255, 255))
qrXY = int((10*MM2PX_FACTOR - qr_box[2]) / 2)
one_qr_canvas.paste(qr_image, (qrXY, qrXY))
one_qr_canvas = one_qr_canvas.resize((int(qr_size_mm*required_resolution_px),
int(qr_size_mm*required_resolution_px)))
one_qr_canvas.save(form_full_path("TLTR"+str(start_range+n)+".pdf"), dpi=(required_resolution, required_resolution))
pil_paper_canvas = pil_paper_canvas.resize((int(paper_width_mm*required_resolution_px),
int(paper_height_mm*required_resolution_px)))
# pil_paper_canvas.show()
pil_paper_canvas.save(form_full_path("TLTR_qr_A4.pdf"), dpi=(required_resolution, required_resolution))
I incorporated 3 changes to fix/workaround the issue:
Instead of specifying fixed number for resizing, switched to scale (m*n).
Used lineType=cv2.LINE_AA for anti-aliasing as suggested by #physicalattraction
That still one issue unresolved which was that PIL generated PDF #96dpi which is not good for printing. Was unable to figure the option to use Print-ready PDF (PDF/A or something on those lines). Hence switched to generating PNG to generate high-quality qrcodes.
I am fairly new to Processing but I have managed to make a good amount of a GUI in the Python Mode. I wanted to graph some data on a white box. I don't want to use background(0) because that'll make the entire window white. Using a rectangular in the draw() function also did not help as the rectangular kept on refreshing the graph. I am trying to simulate the hold on function as in MATLAB
Here's my pseudo code:
class plotEverything:
def __init__
def plotAxis
def plotGraph
def clearGraph
def setup():
size (800,600)
p1 = plotEverything()
background(0)
def draw():
rect (100,100,200,200)
fill(255)
p1.drawAxis()
p1.plotGraph()
Is there any way I can make that rectangle fixed in the background?
EDIT Added graph class | Ignore indents(Assume they are all properly indented) --
class graphData:
def __init__(self, originX, originY, xUpper, yUpper):
self.originX = originX
self.originY = originY
self.xUpper = xUpper
self.yUpper = yUpper
self.pointX1 = originX
self.pointX2 = xUpper
self.pointY1 = originY
self.pointY2 = yUpper
self.scaleFactorX = 10.0/(xUpper - originX) #Assuming data is between is 0 and 10
self.scaleFactorY = 10.0/(originY - yUpper) #Assuming data is between is 0 and 1
def drawAxis(self):
stroke(255)
strokeWeight(1.5)
line(self.originX, self.originY, self.originX, self.yUpper) #y axis
line(self.originX, self.originY, self.xUpper, self.originY) #x axis
def plotStaticData(self,data2Plot): #X-axis static
ab = zip(data2Plot,data2Plot[1:],data2Plot[2:],data2Plot[3:])[::2]
if ab:
(X1,Y1,X2,Y2) = ab[-1]
print (X1,Y1,X2,Y2)
self.pointX1 = self.originX + ceil((float(X1) - 0.0)/self.scaleFactorX)
self.pointX2 = self.originX + ceil((float(X2) - 0.0)/self.scaleFactorX)
self.pointY1 = self.originY - ceil((float(Y1) - 0.0)/self.scaleFactorY)
self.pointY2 = self.originY - ceil((float(Y2) - 0.0)/self.scaleFactorY)
stroke(255)
strokeWeight(2.0)
line(self.pointX1,self.pointY1,self.pointX2,self.pointY2)
def clearPlot(self):
background(0)
self.drawAxis()
I make 2 python files: MineSweeping.py and CmdColor.py
And in MineSweeping.py I want to call a func defined in CmdColor.py to make the shell with color output, but failed.
The code of CmdColor.py is below:
#!/usr/bin/env python
#encoding: utf-8
import ctypes
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE= -11
STD_ERROR_HANDLE = -12
FOREGROUND_BLACK = 0x0
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN= 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text color contains red.
FOREGROUND_INTENSITY = 0x08 # text color is intensified.
BACKGROUND_BLUE = 0x10 # background color contains blue.
BACKGROUND_GREEN= 0x20 # background color contains green.
BACKGROUND_RED = 0x40 # background color contains red.
BACKGROUND_INTENSITY = 0x80 # background color is intensified.
class Color:
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
def set_cmd_color(self, color, handle=std_out_handle):
"""(color) -> bit
Example: set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
"""
bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
return bool
def reset_color(self):
self.set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
def print_red_text(self, print_text):
self.set_cmd_color(FOREGROUND_RED | FOREGROUND_INTENSITY)
print print_text
self.reset_color()
if __name__ == "__main__":
clr = Color()
clr.print_red_text('red')
clr.print_green_text('green')
clr.print_blue_text('blue')
clr.print_red_text_with_blue_bg('background')
And in MineSweeping.py I do so to call the func:
import CmdColor
...
clr = CmdColor.Color()
clr.print_red_text('red')
But the output string 'red' is white
If I merge the CmdColor.py into abc.py, then it can output a red string of 'red'.
The code can be found here:
https://github.com/tomxuetoy/Python_MineSweeping
Why?
Thanks!
I'm trying to implement colour cycling on my text in Python, ie i want it to cycle through the colour of every character typed (amongst other effects) My progress so far has been hacked together from an ansi colour recipe improvement suggestions welcomed.
I was also vaguely aware of, but never used: termcolor, colorama, curses
during the hack i managed to make the attributes not work (ie reverse blink etc) and its not perfect probably mainly because I dont understand these lines properly:
cmd.append(format % (colours[tmpword]+fgoffset))
c=format % attrs[tmpword] if tmpword in attrs else None
if anyone can clarify that a bit, I would appreciate it. this runs and does something, but its not quite there. I changed the code so instead of having to separate colour commands from your string you can include them.
#!/usr/bin/env python
'''
"arg" is a string or None
if "arg" is None : the terminal is reset to his default values.
if "arg" is a string it must contain "sep" separated values.
if args are found in globals "attrs" or "colors", or start with "#" \
they are interpreted as ANSI commands else they are output as text.
#* commands:
#x;y : go to xy
# : go to 1;1
## : clear screen and go to 1;1
#[colour] : set foreground colour
^[colour] : set background colour
examples:
echo('#red') : set red as the foreground color
echo('#red ^blue') : red on blue
echo('#red #blink') : blinking red
echo() : restore terminal default values
echo('#reverse') : swap default colors
echo('^cyan #blue reverse') : blue on cyan <=> echo('blue cyan)
echo('#red #reverse') : a way to set up the background only
echo('#red #reverse #blink') : you can specify any combinaison of \
attributes in any order with or without colors
echo('#blink Python') : output a blinking 'Python'
echo('## hello') : clear the screen and print 'hello' at 1;1
colours:
{'blue': 4, 'grey': 0, 'yellow': 3, 'green': 2, 'cyan': 6, 'magenta': 5, 'white': 7, 'red': 1}
'''
'''
Set ANSI Terminal Color and Attributes.
'''
from sys import stdout
import random
import sys
import time
esc = '%s['%chr(27)
reset = '%s0m'%esc
format = '1;%dm'
fgoffset, bgoffset = 30, 40
for k, v in dict(
attrs = 'none bold faint italic underline blink fast reverse concealed',
colours = 'grey red green yellow blue magenta cyan white'
).items(): globals()[k]=dict((s,i) for i,s in enumerate(v.split()))
bpoints = ( " [*] ", " [!] ", )
def echo(arg=None, sep=' ', end='\n', rndcase=True, txtspeed=0.03, bnum=0):
cmd, txt = [reset], []
if arg:
if bnum != 0:
sys.stdout.write(bpoints[bnum-1])
# split the line up into 'sep' seperated values - arglist
arglist=arg.split(sep)
# cycle through arglist - word seperated list
for word in arglist:
if word.startswith('#'):
### First check for a colour command next if deals with position ###
# go through each fg and bg colour
tmpword = word[1:]
if tmpword in colours:
cmd.append(format % (colours[tmpword]+fgoffset))
c=format % attrs[tmpword] if tmpword in attrs else None
if c and c not in cmd:
cmd.append(c)
stdout.write(esc.join(cmd))
continue
# positioning (starts with #)
word=word[1:]
if word=='#':
cmd.append('2J')
cmd.append('H')
stdout.write(esc.join(cmd))
continue
else:
cmd.append('%sH'%word)
stdout.write(esc.join(cmd))
continue
if word.startswith('^'):
### First check for a colour command next if deals with position ###
# go through each fg and bg colour
tmpword = word[1:]
if tmpword in colours:
cmd.append(format % (colours[tmpword]+bgoffset))
c=format % attrs[tmpword] if tmpword in attrs else None
if c and c not in cmd:
cmd.append(c)
stdout.write(esc.join(cmd))
continue
else:
for x in word:
if rndcase:
# thankyou mark!
if random.randint(0,1):
x = x.upper()
else:
x = x.lower()
stdout.write(x)
stdout.flush()
time.sleep(txtspeed)
stdout.write(' ')
time.sleep(txtspeed)
if txt and end: txt[-1]+=end
stdout.write(esc.join(cmd)+sep.join(txt))
if __name__ == '__main__':
echo('##') # clear screen
#echo('#reverse') # attrs are ahem not working
print 'default colors at 1;1 on a cleared screen'
echo('#red hello this is red')
echo('#blue this is blue #red i can ^blue change #yellow blah #cyan the colours in ^default the text string')
print
echo()
echo('default')
echo('#cyan ^blue cyan blue')
print
echo()
echo('#cyan this text has a bullet point',bnum=1)
print
echo('#yellow this yellow text has another bullet point',bnum=2)
print
echo('#blue this blue text has a bullet point and no random case',bnum=1,rndcase=False)
print
echo('#red this red text has no bullet point, no random case and no typing effect',txtspeed=0,bnum=0,rndcase=False)
# echo('#blue ^cyan blue cyan')
#echo('#red #reverse red reverse')
# echo('yellow red yellow on red 1')
# echo('yellow,red,yellow on red 2', sep=',')
# print 'yellow on red 3'
# for bg in colours:
# echo(bg.title().center(8), sep='.', end='')
# for fg in colours:
# att=[fg, bg]
# if fg==bg: att.append('blink')
# att.append(fg.center(8))
# echo(','.join(att), sep=',', end='')
#for att in attrs:
# echo('%s,%s' % (att, att.title().center(10)), sep=',', end='')
# print
from time import sleep, strftime, gmtime
colist='#grey #blue #cyan #white #cyan #blue'.split()
while True:
try:
for c in colist:
sleep(.1)
echo('%s #28;33 hit ctrl-c to quit' % c,txtspeed=0)
echo('%s #29;33 hit ctrl-c to quit' % c,rndcase=False,txtspeed=0)
#echo('#yellow #6;66 %s' % strftime('%H:%M:%S', gmtime()))
except KeyboardInterrupt:
break
except:
raise
echo('#10;1')
print
should also mention that i have absolutely no idea what this line does :) - well i see that it puts colours into a dictionary object, but how it does it is confusing. not used to this python syntax yet.
for k, v in dict(
attrs = 'none bold faint italic underline blink fast reverse concealed',
colours = 'grey red green yellow blue magenta cyan white'
).items(): globals()[k]=dict((s,i) for i,s in enumerate(v.split()))
This is a rather convoluted code - but, sticking to you r question, about the lines:
cmd.append(format % (colours[tmpword]+fgoffset))
This expression appends to the list named cmd the interpolation of the string contained in the variable format with the result of the expression (colours[tmpword]+fgoffset))- which concatenates the code in the color table (colours) named by tmpword with fgoffset.
The format string contains '1;%dm' which means it expects an integer number, whcih will replace the "%d" inside it. (Python's % string substitution inherits from C's printf formatting) . You "colours" color table ont he other hand is built in a convoluted way I'd recomend in no code, setting directly the entry in "globals" for it - but let's assume it does have the correct numeric value for each color entry. In that case, adding it to fgoffset will generate color codes out of range (IRCC, above 15) for some color codes and offsets.
Now the second line in which you are in doubt:
c=format % attrs[tmpword] if tmpword in attrs else None
This if is just Python's ternary operator - equivalent to the C'ish expr?:val1: val2
It is equivalent to:
if tmpword in attrs:
c = format % attrs[tmpword]
else:
c = format % None
Note that it has less precedence than the % operator.
Maybe you would prefer:
c= (format % attrs[tmpword]) if tmpword in attrs else ''
instead