Search Results

Search found 10741 results on 430 pages for 'self improvement'.

Page 4/430 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How to debug python del self.callbacks[s][cid] keyError when the error message does not indicate where in my code the error is

    - by lkloh
    In a python program I am writing, I get an error saying Traceback (most recent call last): File "/Applications/Canopy.app/appdata/canopy-1.4.0.1938.macosx- x86_64/Canopy.app/Contents/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__ return self.func(*args) File "/Users/lkloh/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 413, in button_release_event FigureCanvasBase.button_release_event(self, x, y, num, guiEvent=event) File "/Users/lkloh/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 1808, in button_release_event self.callbacks.process(s, event) File "/Users/lkloh/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/cbook.py", line 525, in process del self.callbacks[s][cid] KeyError: 103 Do you have any idea how I can debug this/ what could be wrong? The error message does not point to anywhere in code I have personally written. I get the error message only after I close my GUI window, but I want to fix it even though it does not break the functionality of my code. The error is part of a very big program I am writing, so I cannot post all my code, but below is code I think is relevant: def save(self, event): self.getSaveAxes() self.save_connect() def getSaveAxes(self): saveFigure = figure(figsize=(8,1)) saveFigure.clf() # size of save buttons rect_saveHeaders = [0.04,0.2,0.2,0.6] rect_saveHeadersFilterParams = [0.28,0.2,0.2,0.6] rect_saveHeadersOverride = [0.52,0.2,0.2,0.6] rect_saveQuit = [0.76,0.2,0.2,0.6] #initalize axes saveAxs = {} saveAxs['saveHeaders'] = saveFigure.add_axes(rect_saveHeaders) saveAxs['saveHeadersFilterParams'] = saveFigure.add_axes(rect_saveHeadersFilterParams) saveAxs['saveHeadersOverride'] = saveFigure.add_axes(rect_saveHeadersOverride) saveAxs['saveQuit'] = saveFigure.add_axes(rect_saveQuit) self.saveAxs = saveAxs self.save_connect() self.saveFigure = saveFigure show() def save_connect(self): #set buttons self.bn_saveHeaders = Button(self.saveAxs['saveHeaders'], 'Save\nHeaders\nOnly') self.bn_saveHeadersFilterParams = Button(self.saveAxs['saveHeadersFilterParams'], 'Save Headers &\n Filter Parameters') self.bn_saveHeadersOverride = Button(self.saveAxs['saveHeadersOverride'], 'Save Headers &\nOverride Data') self.bn_saveQuit = Button(self.saveAxs['saveQuit'], 'Quit') #connect buttons to functions they trigger self.cid_saveHeaders = self.bn_saveHeaders.on_clicked(self.save_headers) self.cid_savedHeadersFilterParams = self.bn_saveHeadersFilterParams.on_clicked(self.save_headers_filterParams) self.cid_saveHeadersOverride = self.bn_saveHeadersOverride.on_clicked(self.save_headers_override) self.cid_saveQuit = self.bn_saveQuit.on_clicked(self.save_quit) def save_quit(self, event): self.save_disconnect() close()

    Read the article

  • Pygame Sprite/Font rendering issues

    - by Grimless
    Hey guys. Here's my problem: I have a game class that maintains a HUD overlay that has a bunch of elements, including header and footer background sprites. Everything was working fine until I added a 1024x128 footer sprite. Now two of my text labels will not render, despite the fact that they DO exist in my Group and self.elements array. Is there something I'm missing? When I take out the footerHUDImage line, all of the labels render correctly and everything works fine. When I add the footerHUDImage, two of the labels (the first two) no longer render and the third only sometimes renders. HELP PLEASE! Here is the code: class AoWHUD (object): def __init__(self, screen, delegate, dataSource): self.delegate = delegate self.dataSource = dataSource self.elements = [] headerHudImage = KJRImage("HUDBackground.png") self.elements.append(headerHudImage) headerHudImage.userInteractionEnabled = True footerHUDImage = KJRImage("ControlsBackground.png") self.elements.append(footerHUDImage) footerHUDImage.rect.bottom = screen.get_rect().height footerHUDImage.userInteractionEnabled = True lumberMessage = "Lumber: " + str(self.dataSource.lumber) lumberLabel = KJRLabel(lumberMessage, size = 48, color = (240, 200, 10)) lumberLabel.rect.topleft = (_kSpacingMultiple * 0, 0) self.elements.append(lumberLabel) stoneMessage = "Stone: " + str(self.dataSource.stone) stoneLabel = KJRLabel(stoneMessage, size = 48, color = (240, 200, 10)) stoneLabel.rect.topleft = (_kSpacingMultiple * 1, 0) self.elements.append(stoneLabel) metalMessage = "Metal: " + str(self.dataSource.metal) metalLabel = KJRLabel(metalMessage, size = 48, color = (240, 200, 10)) metalLabel.rect.topleft = (_kSpacingMultiple * 2, 0) self.elements.append(metalLabel) foodMessage = "Food: " + str(len(self.dataSource.units)) + "/" + str(self.dataSource.food) foodLabel = KJRLabel(foodMessage, size = 48, color = (240, 200, 10)) foodLabel.rect.topleft = (_kSpacingMultiple * 3, 0) self.elements.append(foodLabel) self.selectionSprites = {32 : pygame.image.load("Selected32.png").convert_alpha(), 64 : pygame.image.load("Selected64.png")} self._sprites_ = pygame.sprite.Group() for e in self.elements: self._sprites_.add(e) print self.elements def draw(self, screen): if self.dataSource.resourcesChanged: lumberMessage = "Lumber: " + str(self.dataSource.lumber) stoneMessage = "Stone: " + str(self.dataSource.stone) metalMessage = "Metal: " + str(self.dataSource.metal) foodMessage = "Food: " + str(len(self.dataSource.units)) + "/" + str(self.dataSource.food) self.elements[2].setText(lumberMessage) self.elements[2].rect.topleft = (_kSpacingMultiple * 0, 0) self.elements[3].setText(stoneMessage) self.elements[3].rect.topleft = (_kSpacingMultiple * 1, 0) self.elements[4].setText(metalMessage) self.elements[4].rect.topleft = (_kSpacingMultiple * 2, 0) self.elements[5].setText(foodMessage) self.elements[5].rect.topleft = (_kSpacingMultiple * 3, 0) self.dataSource.resourcesChanged = False self._sprites_.draw(screen) if self.delegate.selectedUnit: theSelectionSprite = self.selectionSprites[self.delegate.selectedUnit.rect.width] screen.blit(theSelectionSprite, self.delegate.selectedUnit.rect)

    Read the article

  • Simple App Engine Sessions Implementation

    - by raz0r
    Here is a very basic class for handling sessions on App Engine: """Lightweight implementation of cookie-based sessions for Google App Engine. Classes: Session """ import os import random import Cookie from google.appengine.api import memcache _COOKIE_NAME = 'app-sid' _COOKIE_PATH = '/' _SESSION_EXPIRE_TIME = 180 * 60 class Session(object): """Cookie-based session implementation using Memcached.""" def __init__(self): self.sid = None self.key = None self.session = None cookie_str = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(cookie_str) if self.cookie.get(_COOKIE_NAME): self.sid = self.cookie[_COOKIE_NAME].value self.key = 'session-' + self.sid self.session = memcache.get(self.key) if self.session: self._update_memcache() else: self.sid = str(random.random())[5:] + str(random.random())[5:] self.key = 'session-' + self.sid self.session = dict() memcache.add(self.key, self.session, _SESSION_EXPIRE_TIME) self.cookie[_COOKIE_NAME] = self.sid self.cookie[_COOKIE_NAME]['path'] = _COOKIE_PATH print self.cookie def __len__(self): return len(self.session) def __getitem__(self, key): if key in self.session: return self.session[key] raise KeyError(str(key)) def __setitem__(self, key, value): self.session[key] = value self._update_memcache() def __delitem__(self, key): if key in self.session: del self.session[key] self._update_memcache() return None raise KeyError(str(key)) def __contains__(self, item): try: i = self.__getitem__(item) except KeyError: return False return True def _update_memcache(self): memcache.replace(self.key, self.session, _SESSION_EXPIRE_TIME) I would like some advices on how to improve the code for better security. Note: In the production version it will also save a copy of the session in the datastore. Note': I know there are much more complete implementations available online though I would like to learn more about this subject so please don't answer the question with "use that" or "use the other" library.

    Read the article

  • Bounding Box Collision Glitching Problem (Pygame)

    - by Ericson Willians
    So far the "Bounding Box" method is the only one that I know. It's efficient enough to deal with simple games. Nevertheless, the game I'm developing is not that simple anymore and for that reason, I've made a simplified example of the problem. (It's worth noticing that I don't have rotating sprites on my game or anything like that. After showing the code, I'll explain better). Here's the whole code: from pygame import * DONE = False screen = display.set_mode((1024,768)) class Thing(): def __init__(self,x,y,w,h,s,c): self.x = x self.y = y self.w = w self.h = h self.s = s self.sur = Surface((64,48)) draw.rect(self.sur,c,(self.x,self.y,w,h),1) self.sur.fill(c) def draw(self): screen.blit(self.sur,(self.x,self.y)) def move(self,x): if key.get_pressed()[K_w] or key.get_pressed()[K_UP]: if x == 1: self.y -= self.s else: self.y += self.s if key.get_pressed()[K_s] or key.get_pressed()[K_DOWN]: if x == 1: self.y += self.s else: self.y -= self.s if key.get_pressed()[K_a] or key.get_pressed()[K_LEFT]: if x == 1: self.x -= self.s else: self.x += self.s if key.get_pressed()[K_d] or key.get_pressed()[K_RIGHT]: if x == 1: self.x += self.s else: self.x -= self.s def warp(self): if self.y < -48: self.y = 768 if self.y > 768 + 48: self.y = 0 if self.x < -64: self.x = 1024 + 64 if self.x > 1024 + 64: self.x = -64 r1 = Thing(0,0,64,48,1,(0,255,0)) r2 = Thing(6*64,6*48,64,48,1,(255,0,0)) while not DONE: screen.fill((0,0,0)) r2.draw() r1.draw() # If not intersecting, then moves, else, it moves in the opposite direction. if not ((((r1.x + r1.w) > (r2.x - r1.s)) and (r1.x < ((r2.x + r2.w) + r1.s))) and (((r1.y + r1.h) > (r2.y - r1.s)) and (r1.y < ((r2.y + r2.h) + r1.s)))): r1.move(1) else: r1.move(0) r1.warp() if key.get_pressed()[K_ESCAPE]: DONE = True for ev in event.get(): if ev.type == QUIT: DONE = True display.update() quit() The problem: In my actual game, the grid is fixed and each tile has 64 by 48 pixels. I know how to deal with collision perfectly if I moved by that size. Nevertheless, obviously, the player moves really fast. In the example, the collision is detected pretty well (Just as I see in many examples throughout the internet). The problem is that if I put the player to move WHEN IS NOT intersecting, then, when it touches the obstacle, it does not move anymore. Giving that problem, I began switching the directions, but then, when it touches and I press the opposite key, it "glitches through". My actual game has many walls, and the player will touch them many times, and I can't afford letting the player go through them. The code-problem illustrated: When the player goes towards the wall (Fine). When the player goes towards the wall and press the opposite direction. (It glitches through). Here is the logic I've designed before implementing it: I don't know any other method, and I really just want to have walls fixed in a grid, but move by 1 or 2 or 3 pixels (Slowly) and have perfect collision without glitching-possibilities. What do you suggest?

    Read the article

  • PyQt threads and signals - how to properly retrieve values

    - by Cawas
    Using Python 2.5 and PyQt, I couldn't find any question this specific in Python, so sorry if I'm repeating the other Qt referenced questions below, but I couldn't easily understand that C code. I've got two classes, a GUI and a thread, and I'm trying to get return values from the thread. I've used the link in here as base to write my code, which is working just fine. To sum it up and illustrate the question in code here (I don't think this code will run on itself): class MainWindow (QtGui.QWidget): # this is just a reference and not really relevant to the question def __init__ (self, parent = None): QtGui.QWidget.__init__(self, parent) self.thread = Worker() # this does not begin a thread - look at "Worker.run" for mor details self.connect(self.thread, QtCore.SIGNAL('finished()'), self.unfreezeUi) self.connect(self.thread, QtCore.SIGNAL('terminated()'), self.unfreezeUi) self.connect(self.buttonDaemon, QtCore.SIGNAL('clicked()'), self.pressDaemon) # the problem begins below: I'm not using signals, or queue, or whatever, while I believe I should def pressDaemon (self): self.buttonDaemon.setEnabled(False) if self.thread.isDaemonRunning(): self.thread.setDaemonStopSignal(True) self.buttonDaemon.setText('Daemon - converts every %s sec'% args['daemonInterval']) else: self.buttonConvert.setEnabled(False) self.thread.startDaemon() self.buttonDaemon.setText('Stop Daemon') self.buttonDaemon.setEnabled(True) # this whole class is just another reference class Worker (QtCore.QThread): daemonIsRunning = False daemonStopSignal = False daemonCurrentDelay = 0 def isDaemonRunning (self): return self.daemonIsRunning def setDaemonStopSignal (self, bool): self.daemonStopSignal = bool def __init__ (self, parent = None): QtCore.QThread.__init__(self, parent) self.exiting = False self.thread_to_run = None # which def will be running def __del__ (self): self.exiting = True self.thread_to_run = None self.wait() def run (self): if self.thread_to_run != None: self.thread_to_run(mode='continue') def startDaemon (self, mode = 'run'): if mode == 'run': self.thread_to_run = self.startDaemon # I'd love to be able to just pass this as an argument on start() below return self.start() # this will begin the thread # this is where the thread actually begins self.daemonIsRunning = True self.daemonStopSignal = False sleepStep = 0.1 # don't know how to interrupt while sleeping - so the less sleepStep, the faster StopSignal will work # begins the daemon in an "infinite" loop while self.daemonStopSignal == False and not self.exiting: # here, do any kind of daemon service delay = 0 while self.daemonStopSignal == False and not self.exiting and delay < args['daemonInterval']: time.sleep(sleepStep) # delay is actually set by while, but this holds for N second delay += sleepStep # daemon stopped, reseting everything self.daemonIsRunning = False self.emit(QtCore.SIGNAL('terminated')) Tho it's quite big, I hope this is pretty clear. The main point is on def pressDaemon. Specifically all 3 self.thread calls. The last one, self.thread.startDaemon() is just fine, and exactly as the example. I doubt that represents any issue. The problem is being able to set the Daemon Stop Signal and retrieve the value if it's running. I'm not sure that it's possible to set a stop signal on QtCore.QtThread, because I've tried doing the same way and it didn't work. But I'm pretty sure it's not possible to retrieve a return result from the emit. So, there it is. I'm using direct calls to the thread class, and I'm almost positive that's not a good design and will probably fail when running under stress. I read about that queue, but I'm not sure it's the proper solution here, or if I should be using Qt at all, since this is Python. And just maybe there's nothing wrong with the way I'm doing.

    Read the article

  • Problem in understanding connectSlotsByName() in pyqt???

    - by Jebagnanadas
    Hi all, I couldn't understand the connectSlotsByName() method which is predominently used by pyuic4.. As far the class is single in a PyQt file it's ok since we can use self which will be associated with a single object throughout.. But when we try to use various classes from different files the problem and the need to use connectSlotsByName() arises.. Here's what i encountered which is weird.. I created a stacked widget.. I placed my first widget on it.. It has a button called "Next ". On clicking next it hides the current widget and adds another widget which has the "click me" button.. The problem here is the click event for "click me" button in second is not captured.. It's a minimal example that i can give for my original problem.. Please help me.. This is file No.1..(which has the parent stacked widget and it's first page). On clicking next it adds the second page which has "clickme" button in file2.. from PyQt4 import QtCore, QtGui import file2 class Ui_StackedWidget(QtGui.QStackedWidget): def __init__(self,parent=None): QtGui.QStackedWidget.__init__(self,parent) self.setObjectName("self") self.resize(484, 370) self.setWindowTitle(QtGui.QApplication.translate("self", "stacked widget", None, QtGui.QApplication.UnicodeUTF8)) self.createWidget1() def createWidget1(self): self.page=QtGui.QWidget() self.page.setObjectName("widget1") self.pushButton=QtGui.QPushButton(self.page) self.pushButton.setGeometry(QtCore.QRect(150, 230, 91, 31)) self.pushButton.setText(QtGui.QApplication.translate("self", "Next >", None, QtGui.QApplication.UnicodeUTF8)) self.addWidget(self.page) QtCore.QMetaObject.connectSlotsByName(self.page) QtCore.QObject.connect(self.pushButton,QtCore.SIGNAL('clicked()'),self.showWidget2) def showWidget2(self): self.page.hide() obj=file2.widget2() obj.createWidget2(self) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) ui = Ui_StackedWidget() ui.show() sys.exit(app.exec_()) Here's file2 from PyQt4 import QtGui,QtCore class widget2(): def createWidget2(self,parent): self.page = QtGui.QWidget() self.page.setObjectName("page") self.parent=parent self.groupBox = QtGui.QGroupBox(self.page) self.groupBox.setGeometry(QtCore.QRect(30, 20, 421, 311)) self.groupBox.setObjectName("groupBox") self.groupBox.setTitle(QtGui.QApplication.translate("self", "TestGroupBox", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton = QtGui.QPushButton(self.groupBox) self.pushButton.setGeometry(QtCore.QRect(150, 120, 92, 28)) self.pushButton.setObjectName("pushButton") self.pushButton.setText(QtGui.QApplication.translate("self", "Click Me", None, QtGui.QApplication.UnicodeUTF8)) self.parent.addWidget(self.page) self.parent.setCurrentWidget(self.page) QtCore.QMetaObject.connectSlotsByName(self.page) QtCore.QObject.connect(self.pushButton,QtCore.SIGNAL('clicked()'),self.printMessage) def printMessage(self): print("Hai") Though in both the widgets(i mean pages) QtCore.QMetaObject.connectSlotsByName(self.page) the clicked signal in second dialog isn't getting processed. Thanks in advance.. Might be a beginner question..

    Read the article

  • Oracle University Nouveaux cours (Week 35)

    - by swalker
    Parmi les nouveautés d’Oracle Université de ce mois-ci, vous trouverez : Fusion Middleware Oracle Directory Services 11g: Administration (5 days) Oracle SOA Suite 11g: Essential Concepts (Training on Demand) e-Business Suite R12 Oracle HRMS iRecruitment Fundamentals (Self-Study Course) R12 Oracle Payroll Fundamentals: Administration (Self-Study Course) R12 Oracle HRMS System Administration Fundamentals (Self-Study Course) R12 Oracle HRMS Self Service Fundamentals (Self-Study Course) R12 Oracle HRMS Implement and Use Fast Formula (Self-Study Course) R12 HRMS Work Structures Fundamentals (Self-Study Course) R12 HRMS Total Compensation Foundations (Self-Study Course) Siebel Siebel 8.1.x Chat and Voice Integration Using CCA (Self-Study Course) Siebel 8.1.x Search using Oracle Secure Enterprise Search (Self-Study Course) Siebel 8.1.x COM Web Services (Self-Study Course) Siebel 8.1.x COM Asset Based Order Management (Self-Study Course) Siebel 8.1.x COM: What is New in Product Configurator (Self-Study Course) Siebel 8.1.x COM Product Configurator Caching & Performance Management (Self-Study Course) Siebel 8.1.x COM PSP Engine Caching and Performance Management (Self-Study Course) Siebel 8.1.x Remote: Administration (Self-Study Course) Siebel 8.1.x Remote: Technical Foundations (Self-Study Course) Siebel Tools: Configuring Chart and Tree Applets (Self-Study Course) Sun - Server Administration SPARC SuperCluster Administration and Maintenance Seminar (2 days) OPN Only Sparc T4-Based Servers Installation Boot Camp (1 day) Primavera Primavera P6 Application Administration Rel 8.x (2 days) Oracle Retail Retail Merchandising System (RMS) Business Overview (Self-Study Course) Retail Invoice Matching (ReIM) Product Overview (Self-Study Course) Retail Invoice Matching (ReIM) Business Introduction (Self-Study Course) Retail Demand Forecasting: RDF Classic Product Overview (Self-Study Course) Retail Demand Forecasting Introduction (Self-Study Course) Retail Data Warehouse (RDW) Overview 13.1 (Self-Study Course) Oracle Retail Point-of-Service (POS) Product Overview (Self-Study Course) Retail Sales Audit (ReSA) Product Overview (Self-Study Course) Retail Price Management (RPM) Product Overview (Self-Study Course) Retail Merchandising System (RMS) Technical Introduction (Self-Study Course) Oracle Retail Integration Bus (RIB) Product Overview (Self-Study Course) Oracle Communiucations Unified Communications Suite Convergence Customization (2 days) OSM Foundations I: Tasks, Processes and Orders Contacter l’ équipe locale d’ Oracle University pour toute information et dates de cours. Restez connecté à Oracle University : LinkedIn OracleMix Twitter Facebook Google+

    Read the article

  • Oracle University New Courses (Week 35)

    - by swalker
    Oracle University released the following new (versions of) courses recently: Fusion Middleware Oracle Directory Services 11g: Administration (5 days) Oracle SOA Suite 11g: Essential Concepts (Training on Demand) e-Business Suite R12 Oracle HRMS iRecruitment Fundamentals (Self-Study Course) R12 Oracle Payroll Fundamentals: Administration (Self-Study Course) R12 Oracle HRMS System Administration Fundamentals (Self-Study Course) R12 Oracle HRMS Self Service Fundamentals (Self-Study Course) R12 Oracle HRMS Implement and Use Fast Formula (Self-Study Course) R12 HRMS Work Structures Fundamentals (Self-Study Course) R12 HRMS Total Compensation Foundations (Self-Study Course) Siebel Siebel 8.1.x Chat and Voice Integration Using CCA (Self-Study Course) Siebel 8.1.x Search using Oracle Secure Enterprise Search (Self-Study Course) Siebel 8.1.x COM Web Services (Self-Study Course) Siebel 8.1.x COM Asset Based Order Management (Self-Study Course) Siebel 8.1.x COM: What is New in Product Configurator (Self-Study Course) Siebel 8.1.x COM Product Configurator Caching & Performance Management (Self-Study Course) Siebel 8.1.x COM PSP Engine Caching and Performance Management (Self-Study Course) Siebel 8.1.x Remote: Administration (Self-Study Course) Siebel 8.1.x Remote: Technical Foundations (Self-Study Course) Siebel Tools: Configuring Chart and Tree Applets (Self-Study Course) Sun - Server Administration SPARC SuperCluster Administration and Maintenance Seminar (2 days) OPN Only Sparc T4-Based Servers Installation Boot Camp (1 day) Primavera Primavera P6 Application Administration Rel 8.x (2 days) Oracle Retail Retail Merchandising System (RMS) Business Overview (Self-Study Course) Retail Invoice Matching (ReIM) Product Overview (Self-Study Course) Retail Invoice Matching (ReIM) Business Introduction (Self-Study Course) Retail Demand Forecasting: RDF Classic Product Overview (Self-Study Course) Retail Demand Forecasting Introduction (Self-Study Course) Retail Data Warehouse (RDW) Overview 13.1 (Self-Study Course) Oracle Retail Point-of-Service (POS) Product Overview (Self-Study Course) Retail Sales Audit (ReSA) Product Overview (Self-Study Course) Retail Price Management (RPM) Product Overview (Self-Study Course) Retail Merchandising System (RMS) Technical Introduction (Self-Study Course) Oracle Retail Integration Bus (RIB) Product Overview (Self-Study Course) Oracle Communiucations Unified Communications Suite Convergence Customization (2 days) OSM Foundations I: Tasks, Processes and Orders Get in contact with your local Oracle University team for more details and course dates. Stay Connected to Oracle University: LinkedIn OracleMix Twitter Facebook Google+

    Read the article

  • Global name not defined

    - by anteater7171
    I wrote a CPU monitoring program in Python. For some reason sometimes the the program will run without any problem. Then other times the program won't even start because of the following error. Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\Python26\CPUR1.7.pyw", line 601, in app = simpleapp_tk(None) File "C:\Python26\CPUR1.7.pyw", line 26, in init self.initialize() File "C:\Python26\CPUR1.7.pyw", line 107, in initialize self.F() File "C:\Python26\CPUR1.7.pyw", line 517, in F S2 = TL.entryVariableS.get() NameError: global name 'TL' is not defined I can't seem to find the problem, maybe someone more experienced may assist me? Here is a snippet of the part giving me trouble: (The second to last line in the snippet is what's giving me trouble) def E(self): if self.selectedM.get() =='Options...': Setup global TL TL = Tkinter.Toplevel(self) menu = Tkinter.Menu(TL) TL.config(menu=menu) filemenu = Tkinter.Menu(menu) menu.add_cascade(label="| Menu |", menu=filemenu) filemenu.add_command(label="Instruction Manual...", command=self.helpmenu) filemenu.add_command(label="About...", command=self.aboutmenu) filemenu.add_separator() filemenu.add_command(label="Exit Options", command=TL.destroy) filemenu.add_command(label="Exit", command=self.destroy) helpmenu = Tkinter.Menu(menu) menu.add_cascade(label="| Help |", menu=helpmenu) helpmenu.add_command(label="Instruction Manual...", command=self.helpmenu) helpmenu.add_separator() helpmenu.add_command(label="Quick Help...", command=self.helpmenu) Title TL.label5 = Tkinter.Label(TL,text="CPU Usage: Options",anchor="center",fg="black",bg="lightgreen",relief="ridge",borderwidth=5,font=('Arial', 18, 'bold')) TL.label5.pack(padx=15,ipadx=5) X Y scale TL.separator = Tkinter.Frame(TL,height=7, bd=1, relief='ridge', bg='grey95') TL.separator.pack(pady=5,padx=5) # TL.sclX = Tkinter.Scale(TL.separator, from_=0, to=1500, orient='horizontal', resolution=1, command=self.A) TL.sclX.grid(column=1,row=0,ipadx=27, sticky='w') TL.label1 = Tkinter.Label(TL.separator,text="X",anchor="s",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label1.grid(column=0,row=0, pady=1, sticky='S') TL.sclY = Tkinter.Scale(TL.separator, from_=0, to=1500, resolution=1, command=self.A) TL.sclY.grid(column=2,row=1,rowspan=2,sticky='e', padx=4) TL.label3 = Tkinter.Label(TL.separator,text="Y",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label3.grid(column=2,row=0, padx=10, sticky='e') TL.entryVariable2 = Tkinter.StringVar() TL.entry2 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable2, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry2.grid(column=1,row=1,ipadx=20, pady=10,sticky='EW') TL.entry2.bind("<Return>", self.B) TL.label2 = Tkinter.Label(TL.separator,text="X:",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label2.grid(column=0,row=1, ipadx=4, sticky='W') TL.entryVariable1 = Tkinter.StringVar() TL.entry1 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable1, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry1.grid(column=1,row=2,sticky='EW') TL.entry1.bind("<Return>", self.B) TL.label4 = Tkinter.Label(TL.separator,text="Y:", anchor="center",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label4.grid(column=0,row=2, ipadx=4, sticky='W') TL.label7 = Tkinter.Label(TL.separator,text="Text Colour:",fg="black",bg="grey95",font=('Arial', 8 ,'bold'),justify='left') TL.label7.grid(column=1,row=3, sticky='W',padx=10,ipady=10,ipadx=30) TL.selectedP = Tkinter.StringVar() TL.opt1 = Tkinter.OptionMenu(TL.separator, TL.selectedP,'Normal', 'White','Black', 'Blue', 'Steel Blue','Green','Light Green','Yellow','Orange' ,'Red',command=self.G) TL.opt1.config(fg="black",bg="grey90",activebackground="grey90",activeforeground="black", anchor="center",relief="raised",direction='right',font=('Arial', 10)) TL.opt1.grid(column=1,row=4,sticky='EW',padx=20,ipadx=20) TL.selectedP.set('Normal') TL.sclS = Tkinter.Scale(TL.separator, from_=10, to=2000, orient='horizontal', resolution=10, command=self.H) TL.sclS.grid(column=1,row=5,ipadx=27, sticky='w') TL.sclS.set(600) TL.entryVariableS = Tkinter.StringVar() TL.entryS = Tkinter.Entry(TL.separator,textvariable=TL.entryVariableS, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entryS.grid(column=1,row=6,ipadx=20, pady=10,sticky='EW') TL.entryS.bind("<Return>", self.I) TL.entryVariableS.set(600) # TL.resizable(False,False) TL.title('Options') geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") s = self.wm_geometry() m = geomPatt.search(s) X = m.group(4) Y = m.group(6) TL.sclY.set(Y) TL.sclX.set(X) if self.selectedM.get() == 'Exit': self.destroy() def F (self): G = round(psutil.cpu_percent(), 1) G1 = str(G) + '%' self.labelVariable.set(G1) if G < 5: self.imageLabel.configure(image=self.image0) if G >= 5: self.imageLabel.configure(image=self.image5) if G >= 10: self.imageLabel.configure(image=self.image10) if G >= 15: self.imageLabel.configure(image=self.image15) if G >= 20: self.imageLabel.configure(image=self.image20) if G >= 25: self.imageLabel.configure(image=self.image25) if G >= 30: self.imageLabel.configure(image=self.image30) if G >= 35: self.imageLabel.configure(image=self.image35) if G >= 40: self.imageLabel.configure(image=self.image40) if G >= 45: self.imageLabel.configure(image=self.image45) if G >= 50: self.imageLabel.configure(image=self.image50) if G >= 55: self.imageLabel.configure(image=self.image55) if G >= 60: self.imageLabel.configure(image=self.image60) if G >= 65: self.imageLabel.configure(image=self.image65) if G >= 70: self.imageLabel.configure(image=self.image70) if G >= 75: self.imageLabel.configure(image=self.image75) if G >= 80: self.imageLabel.configure(image=self.image80) if G >= 85: self.imageLabel.configure(image=self.image85) if G >= 90: self.imageLabel.configure(image=self.image90) if 100> G >= 95: self.imageLabel.configure(image=self.image95) if G == 100: self.imageLabel.configure(image=self.image100) S2 = TL.entryVariableS.get() self.after(int(S2), self.F)

    Read the article

  • Why does this valid Tkinter code crash when mixed with a bit of PyWin32?

    - by Erlog
    So I'm making a very small program for personal use in tkinter, and I've run into a really strange wall. I'm mixing tkinter with the pywin32 bindings because I really hate everything to do with the syntax and naming conventions of pywin32, and it feels like tkinter gets more done with far less code. The strangeness is happening in the transition between the pywin32 clipboard watching and my program's reaction to it in tkinter. My window and all its controls are being handled in tkinter. The pywin32 bindings are doing clipboard watching and clipboard access when the clipboard changes. From what I've gathered about the way the clipboard watching pieces of pywin32 work, you can make it work with anything you want as long as you provide pywin32 with the hwnd value of your window. I'm doing that part, and it works when the program first starts. It just doesn't seem to work when the clipboard changes. When the program launches, it grabs the clipboard and puts it into the search box and edit box just fine. When the clipboard is modified, the event I want to fire off is firing off...except that event that totally worked before when the program launched is now causing a weird hang instead of doing what it's supposed to do. I can print the clipboard contents to stdout all I want if the clipboard changes, but not put that same data into a tkinter widget. It only hangs like that if it starts to interact with any of my tkinter widgets after being fired off by a clipboard change notification. It feels like there's some pywin32 etiquette I've missed in adapting the clipboard-watching sample code I was using over to my tkinter-using program. Tkinter apparently doesn't like to produce stack traces or error messages, and I can't really even begin to know what to look for trying to debug it with pdb. Here's the code: #coding: utf-8 #Clipboard watching cribbed from ## {{{ http://code.activestate.com/recipes/355593/ (r1) import pdb from Tkinter import * import win32clipboard import win32api import win32gui import win32con import win32clipboard def force_unicode(object, encoding="utf-8"): if isinstance(object, basestring) and not isinstance(object, unicode): object = unicode(object, encoding) return object class Application(Frame): def __init__(self, master=None): self.master = master Frame.__init__(self, master) self.pack() self.createWidgets() self.hwnd = self.winfo_id() self.nextWnd = None self.first = True self.oldWndProc = win32gui.SetWindowLong(self.hwnd, win32con.GWL_WNDPROC, self.MyWndProc) try: self.nextWnd = win32clipboard.SetClipboardViewer(self.hwnd) except win32api.error: if win32api.GetLastError () == 0: # information that there is no other window in chain pass else: raise self.update_search_box() self.word_search() def word_search(self): #pdb.set_trace() term = self.searchbox.get() self.resultsbox.insert(END, term) def update_search_box(self): clipboardtext = "" if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT): win32clipboard.OpenClipboard() clipboardtext = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() if clipboardtext != "": self.searchbox.delete(0,END) clipboardtext = force_unicode(clipboardtext) self.searchbox.insert(0, clipboardtext) def createWidgets(self): self.button = Button(self) self.button["text"] = "Search" self.button["command"] = self.word_search self.searchbox = Entry(self) self.resultsbox = Text(self) #Pack everything down here for "easy" layout changes later self.searchbox.pack() self.button.pack() self.resultsbox.pack() def MyWndProc (self, hWnd, msg, wParam, lParam): if msg == win32con.WM_CHANGECBCHAIN: self.OnChangeCBChain(msg, wParam, lParam) elif msg == win32con.WM_DRAWCLIPBOARD: self.OnDrawClipboard(msg, wParam, lParam) # Restore the old WndProc. Notice the use of win32api # instead of win32gui here. This is to avoid an error due to # not passing a callable object. if msg == win32con.WM_DESTROY: if self.nextWnd: win32clipboard.ChangeClipboardChain (self.hwnd, self.nextWnd) else: win32clipboard.ChangeClipboardChain (self.hwnd, 0) win32api.SetWindowLong(self.hwnd, win32con.GWL_WNDPROC, self.oldWndProc) # Pass all messages (in this case, yours may be different) on # to the original WndProc return win32gui.CallWindowProc(self.oldWndProc, hWnd, msg, wParam, lParam) def OnChangeCBChain (self, msg, wParam, lParam): if self.nextWnd == wParam: # repair the chain self.nextWnd = lParam if self.nextWnd: # pass the message to the next window in chain win32api.SendMessage (self.nextWnd, msg, wParam, lParam) def OnDrawClipboard (self, msg, wParam, lParam): if self.first: self.first = False else: #print "changed" self.word_search() #self.word_search() if self.nextWnd: # pass the message to the next window in chain win32api.SendMessage(self.nextWnd, msg, wParam, lParam) if __name__ == "__main__": root = Tk() app = Application(master=root) app.mainloop() root.destroy()

    Read the article

  • How refresh a DrawingArea in PyGTK ?

    - by Lialon
    I have an interface created with Glade. It contains a DrawingArea and buttons. I tried to create a Thread to refresh every X time my Canva. After a few seconds, I get error messages like: "X Window Server 0.0", "Fatal Error IO 11" Here is my code : import pygtk pygtk.require("2.0") import gtk import Canvas import threading as T import time import Map gtk.gdk.threads_init() class Interface(object): class ThreadCanvas(T.Thread): """Thread to display the map""" def __init__(self, interface): T.Thread.__init__(self) self.interface = interface self.started = True self.start() def run(self): while self.started: time.sleep(2) self.interface.on_canvas_expose_event() def stop(self): self.started = False def __init__(self): self.interface = gtk.Builder() self.interface.add_from_file("interface.glade") #Map self.map = Map.Map(2,2) #Canva self.canvas = Canvas.MyCanvas(self.interface.get_object("canvas"),self.game) self.interface.connect_signals(self) #Thread Canvas self.render = self.ThreadCanvas(self) def on_btnChange_clicked(self, widget): #Change map self.map.change() def on_interface_destroy(self, widget): self.render.stop() self.render.join() self.render._Thread__stop() gtk.main_quit() def on_canvas_expose_event(self): st = time.time() self.canvas.update(self.map) et = time.time() print "Canvas refresh in : %f times" %(et-st) def main(self): gtk.main() How can i fix these errors ?

    Read the article

  • Refactoring a Single Rails Model with large methods & long join queries trying to do everything

    - by Kelseydh
    I have a working Ruby on Rails Model that I suspect is inefficient, hard to maintain, and full of unnecessary SQL join queries. I want to optimize and refactor this Model (Quiz.rb) to comply with Rails best practices, but I'm not sure how I should do it. The Rails app is a game that has Missions with many Stages. Users complete Stages by answering Questions that have correct or incorrect Answers. When a User tries to complete a stage by answering questions, the User gets a Quiz entry with many Attempts. Each Attempt records an Answer submitted for that Question within the Stage. A user completes a stage or mission by getting every Attempt correct, and their progress is tracked by adding a new entry to the UserMission & UserStage join tables. All of these features work, but unfortunately the Quiz.rb Model has been twisted to handle almost all of it exclusively. The callbacks began at 'Quiz.rb', and because I wasn't sure how to leave the Quiz Model during a multi-model update, I resorted to using Rails Console to have the @quiz instance variable via self.some_method do all the heavy lifting to retrieve every data value for the game's business logic; resulting in large extended join queries that "dance" all around the Database schema. The Quiz.rb Model that Smells: class Quiz < ActiveRecord::Base belongs_to :user has_many :attempts, dependent: :destroy before_save :check_answer before_save :update_user_mission_and_stage accepts_nested_attributes_for :attempts, :reject_if => lambda { |a| a[:answer_id].blank? }, :allow_destroy => true #Checks every answer within each quiz, adding +1 for each correct answer #within a stage quiz, and -1 for each incorrect answer def check_answer stage_score = 0 self.attempts.each do |attempt| if attempt.answer.correct? == true stage_score += 1 elsif attempt.answer.correct == false stage_score - 1 end end stage_score end def winner return true end def update_user_mission_and_stage ####### #Step 1: Checks if UserMission exists, finds or creates one. #if no UserMission for the current mission exists, creates a new UserMission if self.user_has_mission? == false @user_mission = UserMission.new(user_id: self.user.id, mission_id: self.current_stage.mission_id, available: true) @user_mission.save else @user_mission = self.find_user_mission end ####### #Step 2: Checks if current UserStage exists, stops if true to prevent duplicate entry if self.user_has_stage? @user_mission.save return true else ####### ##Step 3: if step 2 returns false: ##Initiates UserStage creation instructions #checks for winner (winner actions need to be defined) if they complete last stage of last mission for a given orientation if self.passed? && self.is_last_stage? && self.is_last_mission? create_user_stage_and_update_user_mission self.winner #NOTE: The rest are the same, but specify conditions that are available to add badges or other actions upon those conditions occurring: ##if user completes first stage of a mission elsif self.passed? && self.is_first_stage? && self.is_first_mission? create_user_stage_and_update_user_mission #creates user badge for finishing first stage of first mission self.user.add_badge(5) self.user.activity_logs.create(description: "granted first-stage badge", type_event: "badge", value: "first-stage") #If user completes last stage of a given mission, creates a new UserMission elsif self.passed? && self.is_last_stage? && self.is_first_mission? create_user_stage_and_update_user_mission #creates user badge for finishing first mission self.user.add_badge(6) self.user.activity_logs.create(description: "granted first-mission badge", type_event: "badge", value: "first-mission") elsif self.passed? create_user_stage_and_update_user_mission else self.passed? == false return true end end end #Creates a new UserStage record in the database for a successful Quiz question passing def create_user_stage_and_update_user_mission @nu_stage = @user_mission.user_stages.new(user_id: self.user.id, stage_id: self.current_stage.id) @nu_stage.save @user_mission.save self.user.add_points(50) end #Boolean that defines passing a stage as answering every question in that stage correct def passed? self.check_answer >= self.number_of_questions end #Returns the number of questions asked for that stage's quiz def number_of_questions self.attempts.first.answer.question.stage.questions.count end #Returns the current_stage for the Quiz, routing through 1st attempt in that Quiz def current_stage self.attempts.first.answer.question.stage end #Gives back the position of the stage relative to its mission. def stage_position self.attempts.first.answer.question.stage.position end #will find the user_mission for the current user and stage if it exists def find_user_mission self.user.user_missions.find_by_mission_id(self.current_stage.mission_id) end #Returns true if quiz was for the last stage within that mission #helpful for triggering actions related to a user completing a mission def is_last_stage? self.stage_position == self.current_stage.mission.stages.last.position end #Returns true if quiz was for the first stage within that mission #helpful for triggering actions related to a user completing a mission def is_first_stage? self.stage_position == self.current_stage.mission.stages_ordered.first.position end #Returns true if current user has a UserMission for the current stage def user_has_mission? self.user.missions.ids.include?(self.current_stage.mission.id) end #Returns true if current user has a UserStage for the current stage def user_has_stage? self.user.stages.include?(self.current_stage) end #Returns true if current user is on the last mission based on position within a given orientation def is_first_mission? self.user.missions.first.orientation.missions.by_position.first.position == self.current_stage.mission.position end #Returns true if current user is on the first stage & mission of a given orientation def is_last_mission? self.user.missions.first.orientation.missions.by_position.last.position == self.current_stage.mission.position end end My Question Currently my Rails server takes roughly 500ms to 1 sec to process single @quiz.save action. I am confident that the slowness here is due to sloppy code, not bad Database ERD design. What does a better solution look like? And specifically: Should I use join queries to retrieve values like I did here, or is it better to instantiate new objects within the model instead? Or am I missing a better solution? How should update_user_mission_and_stage be refactored to follow best practices? Relevant Code for Reference: quizzes_controller.rb w/ Controller Route Initiating Callback: class QuizzesController < ApplicationController before_action :find_stage_and_mission before_action :find_orientation before_action :find_question def show end def create @user = current_user @quiz = current_user.quizzes.new(quiz_params) if @quiz.save if @quiz.passed? if @mission.next_mission.nil? && @stage.next_stage.nil? redirect_to root_path, notice: "Congratulations, you have finished the last mission!" elsif @stage.next_stage.nil? redirect_to [@mission.next_mission, @mission.first_stage], notice: "Correct! Time for Mission #{@mission.next_mission.position}", info: "Starting next mission" else redirect_to [@mission, @stage.next_stage], notice: "Answer Correct! You passed the stage!" end else redirect_to [@mission, @stage], alert: "You didn't get every question right, please try again." end else redirect_to [@mission, @stage], alert: "Sorry. We were unable to save your answer. Please contact the admministrator." end @questions = @stage.questions.all end private def find_stage_and_mission @stage = Stage.find(params[:stage_id]) @mission = @stage.mission end def find_question @question = @stage.questions.find_by_id params[:id] end def quiz_params params.require(:quiz).permit(:user_id, :attempt_id, {attempts_attributes: [:id, :quiz_id, :answer_id]}) end def find_orientation @orientation = @mission.orientation @missions = @orientation.missions.by_position end end Overview of Relevant ERD Database Relationships: Mission - Stage - Question - Answer - Attempt <- Quiz <- User Mission - UserMission <- User Stage - UserStage <- User Other Models: Mission.rb class Mission < ActiveRecord::Base belongs_to :orientation has_many :stages has_many :user_missions, dependent: :destroy has_many :users, through: :user_missions #SCOPES scope :by_position, -> {order(position: :asc)} def stages_ordered stages.order(:position) end def next_mission self.orientation.missions.find_by_position(self.position.next) end def first_stage next_mission.stages_ordered.first end end Stage.rb: class Stage < ActiveRecord::Base belongs_to :mission has_many :questions, dependent: :destroy has_many :user_stages, dependent: :destroy has_many :users, through: :user_stages accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true def next_stage self.mission.stages.find_by_position(self.position.next) end end Question.rb class Question < ActiveRecord::Base belongs_to :stage has_many :answers, dependent: :destroy accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:body].blank? }, :allow_destroy => true end Answer.rb: class Answer < ActiveRecord::Base belongs_to :question has_many :attempts, dependent: :destroy end Attempt.rb: class Attempt < ActiveRecord::Base belongs_to :answer belongs_to :quiz end User.rb: class User < ActiveRecord::Base belongs_to :school has_many :activity_logs has_many :user_missions, dependent: :destroy has_many :missions, through: :user_missions has_many :user_stages, dependent: :destroy has_many :stages, through: :user_stages has_many :orientations, through: :school has_many :quizzes, dependent: :destroy has_many :attempts, through: :quizzes def latest_stage_position self.user_missions.last.user_stages.last.stage.position end end UserMission.rb class UserMission < ActiveRecord::Base belongs_to :user belongs_to :mission has_many :user_stages, dependent: :destroy end UserStage.rb class UserStage < ActiveRecord::Base belongs_to :user belongs_to :stage belongs_to :user_mission end

    Read the article

  • how to create an object using self?

    - by Nick
    I thought I understood the use of self while referring to anything in the current class. After encountering this warning and subsequent run failure, I have googled many variants of "define self" or "usage of self" and gotten nowhere. This problem is how to create an object without the warning, and understand why. #import <Cocoa/Cocoa.h> @interface Foo : NSObject { Foo *obj; } -(void)beta; @end #import "Foo.h" @implementation Foo -(void)beta{ obj = [self new]; // 'Foo' may not respond to '-new' } @end Note, if I substitute Foo for self, there's no problem. I thought the class name and self were equivalent, but obviously the compiler doesn't think so. Perhaps an explanation of what's wrong here will not only solve my problem but also enlighten my understanding of the usage of self. Are there any tutorials about proper usage of self? I couldn't find anything beyond something like "self is the receiver of the message," which I didn't help me at all.

    Read the article

  • Segmentation fault while switching QCompleter for QLineEdit [on hold]

    - by san
    I have a QLineEdit that uses autocompletion one which on focusIn event in which it shows paths from XML List(here I have used hardcoded list) but if user doesn't find the path from that list popped by QCompleter than I want user to be able to browse to path typing '/' in QLineEdit , I am not able to select the paths say /Users etc and on trying to type Segmentation fault occurs. from PyQt4.Qt import Qt, QObject,QLineEdit from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT from PyQt4 import QtGui, QtCore import sys class DirLineEdit(QLineEdit, QtCore.QObject): """docstring for DirLineEdit""" def __init__(self): super(DirLineEdit, self).__init__() self.defaultList = ['~/Development/python/searchMethod', '~/Development/Nuke_python', '~/Development/python/openexr', '~/Development/python/cpp2python'] self.textChanged.connect(self.__dirCompleter) def focusInEvent(self, event): if len(self.text()) == 0: self._pathsList() QtGui.QLineEdit.focusInEvent(self, event) self.completer().complete() def __dirCompleter(self): if len(self.text()) == 0: model = MyListModel(self.defaultList, self) completer = QtGui.QCompleter(model, self) completer.setModel(model) else: dirModel = QtGui.QFileSystemModel() dirModel.setRootPath(QtCore.QDir.currentPath()) dirModel.setFilter(QtCore.QDir.AllDirs | QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files) dirModel.setNameFilterDisables(0) completer = QtGui.QCompleter(dirModel, self) completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive) completer.setModel(dirModel) self.setCompleter(completer) def _pathsList(self): completerList = QtCore.QStringList() for i in self.defaultList: completerList.append(QtCore.QString(i)) lineEditCompleter = QtGui.QCompleter(completerList) lineEditCompleter.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion) self.setCompleter(lineEditCompleter) class MyListModel(QtCore.QAbstractListModel): def __init__(self, datain, parent=None, *args): """ datain: a list where each item is a row """ QtCore.QAbstractTableModel.__init__(self, parent, *args) self.listdata = datain def rowCount(self, parent=QtCore.QModelIndex()): return len(self.listdata) def data(self, index, role): if index.isValid() and role == QtCore.Qt.DisplayRole: return QtCore.QVariant(self.listdata[index.row()]) else: return QtCore.QVariant() app = QtGui.QApplication(sys.argv) smObj = DirLineEdit() smObj.show() app.exec_() Please help fix this or suggest better way of implementation?

    Read the article

  • Pygame: Save a list of objects/classes/surfaces

    - by Sam Tubb
    I am working on a game, in which you can create mazes. You place blocks on a 16x16 grid, while choosing from a variety of block to make the level with. Whenever you create a block, it adds this class: class Block(object): def __init__(self,x,y,spr): self.x=x self.y=y self.sprite=spr self.rect=self.sprite.get_rect(x=self.x,y=self.y) to a list called instances. I tried shelving it to a .bin file, but it returns some error dealing with surfaces. How can I go about saving and loading levels? Any help is appreciated! :) Here is the whole code for reference: import pygame from pygame.locals import * #initstuff pygame.init() screen=pygame.display.set_mode((640,480)) pygame.display.set_caption('PiMaze') instances=[] #loadsprites menuspr=pygame.image.load('images/menu.png').convert() b1spr=pygame.image.load('images/b1.png').convert() b2spr=pygame.image.load('images/b2.png').convert() currentbspr=b1spr curspr=pygame.image.load('images/curs.png').convert() curspr.set_colorkey((0,255,0)) #menu menuspr.set_alpha(185) menurect=menuspr.get_rect(x=-260,y=4) class MenuItem(object): def __init__(self,pos,spr): self.x=pos[0] self.y=pos[1] self.sprite=spr self.pos=(self.x,self.y) self.rect=self.sprite.get_rect(x=self.x,y=self.y) class Block(object): def __init__(self,x,y,spr): self.x=x self.y=y self.sprite=spr self.rect=self.sprite.get_rect(x=self.x,y=self.y) while True: #menu items b1menu=b1spr.get_rect(x=menurect.left+32,y=48) b2menu=b2spr.get_rect(x=menurect.left+64,y=48) menuitems=[MenuItem(b1menu,b1spr),MenuItem(b2menu,b2spr)] screen.fill((20,30,85)) mse=pygame.mouse.get_pos() key=pygame.key.get_pressed() placepos=((mse[0]/16)*16,(mse[1]/16)*16) if key[K_q]: if mse[0]<260: if menurect.right<255: menurect.right+=1 else: if menurect.left>-260: menurect.left-=1 else: if menurect.left>-260: menurect.left-=1 for e in pygame.event.get(): if e.type==QUIT: exit() if menurect.right<100: if e.type==MOUSEBUTTONUP: if e.button==1: to_remove = [i for i in instances if i.rect.collidepoint(placepos)] for i in to_remove: instances.remove(i) if not to_remove: instances.append(Block(placepos[0],placepos[1],currentbspr)) for i in instances: screen.blit(i.sprite,i.rect) if not key[K_q]: screen.blit(curspr,placepos) screen.blit(menuspr,menurect) for item in menuitems: screen.blit(item.sprite,item.pos) if item.rect.collidepoint(mse): if pygame.mouse.get_pressed()==(1,0,0): currentbspr=item.sprite pygame.draw.rect(screen, ((255,0,0)), item, 1) pygame.display.flip()

    Read the article

  • Managing Instances in Python

    - by BeensTheGreat
    Hello, I am new to Python and this is my first time asking a stackOverflow question, but a long time reader. I am working on a simple card based game but am having trouble managing instances of my Hand class. If you look below you can see that the hand class is a simple container for cards(which are just int values) and each Player class contains a hand class. However, whenever I create multiple instances of my Player class they all seem to manipulate a single instance of the Hand class. From my experience in C and Java it seems that I am somehow making my Hand class static. If anyone could help with this problem I would appreciate it greatly. Thank you, Thad To clarify: An example of this situation would be p = player.Player() p1 = player.Player() p.recieveCard(15) p1.recieveCard(21) p.viewHand() which would result in: [15,21] even though only one card was added to p Hand class: class Hand: index = 0 cards = [] #Collections of cards #Constructor def __init__(self): self.index self.cards def addCard(self, card): """Adds a card to current hand""" self.cards.append(card) return card def discardCard(self, card): """Discards a card from current hand""" self.cards.remove(card) return card def viewCards(self): """Returns a collection of cards""" return self.cards def fold(self): """Folds the current hand""" temp = self.cards self.cards = [] return temp Player Class import hand class Player: name = "" position = 0 chips = 0 dealer = 0 pHand = [] def __init__ (self, nm, pos, buyIn, deal): self.name = nm self.position = pos self.chips = buyIn self.dealer = deal self.pHand = hand.Hand() return def recieveCard(self, card): """Recieve card from the dealer""" self.pHand.addCard(card) return card def discardCard(self, card): """Throw away a card""" self.pHand.discardCard(card) return card def viewHand(self): """View the players hand""" return self.pHand.viewCards() def getChips(self): """Get the number of chips the player currently holds""" return self.chips def setChips(self, chip): """Sets the number of chips the player holds""" self.chips = chip return def makeDealer(self): """Makes this player the dealer""" self.dealer = 1 return def notDealer(self): """Makes this player not the dealer""" self.dealer = 0 return def isDealer(self): """Returns flag wether this player is the dealer""" return self.dealer def getPosition(self): """Returns position of the player""" return self.position def getName(self): """Returns name of the player""" return self.name

    Read the article

  • Web dev/programmer with 4.5 yrs experience. Better for career: self-study or master's degree? [closed]

    - by Anonymous Programmer
    I'm a 28 year-old web developer/programmer with 4.5 years of experience, and I'm looking to jump-start my career. I'm trying to decide between self-study and a 1-year master's program in CS at a top school. I'm currently making 65K in a high cost-of-living area that is NOT a hot spot for technology firms. I code almost exclusively in Ruby/Rails, PHP/CodeIgniter, SQL, and JavaScript. I've slowly gained proficiency with Git. Roughly half the time I am architecting/coding, and half the time I am pounding out HTML/CSS for static brochureware sites. I'd like to make more more money while doing more challenging/interesting work, but I don't know where to start. I have an excellent academic record (math major with many CS credits, 3.9+ GPA), GRE scores, and recommendations, so I am confident that I could be admitted to a great CS master's program. On the other hand, there is the tuition and opportunity cost to consider. I feel like there are a number of practical languages/tools/skills worth knowing that I could teach myself - shell scripting, .NET, Python, Node.js, MongoDB, natural language processing techniques, etc. That said, it's one thing to read about a subject and another thing to have experience with it, which structured coursework provides. So, on to the concrete questions: What programming skills/knowledge should I develop to increase my earning potential and make me competitive for more interesting jobs? Will a master's degree in CS from a top school help me develop the above skills/knowledge, and if so, is it preferable to self-study (possibly for other reasons, e.g., the degree's value as a credential)?

    Read the article

  • What was the most productive improvement suggestion you ever made for your team

    - by questzen
    I suggested the testing and functional teams to use Freemind map for jotting the functional flows and test steps. There was some paranoia but our module took it up and the QA teams were surprised to see near zero review comments. There was misconception among the team that there are doing more work. I assured them that by the time others would complete their work along with comment fixes, we would be going out for team lunchs and we did. The real returns came when the developers started refering to the created document in their discussions. So share your contribution(s).

    Read the article

  • SOA, Empowerment and Continuous Improvement

    - by Tanu Sood
    Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-family:"Calibri","sans-serif"; mso-bidi-font-family:"Times New Roman";} Rick Beers is Senior Director of Product Management for Oracle Fusion Middleware. Prior to joining Oracle, Rick held a variety of executive operational positions at Corning, Inc. and Bausch & Lomb. With a professional background that includes senior management positions in manufacturing, supply chain and information technology, Rick brings a unique set of experiences to cover the impact that technology can have on business models, processes and organizations. Rick will be hosting the IT Leader Editorial on a regular basis. I met my twin at Open World. We share backgrounds, experiences and even names. I hosted an invitation-only AppAdvantage Leadership Forum with an overcapacity 85 participants: 55 customers, 15 from the Oracle AppAdvantage team and 15 Partners. It was a lively, open and positive discussion of pace layered architectures and Oracle’s AppAdvantage approach to a unified view of Applications and Middleware. Rick Hassman from Pella was one of the customer panelists and during the pre event prep, Rick and I shared backgrounds and found that we had both been plant managers and led ERP deployments prior to leading IT itself. During the panel conversation I explored this with him, discussing the unique perspectives that this provides to CIO’s. He then hit on a point that I wasn’t able to fully appreciate until a week later. First though, some background. The week after the Forum, one of the participants emailed me with the following thoughts: “I am 150% behind this concept……but we are struggling with the concept of web services and the potential use of the Oracle Service Bus technology let alone moving into using the full SOA/BPM/BAM software to extend our JD Edwards application to both integrate and support business processes”. After thinking a bit I responded this way: While I certainly appreciate the degree of change and effort involved, perhaps I could offer the following: One of the underlying principles behind Oracle AppAdvantage is that more often than not, the choice between changing a business process and invasively customizing ERP represents a Hobson's Choice: neither is acceptable. In this case the third option, moving the process out of ERP, is the only acceptable one. Providing this choice typically requires end to end, real time interoperability across applications and/or services. This real time interoperability, to be sustainable over time requires a service oriented architecture. There's just no way around this. SOA adaptation is admittedly tough at the beginning. New skills, new technology and new headaches. But, like any radically new technology, it has a learning curve that drives cost down rather dramatically over time. Tough choices to be sure, but not entirely different than we face with every major technology cycle. Good points of course, but I felt that something was missing. The points were convincing, perhaps even a bit insightful, but they didn’t get at the heart of what Oracle AppAdvantage is focused upon: how the optimization of technology, applications, processes and relationships can change the very way that organizations operate. And then I thought back to the panel discussion with Rick Hassman at Oracle OpenWorld. Rick stressed that Continuous Improvement is a fundamental business strategy at Pella. I remember Continuous Improvement well as I suspect does everyone who was in American manufacturing during the 80’s. Pioneered by W. Edwards Deming in Japan (and still known alternatively as Kaizen), Continuous Improvement sets in place the business culture that we must not become complacent with success and resistant to the ongoing need for change. Many believe that this single handedly drove the renaissance in American manufacturing through the last two decades, which had become complacent during the 70’s and early 80’s. But what exactly does this have to do with SOA? It was Rick’s next point. He drew the connection that moving those business processes that need to continually change over time out of ERP and into edge applications and services enables continuous improvement by empowering people to continually strive for better ways of doing things rather than be being bound by workflows that cannot change. A compelling connection: that SOA, and the overall Oracle AppAdvantage framework of which it is an integral part, can empower people towards continuous improvement in business processes and as a result drive business leadership and business excellence. What better a case for technology innovation?

    Read the article

  • python 'self' explained

    - by richzilla
    What is the purpose of the 'self' word in python. I understand it refers to the specific object created from that class, but i cant see why it explicitly needs to be added to very function as a parameter. To illustrate, in ruby, i could do this: class myClass def myFunc(name) @name = name end end Which i understand, quite easily, However in python i need to include self: class myClass: def myFunc(self, name): self.name = name Can anyone talk me through this? Any help would be appreciated.

    Read the article

  • Ubuntu 12.04 LDAP SSL self-signed cert not accepted

    - by MaddHacker
    I'm working with Ubuntu 12.04, using OpenLDAP server. I've followed the instructions on the Ubuntu help pages and can happily connect without security. To test my connection, I'm using ldapsearch the command looks like: ldapsearch -xv -H ldap://ldap.[my host].local -b dc=[my domain],dc=local -d8 -ZZ I've also used: ldapsearch -xv -H ldaps://ldap.[my host].local -b dc=[my domain],dc=local -d8 As far as I can tell, I've setup my certificate correctly, but no matter why I try, I can't seem to get ldapsearch to accept my self-signed certificate. So far, I've tried: Updating my /etc/ldap/ldap.conf file to look like: BASE dc=[my domain],dc=local URI ldaps://ldap.[my host].local TLS_CACERT /etc/ssl/certs/cacert.crt TLS_REQCERT allow Updating my /etc/ldap.conf file to look like: base dc=[my domain],dc=local uri ldapi:///ldap.[my host].local uri ldaps:///ldap.[my host].local ldap_version 3 ssl start_tls ssl on tls_checkpeer no TLS_REQCERT allow Updating my /etc/default/slapd to include: SLAPD_SERVICES="ldap:/// ldapi:/// ldaps:///" Several hours of Googling, most of which resulted in adding the TLS_REQCERT allow The exact error I'm seeing is: ldap_initialize( ldap://ldap.[my host].local ) request done: ld 0x20038710 msgid 1 TLS certificate verification: Error, self signed certificate in certificate chain TLS: can't connect. ldap_start_tls: Connect error (-11) additional info: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed After several hours of this, I was hoping someone else has seen this issue, and/or knows how to fix it. Please do let me know if I should add more information, or if you need further data.

    Read the article

  • Install self-signed certificate on local server (iis)

    - by ile
    On this page there are instructions on how to create self-signed cert (on apache) and how to install this certificate on server. I found this page (http://www.visualwin.com/SelfSSL/) with instructions on how to create self-signed certificate on windows (iis). I followed instructions and when I type https://myip/myapp (this leads to localhost because I set my router's port forwarding to go to localhost on my pc) this part works. From the first link, the most important part is this: What needs to be installed in IE is actually the Root CA Certificate. In the how-to above, the Root CA Certificate is called ca.crt. Copy this file to the server that is running QuickBooks. The following is for IE6: - Open IE - Tools - Internet Options - Content - Certificates - Trusted Root Certification Authorities Tab - Import, Next, Browse to 'ca.crt' - Next, Next, Finish, Close, OK The part that is missing in second link is that there is no instruction on how to get .crt file, so I tried to get it myself. What I did was following: I opened https://myip/myapp in Firefox and then "This Connection is Untrusted" screen appeared. Then I clicked on "Add Exception" and then below "Certificate Status" I clicked "View". Under the Details tab I clicked on Export and choosed Save as type: "X 509 Certificate (PEM)" and file was saved with .crt extension. Then I opened IE8 and followed above instructions. After opening https://myip/myapp in IE8 I always get warning screen. Does anyone knows what am I doing wrong? Thanks, Ile

    Read the article

  • NSXMLParser & memory leaks

    - by HBR
    Hi, I am parsing an XML file using a custom class that instanciates & uses NSXMLParser. On the first call everything is fine but on the second, third and later calls Instruments show tens of memory leaks on certain lines inside didEndElement, didEndElement and foundCharacters functions. I googled it and found some people having this issue, but I didn't find anything that could really help me. My Parser class looks like this : Parser.h @interface XMLParser : NSObject { NSMutableArray *data; NSMutableString *currentValue; NSArray *xml; NSMutableArray *videos; NSMutableArray *photos; NSXMLParser *parser; NSURLConnection *feedConnection; NSMutableData *downloadedData; Content *content; Video *video; BOOL nowPhoto; BOOL nowVideo; BOOL finished; BOOL webTV; } -(void)parseXML:(NSURL*)xmlURL; -(int)getCount; -(NSArray*)getData; //- (void)handleError:(NSError *)error; //@property(nonatomic, retain) NSMutableString *currentValue; @property(nonatomic, retain) NSURLConnection *feedConnection; @property(nonatomic, retain) NSMutableData *downloadedData; @property(nonatomic, retain) NSArray *xml; @property(nonatomic, retain) NSXMLParser *parser; @property(nonatomic, retain) NSMutableArray *data; @property(nonatomic, retain) NSMutableArray *photos; @property(nonatomic, retain) NSMutableArray *videos; @property(nonatomic, retain) Content *content; @property(nonatomic, retain) Video *video; @property(nonatomic) BOOL finished; @property(nonatomic) BOOL nowPhoto; @property(nonatomic) BOOL nowVideo; @property(nonatomic) BOOL webTV; @end Parser.m #import "Content.h" #import "Video.h" #import "Parser.h" #import <CFNetwork/CFNetwork.h> @implementation XMLParser @synthesize xml, parser, finished, nowPhoto, nowVideo, webTV; @synthesize feedConnection, downloadedData, data, content, photos, videos, video; -(void)parseXML:(NSURL*)xmlURL { /* NSURLRequest *req = [NSURLRequest requestWithURL:xmlURL]; self.feedConnection = [[[NSURLConnection alloc] initWithRequest:req delegate:self] autorelease]; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; */ [[NSURLCache sharedURLCache] setMemoryCapacity:0]; [[NSURLCache sharedURLCache] setDiskCapacity:0]; NSXMLParser *feedParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; //NSXMLParser *feedParser = [[NSXMLParser alloc] initWithData:theXML]; [self setParser:feedParser]; [feedParser release]; [[self parser] setDelegate:self]; [[self parser] setShouldResolveExternalEntities:YES]; [[self parser] parse]; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { if ([elementName isEqualToString:@"articles"]) { self.finished = NO; self.nowPhoto = NO; self.nowVideo = NO; self.webTV = NO; if (!data) { NSMutableArray *tmp = [[NSMutableArray alloc] init]; [self setData:tmp]; [tmp release]; return ; } } if ([elementName isEqualToString:@"WebTV"]) { self.finished = NO; self.nowPhoto = NO; self.nowVideo = NO; self.webTV = YES; if (!data) { NSMutableArray *tmp = [[NSMutableArray alloc] init]; [self setData:tmp]; [tmp release]; return ; } } if ([elementName isEqualToString:@"photos"]) { if (!photos) { NSMutableArray *tmp = [[NSMutableArray alloc] init]; [self setPhotos:tmp]; [tmp release]; return; } } if ([elementName isEqualToString:@"videos"]) { if (!videos) { NSMutableArray *tmp = [[NSMutableArray alloc] init]; [self setVideos:tmp]; [tmp release]; return; } } if ([elementName isEqualToString:@"photo"]) { self.nowPhoto = YES; self.nowVideo = NO; } if ([elementName isEqualToString:@"video"]) { self.nowPhoto = NO; self.nowVideo = YES; } if ([elementName isEqualToString:@"WebTVItem"]) { if (!video) { Video *tmp = [[Video alloc] init]; [self setVideo:tmp]; [tmp release]; } NSString *videoId = [attributeDict objectForKey:@"id"]; [[self video] setVideoId:[videoId intValue]]; } if ([elementName isEqualToString:@"article"]) { if (!content) { Content *tmp = [[Content alloc] init]; [self setContent:tmp]; [tmp release]; } NSString *contentId = [attributeDict objectForKey:@"id"]; [[self content] setContentId:[contentId intValue]]; return; } if ([elementName isEqualToString:@"category"]) { NSString *categoryId = [attributeDict objectForKey:@"id"]; NSString *parentId = [attributeDict objectForKey:@"parent"]; [[self content] setCategoryId:[categoryId intValue]]; [[self content] setParentId:[parentId intValue]]; categoryId = nil; parentId = nil; return; } if ([elementName isEqualToString:@"vCategory"]) { NSString *categoryId = [attributeDict objectForKey:@"id"]; NSString *parentId = [attributeDict objectForKey:@"parent"]; [[self video] setCategoryId:[categoryId intValue]]; [[self video] setParentId:[parentId intValue]]; categoryId = nil; parentId = nil; return; } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (!currentValue) { currentValue = [[NSMutableString alloc] initWithCapacity:1000]; } if (currentValue != @"\n") [currentValue appendString:string]; } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { NSString *cleanValue = [currentValue stringByReplacingOccurrencesOfString:@"\n" withString:@""] ; if ([elementName isEqualToString:@"articles"]) { self.finished = YES; //[content release]; } if ([elementName isEqualToString:@"article"]) { [[self data] addObject:[self content]]; [self setContent:nil]; [self setPhotos:nil]; [self setVideos:nil]; /* [content release]; content = nil; [videos release]; videos = nil; [photos release]; photos = nil; */ } if ([elementName isEqualToString:@"WebTVItem"]) { [[self data] addObject:[self video]]; [self setVideo:nil]; //[video release]; //video = nil; } if ([elementName isEqualToString:@"title"]) { //NSLog(@"Tit: %@",cleanValue); [[self content] setTitle:cleanValue]; } if ([elementName isEqualToString:@"vTitle"]) { [[self video] setTitle:cleanValue]; } if ([elementName isEqualToString:@"link"]) { //NSURL *url = [[NSURL alloc] initWithString:cleanValue] ; [[self content] setUrl:[NSURL URLWithString:cleanValue]]; [[self content] setLink: cleanValue]; //[url release]; //url = nil; } if ([elementName isEqualToString:@"vLink"]) { [[self video] setLink:cleanValue]; [[self video] setUrl:[NSURL URLWithString:cleanValue]]; } if ([elementName isEqualToString:@"teaser"]) { NSString *tmp = [cleanValue stringByReplacingOccurrencesOfString:@"##BREAK##" withString:@"\n"]; [[self content] setTeaser:tmp]; tmp = nil; } if ([elementName isEqualToString:@"content"]) { NSString *tmp = [cleanValue stringByReplacingOccurrencesOfString:@"##BREAK##" withString:@"\n"]; [[self content] setContent:tmp]; tmp = nil; } if ([elementName isEqualToString:@"category"]) { [[self content] setCategory:cleanValue]; } if ([elementName isEqualToString:@"vCategory"]) { [[self video] setCategory:cleanValue]; } if ([elementName isEqualToString:@"date"]) { [[self content] setDate:cleanValue]; } if ([elementName isEqualToString:@"vDate"]) { [[self video] setDate:cleanValue]; } if ([elementName isEqualToString:@"thumbnail"]) { [[self content] setThumbnail:[NSURL URLWithString:cleanValue]]; [[self content] setThumbnailURL:cleanValue]; } if ([elementName isEqualToString:@"vThumbnail"]) { [[self video] setThumbnailURL:cleanValue]; [[self video] setThumbnail:[NSURL URLWithString:cleanValue]]; } if ([elementName isEqualToString:@"vDirectLink"]){ [[self video] setDirectLink: cleanValue]; } if ([elementName isEqualToString:@"preview"]){ [[self video] setPreview: cleanValue]; } if ([elementName isEqualToString:@"thumbnail_position"]){ [[self content] setThumbnailPosition: cleanValue]; } if ([elementName isEqualToString:@"url"]) { if (self.nowPhoto == YES) { [[self photos] addObject:cleanValue]; } else if (self.nowVideo == YES) { [[self videos] addObject:cleanValue]; } } if ([elementName isEqualToString:@"photos"]) { [[self content] setPhotos:[self photos]]; //[photos release]; //photos = nil; self.nowPhoto = NO; } if ([elementName isEqualToString:@"videos"]) { [[self content] setVideos:[self videos]]; //[videos release]; //videos = nil; self.nowVideo = NO; } //[cleanValue release]; //cleanValue = nil; [currentValue release]; currentValue = nil; } - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } -(NSArray*)getData { return data; } -(int)getCount { return [data count]; } - (void)dealloc { [parser release]; //[data release]; //[photos release]; //[videos release]; //[video release]; //[content release]; [currentValue release]; [super dealloc]; } @end Somewhere in my code, I create an instance of this class : XMLParser* feed = [[XMLParser alloc] init]; [self setRssParser:feed]; [feed release]; // Parse feed NSString *url = [NSString stringWithFormat:@"MyXMLURL"]; [[self rssParser] parseXML:[NSURL URLWithString:url]]; Now the problem is that after the first (which has zero leaks), instruments shows leaks in too many parts like this one (they are too much to enumerate them all, but all the calls look the same, I made the leaking line bold) : in didEndElement : if ([elementName isEqualToString:@"link"]) { // THIS LINE IS LEAKING => INSTRUMENTS SAYS IT IS A NSCFString LEAK [self content] setUrl:[NSURL URLWithString:cleanValue]]; [[self content] setLink: cleanValue]; } Any idea how to fix this pealse ? Could this be the same problem as the one mentioned (as an apple bug) by Lee Amtrong here :http://stackoverflow.com/questions/1598928/nsxmlparser-leaking

    Read the article

  • Are there any non-self-taught famous programmers? [closed]

    - by Jon Purdy
    It seems to me that being a self-taught programmer has significant advantages over picking it up only in higher education. Not only does a self-taught developer have a headstart on their 10 000-odd hours of mastery, but their hobby demonstrates genuine interest. This will likely lead to a process of continuous self-improvement over their career, not to mention increased likelihood of producing personal projects that are worthy of fame. A programmer who spends four years in study (not nearly all of which is going to be directly concerned with programming) has far less leisure to explore and learn independently than does a developer who starts college with even a few years of dedicated hobbyist study. I wonder whether there are any famed developers who had no exposure to programming before deciding to study it in university. I simply doubt that an 18-year-old has the capacity to become a brilliant programmer with no prior experience, but that seems like an awfully elitist and unpleasant view, so I'd like to be proven wrong.

    Read the article

  • Freeware (preferably open-source) tool for creating multi-file spanning archives as a self merging SFX

    - by Lockszmith
    I have a large file I want to transfer using either Internet storage hosting, DVD-Rs or USB storage, which sometimes is limited to FAT file-systems (for example: mobile phones) What I'm basically looking for is a tool that create multiple files/volumes (less than 2GB each - FAT's file size limit) which are packed with a self-extracting executable. Currently the only tool I found doing this is WinRAR, but that's shareware, and not free. Is there any Free, preferably Open-Source tool that does that? Thank in advance

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >