text
stringlengths
226
34.5k
How to access popup login form with Selenium in Python Question: I have been trying for a while to figure out how to enter username and password in the popup-window in this exercise: <http://pentesteracademylab.appspot.com//lab/webapp/digest> but I am entirely new to Selenium in Python. I found out how to click the button, so that the login form pops up: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://pentesteracademylab.appspot.com//lab/webapp/digest") driver.find_element_by_css_selector('button').click() but I cannot figure out how to access that window, let alone the fields in it. I have read about `switch_to_frame` and `switch_to_window`. For windows there is the `window_handles` showing you active windows to switch to, but this only returns a single element, which I believe is the main window, not the pop up. I also tried alert = driver.switch_to_alert() to no avail. The problem is that I do not know either which kind of object the popup is (frame,window,alert or something else), and I cannot find any names referring to it in the HTML code for the webpage. Can anyone take me a step further? Answer: Pass the authentication step by accessing the following URL: http://username:[email protected]/lab/webapp/digest/1 See also: * [Handling browser level authentication using Selenium](http://sqa.stackexchange.com/questions/2755/handling-browser-level-authentication-using-selenium)
Python large text file searching Question: I have a 500 MB text file that was made a long time ago. It has what looks like html or xml tags but they are not consistent throughout the file. I am trying to find the information between two tags that do not match. What I am using currently works but is very slow: myDict has a list of keywords in it. I can only guarantee the X+key and /N exist. There are no other tags that are consistent. The Dictionary has 18000 keys. for key in myDict: start_position = 0 start_position = the_whole_file.find('<X>'+key, start_position) end_position = the_whole_file.find('</N>', start_position) date = the_whole_file[start_position:end_position] Is there a way to do this faster? Answer: reverse the way you are doing it, instead of iterating through the dictionary and searching for potential matches. iterate through potential matches and search the dictionary import re for part in re.findall("\<X\>(.*)\<\/N\>",the_whole_text): key = part.split(" ",1)[0] if key in my_dict: do_something(part) since dictionary lookup is `O(1)` as opposed to string finding of `O(N)` (searching the whole file for every key is expensive ...) so searching your file contents is `~O(500,000,000)` and you are doing that 18,000 times this way you only search the file once finding all potentials ... then you look up each one to see if its in your data dictionary
Shared memory Value dissapears from an object Question: here is some strange behavior in Python (2.7.9, Windows) I would like to ask an advice about. I am trying to extend a class with a variable in initialization and I want to share an object of this class between two processes (parent and child). Both of them will use this variable. This code works fine: # coding: utf-8 from multiprocessing import Process, Value from time import sleep class ExQueue(object): def __init__(self, *args, **kwargs): super(ExQueue, self).__init__(*args, **kwargs) self.trust_me_this_name_is_unique = Value('L', 0) def func(ex_queue): print 'I am the child process. Is there a parameter: ', print hasattr(ex_queue, 'trust_me_this_name_is_unique') # this sleep is here to assure no printing overlapping sleep(.5) def main(): ex_queue = ExQueue() print 'I am the parent process. Is there a parameter: ', print hasattr(ex_queue, 'trust_me_this_name_is_unique') child_process = Process(target=func, args=(ex_queue,)) child_process.start() child_process.join() print 'I am the parent process. Is there a parameter: ', print hasattr(ex_queue, 'trust_me_this_name_is_unique') if __name__ == '__main__': main() Output: I am the parent process. Is there a parameter: True I am the child process. Is there a parameter: True I am the parent process. Is there a parameter: True But if `ExQueue` is inherited from `Queue` class (the one from `multiprocessing.queues` module), the trick does not work. At the beginning add: from multiprocessing.queues import Queue and change class ExQueue(object): to: class ExQueue(Queue): Output will be: I am the parent process. Is there a parameter: True I am the child process. Is there a parameter: False I am the parent process. Is there a parameter: True So, in the `ExQueue` example of the child process there is no `trust_me_this_name_is_unique` variable. Any ideas on what I am doing wrong? Thanks! **UPD:** Works as expected on Mac OS. Variable does not disappear. ## Solution Thank you, **tdelaney**! Your answer helped a lot! I added those two methods to the `ExQueue` and it pickles on Windows just fine now: def __getstate__(self): state = super(ExQueue, self).__getstate__() return state + (self.trust_me_this_name_is_unique,) def __setstate__(self, state): state, self.trust_me_this_name_is_unique = state[:-1], state[-1] super(ExQueue, self).__setstate__(state) Still not sure that it's a good approach to inherit from `Queue` at all. :) Answer: Its not a problem with the shared memory value, its the variable on the queue object itself that disappears. Multiprocessing works differently on machines that implement the *nix forking model verses the Windows create-process model. On *nix, when you create a `multiprocessing` process, the parent process is forked and since the child has as copy-on-write view of the parent's memory space, all of the python objects (including your queue) are in the child space ready to be used. On Windows, there is no `fork`. A new process is created and the relevant parts of the parent process is pickled, sent to the child and unpickled. This only works for picklable objects so code that works in linux may fail in windows. If you have an object that isn't natively picklable, you can implement `__getstate__` and `__setstate__` methods that return a pickable subset of the object and rebuild the object from that state. That's been done with the `multiprocessing.Queue` object. It doesn't include your variable in `__getstate__` so the variable isn't included in the child object when its recreated. An easy solution is to put your data some place else. If that isn't viable, create your own subclass of `multiprocessing.Queue` and write your own `__getstate__` and `__setstate__` methods.
How to write python regex to find guid in html? Question: How to find guid in following HTML section? HTML sample: <td>xxxxxxx</td> <td style="display: none">e3aa8247-354b-e311-b6eb-005056b42341</td> <td>yyyyyy</td> <td style="display: none">e3aa8247-354b-e311-b6eb-005056b42342</td> <td>zzzz</td> Answer: Use an HTML Parser, like that "beautiful" and transparent [`BeautifulSoup`](https://beautiful-soup-4.readthedocs.org/en/latest/) package. The idea is to locate `td` elements with `xxxxxxx`, `yyyyyy` texts and get the following `td` sibling's text value (assuming `xxxxxxx` and `yyyyyy` are labels you know beforehand): from bs4 import BeautifulSoup data = """ <tr> <td>xxxxxxx</td> <td style="display: none">e3aa8247-354b-e311-b6eb-005056b42341</td> <td>yyyyyy</td> <td style="display: none">e3aa8247-354b-e311-b6eb-005056b42342</td> <td>zzzz</td> </tr> """ soup = BeautifulSoup(data) print soup.find("td", text="xxxxxxx").find_next_sibling('td').text Prints: e3aa8247-354b-e311-b6eb-005056b42341
nearest timestamp price - ready data structure in Python? Question: Price interpolation. Python data structure for efficient near miss searches? I have price data [1427837961000.0, 243.586], [1427962162000.0, 245.674], [1428072262000.0, 254.372], [1428181762000.0, 253.366], ... with the first dimension a timestamp, and the second a price. Now I want to know the price which is nearest to a given timestamp e.g. to 1427854534654. What is the best Python container, data structure, or algorithm to solve this many hundred or thousand times per second? It is a standard problem, and has to be solved in many applications, so there should be a ready and optimized solution. I have Googled, and found only bits and pieces that I could build upon - but I guess this question is so common, that the whole data structure should be ready as a module? * * * EDIT: Solved. I used [JuniorCompressor's solution](http://stackoverflow.com/a/29526502/3693375) with my [bugfix for future](http://stackoverflow.com/questions/29525050/nearest-timestamp-price- ready-data-structure-in-python/29526502#comment47232453_29526502) dates. The performance is fantastic: 3000000 calls took 12.82 seconds, so 0.00000427 per call (length of data = 1143). Thanks a lot! StackOverFlow is great, and you helpers are the best! Answer: It is very common for this problem to have your data sorted by the timestamp value and then binary search for every possible query. Binary search can be performed using the [bisect module](https://docs.python.org/2/library/bisect.html): data = [ [1427837961000.0, 243.586], [1427962162000.0, 245.674], [1428072262000.0, 254.372], [1428181762000.0, 253.366] ] data.sort(key=lambda l: l[0]) # Sort by timestamp timestamps = [l[0] for l in data] # Extract timestamps import bisect def find_closest(t): idx = bisect.bisect_left(timestamps, t) # Find insertion point # Check which timestamp with idx or idx - 1 is closer if idx > 0 and abs(timestamps[idx] - t) > abs(timestamps[idx - 1] - t): idx -= 1 return data[idx][1] # Return price We can test like this: >>> find_closest(1427854534654) 243.586 If we have `n` queries and `m` timestamp values, then each query needs `O(log m)` time. So the total time needed is `O(n * log m)`. In the above algorithm we search between two indexes. If we use only the midpoints of the timestamp intervals, we can simplify even more and create a faster search: midpoints = [(a + b) / 2 for a, b in zip(timestamps, timestamps[1:])] def find_closest_through_midpoints(t): return data[bisect.bisect_left(midpoints, t)][1]
xlsxwriter charts don't show up? Question: I am using xlsxwriter to add charts to different worksheets in ipython and everything works, except my graphs are never showing up in the worksheets. There are no error messages. When I tested the code from the documentation I also get a empty excel workbook. I've tried it with xlsxwriter.Workbook and pd.ExcelWriter('test.xlsx', engine='xlsxwriter') but with both the workbook generates but no graphs are added. How can I make the graphs show up? Code from the documentation: <http://xlsxwriter.readthedocs.org/en/latest/working_with_charts.html> import xlsxwriter workbook = xlsxwriter.Workbook('chart_line.xlsx') worksheet = workbook.add_worksheet() # Add the worksheet data to be plotted. data = [10, 40, 50, 20, 10, 50] worksheet.write_column('A1', data) # Create a new chart object. chart = workbook.add_chart({'type': 'line'}) # Add a series to the chart. chart.add_series({'values': '=Sheet1!$A$1:$A$6'}) # Insert the chart into the worksheet. worksheet.insert_chart('C1', chart) workbook.close() The results for print(xlsxwriter.**version**) 0.5.7 print(zipfile.ZipFile("chart_line.xlsx").namelist()) ['xl/worksheets/sheet1.xml', 'xl/workbook.xml', 'xl/charts/chart1.xml', 'xl/drawings/drawing1.xml', 'docProps/app.xml', 'docProps/core.xml', '[Content_Types].xml', 'xl/styles.xml', 'xl/theme/theme1.xml', '_rels/.rels', 'xl/_rels/workbook.xml.rels', 'xl/worksheets/_rels/sheet1.xml.rels', 'xl/drawings/_rels/drawing1.xml.rels'] Answer: There haven't been any reported issues of charts not displaying in Excel in any version of XlsxWriter that supported charts. There are also almost 300 chart comparison tests in the XlsxWriter codebase that test the charts that it produces byte for byte against files produces by Excel. These are all passing. Also, the output from zipfile in your post clearly shows the chart elements are there. If they were present but incorrect Excel would complain when it loaded the file. And the code that you link to has a screenshot of the output that clearly shows a chart. I also ran the code and see the chart in 3 versions of Excel and 1 version of LibreOffice. So you need to go back and verify your results. If you think there is an issue then create a small working program that demonstrates it and submit a bug report.
Creating an Algorithm to generate 20 digit codes Question: I am wanting to create an Algorithm that creates a 20 digit number code. Similar to how gift card codes are created. I would like to use python for it, since I know python the best out of ALL programming languages. I would like it to create numbers based on certain rules (For ex. Like how certain gift cards have to start with an S and has to have X number of letters in it and numbers) I do not know if I am explaining this clearly, but basically what I want is to create an Algorithm that will create a 20 digit code that has certain rules so people cannot create "false" codes. Thank you! :) The Code I have currently is import random def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) print random_with_N_digits(20) But I keep getting an error on the print statement? Answer: An algorithm is basically a set of rules to accomplish something, start it as you would start any piece of code. Since your question lacks some data, I will just make an assumption that you want to randomly select a letter or number. The algorithm will require a list of letters and numbers, and will simply state that: for each number in range from 1-20, you want to 'run' a set of rules. This set of rules that you want to run is nothing more than a function or some code that can randomly select a letter/number from your data list. The code above will build you a data list with numbers and letters that you can have the algorithm randomly select from. import string from random import randint data = list(string.ascii_lowercase) [data.append(n) for n in range(0, 10)] The code below will range from 0 through 21 (1, 20) and will generate a 20 character string based on a random selection of a number or letter that is inside your data list x = [str(data[randint(0, len(data)-1)]) for n in range(0, 21)] y = ''.join(x) print y >>> 'km1o07fy9t3j0dktabjsg'
python forloop accessing GPIO pins Question: I'm new to python raspberry pi. Trying to shorten my code and use for loops for repetitive parts in my code like changing all pins to high and low. Trying to use a for loop to access pins. Is this even possible? import RPi.GPIO as GPIO from time import sleep R1=22 R2=10 R3=9 R4=11 GPIO.setup(R1, GPIO.OUT) GPIO.setup(R2, GPIO.OUT) GPIO.setup(R3, GPIO.OUT) GPIO.setup(R4, GPIO.OUT) for x in range(1, 5): print "We're on time %d" % (x) GPIO.output(R + %d % (x), GPIO.HIGH) sleep(1) GPIO.output(R + %d % (x), GPIO.LOW) sleep(1) GPIO.cleanup() Answer: That sort of thing is possible, but often nicer to use a `list` or `dict`: pins = [22, 10, 9, 11] for pin in pins: GPIO.setup(pin, GPIO.OUT) for x in range(1, 5): GPIO.output(pins[x], GPIO.HIGH) sleep(1) GPIO.output(pins[x], GPIO.LOW) sleep(1)
install python-mysqldb using python script Question: I am writing a python script for an application. The application needs python- mysqldb. In terminal, I can install it with apt-get or pip. How can I install using python script? I am using python 2.7. Answer: You could use pip in a python script for installing the package import pip if __name__ == '__main__': pip.main(['install', 'MySQL-python']) Then you can run the script from a terminal.
Python: How many times does the least common string appear? Question: This is a example of a csv file it is linked to the code ![csv image](http://i.stack.imgur.com/uvA80.jpg) I want to know how to find How many times does the least common string appear in the field [gas] def least_string(gas): if gas in gasdic: gasdic[gas] += 1 else: gasdic[gas] = 1 I change the first half in to function if gas in gasCount: gasCount[gas] += 1 else: gasCount[gas] = 1 It printed out {'Nitrogen': 3, 'Methane': 3, 'Helium': 2, 'CarbonDioxide': 1, ' Chlorine': 3, 'Oxygen': 3, 'Xenon': 1, 'Hydrogen': 2, 'Argon': 1} I need to change this in to function smallest = 100000 for key in gasCount: if gasCount[key] < smallest: smallest = gasCount[key] answers = [] for key in gasCount: if gasCount[key] == smallest: answers.append(key) so it would print out The least common string appear in the field [gas]: ['CarbonDioxide', 'Xenon', 'Argon'] This is the full code import string def getFile(): filename = input('Filename: ') #the file name should be .csv file = open(filename, 'r') firstline = True Line = file.readline() if Line == None or Line == '': return None if firstline: # I do not want to read the field names Line = file.readline() # there is more to read firstline = False # so I skip them. the code assuems return file #Count the number of (T's) in the field [correct] def calcT(correct): global tCount found = False for ch in correct:#look at each character in turn if ch in 'tT': found = True if found: tCount +=1 #How many times does the least common string appear in the field [gas] def least_string(gas): if gas in gasdic: gasdic[gas] += 1 else: gasdic[gas] = 1 #Find the sum of the values in the field [quant] less than (408) def sum_quant(quant): global qsum if quant < 408: qsum += quant #How many values in the 'code' field do not match the format 9999(x9+)9? def checkString(astring): if len(astring) != 10: return False if not astring[0] in string.digits: return False if not astring[1] in string.digits: return False if not astring[2] in string.digits: return False if not astring[3] in string.digits: return False if not astring[4]=='(': return False if not astring[5] in string.ascii_lowercase: return False if not astring[6] in string.digits: return False if not astring[7]=='+': return False if not astring[8]==')': return False if not astring[9] in string.digits: return False return True #What is the average value of the numbers in the field [age] in the range (30) and (107) inclusive def average_age(age): global tAge, ageCount if age >= 30 and age <=107: tAge += age ageCount += 1 #Find the sum of the numbers in field [length] between (2.482) and (6.428) inclusive def sum_Length(leng): global lensum if leng >= 2.482 and leng <= 6.428: lensum += leng #count the lines where gas's have the value (Nitrogen) *or* quant is less than 318 def calcGas(gas, quant): global clines if gas == 'Nitrogen' or quant < 318: clines += 1 def processLine(Line): Line = Line.strip() fields = Line.split(',') correct = fields[0] gas = fields[1] quant = int(fields[2]) code = fields[3] if checkString(code): global cCount cCount += 1 age = int(fields[4]) leng = float(fields[5]) calcT(correct) sum_Length(leng) calcGas(gas, quant) average_age(age) sum_quant(quant) least_string(gas) def processFile(data): for line in data: processLine(line) data.close() def displayResults(): #Count the number of (T's) in the field [correct] print('The number of (T) in the field [correct]: %d'%(tCount)) print('-' *10) print(gasdic) print('The least common string appear in the field [gas]:%s'%(answers)) print('-' *10) #Find the sum of the values in the field [quant] less than (408) print('The sum of the values in the field [quant] less than (408): %d'%(qsum)) print('-' *10) #How many values in the 'code' field do not match the format 9999(x9+)9? print('The values in the code field do not match the format 9999(x9+)9: %d'%(cCount)) print('-' *10) #What is the average value of the numbers in the field [age] in the range (30) and (107) inclusive print('The average value of numbers in the field[age] in range(30)and(107):%0.2f'%((tAge/ageCount))) print('-' *10) #Find the sum of the numbers in field [length] between (2.482) and (6.428) inclusive print('The sum of the numbers in field [length] between (2.482) and (6.428): %6.3f'%(lensum)) print('-' *10) #count the lines where gas's have the value (Nitrogen) *or* quant is less than 318 print('The lines where gas have the value (Nitrogen) *or* quant is less than 318: %d' %(clines)) tCount = 0 qsum = 0 gasdic = {} answers =[] cCount = 0 ageCount = 0 tAge = 0 lensum = 0 clines = 0 myfile = getFile() processFile(myfile) displayResults() Answer: from collections import Counter def least_common(ls): c = Counter(ls) m = min(c.values()) return [k for k, v in c.items() if v == m] least_common('Foo Bar FooBar Bar'.split()) # ['FooBar', 'Foo']
Wxpython - remove tabs in application Question: I have a application which I have previously been using multiple tabs. I have since changed the application and now only need a single panel. My issue is I can't seem to figure out how I get rid of the redundant tabs and revert to a single panel. Removing the `self.tabbed` in line 12 and 13 just result in a very odd looking panel, everything squashed to the corner. Below is the current tabbed code, I have removed lots of irrelevant code / classes, etc. What would be the most efficient way without effecting too much code? UPDATE 1: I have updated the below code, so it now runs. import wx import wx.lib.agw.aui as aui import wx.stc as stc import os import platform import time systemType = platform.system() if systemType == "Windows": import win32wnet class MainWindow(wx.Frame): def __init__(self, parent, id, title): run_params = {} self.run_params = run_params # OS dependent info self.run_params["systemType"] = systemType if systemType == "Windows": self.run_params["fontSize"] = 8 self.run_params["fontSize2"] = 7 else: self.run_params["fontSize"] = 10 self.run_params["fontSize2"] = 9 wx.Frame.__init__(self, parent, id, title, size=(900, 710), style=wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.RESIZE_BOX | wx.MAXIMIZE_BOX)) style = aui.AUI_NB_DEFAULT_STYLE ^ aui.AUI_NB_CLOSE_ON_ACTIVE_TAB self.tabbed = aui.AuiNotebook(self, agwStyle=style) self.submissions = SubmissionPane(self.tabbed, self, run_params) self.CreateStatusBar() self.tabbed.AddPage(self.submissions, "TAB1") menuBar = wx.MenuBar() self.Centre() self.Show() class SubmissionPane(wx.Panel): def __init__(self, parent, frame, run_params): wx.Panel.__init__(self, parent) self.parent = parent self.selected_folders = None self.params = run_params self.frame = frame main_sizer = wx.BoxSizer(wx.VERTICAL) self.top_row_sizer = wx.BoxSizer(wx.HORIZONTAL); radio_static_box = wx.StaticBox(self, label='Some Text') radio_static_box_sizer = wx.StaticBoxSizer(radio_static_box, wx.HORIZONTAL) job_static_box = wx.StaticBox(self, label='Some Text') job_static_box_sizer = wx.StaticBoxSizer(job_static_box, wx.HORIZONTAL) ''' radio_labels = ['Some Text', 'Some Text2'] self.radio_box = wx.RadioBox( self, -1, "", choices=radio_labels, ) ''' self.radio1 = wx.RadioButton(self, label='Some Text', style=wx.RB_GROUP) self.radio2 = wx.RadioButton(self, label='Some Text') self.radio1.SetValue(True) radio_static_box_sizer.Add(self.radio1, flag=wx.BOTTOM, border=0) radio_static_box_sizer.Add(self.radio2, flag=wx.LEFT, border=10) self.top_row_sizer.Add(radio_static_box_sizer, flag=wx.LEFT, border=10) self.check_box = wx.CheckBox(self, label="Some Text") self.check_box.SetValue(False) if self.params["systemType"] == "Windows": self.txtTitle = wx.TextCtrl(self, style=wx.SUNKEN_BORDER, value="Some Text...", size=(200, -1), pos=(306, 14)) else: self.txtTitle = wx.TextCtrl(self, style=wx.SUNKEN_BORDER, value="Some Text...", size=(200, -1), pos=(350, 19)) job_static_box_sizer.Add(self.check_box, flag=wx.LEFT, border=0) self.top_row_sizer.Add(job_static_box_sizer, flag=wx.LEFT, border=10); self.txtTitle.Show(False) main_sizer.Add(self.top_row_sizer); main_sizer.Add((-1, 10)) job_static_box2 = wx.StaticBox(self, label='Some Text') third_row_sizer = wx.StaticBoxSizer(job_static_box2, wx.HORIZONTAL); self.tc_files = wx.TextCtrl(self, size=(375, 25)) self.buttonGo = wx.Button(self, label='Go') self.buttonGo.Bind(wx.EVT_BUTTON, self.OnSubmit) third_row_sizer.Add(self.tc_files, flag=wx.RIGHT, border=8) if self.params["systemType"] == "Windows": third_row_sizer.Add(self.buttonGo, flag=wx.LEFT | wx.TOP, border=0) else: third_row_sizer.Add(self.buttonGo, flag=wx.LEFT | wx.TOP, border=2) main_sizer.Add(third_row_sizer, flag=wx.LEFT, border=10) self.log_text22 = wx.ListCtrl(self,size=(875,275), style=wx.LC_REPORT | wx.BORDER_SUNKEN | wx.LC_SINGLE_SEL | wx.LC_VRULES | wx.LC_HRULES) font = wx.Font(self.params["fontSize2"], wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) self.log_text22.SetFont(font) self.log_text22.InsertColumn(1, '1', width=40, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(2, '2', width=50, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(3, '3', width=156) self.log_text22.InsertColumn(4, '4', width=332) self.log_text22.InsertColumn(5, '5', width=100, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(6, '6', width=82, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(7, '7', width=60, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(8, '8', width=50, format=wx.LIST_FORMAT_CENTRE) main_sizer.Add((-1, 10)) list_sizer = wx.BoxSizer(wx.VERTICAL) list_sizer.Add(self.log_text22, flag=wx.LEFT, border=10) main_sizer.Add(list_sizer) self.running_log1 = wx.stc.StyledTextCtrl(self, -1, size=(875,175)) self.running_log1.StyleSetFont(wx.stc.STC_STYLE_DEFAULT, font) self.running_log1.SetMarginWidth(1, 0) self.running_log1.StyleSetBackground(wx.stc.STC_STYLE_DEFAULT, (0,0,0)) self.running_log1.StyleSetForeground(wx.stc.STC_STYLE_DEFAULT, (0,255,0)) self.running_log1.StyleClearAll() main_sizer.Add((-1, 5)) list_sizer = wx.BoxSizer(wx.VERTICAL) list_sizer.Add(self.running_log1, flag=wx.LEFT, border=10) main_sizer.Add(list_sizer) list_sizer.Add((-1, 10)) self.buttonClose = wx.Button(self, -1, "Quit") list_sizer.Add(self.buttonClose, flag=wx.ALIGN_CENTER | wx.TOP | wx.LEFT, border=10) self.SetBackgroundColour("Light Grey") self.SetSizer(main_sizer) self.Show() def OnSubmit(self, event): msg = "Running" jobSubmitmsg = wx.BusyInfo(msg, self) time.sleep(3) jobSubmitmsg = None app = wx.App(redirect=False) MainWindow(None, -1, 'Application') app.MainLoop() UPDATE 2: The below answer works very well. Cheers. Answer: If you don't want a Notebook at all, then you can just use the SubmissionPane itself and remove the aui stuff: import wx import wx.stc as stc import os import platform import time systemType = platform.system() if systemType == "Windows": import win32wnet class MainWindow(wx.Frame): def __init__(self, parent, id, title): run_params = {} self.run_params = run_params # OS dependent info self.run_params["systemType"] = systemType if systemType == "Windows": self.run_params["fontSize"] = 8 self.run_params["fontSize2"] = 7 else: self.run_params["fontSize"] = 10 self.run_params["fontSize2"] = 9 wx.Frame.__init__(self, parent, id, title, size=(900, 710), style=wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.RESIZE_BOX | wx.MAXIMIZE_BOX)) ########################################################## # Passed self here and removed the unnecessary second self ########################################################## self.submissions = SubmissionPane(self, run_params) self.CreateStatusBar() menuBar = wx.MenuBar() self.Centre() self.Show() class SubmissionPane(wx.Panel): ################################################ # changed the init here ################################################ def __init__(self, parent, run_params): wx.Panel.__init__(self, parent) self.parent = parent self.selected_folders = None self.params = run_params ################################################ # changed the ref below ################################################ self.frame = self main_sizer = wx.BoxSizer(wx.VERTICAL) self.top_row_sizer = wx.BoxSizer(wx.HORIZONTAL); radio_static_box = wx.StaticBox(self, label='Some Text') radio_static_box_sizer = wx.StaticBoxSizer(radio_static_box, wx.HORIZONTAL) job_static_box = wx.StaticBox(self, label='Some Text') job_static_box_sizer = wx.StaticBoxSizer(job_static_box, wx.HORIZONTAL) ''' radio_labels = ['Some Text', 'Some Text2'] self.radio_box = wx.RadioBox( self, -1, "", choices=radio_labels, ) ''' self.radio1 = wx.RadioButton(self, label='Some Text', style=wx.RB_GROUP) self.radio2 = wx.RadioButton(self, label='Some Text') self.radio1.SetValue(True) radio_static_box_sizer.Add(self.radio1, flag=wx.BOTTOM, border=0) radio_static_box_sizer.Add(self.radio2, flag=wx.LEFT, border=10) self.top_row_sizer.Add(radio_static_box_sizer, flag=wx.LEFT, border=10) self.check_box = wx.CheckBox(self, label="Some Text") self.check_box.SetValue(False) if self.params["systemType"] == "Windows": self.txtTitle = wx.TextCtrl(self, style=wx.SUNKEN_BORDER, value="Some Text...", size=(200, -1), pos=(306, 14)) else: self.txtTitle = wx.TextCtrl(self, style=wx.SUNKEN_BORDER, value="Some Text...", size=(200, -1), pos=(350, 19)) job_static_box_sizer.Add(self.check_box, flag=wx.LEFT, border=0) self.top_row_sizer.Add(job_static_box_sizer, flag=wx.LEFT, border=10); self.txtTitle.Show(False) main_sizer.Add(self.top_row_sizer); main_sizer.Add((-1, 10)) job_static_box2 = wx.StaticBox(self, label='Some Text') third_row_sizer = wx.StaticBoxSizer(job_static_box2, wx.HORIZONTAL); self.tc_files = wx.TextCtrl(self, size=(375, 25)) self.buttonGo = wx.Button(self, label='Go') self.buttonGo.Bind(wx.EVT_BUTTON, self.OnSubmit) third_row_sizer.Add(self.tc_files, flag=wx.RIGHT, border=8) if self.params["systemType"] == "Windows": third_row_sizer.Add(self.buttonGo, flag=wx.LEFT | wx.TOP, border=0) else: third_row_sizer.Add(self.buttonGo, flag=wx.LEFT | wx.TOP, border=2) main_sizer.Add(third_row_sizer, flag=wx.LEFT, border=10) self.log_text22 = wx.ListCtrl(self,size=(875,275), style=wx.LC_REPORT | wx.BORDER_SUNKEN | wx.LC_SINGLE_SEL | wx.LC_VRULES | wx.LC_HRULES) font = wx.Font(self.params["fontSize2"], wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) self.log_text22.SetFont(font) self.log_text22.InsertColumn(1, '1', width=40, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(2, '2', width=50, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(3, '3', width=156) self.log_text22.InsertColumn(4, '4', width=332) self.log_text22.InsertColumn(5, '5', width=100, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(6, '6', width=82, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(7, '7', width=60, format=wx.LIST_FORMAT_CENTRE) self.log_text22.InsertColumn(8, '8', width=50, format=wx.LIST_FORMAT_CENTRE) main_sizer.Add((-1, 10)) list_sizer = wx.BoxSizer(wx.VERTICAL) list_sizer.Add(self.log_text22, flag=wx.LEFT, border=10) main_sizer.Add(list_sizer) self.running_log1 = wx.stc.StyledTextCtrl(self, -1, size=(875,175)) self.running_log1.StyleSetFont(wx.stc.STC_STYLE_DEFAULT, font) self.running_log1.SetMarginWidth(1, 0) self.running_log1.StyleSetBackground(wx.stc.STC_STYLE_DEFAULT, (0,0,0)) self.running_log1.StyleSetForeground(wx.stc.STC_STYLE_DEFAULT, (0,255,0)) self.running_log1.StyleClearAll() main_sizer.Add((-1, 5)) list_sizer = wx.BoxSizer(wx.VERTICAL) list_sizer.Add(self.running_log1, flag=wx.LEFT, border=10) main_sizer.Add(list_sizer) list_sizer.Add((-1, 10)) self.buttonClose = wx.Button(self, -1, "Quit") list_sizer.Add(self.buttonClose, flag=wx.ALIGN_CENTER | wx.TOP | wx.LEFT, border=10) self.SetBackgroundColour("Light Grey") self.SetSizer(main_sizer) self.Layout() def OnSubmit(self, event): msg = "Running" jobSubmitmsg = wx.BusyInfo(msg, self) time.sleep(3) jobSubmitmsg = None app = wx.App(redirect=False) MainWindow(None, -1, 'Application') app.MainLoop()
What is the point of defining new class as a struct in Python C API Question: [The docs for Python C API](https://docs.python.org/2/extending/newtypes.html#the-basics) describes the pattern of defining a new type: typedef struct { PyObject_HEAD PyObject *first; /* first name */ PyObject *last; /* last name */ int number; } Noddy; ... Then methods such as `init` could be added. My question is - what is the point to define custom fields in a struct, why not define them in `init`, just like in Python, using [PyObject_SetAttr](https://docs.python.org/2/c-api/object.html#c.PyObject_SetAttr) function calls on `self`? Answer: 1. Struct member access is far more efficient than dict lookups. 2. Struct member access is far more _convenient_ to do in C. It's much easier to do `thing->foo` than `PyObject_GetAttrString(thing, "foo")`. 3. Using struct members allows you to store data that isn't of a Python type. This allows you to do things that can't be implemented in terms of Python types, or that would be much less efficient in terms of Python types. 4. Using struct members prevents every object from needing its own dict. The most important result of this is that a dict doesn't have to have an infinite descending chain of dicts, but it also improves space efficiency. 5. This API existed before Python-level `class` statements and the way those statements do things.
Top 3 most frequently occurring words in a string (python) Question: Please no importing counters. I need to write a function that takes out the top 3 most occurring words in a string and returns them in a list in the order of most frequently occurring to least frequently occurring. so `h("the the the the cat cat cat in in hat ")` >>> ["the", "cat", "in"] and if there are less than 3 types of words in a string: h("the the cat") >>> ["the", "cat"] Answer: The frequency hash is first populated with the number of times each word appears in a given string. The top 3 words are then determined based on the counts from the frequency hash. **Code** def h(string): return get_top_3(get_frequency_hash(string)) def get_frequency_hash(text): array = text.split(" ") frequency = {} for word in array: try: frequency[word] += 1 except: frequency[word]= 1 return frequency def get_top_3(frequency_hash): array_of_tuples = [(k,v) for k,v in frequency_hash.items()] sorted_array_of_tuples = sorted(array_of_tuples, key=lambda x: -x[1]) return [k for k,v in sorted_array_of_tuples[0:3]] **Example** h("the the the the cat cat cat in in hat") # ['the', 'cat', 'in']
Use codec error handler for print() in Python3? Question: It is well known that the `encode()` has a `error` param for codec error handling, for example: #!/usr/bin/env python3 # -*- coding: utf-8 -*- # "发" and "财" are not available in 'big5' encoding text = "发财了".encode('big5', errors='replace') However, there is not an `errors` param for `print()`, and if we simply write: #!/usr/bin/env python3 # -*- coding: utf-8 -*- print("发财了") A `UnicodeEncodeError` exception is raised if it's run in a command prompt with big5 encoding (for example, in a Traditional Chinese version Windows). Is there a way to make `print()` act like `encode()`, which accepts more handlers such as `replace`, `backslashreplace`, or `xmlcharrefreplace`, so that the string can be printed safely without raising an exception? Answer: Here is my current solution: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def safeprint(*args, errors='backslashreplace', **kargs): """ Print safely and skips error decode. Acts like print() with an additional "errors" argument to determine the error handler for codec errors and accepts non-str-or-None types for the "sep" and "end" arguments. """ e = (kargs['file'] if 'file' in kargs else sys.stdout).encoding args = [str(x) for x in args] sep = str(kargs['sep']) if 'sep' in kargs and kargs['sep'] is not None else " " end = str(kargs['end']) if 'end' in kargs and kargs['end'] is not None else "\n" text = sep.join(args) + end kargs['sep'] = "" kargs['end'] = "" print(text.encode(e, errors).decode(e, errors), **kargs) if __name__ == "__main__": safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड") safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", errors="ignore") safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", errors="replace") safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", errors="backslashreplace") safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", errors="xmlcharrefreplace") safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", sep=None, end=str) safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", sep=" -发- ", end=" -财- \n") with open("safeprint_big5.log", "w", encoding="big5") as f: safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", file=f) with open("safeprint_gbk.log", "w", encoding="gbk") as f: safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", file=f) with open("safeprint_utf8.log", "w", encoding="utf-8") as f: safeprint("Hello World!", "你好世界!", "ハローワールド", "हैलो वर्ल्ड", file=f) This approach makes a custom function `safeprint()` that acts like native `print()` with these differences: 1. Has an additional `errors` argument to determine how to handle codec errors (`backslashreplace` as default). 2. The `sep` and `end` arguments accept types other than str or None. `safeprint()` checks the encoding of the ouput file that native `print()` are supposed to write into and encodes all text arguments beforewards, and therefore all printable chars are printed as-is and all unprintable chars are printed as transformed. Although encoding and decoding beforewards for all texts being printed seems inefficient, native `encode()` and `decode()` are C based and are running very fast. In a test I print some articles with a utf8-compatible plain text for 5000 times in a utf8 console, the native `print()` takes `0:00:02.366799` and `safeprint()` takes `0:00:02.915871`. It proves that the performance drop is almost negligible. The above script can be saved as a module script, say `safeprint.py`. Other scripts can use `from safeprint import safeprint` and use `safeprint()`, or can even use `from safeprint import safeprint as print` to overwrite the native `print()` so that `print()` will work just like `safeprint()` does.
How do I tell Python to press left mouse button at a button of a website? Question: I want to use Python to press the left mouse button at a button of a website. My code I'm trying: from TKinter import * import webbrowser def blackdesertonline(): webbrowser.open("http://black.game.daum.net/black/index.daum", new=1, autoraise=True) main = Tk() bblackdesertonline = Button(main, text = "Start Black Desert Online", command = blackdesertonline) bblackdesertonline.pack() main.mainloop() How can I tell the program to press a button? Answer: You will need to use a library specifically designed to automate websites, such as [selenium](https://pypi.python.org/pypi/selenium).
How to get a Python dict into an HTML template using Flask/Jinja2 Question: I'm trying to use a Python dict in an HTML file. The dictionary is passed to the HTML template through the `render_template` function in Flask. This is the format of the dict: dict1[counter] = { 'title': l.getTitle(), 'url': l.getLink(), 'img': l.getImg() } Then in the HTML template in which I want to iterate through this dict: {% for l in result.iteritems() %} <div class="link"> <a href="{{ l.url }}"> {{l.title}}</a> <img src="{{ l.img }}" width="100" height="100"> </div> {% endfor %} I don't know what the problem is, since there is no error log in Flask. Answer: The problem is that you’re iterating over `iteritems()`, which is an iterator of (key, value) pairs. This means that the `l` variable is a tuple, not a dictionary. You actually want to iterate over `itervalues()` instead. Update your template code as follows: {% for l in result.itervalues() %} <div class="link"> <a href="{{ l.url }}"> {{l.title}}</a> <img src="{{ l.img }}" width="100" height="100"> </div> {% endfor %} I believe that should get you the behaviour you want. * * * Note that this will return the values in a random order (as iterating over a dictionary is random). If you wanted to sort by the key, you could modify the template as follows: {% for key in result.iterkeys()|sort %} <div class="link"> {%- set val=result[key] %} <a href="{{ val.url }}"> {{val.title}}</a> <img src="{{ val.img }}" width="100" height="100"> </div> {% endfor %} Here we iterate over the sorted keys, get the associated value, and then drop it into the template. You could also swap out the `sort` filter for another filter which applies the ordering of your choice. * * * Here’s a minimal example that demonstrates the new template: TEMPLATE_STR = """ {% for l in result.itervalues() %} <div class="link"> <a href="{{ l.url }}"> {{l.title}}</a> <img src="{{ l.img }}" width="100" height="100"> </div> {% endfor %} """ from jinja2 import Template template = Template(TEMPLATE_STR) class democlass(object): def getTitle(self): return "Hello world" def getLink(self): return "google.co.uk" def getImg(self): return "myimage.png" class democlass2(object): def getTitle(self): return "Foo bar" def getLink(self): return "stackoverflow.com" def getImg(self): return "a_photo.jpeg" l = democlass() m = democlass2() dict1 = {} dict1['l'] = { 'title': l.getTitle(), 'url': l.getLink(), 'img': l.getImg() } dict1['m'] = { 'title': m.getTitle(), 'url': m.getLink(), 'img': m.getImg() } print template.render(result=dict1) Here's the HTML it returns: <div class="link"> <a href="stackoverflow.com"> Foo bar</a> <img src="a_photo.jpeg" width="100" height="100"> </div> <div class="link"> <a href="google.co.uk"> Hello world</a> <img src="myimage.png" width="100" height="100"> </div>
Dict comprehension produces seemingly unwarranted NameError Question: I'm using `brian2` to run neural-network simulations. In order to record data during each simulation, I'm creating several instantiations of `brian2`'s `SpikeMonitor` class. I want to store these monitors in a dict, created using a dict comprehension. As a test, I execute the following in an interactive session: In [1]: import brian2 In [2]: pe_mt = brian2.PoissonGroup(1, 100 * brian2.Hz) In [3]: record_pops = ['pe_mt'] In [4]: {'mon_' + pop: brian2.SpikeMonitor(eval(pop)) for pop in record_pops} Out[4]: {'mon_pe_mt': <SpikeMonitor, recording spikemonitor>} Everything looks great. But now when I move this code into the following function def test_record(): pe_mt = brian2.PoissonGroup(1, 100 * brian2.Hz) record_pops = ['pe_mt'] return {'mon_' + pop: brian2.SpikeMonitor(eval(pop)) for pop in record_pops} and call it, I get the following error In [9]: tests.test_record() --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-9-4d3d585b2c97> in <module>() ----> 1 tests.test_record() /home/daniel/Science/dopa_net/brian/ardid/tests.py in test_record() 61 record_pops = ['pe_mt'] 62 return {'mon_' + pop: brian2.SpikeMonitor(eval(pop)) for pop in ---> 63 record_pops} 64 # DEBUG ################### 65 #monitors = utils.record(['pe_mt'], 'spikes', None, None, pe_mt, None, None) /home/daniel/Science/dopa_net/brian/ardid/tests.py in <dictcomp>((pop,)) 60 # DEBUG ################### 61 record_pops = ['pe_mt'] ---> 62 return {'mon_' + pop: brian2.SpikeMonitor(eval(pop)) for pop in 63 record_pops} 64 # DEBUG ################### /home/daniel/Science/dopa_net/brian/ardid/tests.py in <module>() NameError: name 'pe_mt' is not defined What's going on here? 'pe_mt' _is_ defined within the function. Note that if I change the dict comprehension to a list comprehension, as in return [brian2.SpikeMonitor(eval(pop)) for pop in record_pops] no error is raised! I get a list of `SpikeMonitor` objects, defined appropriately. An answer that has now been erased suggested that I use `locals()[pop]` instead of `eval(pop)`. Note that this raises an equivalent error: In [20]: tests.test_record() --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-20-4d3d585b2c97> in <module>() ----> 1 tests.test_record() /home/daniel/Science/dopa_net/brian/ardid/tests.py in test_record() 61 record_pops = ['pe_mt'] 62 return {'mon_' + pop: brian2.SpikeMonitor(locals()[pop]) for pop in ---> 63 record_pops} 64 # DEBUG ################### 65 #monitors = utils.record(['pe_mt'], 'spikes', None, None, pe_mt, None, None) /home/daniel/Science/dopa_net/brian/ardid/tests.py in <dictcomp>((pop,)) 60 # DEBUG ################### 61 record_pops = ['pe_mt'] ---> 62 return {'mon_' + pop: brian2.SpikeMonitor(locals()[pop]) for pop in 63 record_pops} 64 # DEBUG ################### KeyError: 'pe_mt' Answer: One: Forget `eval`, because it can cause unexpected things to happen if the string passed to it is an expression or a function call, rather than an identifier. If you _really_ need to get a local variable by name you can do it cleanly using `locals()[name]`. Docs: [`locals`](https://docs.python.org/2/library/functions.html#locals) * * * Two: All comprehensions and generator expressions (except list comprehensions in python 2.x) [have their own namespace](http://stackoverflow.com/questions/22485399/python-dictionary- comprehension-gives-keyerror), so `locals()` inside the comprehension will refer to that one - the one that doesn't have your variable. Same goes for `eval` that [captures your local variables by default](https://docs.python.org/2/library/functions.html#eval): > If the locals dictionary is omitted it defaults to the globals dictionary. > If both dictionaries are omitted, the expression is executed in the > environment where eval() is called. You can work that around by getting them earlier: def test_record(): pe_mt = brian2.PoissonGroup(1, 100 * brian2.Hz) record_pops = ['pe_mt'] groups = locals() return {'mon_' + pop: brian2.SpikeMonitor(eval(pop, globals(), groups)) for pop in record_pops} # or better return {'mon_' + pop: brian2.SpikeMonitor(groups[pop]) for pop in record_pops} Or more conventionally, without `locals`: def test_record(): groups = { "pe_mt": brian2.PoissonGroup(1, 100 * brian2.Hz), } return {'mon_' + key: brian2.SpikeMonitor(value) for key, value in groups.iteritems()}
Python Packages and Modules Question: I've never really needed to use packages and modules before in python but now as my code base is getting bigger and bigger i'd like to structure it so its imported easier. I've got 10+ .py files that are all part of a package. Instead of doing `import` each and every class when i need them, how can I just group them in the same name space so that I can also reference `import package.componentA as x`? Right now when ever I utilize my all the code, I got to have the source files in the same directory. Is it also possible to package this in a central location so that I can have clean project code? Thanks, Answer: Use the `__init__.py` file in the package and import the modules you want to use from there. So when you import the package it will import everything in that file. Some good info on this method [here](http://mikegrouchy.com/blog/2012/05/be- pythonic-__init__py.html).
Why is this returning two values? Easy python beginner Question: Can someone please explain why my enter method in the following class is returning two values? I'm learning python and in the process of creating a simple game to grasp OOP and classes. Anyhow I need the enter method to return a random snippet from the snippets list. But I keep getting two snippets instead of one. Can someone explain why? from sys import exit from random import randint class Island(object): def enter(self): pass class Loser(Island): snippets = ["Welcome to loser Island", "Can't win them all", "There's always next time"] def enter(self): print Loser.snippets[randint(0,len(self.snippets)-1)] loser_test = Loser() loser_test.enter() Answer: Why don't you just use [`random.choice`](https://docs.python.org/3/library/random.html#random.choice) def enter(self): print random.choice(self.snippets)
GAE app main.py request handlers Question: I have been following a GAE/Jinja2 tutorial, and thankfully it incorporates a feature I have been struggling with within GAE, which is how to link the html pages using the main.py file so they can be edited using Jinja2. The code for main.py is below. import webapp2 import logging import jinja2 import os jinja_environment = jinja2.Environment( loader = jinja2.FileSystemLoader(os.path.dirname(__file__) + "/templates")) class MainPage(webapp2.RequestHandler): def get(self): template_values = { 'welcome':'Welcome to my website!', } template = jinja_environment.get_template('homepage.html') self.response.write(template.render(template_values)) class FeedbackPage(webapp2.RequestHandler): def get(self): feedbackvalues = { } template = jinja_environment.get_template('feedbackform.html') class TopFinishers(webapp2.RequestHandler): def get(self): template = jinja_environment.get_template('Top10Finishers.html') class Belts(webapp2.RequestHandler): def get(self): template = jinja_environment.get_template('WWETitlesBelt.html') class TopWrestlers(webapp2.RequestHandler): def get(self): template = jinja_environment.get_template('Top10Wrestlers.html') app = webapp2.WSGIApplication([('/',MainPage), ('/feedbackform.html',FeedbackPage), ('/Top10Finishers.html',TopFinishers), ('/WWETitlesBelt.html',Belts), ], debug=True) Within the tutorial I followed the procedure for adding more request handlers and then instantiating them in the app object. However, when I load the page by clicking on the button on the page it takes me to a blank page. When I click to go to 'Top 10 Finishers' it will successfully take me to the page as the URL is 'localhost:etc/Top10Finishers.html. However, the content is not showing, do I need to add any URL handlers within the app.yaml file? application: 205semestertwo version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /css static_dir: styling - url: .* script: main.app libraries: - name: webapp2 version: "2.5.2" - name: jinja2 version: "2.6" My question is 'What is causing this error'? As the console logs do not appear to be giving me any error or insight Answer: You are successfully retrieving the new template on each handler, but forgot to write it on the response, the same way you did for your main handler: class TopFinishers(webapp2.RequestHandler): def get(self): values = {} template = jinja_environment.get_template('Top10Finishers.html') self.response.write(template.render(values)) This applies to all your handlers.
When to use ast.literal_eval Question: I came across this code and it works, but I am not entirely sure about **when to use ast** and **whether there are performance issues** when this is used instead of getting the string value from `input()` and converting it to int. import ast cyper_key = ast.literal_eval(input("Enter the key (a value between 0 and 25) : ")) # this get the user input as an int to the variable cyper_key I read the docs I understand what it does. > This can be used for safely evaluating strings containing Python values from > untrusted sources without the need to parse the values oneself. It is not > capable of evaluating arbitrarily complex expressions, for example involving > operators or indexing. I am looking for an explanation on above bold points. Answer: If it's going to be used as an `int`, then just use: cypher_key = int(input("Enter the key (a value between 0 and 25) : ")) Only use that if you expect the user to be entering `10e7` or something. If you want to handle different bases, you can use `int(input(...), 0)` to automatically divine the base. If it really is an integer value between 0 and 25, there's no reason to use `ast`.
AES-ECB encryption (Difference between Python Crypto.Cipher and openssl) Question: i have a problem with encryption using python and openssl. i wrote this small python script: #!/usr/bin/python from Crypto.Cipher import AES obj = AES.new('Thisisakey123456', AES.MODE_ECB) message = "Sample text....." ciphertext = obj.encrypt(message) print ciphertext When i run the script with this command: $ ./enc.py | base64 i get `E0lNh0wtSg9lxxKClBEITAo=` as a result. If i do the same (or obviously it's not the same ;) ) in openssl i get another result: $ echo -n "Sample text....." | openssl aes-128-ecb -k "Thisisakey123456" -nosalt -nopad | base64 yvNTGC+gwUK38uyJXIk/sQ== What i am doing wrong?? i would expect the same base64 encoded string. btw: i know ecb is bad, but i just play around, so it's no problem... ;) Answer: You can try this command: echo -n "Sample text....." | openssl aes-128-ecb -K 546869736973616b6579313233343536 -nopad | openssl base64 this explicitly specifies the key in [hexadecimals](http://www.asciitohex.com/). With `-k` the following "key" is actually a password, which is converted through an OpenSSL Password Based Key Derivation Function (PBKDF) called `EVP_BytesToKey` (using one iteration of SHA-1). The result is `E0lNh0wtSg9lxxKClBEITA==`. This is not identical to `E0lNh0wtSg9lxxKClBEITAo=` but that's because Python adds a single newline character `\n` to the ciphertext, resulting in one extra byte to encode.
How to suppress the deprecation warnings in Django? Question: Every time I'm using the `django-admin` command — even on TAB–completion — it throws a `RemovedInDjango19Warning` (and a lot more if I use the _test_ command). How can I suppress those warnings? I'm using Django 1.8 with Python 3.4 (in a virtual environment). As far as I can tell, all those warnings come from libraries not from my code, here are some examples: * `…/lib/python3.4/importlib/_bootstrap.py:321: RemovedInDjango19Warning: django.contrib.contenttypes.generic is deprecated and will be removed in Django 1.9. Its contents have been moved to the fields, forms, and admin submodules of django.contrib.contenttypes. return f(*args, **kwds)` * `…/lib/python3.4/site-packages/django/contrib/admin/util.py:7: RemovedInDjango19Warning: The django.contrib.admin.util module has been renamed. Use django.contrib.admin.utils instead. "Use django.contrib.admin.utils instead.", RemovedInDjango19Warning)` * `…/lib/python3.4/site-packages/django/templatetags/future.py:25: RemovedInDjango19Warning: Loading the ``url`` tag from the ``future`` library is deprecated and will be removed in Django 1.9. Use the default ``url`` tag instead. RemovedInDjango19Warning)` Answer: Adding a logging filter to settings.py can suppress these console warnings (at least for manage.py commands in Django 1.7, Python 3.4). A filter can selectively suppress warnings. The following code creates a new "suppress_deprecated" filter for the console and appends it to the default logging filters. Add this block to settings.py to configure the LOGGING variable: import logging, copy from django.utils.log import DEFAULT_LOGGING LOGGING = copy.deepcopy(DEFAULT_LOGGING) LOGGING['filters']['suppress_deprecated'] = { '()': 'mysite.settings.SuppressDeprecated' } LOGGING['handlers']['console']['filters'].append('suppress_deprecated') class SuppressDeprecated(logging.Filter): def filter(self, record): WARNINGS_TO_SUPPRESS = [ 'RemovedInDjango18Warning', 'RemovedInDjango19Warning' ] # Return false to suppress message. return not any([warn in record.getMessage() for warn in WARNINGS_TO_SUPPRESS]) The 'mysite.settings.SuppressDeprecated' string needs to change if the root website module (or filter location and/or name) is different.
WXPython Maximize Frame Disable Resizing Question: I am using Python 2.7.6 and wxPython 2.8.12.1 on Linux Mint 17.1 KDE Desktop 4.14.2. I am trying to develop an application in which the window will start maximized and there will be no maximize box or resize box. In other words users will not be able to resize the window. Here is my code. import wx class Frame1(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = (wx.DEFAULT_FRAME_STYLE|wx.MAXIMIZE) & ~ (wx.RESIZE_BORDER|wx.RESIZE_BOX|wx.MAXIMIZE_BOX) wx.Frame.__init__(self, *args, **kwds) self.Layout() self.Show() if __name__ == "__main__": a = wx.App(0) f = Frame1(None, -1, "No Resize") a.MainLoop() On KDE desktop, I do not get the maximized window. What is it I am missing here? Please help. Thanks. Answer: RESIZE_BOX is not a valid style, after I remove that and add MINIZE_BOX to the styles to be removed it works for me on Win8 and Mint17 with Phoenix and with wxPython 2.8.12.1 (gtk2-unicode): import wx class Frame1(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = (wx.DEFAULT_FRAME_STYLE|wx.MAXIMIZE) & ~ (wx.RESIZE_BORDER|wx.MAXIMIZE_BOX|wx.MINIMIZE_BOX) wx.Frame.__init__(self, *args, **kwds) self.Layout() self.Show() if __name__ == "__main__": a = wx.App(0) f = Frame1(None, -1, "No Resize") a.MainLoop( )
Avoiding code repetition in default arguments in Python Question: Consider a typical function with default arguments: def f(accuracy=1e-3, nstep=10): ... This is compact and easy to understand. But what if we have another function `g` that will call `f`, and we want to pass on some arguments of `g` to `f`? A natural way of doing this is: def g(accuracy=1e-3, nstep=10): f(accuracy, nstep) ... The problem with this way of doing things is that the default values of the optional arguments get repeated. Usually when propagating default arguments like this, one wants the same default in the upper function (`g`) as in the lower function (`f`), and hence any time the default changes in `f` one needs to go through all the functions that call it and update the defaults of any of their arguments they would propagate to `f`. Another way of doing this is to use a placeholder argument, and fill in its value inside the function: def f(accuracy=None, nstep=None): if accuracy is None: accuracy = 1e-3 if nstep is None: nstep=10 ... def g(accuracy=None, nstep=None): f(accuracy, nstep) ... Now the calling function doesn't need to know what `f`'s defaults are. But the `f` interface is now a bit more cumbersome, and less clear. This is the typical approach in languages without explicit default argument support, like fortran or javascript. But if one does everything this way in python, one is throwing away most of the language's default argument support. Is there a better approach than these two? What is the standard, pythonic way of doing this? Answer: Define global constants: ACCURACY = 1e-3 NSTEP = 10 def f(accuracy=ACCURACY, nstep=NSTEP): ... def g(accuracy=ACCURACY, nstep=NSTEP): f(accuracy, nstep) * * * If `f` and `g` are defined in different modules, then you could make a `constants.py` module too: ACCURACY = 1e-3 NSTEP = 10 and then define `f` with: from constants import ACCURACY, NSTEP def f(accuracy=ACCURACY, nstep=NSTEP): ... and similarly for `g`.
Cleanly unload shared library and start over with Python CFFI Question: I'm setting up and opening a DLL like this: from cffi import FFI ffi = FFI() api_path = '/path_to/api.h' lib_path = '/path_to/lib.so' with open(api_path) as f: ffi.cdef(f.read()) mylib = ffi.dlopen(lib_path) myfunc_c = ff.callback('int (char *)', myfunc) #etc... How can I close the library and open it again? If I do del mylib and try the above code again I get `CDefError: cannot parse ...` when attempting `ffi.cdef()`. I've seen some examples for ctypes using `dlclose()` but can't find an equivalent for CFFI. Thanks. Answer: Sorry, CFFI has no way to call explicitly the C-level `dlclose()`. It is only called implicitly if the library object goes out of scope. Also, the `ffi` object keeps this library alive, so `ffi` needs to go out of scope too. If you really want to do it, you need to make sure all references to `mylib` and `ffi` are gone, and call `gc.collect()`. (If you want then to reload, you need to start again with a fresh `ffi = FFI()`.) The next version of CFFI might add something like `ffi.close_libraries()` that unloads the libraries loaded in this `ffi` object. **EDIT:** it won't work for libraries loaded with `verify()` on CPython, because these ones are regular CPython C extension modules, and CPython never unloads its C extension modules. This means that the general `ffi.close_libraries()` idea might be doomed...
Use to Chrome Store Publishing API with OAuth2 Service Account Question: I try to update a chrome app programmatically by using the [Chrome Web Store Publishing API](https://developer.chrome.com/webstore/using_webstore_api). I need to use a server to server authentication method and therefor created an oauth2 service account on the [Google developer console](https://console.developers.google.com/project) for my project. And downloaded the credentials as key.p12. I then try to use the [Google API Client for Python](https://github.com/google/google-api-python-client). Even though the API does not support the Chrome Web Store, it should be possible to use parts of it. I created a small script in Python to try to get a list of my Chrome Web Store items: """Creates a connection to Google Chrome Webstore Publisher API.""" from apiclient.discovery import build import httplib2 from oauth2client import client import os SERVICE_ACCOUNT_EMAIL = ( '[email protected]') def getservice(): # get relative path to p12 key dir = os.path.dirname(__file__) filename = os.path.join(dir, 'key.p12') # Load the key in PKCS 12 format that you downloaded from the Google APIs # Console when you created your Service account. f = file(filename, 'rb') key = f.read() f.close() # Create an httplib2.Http object to handle our HTTP requests and authorize it # with the Credentials. Note that the first parameter, service_account_name, # is the Email address created for the Service account. It must be the email # address associated with the key that was created. credentials = client.SignedJwtAssertionCredentials( SERVICE_ACCOUNT_EMAIL, key, scope='https://www.googleapis.com/auth/chromewebstore.readonly') http = httplib2.Http() http = credentials.authorize(http) response = http.request('https://www.googleapis.com/chromewebstore/v1.1/items/[___my_chrome_webstore_app_id___]') print response Even though the **authentication** towards <https://www.googleapis.com/auth/chromewebstore.readonly> is **successful** , the response results in a **403** error. My questions: 1. Does the 403 occur, because the service account does not have acces to my google chrome webstore items? 2. Is it possible to authenticate and use the Chrome Store API without using my personal account, that publishes into the web store (but the connected service account)? 3. How could I retrieve a valid authToken to use for the Chrome Web Store API without having a user to authenticate through the `flow`. Answer: 1. Does the 403 occur, because the service account does not have acces to my google chrome webstore items? Probably. A Service Account is **not** your own Google account. 2. Is it possible to authenticate and use the Chrome Store API without using my personal account, that publishes into the web store (but the connected service account)? Dunno. Sorry not familiar with the Chrome Store API. You can use the Oauth Playground to test the possibilities without having to write any code. 3. How could I retrieve a valid authToken to use for the Chrome Web Store API without having a user to authenticate through the flow. By authorizing once with "offline access", which will return you a Refresh Token. You can use that at any time, even if not logged in, to request an Access Token. As an aside, there is no such thing as an "authtoken". There is an Authorization Code and there is an Access Token. In your case, it's the Access Token you're interested in.
How to translate script i python 2,7 Question: This script works in Python34 How translate in Python27? import urllib.request, re, urllib.parse from base64 import b64encode import codecs import time def send_cap(key, fn): print ('1') data=open(fn, 'rb') print ('2') s = b64encode(data.read()) print ('3') image = s.decode('latin-1') print ('4') params = urllib.parse.urlencode({'method': 'base64', 'key': key, 'body':image, 'ext':'jpg'}) print ('5') bindata=params.encode('ascii') f = urllib.request.urlopen("http://antigate.com/in.php", bindata)#params) print ('6') res = str(f.read().decode()) print(res) cap_id = re.search('\d+',res) if cap_id == None: return False else: idc = cap_id.group(0) return idc def get_cap_text(key, cap_id): time.sleep(5) res_url= 'http://antigate.com/res.php' res_url+= "?" + urllib.parse.urlencode({'key': key, 'action': 'get', 'id': cap_id}) flag=False while flag==False: res= urllib.request.urlopen(res_url).read() res = res.decode() if res == 'CAPCHA_NOT_READY': time.sleep(1) else: flag=True res= re.split('[\W]+',res) if len(res[0]) == 2: return res[1] else: return ('ERROR', res[0]) res = send_cap('eeeee','capcha2.jpg') print(res) text= get_cap_text('eeeee', res) print (text) Answer: If this works in Python 3, then you should change a few lines containing `urllib` to convert: import urllib, re # first line of imports urllib.urlopen # no urllib.request urllib.urlencode # no urllib.parse
Python: SocketServer closes TCP connection unexpectedly Question: I would like to implement a TCP/IP network client application that sends requests to a Python [SocketServer](https://docs.python.org/2/library/socketserver.html) and expects responses in return. I have started out with the official Python [SocketServer sample code](https://docs.python.org/2/library/socketserver.html#socketserver- tcpserver-example): `server.py:` #!/usr/bin/env python # encoding: utf-8 import SocketServer class MyTCPHandler(SocketServer.StreamRequestHandler): def handle(self): request = self.rfile.readline().strip() print "RX [%s]: %s" % (self.client_address[0], request) response = self.processRequest(request) print "TX [%s]: %s" % (self.client_address[0], response) self.wfile.write(response) def processRequest(self, message): if message == 'request type 01': return 'response type 01' elif message == 'request type 02': return 'response type 02' if __name__ == "__main__": server = SocketServer.TCPServer(('localhost', 12345), MyTCPHandler) server.serve_forever() `client.py:` #!/usr/bin/env python # encoding: utf-8 import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect(('127.0.0.1', 12345)) data = 'request type 01' sent = sock.sendall(data + '\n') if sent == 0: raise RuntimeError("socket connection broken") received = sock.recv(1024) print "Sent: {}".format(data) print "Received: {}".format(received) data = 'request type 02' sent = sock.sendall(data + '\n') if sent == 0: raise RuntimeError("socket connection broken") received = sock.recv(1024) print "Sent: {}".format(data) print "Received: {}".format(received) except Exception as e: print e finally: sock.close() `server.py` output: RX [127.0.0.1]: request type 01 TX [127.0.0.1]: response type 01 `client.py` output: Sent: request type 01 Received: response type 01 [Errno 54] Connection reset by peer What am doing wrong ? It seems the server is closing the connection. How can I make it stay open ? Note: This is a follow-up question to [C++/Qt: QTcpSocket won't write after reading](http://stackoverflow.com/q/29549878) **Update (after[abarnert's answer](http://stackoverflow.com/a/29572128)):** What I take away from this is that `SocketServer.StreamRequestHandler` is not the most recent design and while it allows me to connect over a network, it doesn't really support me with all the TCP/IP-related aspects I need to take care of to implement robust communication. This has been addressed in Python 3 with [asyncio](https://docs.python.org/3.4/library/asyncio.html), but as the project lives in Python 2, that's not an option. I have therefore implemented the server and client described above in [Twisted](https://twistedmatrix.com/): `server.py:` #!/usr/bin/env python # encoding: utf-8 from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor class SimpleProtocol(LineReceiver): def connectionMade(self): print 'connectionMade' # NOTE: lineReceived(...) doesn't seem to get called def dataReceived(self, data): print 'dataReceived' print 'RX: %s' % data if data == 'request type 01': response = 'response type 01' elif data == 'request type 02': response = 'response type 02' else: response = 'unsupported request' print 'TX: %s' % response self.sendLine(response) class SimpleProtocolFactory(Factory): def buildProtocol(self, addr): return SimpleProtocol() reactor.listenTCP(12345, SimpleProtocolFactory(), interface='127.0.0.1') reactor.run() `client.py:` #!/usr/bin/env python # encoding: utf-8 from twisted.internet import reactor from twisted.internet.protocol import Protocol from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol class SimpleClientProtocol(Protocol): def sendMessage(self, msg): print "[TX]: %s" % msg self.transport.write(msg) def gotProtocol(p): p.sendMessage('request type 01') reactor.callLater(1, p.sendMessage, 'request type 02') reactor.callLater(2, p.transport.loseConnection) point = TCP4ClientEndpoint(reactor, '127.0.0.1', 12345) d = connectProtocol(point, SimpleClientProtocol()) d.addCallback(gotProtocol) reactor.run() The client doesn't close, but idles until `CTRL`+`C`. Twisted might take a while to get my head around, but for the job at hand, it clearly seems more reasonable to employ a tested and tried framework than to do all this groundwork myself. **NOTE:** This is continued at [Twisted XmlStream: How to connect to events?](http://stackoverflow.com/q/29683769) Answer: The problem here is that in a `TCPHandler`, a "request" is actually a complete connection, from beginning to end.* Your handler gets called on `accept`, and when you return from it, the socket gets closed. If you want to build a request-response-protocol handler on top of that, which processes multiple protocol-level requests on a single socket-level request, you have to do that yourself (or use a higher-level framework). (Subclasses like [`BaseHTTPServer`](https://docs.python.org/2.7/library/basehttpserver.html) demonstrate how to do this.) For example, you can just use a loop within your `handle` function. Of course you probably want to add an exception handler here and/or deal with EOF from `rfile` (note `self.rfile.readline()` will return `''` for EOF, but `'\n'` for a blank line, so you have to check it before calling `strip` unless you want a blank line to mean "quit" in your protocol). For example: def handle(self): try: while True: request = self.rfile.readline() if not request: break request = request.rstrip() print "RX [%s]: %s" % (self.client_address[0], request) response = self.processRequest(request) print "TX [%s]: %s" % (self.client_address[0], response) self.wfile.write(response + '\n') except Exception as e: print "ER [%s]: %r" % (self.client_address[0], e) print "DC [%s]: disconnected" % (self.client_address[0]) * * * This will _often_ work with your existing client, at least over localhost on an unloaded machine, but it's not actually correct, and "often works" is rarely good enough. See [TCP sockets are byte streams, not message streams](http://stupidpythonideas.blogspot.com/2013/05/sockets-are-byte- streams-not-message.html) for a longer discussion, but briefly, you _also_ need to do the stuff mentioned in [David Schwarz's answer](http://stackoverflow.com/a/29571816/908494): append newlines to what you write from the server (which I already did above), and have the client read line by line instead of just trying to read 1024 bytes at a time (which you can do by writing your own buffer-and-split-lines code, or just by using the [`makefile`](https://docs.python.org/2.7/library/socket.html#socket.socket.makefile) method, so it can use `rfile.readline()` just like the server side does.) Not fixing the client won't cause the problems that answer claims, but it _will_ cause problems like this: Sent: request type 01 Received: resp Sent: request type 02 Received: onse type 01 response typ And you can see that in a real program that actually tried to process the responses programmatically, a response like `resp` or `onse type 01\nresponse typ` isn't going to be very useful… * * * * Note that `SocketServer` is an ancient design that nobody really loves. There's a reason Python 3 added [`asyncio`](https://docs.python.org/3.4/library/asyncio.html), and that people in Python 2 usually use third-party frameworks like [Twisted](https://twistedmatrix.com/) and [gevent](http://www.gevent.org/). They're both simpler for simple tasks, and more flexible/powerful (and a lot more efficient) for complex tasks.
Testing the equality of the sum of a digits within a number on python? Question: for example `def f(n):` and I wanna check whether the sum of the numbers within `n` equal to 100 whether it is in 1s, 2s, 3,s 4s, 5s and so on, depending on the length of `n`. f(5050) >>> True This tests whether `5 + 0 + 5 + 0 == 100` and whether `50 + 50 ==100` and if any are true, it returns `True`. Whether it tests in 1s, 2s 3s 4s and so on, depends on the length of the number. For example a number with a length of 5 can only be tested in 1s. f(12345) >>> False This tests whether `1 + 2 + 3 + 4 + 5 == 100` and only that. If the length of `n` was 15, it would test the digits in 1s, 3s and 5s. and finally one more example: f(25252525) >>> True This would test whether `2+5+2+5+2+5+2+5 == 100` and `25+25+25+25==100` and whether `2525+2525==100` So `n`, which has a length of 8 would be tested in 1s , 2s , and 4s. It cannot be tested with 3s and 5s because the length of all the digits within the number being summed up must be the same. I hope I was able to explain what I'm after. Usually I would post what I've tried but I have no idea how to iterate over the digits of a number in such a way Answer: The below approach uses generator to split the integer, and no `integer <-> string` conversion. This will likely be the most efficient approach of the ones currently listed. import math # Define a generator that will split the integer v into chunks of length cl # Note: This will return the chunks in "reversed" order. # split(1234, 2) => [34, 12] def split(v, cl): while v: (v,c) = divmod(v, 10**cl) yield c def f(v): # Determine the number of digits in v n = int(math.log10(v)) + 1 m = int(math.sqrt(v)) # Check all chunk lengths in [1, sqrt(v)] for cl in range(m): # Skip the chunk lengths that would result in unequal chunk sizes if n % (cl+1): continue # Create a generator, to split the value v into chunks of length cl chunks = split(v, cl+1) # If the sum of the chunks is 100, print a message and return True if sum(chunks) == 100: print("sum = 100 with chunklength: %d" % cl) return True # If we get here, none of the chunk lengths result in a sum of 100, return False return False print(f(5050)) # True (cl=2) print("---") print(f(12345)) # False print("---") print(f(25252525)) # True (cl=2) print("---") Output: sum = 100 with chunklength: 2 True --- False --- sum = 100 with chunklength: 2 True --- Without comments and debugging `print`: import math def split(v, cl): while v: (v,c) = divmod(v, 10**cl) yield c def f(v): n = int(math.log10(v)) + 1 m = int(math.sqrt(v)) for cl in range(m): if n % (cl+1): continue if sum(split(v, cl+1)) == 100: return True return False print(f(5050)) # True print(f(12345)) # False print(f(25252525)) # True
Python3: Calling functions saved as values (strings) in a dictionary Question: _Background:_ I am reading a python file (.py) that has a number of functions defined and using a regex to get the names of all the functions and store them in a list. d_fncs = {} list_fncs = [] with open('/home/path/somefile.py', 'r') as f: for row in f: search = re.search(r'def (.*)\(', row) if search: list_fncs.append(search.group(1)) The above works fine and as expected returns a list of of the function names as strings. I have another list which I plan to use as a counter. counter = [str(i) for i in range(1,len(list_fncs)+1)] Finally, I zip the two lists to get a dictionary where the 'keys' are numbers and the associated 'values' are function names d_fncs = dict(zip(counter,list_fncs)) _The problem:_ The intent here is to ask user for an input which would be matched with the key of this dictionary (counter). Once the key is matched, the function associated with it is executed. Something like this happens later in the code: def option_to_run(check, option_enter_by_user): if check == 'True': return (connection(d_fncs[option])) def connection(fnc): conn_name = Connect(some args..) #class imported fnc(conn_name) In this case, as the values from dict are string, I get the following error: File "/home/path/filename.py", line 114, in connection fnc(conn_name) TypeError: 'str' object is not callable However, if I manually make a dict and run it then I have no issues and functions work as expected: d_fncs_expected = {'1': function1, '2': function2, ....} Right now what I am getting is this: d_fncs = {'1': 'function1', '2': 'function2', ....} ....what can I do to get the dictionary to work in a way so I can call these functions? I want the values not to be strings but a type:class Answer: Replace fnc(conn_name) to eval(fnc)(conn_name) # or eval(fnc(conn_name)) **or** globals()[fnc](conn_name) **For example** def myfn(arg): print(arg +" is printed") d = {1: 'myfn'} fun_name = d[1] # 'myfn' >>>fun_name("something") TypeError: 'str' object is not callable >>>eval(fun_name)("something") something is printed >>>globals()[fun_name]("someting") something is printed
Unpack dictionary that contains a list of dictionaries and insert in columns Question: With the data below, I'm trying to unfold a dictionary that contains a list of dictionaries, and then group each key with the corresponding values of the other dictionaries together. For example: result = { 'themes' : [{ 'a' : 'orange', 'b' : 6, 'c' : 'neutral', 'd' : 6, 'e' : 0.24 }, { 'a' : 'banana', 'b' : 6, 'c' : 'neutral', 'd' : 6, 'e' : 0.16 }, { 'a' : 'phone', 'b' : 5, 'c' : 'neutral', 'd' : 5, 'e' : 0.02 } ] } ...should become something along these lines: themes={'a' : ['orange','banana', 'phone']} count={'b' : [6,6,5]} s_score={'c' : [neutral, neutral, neutral]} ...and so on. I've looked [here](http://stackoverflow.com/questions/16485247/dictionary- that-contains-list), [here](http://stackoverflow.com/questions/3421906/how-to- merge-lists-of-dictionaries), and [here](http://stackoverflow.com/questions/38987/how-can-i-merge-two-python- dictionaries-in-a-single-expression) among other places, but couldn't find something close enough to what I want to do. [This](http://stackoverflow.com/questions/26972204/combine-dictionary-entries- by-common-elements) came pretty close, but it's checking for at least one or more common values, whereas mine should group common keys. I know I can separate the outer key from the values like this: >>>(k, v), = result.items() >>>k >>>'themes' >>>v >>>[{ 'a' : 'orange', 'b :6, 'c' : 'neutral', 'd' : 6, 'e' : 0.24 }, { 'a' : 'banana', 'b' : 6, 'c' : 'neutral', 'd' : 6, 'e' : 0.16 }, { 'a' : 'phone', 'b' : 5, 'c' : 'neutral', 'd' : 5, 'e' : 0.02 } ] but how do I get the v list of dictionaries to the way I described? Do I have to convert them to sets first? To make my intention clear, my ultimate goal is iterate through the list of values of the keys that I want to keep, so I can enter them into their respective columns in my fairly basic flask-sqlalchemy SQLite database. So in the end I'll be able to query and get them displayed as html: +-----------------+----------+----------+-------+ | a | b | c | d | +-----------------+----------+----------+-------+ | orange | 2.4 | neutral | 6 | | banana | 1.6 | neutral | 6 | +-----------------+----------+----------+-------+ Answer: You should first flatMap all your values in the list of tuples (`[('a', 'orange'), ('c', 'neutral'), ('b', '6')`..]) and then groupBy first element. I would do it this way: import itertools pairs = itertools.chain.from_iterable([d.items() for d in result["themes"]]) result = {} for key, elem in pairs: result.setdefault(key, []).append(elem) print result
How to get all elements between two nodes with XPATH? Question: I have HTML code like this: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>test</title> </head> <body> <h3><a href="#" name='title1'>Title</a></h3> <div>para1</div> <div>para2</div> <div>para3</div> <h3><a href="#" name='title2'>Title</a></h3> <div>para4</div> <div>para5</div> </body> </html> What I want is: <div>para1</div> <div>para2</div> <div>para3</div> So I want to get the first part in this html. I need to ignore the second part. for now I just work out this way: #!/usr/bin/env python # encoding: utf-8 import unittest from lxml import etree class SearchPara(unittest.TestCase): def setUp(self): with open('test.html') as f: self.html = f.read() def test_parse_html(self): paras = '' page = etree.HTML(self.html) a_ele = page.xpath("//h3/a[@name='title1']/..") if a_ele is None or len(a_ele) < 1: return paras para = a_ele[0].xpath('following-sibling::*[1][name(.) != "h3"]') while para is not None and len(para) > 0: print para paras += etree.tostring(para[0]) para = para[0].xpath('following-sibling::*[1][name(.) != "h3"]') print paras def tearDown(self): pass if __name__ == "__main__": unittest.main() As you can see, this is a little bit complicated, what I want to know if I have beeter way to do this? Answer: As far as I know, there is no general way to select elements between 2 elements using XPath 1.0. The same output still can be achieved if we can define the assertion differently. For example, by selecting `<div>`s having nearest preceding sibling `<a>` value equals `"Title: Part I"` : //div[preceding-sibling::a[1][. = 'Title: Part I']] and selecting the next `<div>`s group only require changing the `<a>` criteria : //div[preceding-sibling::a[1][. = 'Title: Part II']] The test method to see above xpath in action : def test_parse_html(self): page = etree.HTML(self.html) paras = '' para = page.xpath("//div[preceding-sibling::a[1][. = 'Title: Part I']]") for p in para: paras += etree.tostring(p) print paras Side note. xpath for populating `a_ele` in your code can be simplified this way : a_ele = page.xpath("//a[h3 = 'Title: Part I']") or even further, since the only text element within the `<a>` is "Title: Part I" : a_ele = page.xpath("//a[. = 'Title: Part I']")
choose a list by string python Question: I'm having a problem with lists. Their are 4 list, each with a specific name: a=[] b=[] c=[] d=[] Now I want to store values from a whole bunch of xls files in these lists. All these xls files have a name corresponding with the list. For example: 1-2013_a.xls 1-2014_b.xls I iterate through these files with the following code: rootdir='C:\users\desktop\folder' for subdir, dirs, files in os.walk(rootdir): for file in files: .... Here i want to append date from the xls file to the list with the same letter as in the name of the file. I could do it like this: rootdir='C:\users\desktop\folder' for subdir, dirs, files in os.walk(rootdir): for file in files: if(file[7]=='a'): .... if(file[7]=='b'): .... if(file[7]=='c'): .... if(file[7]=='d'): .... But in my program i have 20 lists, so 20 times an if-condition is a bit odd. Is it possible to call a list by a string without using a dictionary ? Thanks for helping me in advance Answer: You can use a dictionary of lists: dct = {"a": [], ... "d": []} And then, you can do `if file[7] in dct:` and access the list using `dct[file[7]]` * * * Even better, you can use a [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) from collections import defaultdict dct = defaultdict(list) Now, within your code, you simply write: rootdir='C:\users\desktop\folder' for subdir, dirs, files in os.walk(rootdir): for file in files: ... dct[file[7]].append(values) This way, you won't have to define any keys of the dictionary, they will be initialized on the go with an empty list.
zipimporter can't find/load sub-modules Question: I'm trying to load a sub-module from a ZIP package but it won't work. How to do it right? **foo.zip** foo/ __init__.py bar.py **test.py** import os import zipimport dirname = os.path.dirname(__file__) importer = zipimport.zipimporter(os.path.join(dirname, 'foo.zip')) print importer.is_package('foo') print importer.load_module('foo') print importer.load_module('foo.bar') **Output** $ python test.py True <module 'foo' from 'foo.zip/foo/__init__.py'> Traceback (most recent call last): File "test.py", line 8, in <module> print importer.load_module('foo.bar') zipimport.ZipImportError: can't find module 'foo.bar' * * * **Update** 2015/04/11 06:30 AM PT The following would work, but is this the real solution to the problem? The `zipimport.zipimporter` documentation explicitly states _"fullname must be the fully qualified (dotted) module name."_ and has an `is_package()` method that seems to function properly. import os import zipimport dirname = os.path.dirname(__file__) importer = zipimport.zipimporter(os.path.join(dirname, 'foo.zip')) def load_module(name): parts = name.split('.') module = importer.load_module(parts[0]) full_name = parts[0] for part in parts[1:]: full_name += '.' + part if not hasattr(module, '__path__'): raise ImportError('%s' % full_name) path = module.__path__[0] module = zipimport.zipimporter(path).load_module(part) return module print load_module('foo.bar') Answer: It will load if you change `importer.load_module('foo.bar')` to `importer.load_module('foo/bar')`. I am not sure why, because the documentation reads > load_module(fullname) > > Load the module specified by fullname. fullname must be the fully qualified > (dotted) module name. It returns the imported module, or raises > ZipImportError if it wasn’t found.
Installing NumPy on Windows 8.1 with Python 2.7.x Question: I'm very new to Python and programming world and has been going along with tutorials from newcoder.io [This Here! ](http://newcoder.io/dataviz/part-0/) I have been doing as per the instructions but when I try to install NumPy I get an error. " error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from <http://aka.ms/vcpython27> * * * Command "C:\Users\HP.virtualenvs\DataVizProj\Scripts\python.exe -c "import setuptools, tokenize;**file** ='c:\users \appdata\local\temp\pip-build- lsj5sj\numpy\setup.py';exec(compile(getattr(tokenize, 'open', open)(**file**).re .replace('\r\n', '\n'), **file** , 'exec'))" install --record c:\users\hp\appdata\local\temp\pip-6jei4k-record\instal cord.txt --single-version-externally-managed --compile --install-headers C:\Users\HP.virtualenvs\DataVizProj\includ te\python2.7" failed with error code 1 in c:\users\hp\appdata\local\temp\pip-build-lsj5sj\numpy " But that's not enough, I tried to install VCForPython27.msi from the given link. But still, gets the same error. Please Help! Answer: I recommend installing the Anaconda distribution of Python. It contains more packages than you can dream of, including numpy of course: <http://continuum.io/downloads> The installation is as straightforward as installing the usual Python, no matter what OS you are on.
How can I display email messages in Tkinter? Question: I've been writing an email application in python/tkinter, where I download the messages from my gmail then display them in a window. The problem I keep getting though is that most messages contain html and come out as gibberish. Is there any way properly display the emails in tkinter, maybe without the pictures, in a way which doesn't come out as loads of html code etc. I've tried html2text but this doesn't work for all emails and still displays them pretty badly (big gaps between words etc)? Thanks Answer: You can use `BeautifulSoup` assuming you have the `HTML` data and an `id` corresponding to the element in which the message body is contained. Please let me know if that doesn't make sense. from bs4 import * soup = BeautifulSoup(html_data_in_here) text = soup.find(id = body_id).getText()
Python OverflowError: math range error Question: Similar to [Python: OverflowError: math range error](http://stackoverflow.com/questions/4050907/python-overflowerror-math- range-error). Below is my code, along with the error (and variable values) I get when I try to debug. Doing math manually in python console works fine. Is it because sigma is an int? For what it's worth, the MSE variable is generated by summing a numpy array, and the simga variable is just "100" hardcoded. def normalize_error(sigma, mse): return math.exp(-mse/(2*(sigma**2))) ![enter image description here](http://i.stack.imgur.com/ngJ4j.png) Answer: You will get this error if your exponential value becomes too great. Since you are using `math.exp`, this value will be a float. Depending on your system, the largest float number in your system will be defined by your [`sys.float_info`](https://docs.python.org/2/library/sys.html#sys.float_info). >>> import sys >>> sys.float_info sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1) So on my system, `1.7976931348623157e+308` is the largest float I could possibly have. * * * You can check the following runs for an analysis of the same: >>> import math >>> def normalize_error(sigma, mse): ... return math.exp(-mse/(2*(sigma**2))) ... >>> normalize_error(3, 4) 0.36787944117144233 >>> normalize_error(3, -4) 1.0 >>> normalize_error(.3, -4) 4477014353.361036 >>> normalize_error(.3, -100) 1.8824011022575583e+241 >>> normalize_error(.02, -100) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in normalize_error OverflowError: math range error
Can one get hierarchical graphs from networkx with python 3? Question: I am trying to display a tree graph of my class hierarchy using **`networkx.`** I have it all graphed correctly, and it displays _fine_. But as a circular graph with crossing edges, it is a pure hierarchy, and it seems I ought to be able to display it as a tree. I have googled this extensively, and every solution offered involves using **`pygraphviz`**... but **_PyGraphviz does not work with Python 3 (documentation from the pygraphviz site)_**. Has anyone been able to get a tree graph display in Python 3? Answer: Here is a simple recursive program to define the positions: import networkx as nx def hierarchy_pos(G, root, width=1., vert_gap = 0.2, vert_loc = 0, xcenter = 0.5, pos = None, parent = None): '''If there is a cycle that is reachable from root, then this will see infinite recursion. G: the graph root: the root node of current branch width: horizontal space allocated for this branch - avoids overlap with other branches vert_gap: gap between levels of hierarchy vert_loc: vertical location of root xcenter: horizontal location of root pos: a dict saying where all nodes go if they have been assigned parent: parent of this branch.''' if pos == None: pos = {root:(xcenter,vert_loc)} else: pos[root] = (xcenter, vert_loc) neighbors = G.neighbors(root) if parent != None: neighbors.remove(parent) if len(neighbors)!=0: dx = width/len(neighbors) nextx = xcenter - width/2 - dx/2 for neighbor in neighbors: nextx += dx pos = hierarchy_pos(G,neighbor, width = dx, vert_gap = vert_gap, vert_loc = vert_loc-vert_gap, xcenter=nextx, pos=pos, parent = root) return pos and an example usage: G=nx.Graph() G.add_edges_from([(1,2), (1,3), (1,4), (2,5), (2,6), (2,7), (3,8), (3,9), (4,10), (5,11), (5,12), (6,13)]) pos = hierarchy_pos(G,1) nx.draw(G, pos=pos, with_labels=True) py.savefig('hierarchy.png') ![enter image description here](http://i.stack.imgur.com/kUTHb.png) Ideally this should rescale the horizontal separation based on how wide things will be beneath it. I'm not attempting that now.
Morse code to alphanumeric (python) Question: I need to write a program that can encode/decode messages using morse code. To encode a message, the program needs to read an input file containing the alphanumeric characters then output the corresponding Morse encoded message. To decode a message, the program will read a file with the Morse code then output the alphanumeric characters. This is what I have so far but I can't get it to decode correctly: import string def to_from(text, dict_in): for i in text: if i.upper() in dict_in: print "%6s" % (dict_in[i]), else: print i, "not in dictionary" print letters = {'A': '*-', 'B': '-***', 'C': '-*-*', 'D': '-**', 'E': '*', 'F': '**-*', 'G': '--*', 'H': '****', 'I': '**', 'J': '*---', 'K': '-*-', 'L': '*-**', 'M': '--', 'N': '-*', 'O': '---', 'P': '*--*', 'Q': '--*-', 'R': '*-*', 'S': '***', 'T': '-', 'U': '**-', 'V': '***-', 'W': '*--', 'X': '-**-', 'Y': '-*--', 'Z': '--**', '0': '-----', '1': '*----', '2': '**---', '3': '***--', '4': '****-', '5': '*****', '6': '-****', '7': '--***', '8': '---**', '9': '----*' } frommorse = dict((b,a) for a,b in letters.items()) text = raw_input('What is the translation you need?\n') text=text.strip() if text[0] in string.letters: to_from(text, letters) else: to_from(text, frommorse) When I tried decoding *-, it would print "E T" instead of A. What am I doing wrong? Answer: For encoding a string to morse code try this APNU = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.' } string = 'yourstring' for char in string: print APNU[char.upper()] or [APNU[char.upper()] for char in string]
Python executable to Linux list files with sizes Question: I need my test.py to display the following in LINUX shell \- list all files in directory \- descending order of file size in bytes (must display bytes) \- show total files and total size at end (X files X total size) \- does not include sub directories or files in other subdirectories here is my python executable #!/usr/bin/env python import subprocess subprocess.call(["ls", "-l", "-S", "-s"]) this shows me the files and their size in descending order but it includes folders/subdirectories which I do not want additionally replacing the subprocess.call with subprocess.call(["find", "-type","f"]) shows me only the files without the unneeded dates and times but I don't know how to get the info I want. My python code: #!/usr/bin/env python import subprocess, os, operator directory='e:\\Programs/Cyg/home/Dylan/test' list=os.listdir(directory) pairs=[] for file in list: if os.path.isfile: location=os.path.join(directory, file) size=os.path.getsize(location) pairs.append((file,size)) pairs.sort(key=operator.itemgetter(0)) for pair in pairs: print (pair) Answer: ## Current directory from os import listdir from os.path import isfile, getsize from operator import itemgetter files = [(f, getsize(f)) for f in listdir('.') if isfile(f)] files.sort(key=itemgetter(1), reverse=True) for f, size in files: print '%d %s' % (size, f) print '(%d files %d total size)' % (len(files), sum(f[1] for f in files)) ## Other directories from os import listdir from operator import itemgetter from os.path import isfile, getsize, join, basename def listfiles(dir): paths = (join(dir, f) for f in listdir(dir)) files = [(basename(p), getsize(p)) for p in paths if isfile(p)] files.sort(key=itemgetter(1), reverse=True) for f, size in files: print '%d %s' % (size, f) print '(%d files %d total size)' % (len(files), sum(f[1] for f in files))
'UserCreationForm' object has no attribute 'get_username' django 1.8 Question: So I'm a newbie to django, know python enough not to call myself a beginner but I'm by no means a pro. I'm just trying to get user authentication working on a small django app. I'm using the default authentication system <https://docs.djangoproject.com/en/1.8/topics/auth/default/> and the built in forms, the login, logout, etc have their own views but the UserCreationForm doesn't have it's own view, so I figured I had to make my own. Not sure what I'm doing wrong. this is my views.py 1 from django.shortcuts import render 2 from django.http import HttpResponse 3 from django.contrib.auth.forms import UserCreationForm 4 from django.contrib.auth import login 5 6 def home(request): 7 return HttpResponse("This is a barebones homepage") 8 9 def register(request): 10 registered = False 11 12 if request.method == 'POST': 13 user_form = UserCreationForm(data=request.POST) 14 15 if user_form.is_valid(): 16 user = user_form.save() 17 username = user_form.get_username() 18 password = user_form.clean_password2() 19 login(request,user) 20 else: 21 print user_form.errors 22 else: 23 user_form = UserCreationForm() 24 25 return render(request, 'registration/register.html', {'user_form': user_form, 'registered': registered} ) ~ this is my register.html <!DOCTYPE html> <html> <head> <title>Jet!</title> </head> <body> {% if registered %} Jet! says Thank you for registering! <a href='/'>Return to the homepage.</a><br /> {% else %} <form method="post" action="/register/"> {% csrf_token %} {{ user_form.as_p }} <input type="submit" name="submit" value="Register" /> </form> {% endif %} </body> </html> Answer: Firstly, the line `username = user_form.get_username()` is giving an error because, as the message says, the form does not have a `get_username` method. You can access the username with user_form.cleaned_data['username'] Secondly, the line `password = user_form.clean` would give an error, because the form has no attribute `clean`. If you needed it, you could get the value from the `password1` field with `user_form.cleaned_data['password1']`. Before you `login` the user, you must authenticate them, otherwise you will get an error about the user having no attribute `backend`. Putting it together, you have: if user_form.is_valid(): user_form.save() username = user_form.cleaned_data['username'] password = user_form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) You'll have to import the `authenticate` method by changing your import to: from django.contrib.auth import authenticate, login Note that you haven't set `registered=True` anywhere in your code. Usually, it is good practice to redirect after the form has been successfully submitted, to prevent duplicate submissions.
matplotlib: Different Marker colour when value crosses a threshold Question: Iam new to matplotlib and here is an image of simplified plot of the situation: <http://postimg.org/image/qkdm6p31p/> I would like to have a red marker for the values above a certain threshold value, in this case, the two points above the red line to have a red marker. Is it possible in matplotlib? And I really don't get why my code never completes execution when I close the window. Here's my code : import wx import numpy as np import matplotlib matplotlib.use('WXAgg') import matplotlib.pyplot as plt from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas class GraphFrame(wx.Frame): def __init__(self): self.displaySize = wx.DisplaySize() wx.Frame.__init__(self, None, -1, style = wx.DEFAULT_FRAME_STYLE, size = (self.displaySize[0], self.displaySize[1])) self.threshold = 3000 self.create_main_panel() self.draw_plot() def create_main_panel(self): self.panel = wx.Panel(self,-1, style = wx.SUNKEN_BORDER) self.fig = plt.figure() self.canvas = FigureCanvas(self.panel, -1, self.fig) self.panelsizer = wx.BoxSizer(wx.HORIZONTAL) self.panelsizer.Add(self.canvas, 1, wx.EXPAND) self.panel.SetSizer(self.panelsizer) mainsizer = wx.BoxSizer(wx.VERTICAL) mainsizer.Add(self.panel, 1, wx.EXPAND ) self.SetSizerAndFit(mainsizer) self.init_plot() def init_plot(self): self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('white') self.axes.set_title('TITLE', size=12) self.data = ['2000','2869','4694','2356','3600','1500'] self.xmin = 0 self.xmax = len(self.data) def draw_plot(self): self.plot_data = self.axes.plot( self.data, linewidth=3, label = "plot1", marker = "o", markersize =7, )[0] self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) thresholdplot = self.axes.plot([self.xmin,self.xmax], [self.threshold,self.threshold],"r--",label = "threshold",linewidth = 1) lg=self.axes.legend(loc="upper left", bbox_to_anchor=(1,1),ncol=1) self.canvas.draw() if __name__ == "__main__": app = wx.PySimpleApp() app.frame = GraphFrame() app.frame.Show() app.MainLoop() print "Finished" I am using Matplotlib, wx with Python 2.7 Would really appreciate your help. Answer: Perhaps the easiest way to accomplish this effect would be to simply plot the subset of your data that is greater than the threshold value a second time. For example: import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ys = np.random.rand(10) threshold = 0.5 ax.axhline(y=threshold, color='r', linestyle=':') ax.plot(ys) greater_than_threshold = [i for i, val in enumerate(ys) if val>threshold] ax.plot(greater_than_threshold, ys[greater_than_threshold], linestyle='none', color='r', marker='o') plt.show()
Translating Java code to Python Question: I'm trying translate this Java code to Python: double grades = -32.33f; System.out.println("grades: "+grades); double radians = Math.toRadians(grades); System.out.println("rad: "+radians); long radiansUp8 = 0xFFFF_FFFFL & (long)(radias * 100_000_000); System.out.println("rad: "+radiansUp8); String hex = Long.toHexString(radiansUp8); System.out.println("signed to hex: "+hex); I've done this: import math grades = -32.33 radians = math.radians(grades) print radians radians = radians * 100000000 print radians hexValue = hex(int(radians)) print hexValue But I'm not getting the same result. The Java code works fine, but in Python not. This line in particular I'm not sure how translate to Python, maybe that is the problem: long radiansUp8 = 0xFFFF_FFFFL & (long)(radianes * 100_000_000); The (correct) output for the Java code is: grades: -32.33000183105469 rad: -0.5642649791276998 rad: 4238540799 signed to hex: fca2ffff The (incorrect) output for the Python code is: grades: -32.33 radians: -0.56426494717 radians: -56426494.717 signed to hex: -0x35cfffe Answer: The translation for that line into Python is: radians = 0xffffffff & long(radians * 100000000) This gives (roughly!) the answer you expect: >>> 0xffffffff & long(math.radians(-32.33) * 100000000) 4238540802L * * * What the line **does** is multiply the number of radians by 100,000,000 (giving `-56426494.71697667`), convert the result to a `long` integer (`-56426494L`) then do a _"bitwise and"_ (see e.g. <https://wiki.python.org/moin/BitwiseOperators>) between that and `0xffffffff`. Your current code only performs the first of these three steps. For a simple example of what bitwise and does: >>> '{:04b}'.format(int('1010', 2) & (int('0111', 2))) '0010' For each binary digit, the output digit is `1` only if both input digits are `1`.
Maya Python - Using data from UI Question: I am working on a scripting program and struggling a bit with the UI. I've made a couple of UIs, all of which seem to work fine individually, but I don't know how to use the data inputted in a UI to another function. I'm trying to get the Gun Type (selected by the user in `Bullet_Spray_Generator`) to then affect which of the UIs is then called. Each Gun Type requires a different set of values for the sliders, so I made a different UI for each. I think I need to pass the data selected from the BSG into an `if` function in order to call the correct (second) UI, but running it just always jumps to the `else` function and closes the window. Here's my code so far: import maya.cmds as cmds from functools import partial if (cmds.window("Bullet_Spray_Generator", exists = True)): cmds.deleteUI("Bullet_Spray_Generator") if (cmds.window("BSG2", exists = True)): cmds.deleteUI("BSG2") cmds.select(all=True) cmds.delete() def goShoot(numOfShots, distToTarget, *pArgs): print "Begin" cmds.deleteUI("BSG2") createWall() def cancelShoot(*pArgs): print "cancel" cmds.deleteUI("Bullet_Spray_Generator") def createWall(): cmds.select(all=True) cmds.delete() wall = cmds.polyCube(h=10, w=15, d=1, name='wall') cmds.move(0,5,0, 'wall') def createGunUI(gunType, *pArgs): if (GunSelectCtrl == 'Pistol'): createPistolUI() elif (GunSelectCtrl == 'Shotgun'): createShotgunUI() elif (GunSelectCtrl == 'SMG'): createSMGUI() elif (GunSelectCtrl == 'Sniper Rifle'): createSniperUI() elif (GunSelectCtrl == 'RPG'): createRPGUI() else: print "Something went wrong" cancelShoot() def createPistolUI(): cmds.window("Pistol") cmds.columnLayout(adjustableColumn=True) cmds.deleteUI("Bullet_Spray_Generator") NumBulletsCtrl = cmds.intSliderGrp(label='Number of Shots', minValue=1, maxValue=9, value=4, field=True) DistCtrl = cmds.intSliderGrp(label='Distance to Target (metres)', minValue=1, maxValue=50, value=25, field=True) cmds.button(label = "Fire", command = lambda *args: goShoot(cmds.intSliderGrp(NumBulletsCtrl, query=True, value=True), cmds.intSliderGrp(DistCtrl, query=True, value=True), )) cmds.button(label = "Cancel", command = cancelShoot) cmds.showWindow("Pistol") def createShotgunUI(): cmds.window("Shotgun") cmds.columnLayout(adjustableColumn=True) cmds.deleteUI("Bullet_Spray_Generator") NumBulletsCtrl = cmds.intSliderGrp(label='Number of Shots', minValue=1, maxValue=4, value=2, field=True) DistCtrl = cmds.intSliderGrp(label='Distance to Target (metres)', minValue=1, maxValue=50, value=25, field=True) cmds.button(label = "Fire", command = lambda *args: goShoot(cmds.intSliderGrp(NumBulletsCtrl, query=True, value=True), cmds.intSliderGrp(DistCtrl, query=True, value=True), )) cmds.button(label = "Cancel", command = cancelShoot) cmds.showWindow("Shotgun") def createSMGUI(): cmds.window("SMG") cmds.columnLayout(adjustableColumn=True) cmds.deleteUI("Bullet_Spray_Generator") NumBulletsCtrl = cmds.intSliderGrp(label='Number of Shots', minValue=1, maxValue=20, value=4, field=True) DistCtrl = cmds.intSliderGrp(label='Distance to Target (metres)', minValue=1, maxValue=50, value=25, field=True) cmds.button(label = "Fire", command = lambda *args: goShoot(cmds.intSliderGrp(NumBulletsCtrl, query=True, value=True), cmds.intSliderGrp(DistCtrl, query=True, value=True), )) cmds.button(label = "Cancel", command = cancelShoot) cmds.showWindow("SMG") def createSniperUI(): cmds.window("Sniper") cmds.columnLayout(adjustableColumn=True) cmds.deleteUI("Bullet_Spray_Generator") NumBulletsCtrl = cmds.intSliderGrp(label='Number of Shots', minValue=1, maxValue=2, value=2, field=True) DistCtrl = cmds.intSliderGrp(label='Distance to Target (metres)', minValue=1, maxValue=50, value=25, field=True) cmds.button(label = "Fire", command = lambda *args: goShoot(cmds.intSliderGrp(NumBulletsCtrl, query=True, value=True), cmds.intSliderGrp(DistCtrl, query=True, value=True), )) cmds.button(label = "Cancel", command = cancelShoot) cmds.showWindow("Sniper") def createRPGUI(): cmds.window("RPG") cmds.columnLayout(adjustableColumn=True) cmds.deleteUI("Bullet_Spray_Generator") NumBulletsCtrl = cmds.intSliderGrp(label='Number of Shots', minValue=1, maxValue=1, value=1, field=True) DistCtrl = cmds.intSliderGrp(label='Distance to Target (metres)', minValue=1, maxValue=50, value=25, field=True) cmds.button(label = "Fire", command = lambda *args: goShoot(cmds.intSliderGrp(NumBulletsCtrl, query=True, value=True), cmds.intSliderGrp(DistCtrl, query=True, value=True), )) cmds.button(label = "Cancel", command = cancelShoot) cmds.showWindow("RPG") def printNewMenuItem(item): print item return item def createUI(): cmds.window("Bullet_Spray_Generator") cmds.columnLayout(adjustableColumn=True) GunSelectCtrl = cmds.optionMenu(label='Gun', changeCommand=printNewMenuItem) cmds.menuItem(label='Pistol') cmds.menuItem(label='Shotgun') cmds.menuItem(label='SMG') cmds.menuItem(label='Sniper Rifle') cmds.menuItem(label='RPG') cmds.button(label = "Continue", command = partial(createGunUI, GunSelectCtrl)) cmds.button(label = "Cancel", command = cancelShoot) cmds.showWindow("Bullet_Spray_Generator") createUI() Any help would be greatly appreciated, thanks very much. Answer: The easiest way to pass complex information around inside a GUI in Maya is to wrap the whole UI in python class. The class can 'remember' all of your fields, sliders, etc so that you can easily collect information from one or more GUI items and act on them without too much extra work. class PistoUI(object): def __init__(self): self.window = cmds.window("Pistol") cmds.columnLayout(adjustableColumn=True) self.bullet_count = cmds.intSliderGrp(label='Number of Shots', minValue=1, maxValue=9, value=4, field=True) self.distance = cmds.intSliderGrp(label='Distance to Target (metres)', minValue=1, maxValue=50, value=25, field=True) cmds.button(label = "Fire", command = self.fire) cmds.button(label = "Cancel", command = self.cancel) cmds.showWindow(self.window) def fire(self, _ignore): bullets = cmds.intSliderGrp(self.bullet_count, q=True, v=True) distance = cmds.intSliderGrp(self.distance, q=True, v=True). goShoot(bullets, distance) def cancel(self, _ignore): cmds.deleteUI(self.window) As you can see above, the `fire` function gets the correct fields from the active window and collects their values to pass to the goShoot function without any extra work in the layout step to pass the values directly to a function. This is much simpler and more elegant than leaving all the pieces lying around in the open. It's also more self-contained - you can create multiple windows side-by-side in that scheme without worrying about creating and deleting them by name. Even better, the clases are really good for separating out differences in logic from difference in data, so you can resuse the repetitive code with ease: class WeaponUI(object): LABEL = 'weapon_name' #default name SHOTS = (1, 9, 4) # default shots RANGE = (1, 50, 25) # default range def __init__(self): self.window = cmds.window(title = self.LABEL) cmds.columnLayout(adjustableColumn=True) self.bullet_count = cmds.intSliderGrp(label='Number of Shots', minValue=self.SHOTS[0], maxValue=self.SHOTS[1], value=self.SHOTS[2], field=True) self.distance = cmds.intSliderGrp(label='Distance to Target (metres)', minValue=self.RANGE[0], maxValue=self.RANGE[1], value=self.RANGE[2], field=True) cmds.button(label = "Fire", command = self.fire) cmds.button(label = "Cancel", command = self.cancel) cmds.showWindow(self.window) def fire(self, _ignore): bullets = cmds.intSliderGrp(self.bullet_count, q=True, v=True) distance = cmds.intSliderGrp(self.distance, q=True, v=True). print "firing", self.LABEL goShoot(bullets, target) def cancel(self, _ignore): cmds.deleteUI(self.window) class PistolUI(WeaponUI): LABEL = 'pistol' SHOTS = (1, 9, 4) RANGE = (1, 50, 25) class ShotgunUI(WeaponUI): LABEL = 'shotgun' SHOTS = (1, 4, 2) RANGE = (1, 50, 25) class SniperUI(WeaponUI): LABEL = 'sniper' SHOTS = (1, 4, 2) RANGE = (1, 50, 25) ... and so on More about maya GUI connections [here](http://techartsurvival.blogspot.com/2014/04/maya-callbacks-cheat- sheet.html) and [here](http://techartsurvival.blogspot.com/2014/02/rescuing- maya-gui-from-itself.html)
sending email from python 3.4 script, WITHOUT enabling 'less secure apps' in gmail Question: i would like to send mail using a python 3.4 script, from my gmail address. i use the following code: import smtplib def sendmail(): sender='[email protected]' receiver=['[email protected]'] message='text here' try: session=smtplib.SMTP('smtp.gmail.com',587) session.ehlo() session.starttls() session.ehlo() session.login(sender,'mypassword') session.sendmail(sender,receiver,message) session.quit() except smtplib.SMTPException: print('Error, can not send mail!') if i 'allow less secure apps' in my gmail account, the script works fine. however, if i disable 'less secure apps', it doesn't works (i get a warning email from google, with 'sign-in attempt blocked') . i would like to modify my code, to be able to send mail without enabling this thing. i have read all the questions and answers regarding similar problems, but did not find any useful answers or methods. someone has any solution for this? Answer: From ["Allowing less secure apps to access your account" support page](https://support.google.com/accounts/answer/6010255) > Google may block sign in attempts from some apps or devices that do not use > modern security standards. A login/password is not a modern mechanism to authenticate. You should implement [SASL XOAuth2](https://developers.google.com/gmail/oauth_overview).
Using python to run bash commands and get Output Question: I want to download videos through Youtube-he. So,I wrote program but it isn't working.The code is import os l=["sets","relation_and_functions","Trig","Complex_Quad","Linear_inequalities","Permutation","Binomial","Sequence","Straight","conic","Three_d","Limit_Derivative","Stats","Probability","Math_reasoning"] r=["https://www.youtube.com/playlist?list=PLD5EF274490578CC4","https://www.youtube.com/playlist?list=PL548FAD237A4B6D2E","https://www.youtube.com/playlist?list=PL42123C3873AED16F","https://www.youtube.com/playlist?list=PL880E3116D67E42FD","https://www.youtube.com/playlist?list=PLC5D1199BAE318878","https://www.youtube.com/playlist?list=PL812413BD6B55AA6E","https://www.youtube.com/playlist?list=PL78FAFAFA8496BCE1","https://www.youtube.com/playlist?list=PL6F57725E2DA8B557","https://www.youtube.com/playlist?list=PLA243228EA688A835","https://www.youtube.com/playlist?list=PL41B47FB4E23B392A","https://www.youtube.com/playlist?list=PLa2X112u1cdjdl-dsLJC1HaCeGrOarZZz","https://www.youtube.com/playlist?list=PLF6640F0A9F39F7BA","https://www.youtube.com/playlist?list=PL6FDE1AB3AE32E614","https://www.youtube.com/playlist?list=PL7FF5AD1CFF0981E5","https://www.youtube.com/playlist?list=PL13B63CD6FFAB9EA8"] for i in range(len(l)): a=l[i] b=r[i] os.system("mkdir a") os.chdir("a") os.system("youtube-dl b") Answer: You need to pass the actual variables, not a string. You should also use the subprocess module in particular [check_call](https://docs.python.org/2/library/subprocess.html#subprocess.check_call): l =["sets","relation_and_functions","Trig","Complex_Quad","Linear_inequalities","Permutation","Binomial","Sequence","Straight","conic","Three_d","Limit_Derivative","Stats","Probability","Math_reasoning"] r=["https://www.youtube.com/playlist?list=PLD5EF274490578CC4","https://www.youtube.com/playlist?list=PL548FAD237A4B6D2E","https://www.youtube.com/playlist?list=PL42123C3873AED16F","https://www.youtube.com/playlist?list=PL880E3116D67E42FD","https://www.youtube.com/playlist?list=PLC5D1199BAE318878","https://www.youtube.com/playlist?list=PL812413BD6B55AA6E","https://www.youtube.com/playlist?list=PL78FAFAFA8496BCE1","https://www.youtube.com/playlist?list=PL6F57725E2DA8B557","https://www.youtube.com/playlist?list=PLA243228EA688A835","https://www.youtube.com/playlist?list=PL41B47FB4E23B392A","https://www.youtube.com/playlist?list=PLa2X112u1cdjdl-dsLJC1HaCeGrOarZZz","https://www.youtube.com/playlist?list=PLF6640F0A9F39F7BA","https://www.youtube.com/playlist?list=PL6FDE1AB3AE32E614","https://www.youtube.com/playlist?list=PL7FF5AD1CFF0981E5","https://www.youtube.com/playlist?list=PL13B63CD6FFAB9EA8"] from subprocess import check_call for direc, url in zip(l, r): check_call(["mkdir", direc]) check_call(["youtube-dl", ele2],cwd=direc) `zip(l, r)` zips the corresponding elements from each list so we simply unpack the pairs in the loop. `cwd=direc` will set the directory to download the file to.
Python 3 Multi-Threading with Tkinter Question: I have been writing a bit of code that will eventually take commands from a remote and local (within the code itself) source and and then will be carried out and the results displayed using tkinter. The Problem I am currently having is that when I run the code using threading and queues this error appears and I have tried putting the gui code at the bottom under the for loops for the threading but this had another error that occurred. Exception in thread Thread-1: Traceback (most recent call last): File "C:\Python34\lib\threading.py", line 921, in _bootstrap_inner self.run() File "C:\Python34\lib\threading.py", line 869, in run self._target(*self._args, **self._kwargs) File "C:/Users/Eddy/Programing/Python/Sockets/GUI Server.py", line 60, in threader t_visuals() File "C:/Users/Eddy/Programing/Python/Sockets/GUI Server.py", line 49, in t_visuals label = Label(root, width=70, height=30,relief=RIDGE,bd=5,bg="white",textvariable=v,anchor=NW,justify= LEFT,font=("Times New Roman", 12)).grid(row=1,column=0) File "C:\Python34\lib\tkinter\__init__.py", line 2604, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "C:\Python34\lib\tkinter\__init__.py", line 2122, in __init__ (widgetName, self._w) + extra + self._options(cnf)) RuntimeError: main thread is not in main loop Exception in thread Thread-2: Traceback (most recent call last): File "C:\Python34\lib\threading.py", line 921, in _bootstrap_inner self.run() File "C:\Python34\lib\threading.py", line 869, in run self._target(*self._args, **self._kwargs) File "C:/Users/Eddy/Programing/Python/Sockets/GUI Server.py", line 58, in threader t_connections() File "C:/Users/Eddy/Programing/Python/Sockets/GUI Server.py", line 43, in t_connections sLog_update("waiting for connection...") File "C:/Users/Eddy/Programing/Python/Sockets/GUI Server.py", line 40, in sLog_update v.set(g) File "C:\Python34\lib\tkinter\__init__.py", line 263, in set return self._tk.globalsetvar(self._name, value) RuntimeError: main thread is not in main loop This is the code: from socket import * import time from tkinter import * import threading from queue import Queue #server setup HOST = '' PORT = 24601 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) #Window Setup HEIGHT = 720 WIDTH = 1280 root = Tk() root.title("Server Controler") root.geometry("1280x720") #Variables needed v =StringVar() f =StringVar() g = "" #Server update log #locked variables sLog_lock = threading.Lock() #t_ means threaded def sLog_update(self): with sLog_lock: global g currentTime = str("["+time.ctime()+"] ") g+=str(currentTime) g+=str(self) g+=str("\n") v.set(g) def t_connections(): sLog_update("waiting for connection...") tcpCliSock, addr = tcpSerSock.accept() avr = "connected from: " + str(addr) sLog_update(avr) def t_visuals(): label = Label(root, width=70, height=30,relief=RIDGE,bd=5,bg="white",textvariable=v,anchor=NW,justify= LEFT,font=("Times New Roman", 12)).grid(row=1,column=0) entry = Entry(root, width=105,relief=RIDGE,bd=5,textvariable=f).grid(row=2,column=0) button = Button(root,command= lambda:sLog_update(f.get()),text="send").grid(row=3,column=0) mainloop() def threader(): worker = q.get() print(worker) if worker == 1: t_connections() elif worker == 0: t_visuals() q =Queue() for x in range(2): t = threading.Thread(target=threader) t.daemon = True t.start() for worker in range(20): q.put(worker) q.join() Answer: You can make this problem going away by keeping all of the GUI code in the main thread.
Using tkinter to plot pandas dataframes Question: So I'm trying to write a small GUI that will allow an end use to plot X vs Y of any 2 columns in an Excel file. Here's my code: import pandas as pd import matplotlib.pyplot as plt import tkinter as tk my_base=pd.read_excel('my_base.xlsx', 'the_tab', index_col=None, na_values = ['NA']) my_base_header = list(my_base.columns.values) my_base['Generated Date'] = pd.to_datetime(my_base['Generated Date']) main_win = tk.Tk() def plot_graph(): print(option1.get()) print(option2.get()) my_base.plot(x = option1.get(), y = option2.get(), style = 'x') plt.show() option1 = tk.StringVar(main_win) option1.set(my_base_header[0]) option2 = tk.StringVar(main_win) option2.set(my_base_header[0]) opt1 = tk.OptionMenu(main_win, option1, *my_base_header) opt1.pack() opt2 = tk.OptionMenu(main_win, option2, *my_base_header) opt2.pack() runbtn = tk.Button(main_win, text = 'Plot', command = plot_graph) runbtn.pack() main_win.mainloop() I can get the program to plot if I put the dataframe headers in directly like so: my_base.plot(x = 'Generated Date', y = 'How many', style = 'x') But when I use for example `x = option1.get()` in there I get this traceback Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> my_base.plot(x= x_ax, y = y_ax, style = 'x') File "C:\Python34\lib\site-packages\pandas\tools\plotting.py", line 2485, in plot_frame **kwds) File "C:\Python34\lib\site-packages\pandas\tools\plotting.py", line 2325, in _plot plot_obj.generate() File "C:\Python34\lib\site-packages\pandas\tools\plotting.py", line 921, in generate self._compute_plot_data() File "C:\Python34\lib\site-packages\pandas\tools\plotting.py", line 997, in _compute_plot_data 'plot'.format(numeric_data.__class__.__name__)) TypeError: Empty 'Series': no numeric data to plot Answer: It's as the error says: the data you're trying to plot is non-numeric, so it's probably a string or from the looks of it, maybe a datetime. If you include the data and which column is giving you this error, we could point out the problem. If it is a datetime, you may need to convert it to a pandas timestamp type, like: pandas.DatetimeIndex([yourDatetime]) Your code seems to work for me. I used this demo dataset: <http://www.contextures.com/xlSampleData01.html> If I try to plot something non-numeric, such as 'Region' or 'Rep', it gives me the same error you have (no numeric data to plot). If I plot 'Unit Cost' vs 'Total', or any other combination of 2 numeric datasets, it works. import pandas as pd import matplotlib.pyplot as plt import Tkinter as tk my_base=pd.read_excel('SampleData.xls', 'SalesOrders', index_col=None, na_values = ['NA']) my_base_header = list(my_base.columns.values) #print my_base my_base['OrderDate'] = pd.to_datetime(my_base['OrderDate']) main_win = tk.Tk() def plot_graph(): print(option1.get()) print(option2.get()) my_base.plot(x = option1.get(), y = option2.get(), style = 'x') plt.show() option1 = tk.StringVar(main_win) option1.set(my_base_header[0]) option2 = tk.StringVar(main_win) option2.set(my_base_header[0]) opt1 = tk.OptionMenu(main_win, option1, *my_base_header) opt1.pack() opt2 = tk.OptionMenu(main_win, option2, *my_base_header) opt2.pack() runbtn = tk.Button(main_win, text = 'Plot', command = plot_graph) runbtn.pack() main_win.mainloop()
How to identify data after they have been through a whitening transformation and K-means clustering, python Question: I am performing a K-means clustering in Python following this: <http://glowingpython.blogspot.no/2012/04/k-means-clustering-with-scipy.html> tutorial. I have my data, which are length, breadth and height - which I am whitening using: from scipy.cluster.vq import whiten data = whiten(data) After whitening I am doing the k-means clustering, following the tutorial. My question is: how do I identify the data after I have whitened it? Both when it comes to the plot, and when doing further analysis on the data. I want a way of identifying which data comes in which cluster. Answer: Do the whitening transform _manually_. It's really easy, if you **look at the source code of`vq.whiten`**! No black magic involved, only linear algebra. Then it's easy to store the _linear transformation_ \- and it's _reverse_ (a multiplication, OMG!). Then you can map back the means to the original data. If you didn't reduce dimensionality afterwards, it is fairly accurate. Alternatively, just _recompute the means in the original data space_. This is probably more accurate, but can be much more expensive if you have a lot of data points.
Find sum of first 1000 prime numbers in python Question: I have written a program which counts the sum of the primes uptill 1000. The program is as follows: limit = 1000 def is_prime(n): for i in range(2, n): if n%i == 0: return False return True sum = 0 for i in range(2, int(limit+1)): if is_prime(i): sum = sum + i count += 1 print sum What changes can I make to find 1000 primes instead of upto 1000 numbers? Also, I am looking for space complexity as O(1) and time complexity as O(n) (As I know other methods can do it :-) such as "Sieve of Eratosthenes" and finding prime while iterating upto sqrt(n) <http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/>) Please correct me if I am going wrong some where. Thank you. Answer: Code: def f(): i = 2 while True: if all(i % x != 0 for x in range(2, i-1)): yield i i += 1 primes = f() print sum(primes.next() for _ in range(1000)) Or a one liner: import itertools print sum(itertools.islice(itertools.ifilter(lambda x: all(x % i != 0 for i in range(2, x)), f()), 0, 1000))
Syntax error while declaring path Question: wanted to know why is it a syntax error while compiling this script if I'm declaring a path? I already searched a bit about it and couldn't find anything related to this, can someone explain me how to add a path ? if __name__ == "__main__": # This isn't part of the actual code spread = Spreader (C:\Users\Test\bin.exe) # C: the ':' is the syntax error import win32api import win32con import win32file import sys import os class Spreader(object): def __init__(self, path): # path must be absolute print (" [*] Checking information") self.filename = path.split("\\")[-1] self.driveFilename = self.filename if not self.driveFilename.startswith("~"): self.driveFilename = "~" + self.driveFilename print ("\t- Local filename: ") + self.filename print ("\t- Driver filename: ") + self.driveFilename self.path = "\\".join(path.split("\\")[:-1]) + "\\" + self.filename print ("\t- Full path: ") + self.path print ("\n [*] Getting removable drives") self.drives = self.__getRemovableDrives() if len(self.drives) == None: print (" [-] No removable drives available") sys.exit() for drive in self.drives: print ("\t- ") + drive print ("\n [*] Spreading") self.__spread() print ("\n [+] Successfully spread") def __getRemovableDrives(self): removableDrives = [] drives = win32api.GetLogicalDriveStrings().split("\000")[:-1] for drive in drives: driveType = win32file.GetDriveType(drive) if driveType == win32file.DRIVE_REMOVABLE: removableDrives.append(drive) return removableDrives def __spread(self): for drive in self.drives: if drive == "A:\\": continue else: driveFile = drive + self.driveFilename driveAutorun = drive + "autorun.inf" print (" [+] ") + drive if not os.path.exists(driveFile): self.__copyFile(driveFile) if not os.path.exists(driveAutorun): self.__createAutorun(driveAutorun) def __copyFile(self, driveFile): print ("\t- Copying file: ") + self.driveFilename, win32file.CopyFile(self.path, driveFile, 0) print ("\t\t\tDONE") print ("\t- Hidding file"), win32api.SetFileAttributes(driveFile,\ win32con.FILE_ATTRIBUTE_HIDDEN) print ("\t\t\tDONE") def __createAutorun(self, driveAutorun): print ("\t- Creating autorun.inf"), autorun = open(driveAutorun, "w") content = """[Autorun] open={0} icon={0} label=Python Spreader UseAutoPlay=1 action=Start my App action=@{0} shell\open=Open shell\open\Command={0} shell\explore=explore shell\explore\command={0}""".format(self.driveFilename) autorun.write(content) autorun.close() print ("\t\t\tDONE") print ("\t- Hidding autorun"), win32api.SetFileAttributes(driveAutorun,\ win32con.FILE_ATTRIBUTE_HIDDEN) print ("\t\t\tDONE") if __name__ == "__main__": spread = Spreader (C:\Users\Test\bin.exe) Answer: You must enclose the path in quotes to make it a string: spread = Spreader('C:/Users/Test/bin.exe')
django-registration-redux add extra field Question: 7 and python 2.7. i want to add extra field in django registration. i try to extend with my model like this: class Seller(models.Model): user = models.ForeignKey(User, unique=True) name = models.CharField(max_length=25) phone_number = models.BigIntegerField() email = models.EmailField(max_length=75) def __str__(self): return self.name; and i add form.py like this from django import forms from registration.forms import RegistrationForm from django.forms import ModelForm from django.contrib.auth.models import User from kerajinan.models import Product, Category, Seller class SellerForm(forms.ModelsForm): class Meta: model = Seller fields = ('name','phone_number','email') and modify url.py like this: url(r'^accounts/', 'registration.views.register',{'form_class':SellerForm,'backend': 'registration.backends.default.DefaultBackend'}) how to use those model with django registration and i get error syntax with my ulr.py? thanks Answer: It's works for me: models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): field = models.CharField(max_length=3) user = models.OneToOneField(User) forms.py from registration.forms import RegistrationFormUniqueEmail from django import forms class UserProfileRegistrationForm(RegistrationFormUniqueEmail): field = forms.CharField() Create regbackend.py and write: from registration.backends.default.views import RegistrationView from forms import UserProfileRegistrationForm from models import UserProfile class MyRegistrationView(RegistrationView): form_class = UserProfileRegistrationForm def register(self, request, form_class): new_user = super(MyRegistrationView, self).register(request, form_class) user_profile = UserProfile() user_profile.user = new_user user_profile.field = form_class.cleaned_data['field'] user_profile.save() return user_profile And urls.py from django.conf.urls import include, url import regbackend urlpatterns = [ url(r'^accounts/register/$', regbackend.MyRegistrationView.as_view(), name='registration_register'), ]
python: import error: no module named Question: Out of nowhere my scripts aren't finding locations anymore, that worked previously. The only thing i changed was to add a environmental variable in Windows because i didn't get access python via the command line. But also after deleting it and resetting the "PATH" variable the problem is the same. The error only occurs for modules in my project directory which i import via "from... import..." no problem with "import sys" and so on. I don't understand what's going on. I use eclipse and Python 2.7. Update: I "auto configured" in the interpreter menu so that PYTHONPATH was rebuilt, i used File-->Restart but i won't damn work! I even removed the system environmental variable from windows. What is wrong with my setup? Update2: Now i even reinstalled Eclipse but the f***ing errormessage is still there. It's driving me crazy! Anybody with more tips? Update3: The problem occured after my laptop shut down because the battery was low. During that it was executing a script. Maybe it has sth. to do with the forced shutdown. Answer: Ok, i found the solution. Somehow the inner structure of my project got messed up, that the relative path in "from main.path1.path2 import ..." wasn't valid anymore. Either it worked like "from path1.path2 import..." or (what i did) I created a project and included again the folder structure, but in the way that it works.
How do I multiply each element in an array with a large number without getting OverflowError: Python int too large to convert to C long? Question: I'm writing a program where I want to multiply each number in an array (from numpy) with a big number (`1.692287392646066e+41`) and I do it like this: x = array([ 16, 18, 19, 15, 27, 26, 13, 34, 38, 36, 43, 42, 48, 50, 55, 57, 70, 67, 65, 85, 99, 94, 90, 112, 126, 130, 142, 120]) weight = 1.692287392646066e+41 x[:] = [i*weight for i in x] But then I recieve the error "OverflowError: Python int too large to convert to C long". The strange thing is that multiplying the numbers outside the for loop seems to work: In [1]: x[0]*weight Out[1]: 2.7076598282337055e+42 My question is then, is there any way for me to do this inside a for loop, since I don't know beforehand how long my array is? (I know it has 1 row.) Answer: It makes no sense to make the multiplication in `python` and not in `numpy`. Not only is `numpy` faster, but it also works better. What you are trying to do creates a `python list`, which it then tries to copy into the `numpy array` element wise. Instead just use x = x * weight and you're fine. EOL doubted that this works, so here's what I just did on my computer: $ python Python 2.7.3 (default, Dec 18 2014, 19:03:52) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from numpy import array >>> x = array([ 16, 18, 19, 15, 27, 26, 13, 34, 38, 36, 43, 42, 48, ... 50, 55, 57, 70, 67, 65, 85, 99, 94, 90, 112, 126, 130, ... 142, 120]) >>> weight = 1.692287392646066e+41 >>> x = x * weight >>> x array([ 2.70765983e+42, 3.04611731e+42, 3.21534605e+42, 2.53843109e+42, 4.56917596e+42, 4.39994722e+42, 2.19997361e+42, 5.75377713e+42, 6.43069209e+42, 6.09223461e+42, 7.27683579e+42, 7.10760705e+42, 8.12297948e+42, 8.46143696e+42, 9.30758066e+42, 9.64603814e+42, 1.18460117e+43, 1.13383255e+43, 1.09998681e+43, 1.43844428e+43, 1.67536452e+43, 1.59075015e+43, 1.52305865e+43, 1.89536188e+43, 2.13228211e+43, 2.19997361e+43, 2.40304810e+43, 2.03074487e+43]) >>>
How to layout controlArea and mainArea horizontally Question: I am trying to create a new widget for Orange 3. I see that it provides some default areas (controlArea and mainArea) to which I can add my components. As far as I can tell, widget.py places both of these inside 'self.leftWidgetPart' which uses vertical orientation for its layout. From widget.py: self.leftWidgetPart = gui.widgetBox(self.topWidgetPart, orientation="vertical", margin=0) if self.want_main_area: ... self.mainArea = gui.widgetBox(self.topWidgetPart, orientation="vertical", sizePolicy=QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding), margin=0) I would like to layout controlArea and mainArea horizontally instead. I believe this is possible because the OWBoxPlot widget appears to do it, but I can't work out what/where the relevant code snippet is (I guess my Python is weak). Any help appreciated, David Answer: In PyQt in general, you can change the orientation by removing the existing layout and replacing it with another (hopefully before you populate it). For `self.controlArea` in Orange, you can do something like this. from PyQt4.QtGui import QHBoxLayout import sip sip.delete(self.controlArea.layout()) self.controlArea.setLayout(QHBoxLayout())
Error loading Mysqldb module in Python Django Question: I am currently working on Ubuntu 14.10/Python/Django/MySQL and encountering the following error when I try to run: $python manage.py makemigrations polls or $python manage.py migrate polls I have also tried syncdb The error is: > (Aaronpythonenv)aaron@aaron-N550JK:~/mysite$ python manage.py makemigrations > polls Traceback (most recent call last): File "manage.py", line 10, in > execute_from_command_line(sys.argv) File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/core/management/**init**.py", line 338, > in execute_from_command_line utility.execute() File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/core/management/**init**.py", line 312, > in execute django.setup() File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/**init**.py", line 18, in setup > apps.populate(settings.INSTALLED_APPS) File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/apps/registry.py", line 108, in > populate app_config.import_models(all_models) File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/apps/config.py", line 198, in > import_models self.models_module = import_module(models_module_name) File > "/usr/lib/python2.7/importlib/**init**.py", line 37, in import_module > **import**(name) File "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/contrib/auth/models.py", line 41, in > class Permission(models.Model): File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/db/models/base.py", line 139, in > **new** new_class.add_to_class('_meta', Options(meta, **kwargs)) File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/db/models/base.py", line 324, in > add_to_class value.contribute_to_class(cls, name) File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/db/models/options.py", line 250, in > contribute_to_class self.db_table = truncate_name(self.db_table, > connection.ops.max_name_length()) File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/db/**init**.py", line 36, in > **getattr** return getattr(connections[DEFAULT_DB_ALIAS], item) File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/db/utils.py", line 240, in **getitem** > backend = load_backend(db['ENGINE']) File > "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/db/utils.py", line 111, in load_backend > return import_module('%s.base' % backend_name) File > "/usr/lib/python2.7/importlib/**init**.py", line 37, in import_module > **import**(name) File "/home/aaron/Aaronpythonenv/local/lib/python2.7/site- > packages/Django-1.8-py2.7.egg/django/db/backends/mysql/base.py", line 27, in > raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) > django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: > No module named MySQLdb I have used PIP to install mysql-python to my environment which I recieved another error. I then used sudo apt-get command to install correct the error PIP brought up. massive thank you in advance please let me know if I need to add anything else. Answer: I faced somewhat similar problem. Try these steps: 1). Upgrade `pip` to the latest version. sudo pip install pip --upgrade 2). Build the dependencies for python-mysqldb libraries: sudo apt-get build-dep python-mysqldb 3). Install the Python MySQL libraries: sudo pip install MySQL-python
Calculating all possible combinations using a list of random numbers and ALL simple math operators to reach a given target Question: I am writing a simple Python script that generates 6 numbers at random (from 1 to 100) and a larger number (from 100 to 1000). My goals for this script are to: 1. Calculate all of the possible combinations using at least 2 numbers and any of the simple math operations (adding, subtracting, multiplying and dividing) 2. Output all of the combinations whose total is within 10 above or below the larger number as 'matches' The list of numbers need not be exhausted, but repeating numbers isn't accepted. Plus I don't care too much if the code is efficient or not (if anyone decides to post any - I can post mine so far if anyone needs it - preferably post it in Python); as long as it works, I'm happy to optimize it. I have attempted this myself, only to fail as the program quickly ended with a RunTime Error. I also tried putting in a counter to stop the loop after x passes (where x is a small number such as 50), but that just makes matters worse as it keeps on going infinitely. I've also done some research, and I found that this ([Computing target number from numbers in a set](http://stackoverflow.com/questions/2392379/computing- target-number-from-numbers-in-a-set) \- the second to last answer) is the closest I found to meet my requirements but hasn't got quite there yet. Thanks for the help! :-) EDIT: Here is my code: import random, time, operator i = 0 numlist = [] while i != 6: number = random.randint(1, 100) numlist.append(number) i += 1 largenumber = random.randint(100, 1000) print(numlist) print(largenumber) def operationTesting(): a, c, m, total = 0, 0, 0, 0 totalnums = 0 operators = ['+', '-', '*', '/'] while total != largenumber: for a in numlist[m]: for c in numlist[m+1]: print(a) print(c) if a == c: operationTesting() else: b = random.choice(operators) if b == '+': summednums = operator.add(int(a), int(c)) print(summednums) totalnums = totalnums + summednums elif b == '-': summednums = operator.sub(int(a), int(c)) print(summednums) totalnums = totalnums + summednums elif b == '*': summednums = operator.mul(int(a), int(c)) print(summednums) totalnums = totalnums + summednums elif b == '/': summednums = operator.floordiv(int(a), int(c)) print(summednums) totalnums = totalnums + summednums print(totalnums) SystemExit(None) operationTesting() Answer: A very neat way to do it is using [Reverse Polish Notation or Postfix](http://en.wikipedia.org/wiki/Reverse_Polish_notation) notation. This notation avoids the need for brackets that you would probably want if you were doing it using conventional arithmetic with operator precedence etc. You can do this with brute force if you are not too bothered about time efficiency. You need to consider what you want to do with division too - if two numbers do not divide exactly, do you want to return the result as 'invalid' in some way (I guess so), or really return a floored division? Note the latter might give you some invalid answers... Consider the test case of `numlist = [1,2,3,4,5,6]`. In RPN, we could do something like this RPN Equivalent to 123456+++++ (1+(2+(3+(4+(5+6))))) 123456++++- (1-(2+(3+(4+(5+6))))) 123456+++-+ (1+(2-(3+(4+(5+6))))) ... 12345+6+-++ (1+(2+(3-((4+5)+6)))) 12345+6-+++ (1+(2+(3+((4+5)-6)))) ... And so on. You can probably see that with sufficient combinations, you can get any combinations of numbers, operators and brackets. The brackets are important - to take only 3 numbers obviously 1+2*6 is normally interpreted (1 + (2*6)) == 13 and is quite different to ((1+2)*6) == 18 In RPN, these would be `126*+` and `12+6*` respectively. So, you've got to generate all your combinations in RPN, then develop an RPN calculator to evaluate them. Unfortunately, there are quite a lot of permutations with 6 numbers (or any subset thereof). First you can have the numbers in any order, thats `6! = 720` combinations. You will always need `n-1 == 5` operators and they can be any one of the 4 operators. So that's `4**5 == 1024` permutations. Finally those 5 operators can be in any one of 5 positions (after first pair of numbers, after first 3, after 4 and so on). You can have maximum 1 operator in the first position, two in the second and so on. That's `5! == 120` permutations. So in total you have `720*1024*120 == 88473600` permutations. Thats roughly `9 * 10**7` Not beyond the realms of computation at all, but it might take 5 minutes or so to generate them all on a fairly quick computer. You could significantly improve on this by "chopping" the search tree 1. Loads of the RPN combinations will be arithmetically identical (e.g. `123456+++++ == 12345+6++++ == 1234+5+6+++` etc) - you could use some prior knowledge to improve generate_RPN_combinations so it didn't generate them 2. identifying intermediate results that show certain combinations could never satisfy your criterion and not exploring any further combinations down that road. You then have to send each string to the RPN calculator. These are fairly easy to code and a typical programming exercise - you push values onto a stack and when you come to operators, pop the top two members from the stack, apply the operator and push the result onto the stack. If you don't want to implement that - google `minimal python rpn calculator` and there are resources there to help you. Note, you say you don't have to use all 6 numbers. Rather than implementing that separately, I would suggest checking any intermediate results when evaluating the combinations for all 6 numbers, if they satisfy the criterion, keep them too.
Firefox sees element where PhantomJS does not when using Selenium-Webdriver Question: I have been looking around for quite a long time now to find a solution to my problem, hope someone here can think of something that could help. I have a working selenium script (in Python) working with the Firefox driver to connect on a website. When using PhantomJS as driver, it doesn't work anymore. The form is generated by javascript and is on a https website. Here is the code of the user input : <script language="JavaScript1.2"> document.writeln("<input class=\"textform\" type=\"text\" id=\"user\" name=\"user\" size=\"" + size + "\" tabindex=1 onFocus=\"hadFocus(true)\">"); </script> Here is the part of the script looking for it : (working on firefox but not PhantomJS) from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time driver = webdriver.Firefox() driver.get([MY URL]) print driver.page_source driver.find_element_by_id("user").clear() driver.find_element_by_id("user").send_keys([MY USER ID]) driver.find_element_by_id("pass").clear() driver.find_element_by_id("pass").send_keys([MY PASS]) driver.find_element_by_name("login_btn").click() html_source = driver.page_source print html_source driver.close() And here is the error I get : selenium.common.exceptions.NoSuchElementException If I print the `page_source` just after reaching the page, Firefox shows the right source code, where PhantomJS only has : `<html><head></head><body></body></html>` Do you think of anything that could be the cause of this ? Answer: I have solved my problem thanks to Artjom B. answer : Just change in the code : driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true']) It was due to the ssl certificate I guess.
Soundcloud python OAuth error Question: This should be a fairly simple Python app which uses OAuth to authenticate itself with the soundclodu API. It follows very closely the code for the official library: <https://github.com/soundcloud/soundcloud-python> When I load my app, I get sent to the soundcloud login page, which then re- directs me to /user with the code query string. However, it fails at the part where I attempt to obtain the access token,etc... This is the error I get: File "/Users/asselinpaul/Dropbox/UPENN/SPRING15/CIS192/final_project/server.py", line 19, in user code = request.args.get('code')) TypeError: 'Resource' object is not iterable I'm pretty sure this just means that client.exchange_token is returning a 401 error (this is what happens when I try to print client.exchange_token(code = request.args.get('code')). Code: import soundcloud from flask import Flask, redirect, request app = Flask(__name__) client = soundcloud.Client( client_id="*****************************", client_secret="*****************************", redirect_uri='http://127.0.0.1:5000/user' ) @app.route('/') def hello_world(): return redirect(client.authorize_url()) @app.route('/user') def user(): access_token, expires, scope, refresh_token = client.exchange_token( code = request.args.get('code')) return ("Hi There, %s" % client.get('/me').username) if __name__ == '__main__': app.run(debug=True) Answer: I have a similar application (exactly the same, basically) and when I run it I get an error that says: AttributeError: 'module' object has no attribute 'args' As far as I can tell, because request.py in the soundcloud module uses urllib this is probably an issue with python 2.x versus python 3.x. I am using python 3 which I don't think can use urllib. I'd love to have a better answer or a real solution, but this is just what I've gathered.
Iterating two files at same time, and compare words with strings PYTHON Question: I'm trying to print whenever a word appears on a string, but actually it doesn't print anything.My text files are: words={'apple', 'banana', 'pie'} strings={'Hello World!', 'I love pie', 'Ate an apple'} `with open("words.txt") as words_file: with open("strings.txt") as strings_file: all_strings = list(map(str.strip,strings_file)) for a_string in all_strings: for word in words_file: if word in a_string: print a_string` and the output would be like Ate an apple I love pie Answer: from itertools import izip with open("file1.txt") as f1: with open("file2.txt") as f2: for f1_line,f2_line in izip(f1,f2): #this will return the same lines from both files do_something(f1_line,f2_line) the reason you saw the same thing over and over was that you for line2 in file2: print line1.split() # line 1 will not change until you go through every line in file2 [edit] as mentioned in the comments if you are using python2.7+ you can combine the file opening into one line with open("file1.txt") as f1, open("file2.txt") as f2: for f1_line,f2_line in izip(f1,f2): #this will return the same lines from both files do_something(f1_line,f2_line) the code below may do what you are hoping for ... from itertools import izip with open("words.txt") as words_file: with open("strings.txt") as strings_file: all_strings = list(map(str.strip,strings_file)) for word in words_file: for a_string in all_strings: if word in a_string: print a_string
Python 3: Multiprocessing API calls with exit condition Question: I'm trying to write an application which works through a list of database entries, making an API call with those, return the value and if one value of the APIs JSON response is `True` for 5 calls, I want to have the list of those 5 calls. As the database entries are a couple of thousand entries, I want to realise this with `multiprocessing`. But I'm a beginner with parallelisation and it seems I can't get the grasp of how it works and how to set the exit condition. Here's what I got: from multiprocessing.dummy import Pool import requests def get_api_response(apikey, result, subscription_id): r = requests.get("https://api.example.com/" + subscription_id) if r.json()['subscribed'] == True: result.append(r.json()) return result def pass_args(args): foo = get_api_response(*args) if foo: return foo def check_response_amount(result): if len(result) >= 5: pool.terminate() # One entry looks like that: {"id": 1, "name": "smith", "subscription_id": 123} db_entries = get_db_entries() apikey = 'abcd1234' result = [] request_tuples = [(apikey, result, entry['subscription_id']) for entry in db_entries] pool = Pool(5) pool_result = pool.map_async(pass_args, request_tuples, callback=check_response_amount) pool_result.wait() pool.close() pool.join() The application checks every database entry and returns every api response which has `subscribed == True` without even running through the callback. I tried applying the answer from another question ([Python Multiprocessing help exit on condition](http://stackoverflow.com/questions/21490137/python- multiprocessing-help-exit-on-condition)), but couldn't get it to work. Can somebody help me? Answer: When you use `map_async`, the callback won't be executed until every work item in the iterable has completed. If you want the callback to execute for every item in `request_tuples`, rather than only after all of them are done, you need to use `apply_async` inside a for loop instead: results = [] for item in request_tuples: results.append(pool.apply_async(get_api_response, args=item, callback=check_response_amount)) for result in results: result.wait() Additionally, calling `pool.terminate` isn't going to work the way you want; the items you've already submitted to the pool are going to hang forever once you call it, which will make your script hang, since you're waiting on them to finish before exiting. You can work around this by just waiting on the pool to join, rather than actually waiting on any individual task to finish. import time from multiprocessing.dummy import Pool from multiprocessing.pool import TERMINATE def get_api_response(apikey, result, subscription_id): url = ("https://api.example.com/" + str(subscription_id)) time.sleep(2) result.append(url) return result def pass_args(args): foo = get_api_response(*args) if foo: return foo def check_response_amount(result): if result and len(result) >= 5: print("DONE %s" % result) pool.terminate() def get_db_entries(): return [{'subscription_id' : i} for i in range(100)] # One entry looks like that: {"id": 1, "name": "smith", "subscription_id": 123} db_entries = get_db_entries() apikey = 'abcd1234' result = [] request_tuples = [(apikey, result, entry['subscription_id']) for entry in db_entries] pool = Pool(2) results = [] for item in request_tuples: results.append(pool.apply_async(get_api_response, item, callback=check_response_amount)) pool.close() pool.join() print("done") Output: IN HERE IN HERE IN HERE IN HERE IN HERE ... (a bunch more of this)... IN HERE IN HERE DONE ['https://api.example.com/1', 'https://api.example.com/0', 'https://api.example.com/2', 'https://api.example.com/3', 'https://api.example.com/4', 'https://api.example.com/5'] done Note that the `result` list can end up being a little bigger than you want, since the `terminate` call won't actually stop in-progress tasks.
ReCreating threads in python Question: I'm using the following template to recreate threads that I need to run into infinity. I want to know if this template is scalable in terms of memory. Are threaded destroyed properly? import threading import time class aLazyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): time.sleep(10) print "I don not want to work :(" class aWorkerThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): time.sleep(1) print "I want to work!!!!!!!" threadA = aLazyThread() threadA.start() threadB = aWorkerThread() threadB.start() while True: if not (threadA.isAlive()): threadA = aLazyThread() threadA.start() if not (threadB.isAlive()): threadB = aWorkerThread() threadB.start() The thing that bother me is the following picture taking in eclipse which show debug info, and It seems that thread are stacking it. ![Thread counts](http://i.stack.imgur.com/0c6eH.png) Answer: 1) I see nothing wrong with the image. There's the main thread and the 2 threads that you created (according to the code 3 threads are supposed to be running at any time). 2) Like any other python objects, threads are garbage collected when they're not used; e.g. in your main while cycle, when you instantiate the class (let's say aLazyThread), the old threadA value is destroyed (maybe not exactly at that point, but shortly after). 3) The main while cycle, could also use a sleep - e.g. time.sleep(1) - , otherwise it will consume the processor, uselessly checking if the other threads are running.
Django cannot find contents of static/ Question: I'm trying to deploy an application to Heroku, but it cannot find my JS/CSS files. Here's my settings.py # settings.py """ Django settings for the MyApp project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = SUPER SECRET # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'rest_framework', 'compressor', 'authentication', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'MyApp.urls' WSGI_APPLICATION = 'MyApp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases import dj_database_url DATABASES = { 'default': dj_database_url.config( default='sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') ) } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'dist/static'), os.path.join(BASE_DIR, 'static'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) COMPRESS_ENABLED = True TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ) } # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] AUTH_USER_MODEL = 'authentication.Account' if not DEBUG: # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES['default'] = dj_database_url.config() # Enable Connection Pooling DATABASES['default']['ENGINE'] = 'django_postgrespool' # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Here's the file containing CSS that I want to serve: # /static/templates/stylesheets.html {% load compress %} {% load static %} {% compress css %} <link rel="stylesheet" type="text/css" href="{% static "bower_components/bootstrap/dist/css/bootstrap.css" %}" /> <link rel="stylesheet" type="text/css" href="{% static "bower_components/bootstrap-material-design/dist/css/material.css" %}" /> <link rel="stylesheet" type="text/css" href="{% static "bower_components/bootstrap-material-design/dist/css/ripples.min.css" %}" /> <link rel="stylesheet" type="text/css" href="{% static "bower_components/ngDialog/css/ngDialog.css" %}" /> <link rel="stylesheet" type="text/css" href="{% static "bower_components/ngDialog/css/ngDialog-theme-default.css" %}" /> <link rel="stylesheet" type="text/css" href="{% static "lib/snackbarjs/snackbar.min.css" %}" /> <link rel="stylesheet" type="text/css" href="{% static "stylesheets/styles.css" %}" /> {% endcompress %} Is there something super wrong with my `settings.py`? `/static/` exists in the root of my directory and does contain all of the files in the HTML file. If more information is needed, please let me know. Answer: Django won't serve static files when `debug` is `False`, because the view is inefficient and potentially insecure, therefore you have to config your webserver. See "Deploying static files" in Django manual.
How can I use python xlib to generate a single keypress? Question: I want to make a very simple python 3 script that will generate a single keypress (F15). I don't want to use a bunch of libraries to do this as I only need one key to be pressed and don't need support for the whole keyboard. I know I need to use KeyPress and KeyRelease in order to generate a keyboard event. I'm just not sure where exactly to start and the documentation is a little confusing. <http://tronche.com/gui/x/xlib/events/keyboard-pointer/keyboard-pointer.html> <http://python-xlib.sourceforge.net/?page=documentation> Answer: I'll use [`ctypes`](https://docs.python.org/2/library/ctypes.html) to show you how it could work, but porting it to [`python-xlib`](http://python- xlib.sourceforge.net/) should be straightforward. So lets start with loading the library: import ctypes X11 = ctypes.CDLL("libX11.so") and defining the structures needed: class Display(ctypes.Structure): """ opaque struct """ class XKeyEvent(ctypes.Structure): _fields_ = [ ('type', ctypes.c_int), ('serial', ctypes.c_ulong), ('send_event', ctypes.c_int), ('display', ctypes.POINTER(Display)), ('window', ctypes.c_ulong), ('root', ctypes.c_ulong), ('subwindow', ctypes.c_ulong), ('time', ctypes.c_ulong), ('x', ctypes.c_int), ('y', ctypes.c_int), ('x_root', ctypes.c_int), ('y_root', ctypes.c_int), ('state', ctypes.c_uint), ('keycode', ctypes.c_uint), ('same_screen', ctypes.c_int), ] class XEvent(ctypes.Union): _fields_ = [ ('type', ctypes.c_int), ('xkey', XKeyEvent), ('pad', ctypes.c_long*24), ] X11.XOpenDisplay.restype = ctypes.POINTER(Display) Now we just need to send the event to the root window: display = X11.XOpenDisplay(None) key = XEvent(type=2).xkey #KeyPress key.keycode = X11.XKeysymToKeycode(display, 0xffcc) #F15 key.window = key.root = X11.XDefaultRootWindow(display) X11.XSendEvent(display, key.window, True, 1, ctypes.byref(key)) X11.XCloseDisplay(display) This minimal example worked well for me (just using `F2` instead). The same can be done to send a `KeyRelease` event. If a special window is to be targeted, `key.window` should be set appropriately. I'm not sure, if it's necessary to use the `XEvent` union, since it'd worked with the `XKeyEvent` all alone for me, but it's better to be safe.
extract contact information from html with python Question: Here is a sample html <div class="yui3-u-5-6" id="browse-products"> <div id="kazbah-contact"> <span class="contact-info-title">Contact 00Nothing:</span> <a href="mailto:[email protected]">[email protected]</a> | 800-410-2074 | C/O Score X Score &nbsp;8118-D Statesville Rd , Charlotte, NC 28269 </div> <div class="clearfix"></div> I want to extract the contact information here, email, phone, and address. How should I do that with python? Thanks Answer: I use this code to extract information # _*_ coding:utf-8 _*_ import urllib2 import urllib import re from bs4 import BeautifulSoup import sys reload(sys) sys.setdefaultencoding('utf-8') def grabHref(url,localfile): html = urllib2.urlopen(url).read() html = unicode(html,'gb2312','ignore').encode('utf-8','ignore') soup = BeautifulSoup(html) myfile = open(localfile,'wb') for link in soup.select("div > a[href^=http://www.karmaloop.com/kazbah/browse]"): for item in BeautifulSoup(urllib2.urlopen(link['href']).read()).select("div > a[href^=mailto]"): contactInfo = item.get_text() print link['href'] print contactInfo myfile.write(link['href']) myfile.write('\r\n') myfile.write(contactInfo) myfile.write('\r\n') myfile.close() def main(): url = "http://www.karmaloop.com/brands" localfile = 'Contact.txt' grabHref(url,localfile) if __name__=="__main__": main() But I still can only get email address here, how can I get phone number and address? Thanks
How to use Pygments in Pelican with Markdown? Question: TLDR: I am trying to do CSS line numbering in pelican, while writing in markdown. Pygments is used indirectly and you can't pass options to it, so I can't separate the lines and there is no CSS selector for "new line". Using Markdown in Pelican, I can generate code blocks using the CodeHilite extension. Pelican doesn't support using pygments directly if you are using Markdown...only RST(and ... no to converting everything to RST). So, what I have tried: MD_EXTENSIONS = [ 'codehilite(css_class=highlight,linenums=False,guess_lang=True,use_pygments=True)', 'extra'] And: :::python <div class="line">import __main__ as main</div> And: PYGMENTS_RST_OPTIONS = {'classprefix': 'pgcss', 'linenos': 'table'} Can I get line numbers to show up? Yes. Can I get them to continue to the next code block? No. And that is why I want to use CSS line numbering...its way easier to control when the numbering starts and stops. Any help would be greatly appreciated, I've been messing with this for a few hours. Answer: The only way I'm aware of is to fork the CodeHilite Extension (and I'm the developer). First you will need to make a copy of the existing extension (this [file](https://github.com/waylan/Python- Markdown/blob/master/markdown/extensions/codehilite.py)), make changes to the code necessary to effect your desired result, and save the file to your PYTHONPATH (probably in the "sitepackages" directory, the exact location of which depends on which system you are on and how Python was installed). Note that you will want to create a unique name for your file so as not to conflict with any other Python packages. Once you have done that, you need to tell Pelican about it. As Pelican's config file is just Python, import your new extension (use the name of your file without the file extension: `yourmodule.py` => `yourmodule`) and include it in the list of extensions. from yourmodule import CodeHiliteExtension MD_EXTENSIONS = [ CodeHiliteExtension(css_class='highlight', linenums=False), 'extra'] Note that the call to `CodeHiliteExtension` is not a string but actually calling the class and passing in the appropriate arguments, which you can adjust as appropriate. And that should be it. If you would like to set up a easier way to deploy your extension (or distribute it for others to use), you might want to consider creating a `setup.py` file, which is beyond the scope of this question. See this [tutorial](https://github.com/waylan/Python- Markdown/wiki/Tutorial:-Writing-Extensions-for-Python-Markdown) for help specific to Markdown extensions. If you would like specific help with the changes you need to make to the code within the extension, that depends on what you want to accomplish. To get started, the arguments are passing to Pygments on line 117. The simplest approach would be to hardcode your desired options there. * * * Be ware that if you are trying to replicate the behavior in reStructuredText, you will likely be disappointed. Docutils wraps Pygments with some of its own processing. In fact, a few of the options never get passed to Pygments but are handled by the reStructeredText parser itself. If I recall correctly, CSS line numbering is one such feature. In fact, Pygments does not offer that as an option. That being the case, you would need to modify your fork of the CodeHilite Extension by having Pygments return non-numbered code, then applying the necessary hooks yourself before the extension returns the highlighted code block. To do so, you would likely need to split on line breaks and then loop through the lines wrapping each line appropriately. Finally, join the newly wrapped lines and return. * * * I suspect the following (untested) changes will get you started: diff --git a/markdown/extensions/codehilite.py b/markdown/extensions/codehilite.py index 0657c37..fbd127d 100644 --- a/markdown/extensions/codehilite.py +++ b/markdown/extensions/codehilite.py @@ -115,12 +115,18 @@ class CodeHilite(object): except ValueError: lexer = get_lexer_by_name('text') formatter = get_formatter_by_name('html', - linenos=self.linenums, + linenos=self.linenums if self.linenumes != 'css' else False, cssclass=self.css_class, style=self.style, noclasses=self.noclasses, hl_lines=self.hl_lines) - return highlight(self.src, lexer, formatter) + result = highlight(self.src, lexer, formatter) + if self.linenums == 'css': + lines = result.split('\n') + for i, line in enumerate(lines): + lines[i] = '<div class="line">%s</div>' % line + result = '\n'.join(lines) + return result else: # just escape and build markup usable by JS highlighting libs txt = self.src.replace('&', '&amp;') * * * You may have better success in attaining what you want by disabling Pygments and using a JavaScript library to do the highlighting. That depends on which JavaScript Library you choose and what features it has.
Conditionally replacing items in nested list based on values in dictionary Question: Right now I have this nested list and dictionary: phrases = [['Lionhearted', 'Baby Preach'], ['Lionhearted Baby', 'Preach'], ['Lionhearted', 'Baby', 'Preach']] artist_info = {u'Baby': u'Baby by Justin Bieber', u'Lionhearted': u'Lionhearted by Porter Robinson', u'Preach': u'Preach by Drake', u'Baby Preach': u:'Baby Preach by some pop singer'} Basically, what I would like to do is try to replace the values in phrases with the values from artist_info if there is a match, other wise I would like to omit that particular nested list. So since there is a dictionary entry for `'Lionhearted'`, `'Baby'`, 'baby preach' and `'Preach'`, the output would read something like this: phrases2 = [['Lionhearted by Porter Robinson','Baby Preach by some pop singer'] ['Lionhearted by Porter Robinson', 'Baby by Justin Bieber', 'Preach by Drake']] Is there a way to do this? I've been at this for hours. It's important that the three phrases result in the order of "Lionhearted Baby Preach". I'm a bit of a Python noob, and I haven't been able to find a comparable example. Answer: Is this what you are looking for? From your example it looks like you want to omit the sublist within `phrases` if any item of that sublist is not present in the dictionary `artist_info`. The code below does that before doing the replacements you mentioned. phrases = [['Lionhearted', 'Baby Preach'], ['Lionhearted Baby', 'Preach'], ['Lionhearted', 'Baby', 'Preach']] artist_info = {u'Baby': u'Baby by Justin Bieber', u'Lionhearted': u'Lionhearted by Porter Robinson', u'Preach': u'Preach by Drake', u'Baby Preach': u'Baby Preach by some pop singer'} lst = filter(lambda x: all(y in artist_info for y in x), phrases) phrases2 = map(lambda x: [artist_info[y] for y in x], lst) print phrases2
UnboundLocalError: local variable referenced before assignment in python closure Question: I implemented two simple closures in Python. To me, they looks the same, but one works and the other doesn't. The working one is: def makeInc(x, y): def inc(): return y + x return inc inc5 = makeInc(5, 10) inc10 = makeInc(10, 5) inc5 () # returns 15 inc10() # returns 15 But the second one doesn't work: import os def linker(dest, filename): print filename def link(): if os.path.isfile(filename): # line 17 filename = os.path.join(os.getcwd(), filename) dest = os.path.join(dest, filename) y = rawinput('[y]/n: ln -sf %s %s' % (dest, filename)) if y == 'n': return 1 else: return os.system('ln -sf %s %s' %(dest, filename)) else: return -1 return link l = linker('~', '.vimrc') l() # line 30 It faults at the first line of `link()` when executing `l()`: Traceback (most recent call last): File "test.py", line 30, in <module> l() File "test.py", line 17, in link if os.path.isfile(filename): UnboundLocalError: local variable 'filename' referenced before assignment They seem identical to me so I don't understand why the second one doesn't work. Any idea? Answer: You have overwritten the variable with `filename = os.path.join(os.getcwd(), filename)`, if you change the `filename =` to something other than `filename` you won't get a `local variable 'filename' referenced before assignment` error. Once you set `filename =` you are no longer referring to the parameter `filename` that is passed in you are referring to the local `filename` in the scope of the inner function which you try to use in the if **before** you have it defined. You will have the same problem with dest, if you change the two lines and the other variables to something like: filename_ = os.path.join(os.getcwd(), filename) dest_ = os.path.join(dest, filename) You will see the code runs fine as filename now refers to the parameter not to a local variable defined in your inner function. You will see the exact same behaviour if you try to reassign `x` in your first function and try to access `x` before you have defined it: def makeInc(x, y): def inc(): print y + x # will cause referenced before assignment error x = 5 # now x is local to the inner func, the x from the outer function is overridden return y + x return inc If you print the `__closure__` attribute you will see what happens: def makeInc(x, y): def inc(): return y + x return inc inc5 = makeInc(5, 10) inc10 = makeInc(10, 5) print(inc5.__closure__) (<cell at 0x7f180df67e50: int object at 0xef00f8>, <cell at 0x7f180df67fa0: int object at 0xef0080>) Now reassigning x: def makeInc(x, y): def inc(): print y + x x= 5 return y + x return inc inc5 = makeInc(5, 10) inc10 = makeInc(10, 5) print(inc5.__closure__) (<cell at 0x7fea11889fd8: int object at 0x291e080>,) After reassigning in the inner function, there is no longer a reference to `x`. So basically the fundamental difference between your two original functions is that in one you are reassigning the variable in the local scope and in the other you are not. As you can see from the code above if you do something similar in the first function the outcome is exactly the same. There is a nice tut [here](http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/scope_resolution_legb_rule.ipynb#section_1) on scopes LEGB etc..
Keeping progress of the letters guessed in hang man python Question: Graphics=[''' ------------ | |''',''' ------------ | | | O''',''' ------------ | | | O | / ''',''' ------------ | | | O | / |''',''' ------------ | | | O | / | | | ''',''' ------------ | | | O | / | | | | / | | ''',''' ------------ | | | O | / | | | | / | | | '''] import random class Hangman(): def Playing(self): listOfWords = ["example", "says", "python", "rocks"] again = True while again: guessWord = random.choice(listOfWords) board = "*" * len(guessWord) alreadySaid = set() mistakes = 7 print(" ".join(board)) guessed = False # These are the guesses I want to keep track of while not guessed and mistakes > 0: whatplayersaid = input("Guess a letter: ") if whatplayersaid in guessWord: alreadySaid.add(whatplayersaid) board = "".join([char if char in alreadySaid else "_" for char in guessWord]) if board == guessWord: guessed = True else: mistakes -= 1 print("Nope.", mistakes, "mistakes left.") print("Letters Guessed:",guessed) # This is where my mistake is. print(Graphics[6-mistakes]) print(" ".join(board)) again = (input("Again [y/n]: ").lower() == 'y') Hangman().Playing() > I want to keep progress of the guessed letters, and print them every guess. > How do I do that?, what I have now returns only the last incorrect guess Answer: What you need to do is not print the `print(Graph)` This prints the location of the Graph array. You need to print something like: print(Graph[7-mistakes])
Removal of duplicate lines from a text file using python Question: Earlier I wrote the code for extracting a specific string from multiple files and the result is stored in a separate file.Now this file has duplicate results which I need to remove . import glob import re import os.path path=r"H:\sample" file_array=glob.glob(os.path.join(path,'*.txt')) with open("aiq_hits.txt","w") as out_file; for input_filename in file_array: with open(input_filename) as in_file: for line in in_file: match=re.findall(r"""(?<=')[^']*\.aiq(?=')|(?<=")[^"]*\.aiq(?=")""") for item in match: out_file.write("%s\n" %item) out_file.close() This out_file has duplicate results which I need to remove and result should be the same file Answer: 1. **Load** input file. 2. **Read** input file by lines. The `readlines` will return a list of lines from the file content. 3. Create a new list. 4. **Iterate** every line from the `lines`. 5. **Strip** the white spaces from the `line`. 6. **Check** if the line is present in `new_lines`. 7. If not, then **append** the `line` in the `new_lines` list. 8. **Write** `new_lines` into the file. Demo: input_file = "input.txt" with open(input_file, "rb") as fp: lines = fp.readlines() new_lines = [] for line in lines: #- Strip white spaces line = line.strip() if line not in new_lines: new_lines.append(line) output_file = "output.txt" with open(output_file, "wb") as fp: fp.write("\n".join(new_lines))
Sending Multiple SMS Messages in Twilio Reply Question: I am writing software using the Twilio API, Flask, and Python to send and receive SMS messages. When I reply to a message, I also want to send out a message to a different phone number (thereby sending 2 messages in total, one to the original sender, and one to an entirely different individual). I reply to an SMS using: @app.route("/", methods=['GET', 'POST']) def reply(): # Send other text sendMessage(to_number, text) # Send response resp = twilio.twiml.Response() resp.sms(response) return str(resp) Where the `sendMessage` function is: from twilio.rest import TwilioRestClient def sendMessage(to_number, text): ACCOUNT_SID = "XXXXXXXXX" AUTH_TOKEN = "XXXXXXXX" twilioNumber = "XXXXXXXXX" client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) client.messages.create( to=to_number, from_=twilioNumber, body=text, ) But the `sendMessage` function does not actually send a text to the separate number (note the reply still works). Note also that the `sendMessage`function works fine when it is called outside of the reply function. How should I go about sending two different texts to two different numbers in response to a text from only one of those numbers? Answer: This worked for me to send the same message to multiple numbers: from twilio.rest import TwilioRestClient def sendMessage(text): ACCOUNT_SID = "ACXXXXXXXX" AUTH_TOKEN = "YYYYYYYYYY" twilioNumber = "+15551235554" client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) NUMBERS = { 'Foo':'+15551235555', 'Bar':'+15551235556' } for name, number in NUMBERS.items(): message = client.messages.create( to=number, from_=twilioNumber, body=text) print message.sid Maybe you can find a way to adapt this to your specific needs. Note that Twilio limits your outbound SMS to 1 SMS message segment per-second, per- number. [More info on Rate-Limits](https://www.twilio.com/help/faq/twilio- basics/what-are-the-limits-on-outbound-calls-and-sms-messages-per-second)
import list to excel Question: I want to import the python list to excel. My example code is: import win32com.client as win32 excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = 1 wb = excel.Workbooks.Add() ws = wb.Worksheets("Sheet1") list1 =("a","b","c","c","c","c","c","c","c","c") ws.Range("B1:B10").Value = list1 How I have to change the list1 type to use the code ws.Range("B1:B10").Value = list1? What kind of list can use in excel file? Answer: It looks like this [post](http://stackoverflow.com/questions/5014261/python- excel-writing-to-multiple-cells-takes-time) may do what you need by wrapping your range statement in a function like: def writeLinesToExcel(ws,lines): ws.Range("A1:"+chr(len(lines)+96).upper()+str(len(lines[0]))).Value=lines Then you can call `writeLineToExcel(ws,list1)`. You can also use things like [["a"],["b"]] apparently... Based on your question, I'm not sure this appears to be working for you. If your data is simple enough, you could just use a loop, def writeRowsToExcel(ws,col,rows): for i,l in enumerate(rows): ws.Cells(col,i)= l then call `writeRowsToExcel(ws, col, rows)`. Other [posts](http://stackoverflow.com/questions/21478946/writing-array-to-excel-in- python-with-win32com) suggest this will be slow and to use other libraries like `xlwt`.
why does this python regex return no match? Question: >>> match = re.search(r'\d', 'ca\d') >>> type(match) <type 'NoneType'> From my understanding 'r' means don't do any special processing with blackslashes and just return the raw string. Also, why do i get the output below: >>> match = re.search(r'\a', 'ca\a') >>> match.group() '\x07' Answer: Because your input string has no digit. `\d` means `capture a digit`. If you want to capture a literal `\d`, you should use `\\d` pattern. See [example here](https://regex101.com/r/aK4fA4/1). This program import re p = re.compile(ur'\\d') test_str = u"ca\d" print re.search(p, test_str).group(0) Will output `\d`. As for `r''`, please check this [re documentation](https://docs.python.org/2/library/re.html): > The solution is to use Python’s raw string notation for regular expression > patterns; backslashes are not handled in any special way in a string literal > prefixed with 'r'. So r"\n" is a two-character string containing '\' and > 'n', while "\n" is a one-character string containing a newline. Usually > patterns will be expressed in Python code using this raw string notation. It does not mean it does not process slashes anyhow, this just lets you use a single slash instead of a doubled one. The slash is meaningful before `d` in a regular expression. And as for `\a`, there is no such a regex metacharacter, so `\` is treated as a literal.
Hard time catching Environment Exception in Python Question: I have this simple code to setup a logfile at specific location: (Python 2.7.3) import os, errno try: CCustomLogger.setup_daemon_logger('TRexServer', "/var/log/trex/trex_daemon_server.log") except EnvironmentError, e: print "caught some exception...!" if e.errno == errno.EACCES: # catching permission denied error print "Launching user must have sudo privileges in order to run T-Rex daemon." exit(1) However, when I try to run it, I still get the error and can't catch it: Traceback (most recent call last): File "trex_daemon_server.py", line 50, in <module> handler = logging.FileHandler("/var/log/trex/trex_daemon_server.log") File "/usr/lib64/python2.7/logging/__init__.py", line 897, in __init__ StreamHandler.__init__(self, self._open()) File "/usr/lib64/python2.7/logging/__init__.py", line 916, in _open stream = open(self.baseFilename, self.mode) IOError: [Errno 13] Permission denied: '/var/log/trex/trex_daemon_server.log' What's weird here is that even the `some error` print in not printed. I Googled a little bit and found out that this may be caused by indentation error ([see here for example](http://stackoverflow.com/questions/4799974/continue-on-except-of-a- try-block-in-python)) but I think this isn't it... What else could be the problem? Thanks, Answer: The code appears to be raising `IOError`, not `EnvironmentError`.
Py2exe, Runtimeerror with tweepy Question: I wanted to use the python plugin for twitter called tweepy. in my main.py file I just imported tweepy import tweepy My setup-file looks like this: from distutils.core import setup import py2exe setup( windows=[{ "script": 'main.py', }], options={ "py2exe": { "includes": ["sip", "tweepy"] } } ) When i execute python setupy.py py2exe via command line I get this repeating codeblock until I get an RuntimeError: maximum recursion depth exceeded in comparison. File "C:\Python34\lib\site-packages\py2exe\hooks.py", line 291, in __getattr__ self.__finder.safe_import_hook(renamed, caller=self) File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 138, in safe_import_hook self.import_hook(name, caller, fromlist, level) File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 120, in import_hook module = self._gcd_import(name) File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 274, in _gcd_import return self._find_and_load(name) File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 298, in _find_and_load getattr(parent_module, name.rpartition('.')[2]) Does anyone knows a way to break out of this cycle? Answer: [There seems to be a bug](http://sourceforge.net/p/py2exe/mailman/message/33804567/) in the `0.9.2.2` version of py2exe where the module `six.moves.urllib.parse` gets into an infinite recursion loop until it reaches the maximum depth. One way to go around it, if you don't really need the module, is to exclude the module in your `setup.py`: options={ "py2exe": { "includes": ["sip", "tweepy"], "excludes": ["six.moves.urllib.parse"] } }
PyQt : Manage two MainWindow Question: i'm trying to manage two MainWindow (MainWindow & AccessWindow) with PyQt for my RFID ACCESS CONTROL Project. I want to show the first MainWindow all time (Endless Loop). Then, i want to hide it and show the second MainWindow when the RFID Reader (who's working on "auto-reading mode") read an RFID Tag. so in the main python program i have a pseudo "do while" loop (while True: and break with a condition) to read on serial port the data provided by the reader. Then i check a DB.. It's not important. So the trigger event is "when the reader read something). I got some help from another forum and now i have this: # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui import sys, pyodbc, serial import os import time #Variables Code_Zone = "d" class MainWindow(QtGui.QWidget): def __init__(self, main): super(MainWindow, self).__init__() self.main = main self.grid = QtGui.QGridLayout(self) self.welcome = QtGui.QLabel("WELCOME", self) self.grid.addWidget(self.welcome, 2, 2, 1, 5) class AccessWindow(QtGui.QWidget): def __init__(self): super(AccessWindow, self).__init__() self.setMinimumSize(150, 50) self.grid = QtGui.QGridLayout(self) self.label = QtGui.QLabel(self) self.grid.addWidget(self.label, 1, 1, 1, 1) class Main(object): def __init__(self): self.accueil = MainWindow(self) self.accueil.show() self.access = AccessWindow() def wait(self): # RFID READER ENDLESS LOOP while 1: global EPC_Code ser = serial.Serial(port='COM6', baudrate=115200) a = ser.read(19).encode('hex') if (len(a)==38): EPC_Code = a[14:] print ('EPC is : ' + EPC_Code) break else: continue ser.close() self.on_event(EPC_Code) def on_event(self, data): def refresh(): self.toggle_widget(False) self.wait() # vérification des données EPC_Code = data sql_command = "[Get_Access_RFID] @Code_RFID = '"+EPC_Code+"', @Code_Zone = '"+Code_Zone+"'" # STORED PROCEDURE db_cursor.execute(sql_command) rows = db_cursor.fetchone() result= str(rows[0]) print ("result = " + str(result)) if result == "True": # si OK self.access.label.setText('ACCESS GRANTED') else: # si pas OK self.access.label.setText('ACCESS DENIED') self.toggle_widget(True) QtCore.QTimer.singleShot(2000, refresh) def toggle_widget(self, b): self.accueil.setVisible(not b) self.access.setVisible(b) if __name__=='__main__': cnxn = """DRIVER={SQL Server};SERVER=***;PORT=***;UID=***;PWD=***;DATABASE=***""" db_connection = pyodbc.connect(cnxn) db_cursor = db_connection.cursor() print ('Connected TO DB & READY') app = QtGui.QApplication(sys.argv) main = Main() main.wait() sys.exit(app.exec_()) and now my problem is that the text of the first window doesn't appear when i run the program but the text of the second window appear when i keep my badge near the RFID Reader. Answer: Instead of two `MainWindow`, create one. As content, create two classes which extend `QtGui.QWidget` called `MainView` and `AccessView`. Instead of replacing the window, just put the correct view into the window. That way, you can swap views without opening/closing windows. If you use a layout, then the window will resize to fit the view. The next problem is that you block the UI thread which means Qt can't handle events (like the "paint UI" event). To fix this, you must move the RFID handling code in a background thread. You can emit signals from this background thread to update the UI. Note: You must not call UI code from a thread!! Just emit signals. PyQt's main loop will see them and process them. Related: * <https://joplaete.wordpress.com/2010/07/21/threading-with-pyqt4/> * [Updating GUI elements in MultiThreaded PyQT](http://stackoverflow.com/questions/9957195/updating-gui-elements-in-multithreaded-pyqt), especially the second example using signals. The first example is broken (calling `addItem()` from a thread) is not allowed)
How can I fix this error with django-autocomplete-light - Importerror No Module Named Shortcuts? Question: So, for two days now I have been struggling to set up django-autocomplete- light to do the most basic autocompletes, but to no avail. I've ran into so many problems and so many errors that I cannot specify them here to solicit a clear solution. So, what I am attempting to do now is create a basic django application, from scratch and drop in the "basic" example from the django-autocomplete-light repository. Doing this to try to create a reproducible problem so I can get support. However, this too has been frustrating. I have ran into this error now... File "/Users/josh/.virtualenvs/testaclite/lib/python2.7/site-packages/django/__init__.py", line 21, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/josh/.virtualenvs/testaclite/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/Users/josh/.virtualenvs/testaclite/lib/python2.7/site-packages/autocomplete_light/apps.py", line 10, in ready autocomplete_light.autodiscover() File "/Users/josh/.virtualenvs/testaclite/lib/python2.7/site-packages/autocomplete_light/registry.py", line 290, in autodiscover autodiscover_modules('autocomplete_light_registry') File "/Users/josh/.virtualenvs/testaclite/lib/python2.7/site-packages/django/utils/module_loading.py", line 74, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/josh/Development/python/testaclite/aclite/basic/autocomplete_light_registry.py", line 1, in <module> import autocomplete_light.shortcuts as autocomplete_light ImportError: No module named shortcuts What can I do to resolve this? Answer: Really, credit for this answer should go to karthikr for pointing out to me the problem. To fix it, I installed django-autocomplete-light from a particular branch that had recently been updated. I used the following command to do so: pip install -e git+git://github.com/yourlabs/[email protected]#egg=autocomplete_light
Dynamodb2 Table.get_item() throws ValidationException "The number of conditions on the keys is invalid" Question: I am just doing a simple task in DynamoDB: 1. Create a Table, 2. Add an Item to it 3. Query the Table for that Item. Here's a script that I am using: from boto.dynamodb2.fields import HashKey, RangeKey, AllIndex, GlobalAllIndex from boto.dynamodb2.items import Item from boto.dynamodb2.layer1 import DynamoDBConnection from boto.dynamodb2.table import Table # Using DynamoDB Local conn = DynamoDBConnection(host='localhost', port=8000, is_secure=False) ## ----- Create a table ----- throughput = { 'write': 1, 'read': 1 } schema = [ HashKey('id'), RangeKey('rating') ] local_indexes = [ AllIndex('local_all_index_seats', parts=[ HashKey('id'), RangeKey('seats') ]) ] global_indexes = [ GlobalAllIndex('global_all_index_color', parts=[ HashKey('color'), RangeKey('rating') ]) ] new_table = Table.create('items', schema=schema, indexes=local_indexes, global_indexes=global_indexes, connection=conn, throughput=throughput) print 'Table created' ## -------- Table created --------- ## -------- Add an item -------- items_table = Table('items', connection=conn) # New reference to the table we created new_item_data = { "category": "Sofa", "rating": "4", "color": "beige", "seats": "6", "id": "first_id" } new_item = Item(items_table, new_item_data) new_item.save() print 'New item saved' ## -------- Item added -------- ## -------- Query Item -------- items_table = Table('items', connection=conn) # New reference to the table we created queried_item = items_table.get_item(id='first_id') print 'Query done. Category is: {}'.format(queried_item['Category']) ## -------- Querying Done -------- When I run this script, I get a `ValidationException`: (backend)aniket [~/PycharmProjects/website_backend] -> python reproduce.py ±[●●][master] Table created New item saved Traceback (most recent call last): File "reproduce.py", line 59, in <module> queried_item = items_table.get_item(id='first_id') File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/dynamodb2/table.py", line 705, in get_item consistent_read=consistent File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/dynamodb2/layer1.py", line 1099, in get_item body=json.dumps(params)) File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/dynamodb2/layer1.py", line 2842, in make_request retry_handler=self._retry_handler) File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/connection.py", line 954, in _mexe status = retry_handler(response, i, next_sleep) File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/dynamodb2/layer1.py", line 2882, in _retry_handler response.status, response.reason, data) boto.dynamodb2.exceptions.ValidationException: ValidationException: 400 Bad Request {u'Message': u'The number of conditions on the keys is invalid', u'__type': u'com.amazon.coral.validate#ValidationException'} I am pretty sure I am doing something wrong, but I can't figure out what. The DynamoDB Docs mention that it is possible to query using _only_ the HashKey, so what I am doing seems to be pretty normal. In case it helps, I also added debug logging, and here's the output: (backend)aniket [~/PycharmProjects/website_backend] -> python reproduce.py ±[●●][master] 2015-04-15 20:04:48,218 [DEBUG] (boto) Using access key found in shared credential file. 2015-04-15 20:04:48,218 [DEBUG] (boto) Using secret key found in shared credential file. 2015-04-15 20:04:48,219 [DEBUG] (boto) Method: POST 2015-04-15 20:04:48,219 [DEBUG] (boto) Path: / 2015-04-15 20:04:48,219 [DEBUG] (boto) Data: {"GlobalSecondaryIndexes": [{"KeySchema": [{"KeyType": "HASH", "AttributeName": "color"}, {"KeyType": "RANGE", "AttributeName": "rating"}], "IndexName": "global_all_index_color", "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"WriteCapacityUnits": 5, "ReadCapacityUnits": 5}}], "AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}, {"AttributeName": "rating", "AttributeType": "S"}, {"AttributeName": "seats", "AttributeType": "S"}, {"AttributeName": "color", "AttributeType": "S"}], "LocalSecondaryIndexes": [{"KeySchema": [{"KeyType": "HASH", "AttributeName": "id"}, {"KeyType": "RANGE", "AttributeName": "seats"}], "IndexName": "local_all_index_seats", "Projection": {"ProjectionType": "ALL"}}], "ProvisionedThroughput": {"WriteCapacityUnits": 1, "ReadCapacityUnits": 1}, "TableName": "items", "KeySchema": [{"KeyType": "HASH", "AttributeName": "id"}, {"KeyType": "RANGE", "AttributeName": "rating"}]} 2015-04-15 20:04:48,219 [DEBUG] (boto) Headers: {'Host': 'localhost', 'Content-Type': 'application/x-amz-json-1.0', 'Content-Length': '942', 'X-Amz-Target': 'DynamoDB_20120810.CreateTable'} 2015-04-15 20:04:48,219 [DEBUG] (boto) Host: localhost 2015-04-15 20:04:48,219 [DEBUG] (boto) Port: 8000 2015-04-15 20:04:48,219 [DEBUG] (boto) Params: {} 2015-04-15 20:04:48,219 [DEBUG] (boto) establishing HTTP connection: kwargs={'port': 8000, 'timeout': 70} 2015-04-15 20:04:48,219 [DEBUG] (boto) Token: None 2015-04-15 20:04:48,219 [DEBUG] (boto) CanonicalRequest: POST / host:localhost x-amz-date:20150415T143448Z x-amz-target:DynamoDB_20120810.CreateTable host;x-amz-date;x-amz-target 4d4b471da224cff0353d444ba9f31ecbda7ac332b618c8db038940477cf5fbd9 2015-04-15 20:04:48,219 [DEBUG] (boto) StringToSign: AWS4-HMAC-SHA256 20150415T143448Z 20150415/localhost/localhost/aws4_request a54fd62c95217cf6fafe69876388ac3ae8ffd4b2d87e23f71a131741d3e64792 2015-04-15 20:04:48,219 [DEBUG] (boto) Signature: 51e3035fcfef8b31f8d6c0e22779ba4b17990d3f91f8dfda6b70e559ee5c384e 2015-04-15 20:04:48,220 [DEBUG] (boto) Final headers: {'Content-Length': '942', 'User-Agent': 'Boto/2.38.0 Python/2.7.6 Linux/3.16.0-30-generic', 'Host': 'localhost', 'X-Amz-Date': '20150415T143448Z', 'X-Amz-Target': 'DynamoDB_20120810.CreateTable', 'Content-Type': 'application/x-amz-json-1.0', 'Authorization': 'AWS4-HMAC-SHA256 Credential=AKIAJW2Q5MT375WFZIMA/20150415/localhost/localhost/aws4_request,SignedHeaders=host;x-amz-date;x-amz-target,Signature=51e3035fcfef8b31f8d6c0e22779ba4b17990d3f91f8dfda6b70e559ee5c384e'} 2015-04-15 20:04:49,004 [DEBUG] (boto) Response headers: [('x-amzn-requestid', 'e4cd23ec-ad5a-4f94-8d80-dd9f002b0f28'), ('content-length', '1160'), ('content-type', 'application/x-amz-json-1.0'), ('x-amz-crc32', '175075191'), ('server', 'Jetty(8.1.12.v20130726)')] 2015-04-15 20:04:49,004 [DEBUG] (boto) Saw HTTP status: 200 2015-04-15 20:04:49,004 [DEBUG] (boto) Validating crc32 checksum for body: {"TableDescription":{"AttributeDefinitions":[{"AttributeName":"id","AttributeType":"S"},{"AttributeName":"rating","AttributeType":"S"},{"AttributeName":"seats","AttributeType":"S"},{"AttributeName":"color","AttributeType":"S"}],"TableName":"items","KeySchema":[{"AttributeName":"id","KeyType":"HASH"},{"AttributeName":"rating","KeyType":"RANGE"}],"TableStatus":"ACTIVE","CreationDateTime":1429108488.651,"ProvisionedThroughput":{"LastIncreaseDateTime":0.000,"LastDecreaseDateTime":0.000,"NumberOfDecreasesToday":0,"ReadCapacityUnits":1,"WriteCapacityUnits":1},"TableSizeBytes":0,"ItemCount":0,"LocalSecondaryIndexes":[{"IndexName":"local_all_index_seats","KeySchema":[{"AttributeName":"id","KeyType":"HASH"},{"AttributeName":"seats","KeyType":"RANGE"}],"Projection":{"ProjectionType":"ALL"},"IndexSizeBytes":0,"ItemCount":0}],"GlobalSecondaryIndexes":[{"IndexName":"global_all_index_color","KeySchema":[{"AttributeName":"color","KeyType":"HASH"},{"AttributeName":"rating","KeyType":"RANGE"}],"Projection":{"ProjectionType":"ALL"},"IndexStatus":"ACTIVE","ProvisionedThroughput":{"ReadCapacityUnits":5,"WriteCapacityUnits":5},"IndexSizeBytes":0,"ItemCount":0}]}} 2015-04-15 20:04:49,004 [DEBUG] (boto) {"TableDescription":{"AttributeDefinitions":[{"AttributeName":"id","AttributeType":"S"},{"AttributeName":"rating","AttributeType":"S"},{"AttributeName":"seats","AttributeType":"S"},{"AttributeName":"color","AttributeType":"S"}],"TableName":"items","KeySchema":[{"AttributeName":"id","KeyType":"HASH"},{"AttributeName":"rating","KeyType":"RANGE"}],"TableStatus":"ACTIVE","CreationDateTime":1429108488.651,"ProvisionedThroughput":{"LastIncreaseDateTime":0.000,"LastDecreaseDateTime":0.000,"NumberOfDecreasesToday":0,"ReadCapacityUnits":1,"WriteCapacityUnits":1},"TableSizeBytes":0,"ItemCount":0,"LocalSecondaryIndexes":[{"IndexName":"local_all_index_seats","KeySchema":[{"AttributeName":"id","KeyType":"HASH"},{"AttributeName":"seats","KeyType":"RANGE"}],"Projection":{"ProjectionType":"ALL"},"IndexSizeBytes":0,"ItemCount":0}],"GlobalSecondaryIndexes":[{"IndexName":"global_all_index_color","KeySchema":[{"AttributeName":"color","KeyType":"HASH"},{"AttributeName":"rating","KeyType":"RANGE"}],"Projection":{"ProjectionType":"ALL"},"IndexStatus":"ACTIVE","ProvisionedThroughput":{"ReadCapacityUnits":5,"WriteCapacityUnits":5},"IndexSizeBytes":0,"ItemCount":0}]}} Table created 2015-04-15 20:04:49,004 [DEBUG] (boto) Method: POST 2015-04-15 20:04:49,004 [DEBUG] (boto) Path: / 2015-04-15 20:04:49,004 [DEBUG] (boto) Data: {"Expected": {"category": {"Exists": false}, "rating": {"Exists": false}, "id": {"Exists": false}, "color": {"Exists": false}, "seats": {"Exists": false}}, "Item": {"category": {"S": "Sofa"}, "rating": {"S": "4"}, "id": {"S": "first_id"}, "color": {"S": "beige"}, "seats": {"S": "6"}}, "TableName": "items"} 2015-04-15 20:04:49,004 [DEBUG] (boto) Headers: {'Host': 'localhost', 'Content-Type': 'application/x-amz-json-1.0', 'Content-Length': '307', 'X-Amz-Target': 'DynamoDB_20120810.PutItem'} 2015-04-15 20:04:49,005 [DEBUG] (boto) Host: localhost 2015-04-15 20:04:49,005 [DEBUG] (boto) Port: 8000 2015-04-15 20:04:49,005 [DEBUG] (boto) Params: {} 2015-04-15 20:04:49,005 [DEBUG] (boto) Token: None 2015-04-15 20:04:49,005 [DEBUG] (boto) CanonicalRequest: POST / host:localhost x-amz-date:20150415T143449Z x-amz-target:DynamoDB_20120810.PutItem host;x-amz-date;x-amz-target 96fd2aee6eabd2c812d7111c9a47ba21c31ccc86859c963cfa3fd69a18edc957 2015-04-15 20:04:49,005 [DEBUG] (boto) StringToSign: AWS4-HMAC-SHA256 20150415T143449Z 20150415/localhost/localhost/aws4_request 9ed70485aa9e7036fd2db89e34036c9e24a3c91b6e35dbb7fc2cd476b4766f21 2015-04-15 20:04:49,005 [DEBUG] (boto) Signature: 1d81bae229584b7466c6951a71010c8e2d7a441e80b2e9b5a60d9782859345dc 2015-04-15 20:04:49,005 [DEBUG] (boto) Final headers: {'Content-Length': '307', 'User-Agent': 'Boto/2.38.0 Python/2.7.6 Linux/3.16.0-30-generic', 'Host': 'localhost', 'X-Amz-Date': '20150415T143449Z', 'X-Amz-Target': 'DynamoDB_20120810.PutItem', 'Content-Type': 'application/x-amz-json-1.0', 'Authorization': 'AWS4-HMAC-SHA256 Credential=AKIAJW2Q5MT375WFZIMA/20150415/localhost/localhost/aws4_request,SignedHeaders=host;x-amz-date;x-amz-target,Signature=1d81bae229584b7466c6951a71010c8e2d7a441e80b2e9b5a60d9782859345dc'} 2015-04-15 20:04:49,287 [DEBUG] (boto) Response headers: [('x-amzn-requestid', '80571386-1ce7-4f9b-84fb-6805a0dfa171'), ('content-length', '2'), ('content-type', 'application/x-amz-json-1.0'), ('x-amz-crc32', '2745614147'), ('server', 'Jetty(8.1.12.v20130726)')] 2015-04-15 20:04:49,287 [DEBUG] (boto) Saw HTTP status: 200 2015-04-15 20:04:49,287 [DEBUG] (boto) Validating crc32 checksum for body: {} 2015-04-15 20:04:49,287 [DEBUG] (boto) {} New item saved 2015-04-15 20:04:49,288 [DEBUG] (boto) Method: POST 2015-04-15 20:04:49,288 [DEBUG] (boto) Path: / 2015-04-15 20:04:49,288 [DEBUG] (boto) Data: {"ConsistentRead": false, "TableName": "items", "Key": {"id": {"S": "first_id"}}} 2015-04-15 20:04:49,288 [DEBUG] (boto) Headers: {'Host': 'localhost', 'Content-Type': 'application/x-amz-json-1.0', 'Content-Length': '81', 'X-Amz-Target': 'DynamoDB_20120810.GetItem'} 2015-04-15 20:04:49,289 [DEBUG] (boto) Host: localhost 2015-04-15 20:04:49,289 [DEBUG] (boto) Port: 8000 2015-04-15 20:04:49,289 [DEBUG] (boto) Params: {} 2015-04-15 20:04:49,289 [DEBUG] (boto) Token: None 2015-04-15 20:04:49,289 [DEBUG] (boto) CanonicalRequest: POST / host:localhost x-amz-date:20150415T143449Z x-amz-target:DynamoDB_20120810.GetItem host;x-amz-date;x-amz-target 1563f0044c8fc746bb9a0ec2e4754e5fd03e62d604102f0745920d8c49481e88 2015-04-15 20:04:49,289 [DEBUG] (boto) StringToSign: AWS4-HMAC-SHA256 20150415T143449Z 20150415/localhost/localhost/aws4_request 059601773b2e09d4c42f984cb185bf565e47a9dff8d42b3ae15dd61b4fc41f76 2015-04-15 20:04:49,289 [DEBUG] (boto) Signature: e22cfe8b3e3e03dfa4e05ec11f333f9aaff0edcdbf498ebfa9d0e7dc5b452916 2015-04-15 20:04:49,290 [DEBUG] (boto) Final headers: {'Content-Length': '81', 'User-Agent': 'Boto/2.38.0 Python/2.7.6 Linux/3.16.0-30-generic', 'Host': 'localhost', 'X-Amz-Date': '20150415T143449Z', 'X-Amz-Target': 'DynamoDB_20120810.GetItem', 'Content-Type': 'application/x-amz-json-1.0', 'Authorization': 'AWS4-HMAC-SHA256 Credential=AKIAJW2Q5MT375WFZIMA/20150415/localhost/localhost/aws4_request,SignedHeaders=host;x-amz-date;x-amz-target,Signature=e22cfe8b3e3e03dfa4e05ec11f333f9aaff0edcdbf498ebfa9d0e7dc5b452916'} 2015-04-15 20:04:49,315 [DEBUG] (boto) Response headers: [('x-amzn-requestid', '51547354-f266-4870-8c79-6192e7d7c7b5'), ('content-length', '118'), ('content-type', 'application/x-amz-json-1.0'), ('server', 'Jetty(8.1.12.v20130726)')] 2015-04-15 20:04:49,316 [DEBUG] (boto) Saw HTTP status: 400 2015-04-15 20:04:49,316 [DEBUG] (boto) {"__type":"com.amazon.coral.validate#ValidationException","Message":"The number of conditions on the keys is invalid"} Traceback (most recent call last): File "reproduce.py", line 71, in <module> queried_item = items_table.get_item(id='first_id') File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/dynamodb2/table.py", line 705, in get_item consistent_read=consistent File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/dynamodb2/layer1.py", line 1099, in get_item body=json.dumps(params)) File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/dynamodb2/layer1.py", line 2842, in make_request retry_handler=self._retry_handler) File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/connection.py", line 954, in _mexe status = retry_handler(response, i, next_sleep) File "/home/aniket/venv/backend/local/lib/python2.7/site-packages/boto/dynamodb2/layer1.py", line 2882, in _retry_handler response.status, response.reason, data) boto.dynamodb2.exceptions.ValidationException: ValidationException: 400 Bad Request {u'Message': u'The number of conditions on the keys is invalid', u'__type': u'com.amazon.coral.validate#ValidationException'} Answer: `GetItem` in DynamoDB needs the same number of key conditions as the number of keys, largely because the operation must find the exact item in the table. For the primary key, you must provide all of the attributes. There should be only one item, if any, matching the **Get** expectations. This is written in the [DynamoDB doc](http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_GetItem.html). On contrast, you can use `Query` to get multiple (possibly) items for a given condition. Since you know this I believe, I think you mistakenly used the wrong `get_item()` api, instead of `query()` or something alike.
Find what part of a string do not match with regular expression python Question: In order to see if a filename is correctly named (using re) I use the following regular expression pattern : *^S_hc_[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}_[0-9]{4,4}-[0-9]{1,3}T[0-9]{6,6}\.xml$"* Here is a correct file name : `*S_hc_1.2.3_2014-213T123121.xml*` Here is an incorrect file name : `*S_hc_1.2.IncorrectName_2014-213T123121.xml*` I would like to know if a simple way to retrieve the part of the file which to do not match exits. In the end, an error message would display : Error, incorrect file name, the part 'IncorrectName' does not match with expected name. Answer: You can use `re.split` and a generator expression within [`next`](https://docs.python.org/2/library/functions.html#next) but you also need to check the structure of your string that match waht you want, you can do it with following re.match : re.match(r"^S_hc_(.*)\.(.*)\.(.*)_(.*)-(.*)\.xml$",s2) And in code: >>> import re >>> s2 ='S_hc_1.2.IncorrectName_2014-213T123121.xml' >>> s1 'S_hc_1.2.3_2014-213T123121.xml' #with s1 >>> next((i for i in re.split(r'^S_hc_|[0-9]{1,2}\.|[0-9]{1,2}_|_|[0-9]{4,4}|-|[0-9]{1,3}T[0-9]{6}|\.|xml$',s1) if i and re.match(r"^S_hc_(.*)\.(.*)\.(.*)_(.*)-(.*)\.xml$",s2)),None) #with s2 >>> next((i for i in re.split(r'^S_hc_|[0-9]{1,2}\.|[0-9]{1,2}_|_|[0-9]{4,4}|-|[0-9]{1,3}T[0-9]{6}|\.|xml$',s2) if i and re.match(r"^S_hc_(.*)\.(.*)\.(.*)_(.*)-(.*)\.xml$",s2)),None) 'IncorrectName' All you need is to use pip (`|`) between unique part of your regex patterns,then the `split` function will split your string based on one of that patterns. And the part that doesn't match with one of your pattern will not be split and you can find it with looping over your split text! > **next(iterator[, default])** > > Retrieve the next item from the iterator by calling its next() method. If > default is given, it is returned if the iterator is exhausted, otherwise > StopIteration is raised. If you want in several line : >>> for i in re.split(r'^S_hc_|[0-9]{1,2}\.|[0-9]{1,2}_|_|[0-9]{4,4}|-|[0-9]{1,3}T[0-9]{6}|\.|xml$',s2): ... if i and re.match(r"^S_hc_(.*)\.(.*)\.(.*)_(.*)-(.*)\.xml$",s2): ... print i ... IncorrectName
XPath Syntax - Scrapy Question: So I've been trying to find a syntax reference guide to finish off a basic screen scraper tool using Scrapy and a Craigslist Jobs site. This is just for practice as I learn about Scrapy more and move into more complex projects - jumping pages, filling out search forms, etc. This is what my code looks like for Scrapy: from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from craigslist_sample.items import CraigslistSampleItem class MySpider(BaseSpider): name = "craig" allowed_domains = ["craigslist.org"] start_urls = ["https://gainesville.craigslist.org/search/jjj"] def parse(self, response): hxs = HtmlXPathSelector(response) titles = hxs.select("//p") items = [] for titles in titles: item = CraigslistSampleItem() item ["title"] = titles.select("").extract() item ["link"] = titles.select("a/@href").extract() items.append(item) return items Obviously as you can see, I have a craiglist sample item python file that contains the elemetns for title and link. I can't seem to figure out line 16: the XPath for the element I am trying to grab - which is the title of the Craiglist posting. My XPath for the link works, it's under <p><a href='URL'> in the craigslist posting. The craigslist posting title is under: <p><span><span><a class="hdrlnk">Example Job Description</a> I've messed around with it and I've been able to get the outputs for title of hdrlnk and also '1'. I'm not sure what Im doing wrong. Any help would be greatly appreciated! As a bonus, does anyone know how I would then tell Scrapy to go to the next page and run the same script? Thanks! Answer: you can try this out, BASE_URL = 'https://gainesville.craigslist.org' titles = response.xpath('//p[@class="row"]') for title in titles: # extracting the title name = title.xpath('.//a[@class="hdrlnk"]/text()').extract() # cleaning the data name = name[0].strip() if name else 'N/A' link = title.xpath('.//a[@class="hdrlnk"]/@href').extract() link = BASE_URL + link[0].strip() if link else 'N/A item = CraigslistSampleItem(title=name, link=link) yield items if you want the pagination, then the complete code will look like, def parse(self, response): BASE_URL = 'https://gainesville.craigslist.org' titles = response.xpath('//p[@class="row"]') for title in titles: # extracting the title name = title.xpath('.//a[@class="hdrlnk"]/text()').extract() # cleaning the data name = name[0].strip() if name else 'N/A' link = title.xpath('.//a[@class="hdrlnk"]/@href').extract() link = BASE_URL + link[0].strip() if link else 'N/A item = CraigslistSampleItem(title=name, link=link) yield items next_page = response.xpath('//a[@class="button next"]/@href').extract() if next_page: next_page_url = BASE_URL + next_page[0].strip() yield Request(url=next_page_url, callback=self.parse)
Having python 3.4 find my custom package Question: I wrote a package in python and now I am trying to add it to my site-packages folder using a .pth file so that I can call it from anywhere using import statement, but it is not working. `sste.pth` file in my site-packages folder /scratch/automation/sste sste folder structure sste-\ ---__init__.py ---module1.py ---module2.py From what I understand when I launch python it should source the site_packages file, including my `sste.pth` file and add `/scratch/automation/sste` to the module list so I can import it by doing `import sste`, but I get an `import error`, and can't figure out why. Answer: It looks like you have directed Python to look for your module in `/scratch/automation/sste` when `sste` is itself a package. When Python looks in `/scratch/automation/sste` it is not going to find a package named `sste`, only `.py` files named `__init__.py`, `module1.py`, and `module2.py`. In short, you should be telling Python to look in `/scratch/automation` for modules instead. Python's path is not a list of modules it can import, but rather a list of directories that may _contain_ modules. Also, check `sys.modules` to make sure the directories you expect to be in it are there.
how to test mnist on my own dataset images Question: I'm trying to test mnist using my own dataset of digits images. I wrote a python script for that but it is giving an error. error is in line no 16 of code. Actually i'm not able to send image for test. give me some suggestions. thanks in advance. import numpy as np import sys import caffe import matplotlib.pyplot as plt import os caffe_root = '../caffe-master/' MODEL_FILE = './examples/mnist/lenet.prototxt' PRETRAINED = './examples/mnist/lenet_iter_10000.caffemodel' IMAGE_FILE = '/home/hemant/OpenCVProject/grey/img001-00001.png'#image path input_image = caffe.io.load_image(IMAGE_FILE) net = caffe.Net(MODEL_FILE, PRETRAINED,caffe.TEST) caffe.set_mode_cpu() out = net.forward([input_image]) print out['prob'] Answer: Why don't you use the python wrapper class `Classifier`? net = caffe.Classifier( MODEL_FILE, PRETRAINED ) net.predict( [input_image], oversmaple=False ) I'm not 100% sure, but I think LeNeT model expect gray scale image, you might need to read the image input_image = caffe.io.load_image(IMAGE_FILE, color=False)
Python SIGINT not catched Question: I don't manage to understand why my SIGINT is never catched by the piece of code below. #!/usr/bin/env python from threading import Thread from time import sleep import signal class MyThread(Thread): def __init__(self): Thread.__init__(self) self.running = True def stop(self): self.running = False def run(self): while self.running: for i in range(500): col = i**i print col sleep(0.01) global threads threads = [] for w in range(150): threads.append(MyThread()) def stop(s, f): for t in threads: t.stop() signal.signal(signal.SIGINT, stop) for t in threads: t.start() for t in threads: t.join() To clean this code I would prefer try/except the join() and closing all threads in case of exception, would that work? Answer: One of the problems with multithreading in python is that `join()` more or less disables signals. This is because the signal can only be delivered to the main thread, but the main thread is already busy with performing the `join()` and the join is not interruptible. You can deduce this from the documentation of the `signal` module > Some care must be taken if both signals and threads are used in the same > program. The fundamental thing to remember in using signals and threads > simultaneously is: always perform signal() operations in the main thread of > execution. Any thread can perform an alarm(), getsignal(), pause(), > setitimer() or getitimer(); only the main thread can set a new signal > handler, and **the main thread will be the only one to receive signals** > (this is enforced by the Python signal module, even if the underlying thread > implementation supports sending signals to individual threads). This means > that signals can’t be used as a means of inter-thread communication. Use > locks instead. You can work your way around it, by busy-looping over the join operation: for t in threads: while t.isAlive(): t.join(timeout=1) This is, however, none to efficient: > The workaround of calling join() with a timeout has a drawback: Python's > threading wait routine polls 20 times a second when given any timeout. All > this polling can mean lots of CPU interrupts/wakeups on an otherwise idle > laptop and drain the battery faster. Some more details are provided here: [Python program with thread can't catch CTRL+C](http://stackoverflow.com/questions/19652446/python-program-with- thread-cant-catch-ctrlc) Bug reports for this problem with a discussion of the underlying issue can be found here: <https://bugs.python.org/issue1167930> <https://bugs.python.org/issue1171023>
Automatically updating GET request python Question: I have a exchange rate request that I would like to update every second. As of now I have to re-load the program to refresh the rate. How would I go about doing this in Python? Any help would be appreciated, thanks in advance.. script: import oandapy oanda = oandapy.API(environment="practice", access_token="xxxxxxxxxxxx") response = oanda.get_prices(instruments="EUR_USD") prices = response.get("prices") asking_price = prices[0].get("ask") stop = asking_price - .001 Per answer: while True: response = oanda.get_prices(instruments="EUR_USD") prices = response.get("prices") asking_price = prices[0].get("ask") stop = asking_price - .001 time.sleep(1) Answer: The general method is to wrap the entire thing in an infinite loop, and wait between requests: while True: # ... do and print request time.sleep(1) # then wait one second Make sure that your API access token allows sending a request every second. * * * However, after a quick Google I found that the API you're using supports streaming rates: <https://github.com/oanda/oandapy#rates-streaming>
python error "ValueError: Invalid vertices array" Question: I'm running the following code and get the following error for making the plot. When I print the cov variable, the numbers in it have single quotes around them. I'm assuming this is the problem? When I try to plot x and y, it works just fine. I'm a new python user. Any suggestions? Thanks! #!/bin/python import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np from sys import argv #from numpy import array #array = numpy.float64(array) script, filename = argv file = open(filename) pos = [] cov = [] for line in file: if (line.split()[0])=='1': ch = int(line.split()[0]) #adjpos = int(line.split()[1]) pos.append(line.split()[1]) cov.append(line.split()[2]) file.close() print cov x = [0, 1, 2, 3] y = [5, 10, 5, 5] print x print y fig = plt.figure(figsize=(16,3),edgecolor='w') plt.scatter(pos,cov,marker='.',s=1) plt.show() Traceback (most recent call last): File "/Users/eflannery/Dropbox/plotSamFlags.py", line 37, in <module> plt.scatter(pos,cov,marker='.',s=1) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/pyplot.py", line 2557, in scatter ret = ax.scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, faceted, verts, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 5876, in scatter self.add_collection(collection) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 1445, in add_collection self.update_datalim(collection.get_datalim(self.transData)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/collections.py", line 160, in get_datalim offsets = transOffset.transform_non_affine(offsets) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/transforms.py", line 1925, in transform_non_affine self._a.transform(points)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/transforms.py", line 1415, in transform return affine_transform(points, mtx) ValueError: Invalid vertices array. Answer: The numbers need to be converted to a type that matplotlib can use; right now it just makes a list of strings, as `split()` returns a list of strings. You can fix this by calling `int()` (or `float()`, if the numbers aren't all integers) to convert the strings when you read the file, which you already did in the assignment to `ch`: for line in file: if (line.split()[0])=='1': ch = int(line.split()[0]) pos.append(int(line.split()[1])) cov.append(int(line.split()[2]))
How to document Matlab project with multiple classes using sphinxcontrib-matlabdomain? Question: I tried to document a larger Matlab project using Sphinx and the sphinxcontrib-matlabdomain package. It works fine for a single folder that stores all .m files. However my project contains multiple classes stored in separate folders such as: project |-- matfiles | |-- @class1 | | |-- class1.m | | |-- method1.m | | |-- method2.m | | +-- method1.m | |-- @class2 | | |-- class2.m | | |-- methodA.m | | |-- methodB.m | | +-- methodC.m | +-- function | |-- fun1.m | |-- fun2.m | +-- fun3.m +-- doc |-- conf.py +-- index.rst I adde the following lines to `conf.py`: matlab_src_dir = os.path.abspath('..') extensions = [ 'sphinx.ext.autodoc', 'sphinxcontrib.matlab', ] primary_domain = 'mat' And I added the following lines to `index.rst`: .. module:: matfiles .. automethod:: class1.method1 I got the following error: Exception occurred: File "/Library/Python/2.7/site-packages/sphinxcontrib/mat_documenters.py", line 788, in import_object if self.object.attrs.get('Static'): AttributeError: 'NoneType' object has no attribute 'attrs' The full traceback has been saved in /var/folders/70/g0lr37wn60gbbymnsks_t5vm0000gn/T/sphinx-err-uD8qpe.log, if you want to report the issue to the developers. Please also report this if it was a user error, so that a better error message can be provided next time. A bug report can be filed in the tracker at <https://github.com/sphinx-doc/sphinx/issues>. Thanks! | reading sources... [100%] index So my question is, is there a way to document multi class Matlab projects where class methods are saved in a folder with name @class? Answer: I believe this issue has been resolved in the latest version, [sphinxcontrib- matlabdomain-0.2.7](https://pypi.python.org/pypi/sphinxcontrib-matlabdomain), which autodocuments class methods with attributes defined in separate files of a `@classfolders`. Let me know if it's still an issue.
Django/Python: form data doesn't get stored in database Question: Django 1.8 / Python 3.4 I wanna add data from an html-form via a Django view named "add" to my database. However, for some reason this just doesn't happen and I can't figure out what's wrong. Presumably the mistake is in the view's code, but what exactly do I need to change? models.py from django.db import models from model_utils import Choices class Entry(models.Model): user = models.CharField(max_length=50) title = models.CharField(max_length=200) description = models.TextField() due_date = models.DateField('Date') due_time = models.TimeField('Time') STATUS = Choices('Open', 'Done') status = models.CharField(choices=STATUS, default=STATUS.Open, max_length=4) def __unicode__(self): return u"%s %s %s %s %s" % (self.user, self.title, self.description, self.expiry, self.status) def expiry(self): return u"%s %s" % (self.due_date, self.due_time) The interesting part of my add.html <td><input type="text" name="title"></td> <td><input type="text" name="description"></td> <td><input type="text" name="due_date"></td> <td><input type="text" name="due_time"></td> <td> <select name="status" size="1" selected value="Open"> <option>Open</option> <option>Done</option> </select> </td> forms.py from django import forms from django.forms.widgets import TextInput class EntryForm(forms.Form): title = forms.CharField(max_length=200) description = forms.widgets.TextInput() due_date = forms.DateField() due_time = forms.TimeField() status = forms.ChoiceField(choices=[(x, x) for x in range(1, 2)]) And the relevant view in my views.py from django import forms from django.shortcuts import render from django.shortcuts import redirect from website.list.forms import EntryForm def add(request): if request.method == "POST": form = EntryForm(request.POST) if form.is_valid(): new_entry = form.save() new_entry.save() return redirect('website') else: form = EntryForm() return render(request,'add.html', {'form': form}) Any help is appreciated! * * * [EDIT] So, this is what my add.html looks like now: <form action="." method="post"> {% csrf_token %} {{ form }} <br><input type="submit" value="Send"/> <br><br><a href="{% url 'overview' %}">Cancel</a> </form> And the slightly edited views.py again: from django import forms from django.shortcuts import render from django.shortcuts import redirect from www.todolist.forms import EntryForm from django.contrib.auth.models import User def add(request): if request.method == "POST": form = EntryForm(request.POST) if form.is_valid()) form.save() return redirect('website') else: form = EntryForm() return render(request,'add.html', {'form': form}) Answer: Figured it out ... This is what forms.py has to look like in order for the save() function to work in the view: class EntryForm(forms.ModelForm): CHOICES = ( ('1', 'Open'), ('2', 'Done'), ) title = forms.CharField(max_length=200) description = forms.CharField(widget=forms.Textarea) due_date = forms.DateField() due_time = forms.TimeField() status = forms.ChoiceField(choices=CHOICES) class Meta: model = Entry fields = '__all__' The important things to notice are "ModelForm" instead of just "Form" and the class Meta information.
pyGtk: Image prevents window resize Question: So I am attempting to make a GTK application using python, and I have run into this issue where after I place an image on a window, I can increase the size of the window, but not decrease it. Given that the purpose of this particular window is to display a resizable image, this is rather bothersome. I have extracted the relevant code which demonstrates this behavior below #!/usr/bin/env python from gi.repository import Gtk, GdkPixbuf import sys class ImageWindow(Gtk.Window): def __init__(self, image_data): Gtk.Window.__init__(self, title="image test") if image_data and len(image_data) > 0: self.loader = GdkPixbuf.PixbufLoader() self.loader.write(image_data) self.pixbuf = self.loader.get_pixbuf() self.image = Gtk.Image.new_from_pixbuf(self.pixbuf) else: self.image = Gtk.Image.new() self.add(self.image) self.connect('delete-event', Gtk.main_quit) win = ImageWindow(sys.stdin.read()) win.show_all() Gtk.main() If you pipe in nothing, the window resizes fine. Pipe in an image, and the form clicks to the size of the image, and can resize bigger, but cannot resize smaller. Answer: So here is an example of a scaling image. The idea is that you put the image in a Gtk.ScrolledWindow() and resize the image as soon as the window is resized.: #!/usr/bin/env python from gi.repository import Gtk, GdkPixbuf, GLib import sys class ImageWindow(Gtk.Window): def __init__(self, image_data): Gtk.Window.__init__(self, title="image test") self.connect('delete-event', Gtk.main_quit) self.image = Gtk.Image() scrolled_window = Gtk.ScrolledWindow() scrolled_window.add(self.image) self.add(scrolled_window) if len(image_data) == 0: return self.loader = GdkPixbuf.PixbufLoader() self.loader.write(image_data) self.loader.close() self.pixbuf = self.loader.get_pixbuf() self.image.set_from_pixbuf(self.pixbuf) width = self.pixbuf.get_width() height = self.pixbuf.get_height() self.dimension = float(width) / height self.set_default_size(width, height) self.connect('check-resize', self.on_resize) def on_resize(self, window): width, height = self.get_size() if float(width) / height > self.dimension: self.pixbuf = self.pixbuf.scale_simple( self.dimension * height, height, GdkPixbuf.InterpType.NEAREST ) else: self.pixbuf = self.pixbuf.scale_simple( width, width / self.dimension, GdkPixbuf.InterpType.NEAREST ) GLib.idle_add(self.image.set_from_pixbuf, self.pixbuf) win = ImageWindow(sys.stdin.read()) win.show_all() Gtk.main() As an alternative, you can load the pixbuf again from the loader and scale it afterwards. This looks better if you make your image smaller and then larger again but needs more processing: def on_resize(self, window): width, height = self.get_size() self.pixbuf = self.loader.get_pixbuf() if float(width) / height > self.dimension: self.pixbuf = self.pixbuf.scale_simple( self.dimension * height, height, GdkPixbuf.InterpType.BILINEAR ) else: self.pixbuf = self.pixbuf.scale_simple( width, width / self.dimension, GdkPixbuf.InterpType.BILINEAR ) GLib.idle_add(self.image.set_from_pixbuf, self.pixbuf)
Cyclic label update in Python Question: I'm trying to get dynamic cyclic (every half a second) label updates from a Webservice in Python where I parse a JSON string and return its contents to the GUI (made with Glade 3.8.1). I have started from a basic example and the code I've written so far looks like this: import sys import json import urllib2 import time try: import pygtk pygtk.require("2.0") except: pass try: import gtk.glade import gtk except: sys.exit(1) class cRioHMI(): def on_MainWindow_destroy(self, data = None): print "quit with cancel" gtk.main_quit() def on_gtk_quit_activate(self, data = None): print "quit from menu" gtk.main_quit() def on_btnTest_clicked(self, widget): print "Button Pressed" def on_gtk_about_activate(self, data = None): print "About Page Accessed" self.response = self.about.run() self.about.hide() def __init__(self): self.gladefile = "Assets/HMI.glade" self.builder = gtk.Builder() self.builder.add_from_file(self.gladefile) self.builder.connect_signals(self) self.window = self.builder.get_object("MainWindow") self.about = self.builder.get_object("AboutDialogue") self.templable = self.builder.get_object("lbl_Temperature") self.window.show() def update_Values(self, data = None): response = urllib2.urlopen('http://10.10.10.11:8001/WebUI/Temperatures/GetTemperatures') data = json.load(response) temperature = data['Temperature2'][1] self.templable.set_text(str(temperature)) time.sleep(.5) if __name__ == "__main__": HMI = cRioHMI() gtk.main() When I use the code from the update_Values method on a click event, the code performs as expected def on_btnTest_clicked(self, widget): response = urllib2.urlopen('http://10.10.10.11:8001/WebUI/Temperatures/GetTemperatures') data = json.load(response) temperature = data['Temperature2'][1] self.templable.set_text(str(temperature)) time.sleep(.5) print "Button Pressed" * but I would like to update multiple labels in a cyclic manner and still have event driven actions. What is the best way to do that? Please note, that I'm new to python. Answer: You can use `gobject.timeout_add` (see the documentation [here](http://www.pygtk.org/pygtk2reference/gobject-functions.html#function- gobject--timeout-add)). So in your `__init__` you would have something like `gobject.timeout_add(1000, self.updateValues)`. If you return False the timeout will not be called again. You should also not use `time.sleep`. This is a blocking call. That means your GUI will freeze as it cannot handle incoming events. The same thing will happen with the `urllib2.urlopen` call, if it takes too much time. To prevent this you can run updateValues in a separate Thread. Then you would have to use `gobject.idle_add` to set the text of the label (see [documentation](http://www.pygtk.org/pygtk2reference/gobject- functions.html#function-gobject--idle-add)). Here is a small example. It is just a counter (and would not need threading) but I marked the place where your urllib2.urlopen would go with a comment: #!/usr/bin/env python2 from threading import Thread from pygtk import gtk, gobject class Window(gtk.Window): def __init__(self): gtk.Window.__init__(self) self.connect('delete-event', gtk.main_quit) self.label = gtk.Label('1') self.add(self.label) gobject.timeout_add_seconds(1, self.threaded) def threaded(self): thread = Thread(target=self.updateValues) thread.start() return True def updateValues(self): # urllib.urlopen calls n = int(self.label.get_text()) gobject.idle_add(self.label.set_text, str(n + 1)) win = Window() win.show_all() gobject.threads_init() gtk.main()
Prediction io pio train says appId does not exist Question: I'm trying out the latest version of prediction.io (version 0.9.1). I have installed prediction io along with its dependencies by following the tutorial in this page: <http://docs.prediction.io/install/install-linux/> I've added the path to the `predictionio/bin` directory into my `.bashrc` file so I could use the command line tools from my terminal: export PATH=$PATH:/home/wern/PredictionIO-0.9.1/bin export JAVA_HOME="/usr/lib/jvm/java-8-oracle" I get the following when executing `pio-start-all`: Starting Elasticsearch... Starting HBase... starting master, logging to /home/wern/hbase-0.98.11-hadoop2/bin/../logs/hbase-me-master-mycomputer.out Waiting 10 seconds for HBase to fully initialize... Starting PredictionIO Event Server... Executing `java -version` returns the following: java version "1.8.0_40" Java(TM) SE Runtime Environment (build 1.8.0_40-b25) Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode) Executing `pio status` returns the following: PredictionIO Installed at: /home/me/PredictionIO-0.9.1 Version: 0.9.1 Apache Spark Installed at: /home/wern/spark-1.2.1-bin-hadoop2.4 Version: 1.2.1 (meets minimum requirement of 1.2.0) Storage Backend Connections Verifying Meta Data Backend Verifying Model Data Backend Verifying Event Data Backend [WARN] [NativeCodeLoader] Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Test write Event Store (App Id 0) [INFO] [HBLEvents] The table predictionio_eventdata:events_0 doesn't exist yet. Creating now... [INFO] [HBLEvents] Removing table predictionio_eventdata:events_0... (sleeping 5 seconds for all messages to show up...) Your system is all ready to go. Next I get a generic template. I executed this command from the home directory so I got a `RecommendationApp` directory when it was done: pio template get PredictionIO/template-scala-parallel-recommendation RecommendationApp Next I created a new prediction io app: pio app new MyGenericRecommendationApp This returns the following: [WARN] [NativeCodeLoader] Unable to load native-hadoop library for your platform... using builtin-java classes where applicable [INFO] [HBLEvents] The table predictionio_eventdata:events_3 doesn't exist yet. Creating now... [INFO] [App$] Initialized Event Store for this app ID: 3. [INFO] [App$] Created new app: [INFO] [App$] Name: MyGenericRecommendationApp [INFO] [App$] ID: 3 [INFO] [App$] Access Key: C7vfcipXd0baQcZYzqr73EwSPT2Bd0YW1OTLgEdlUA9FOeBja6dyBVIKaYnQbsUO Next I navigate to the `RecommendationApp` engine directory and download the sample data: curl https://raw.githubusercontent.com/apache/spark/master/data/mllib/sample_movielens_data.txt --create-dirs -o data/sample_movielens_data.txt Then I import it using python: python data/import_eventserver.py --access_key C7vfcipXd0baQcZYzqr73EwSPT2Bd0YW1OTLgEdlUA9FOeBja6dyBVIKaYnQbsUO This successfully imports the data. Next I updated the `engine.json` file to match the ID of the app that I created earlier. "datasource": { "params" : { "appId": 3 } }, Then I executed `pio build`. This took a while but it finally returned the following: [INFO] [Console$] Your engine is ready for training. Finally here's where my issue is. Executing `pio train` results in the follwing: [INFO] [Console$] Using existing engine manifest JSON at /home/wern/RecommendationApp/manifest.json [WARN] [NativeCodeLoader] Unable to load native-hadoop library for your platform... using builtin-java classes where applicable [INFO] [RunWorkflow$] Submission command: /home/wern/spark-1.2.1-bin-hadoop2.4/bin/spark-submit --class io.prediction.workflow.CreateWorkflow --name PredictionIO Training: RTn3BZbRfxOlOkDQCHBmOaMBHTP1gmOg 92c46ac3197f8bf4696281a1f76eaaa943495d3f () --jars file:/home/wern/.pio_store/engines/RTn3BZbRfxOlOkDQCHBmOaMBHTP1gmOg/92c46ac3197f8bf4696281a1f76eaaa943495d3f/template-scala-parallel-recommendation-assembly-0.1-SNAPSHOT-deps.jar,file:/home/wern/.pio_store/engines/RTn3BZbRfxOlOkDQCHBmOaMBHTP1gmOg/92c46ac3197f8bf4696281a1f76eaaa943495d3f/template-scala-parallel-recommendation_2.10-0.1-SNAPSHOT.jar --files /home/wern/PredictionIO-0.9.1/conf/log4j.properties,/home/wern/PredictionIO-0.9.1/conf/hbase-site.xml --driver-class-path /home/wern/PredictionIO-0.9.1/conf:/home/wern/PredictionIO-0.9.1/conf /home/wern/PredictionIO-0.9.1/lib/pio-assembly-0.9.1.jar --env PIO_STORAGE_SOURCES_HBASE_TYPE=hbase,PIO_ENV_LOADED=1,PIO_STORAGE_SOURCES_HBASE_HOSTS=0,PIO_STORAGE_REPOSITORIES_METADATA_NAME=predictionio_metadata,PIO_FS_BASEDIR=/home/wern/.pio_store,PIO_STORAGE_SOURCES_ELASTICSEARCH_HOSTS=localhost,PIO_STORAGE_SOURCES_HBASE_HOME=/home/wern/hbase-0.98.11-hadoop2,PIO_HOME=/home/wern/PredictionIO-0.9.1,PIO_FS_ENGINESDIR=/home/wern/.pio_store/engines,PIO_STORAGE_SOURCES_HBASE_PORTS=0,PIO_STORAGE_SOURCES_ELASTICSEARCH_TYPE=elasticsearch,PIO_STORAGE_REPOSITORIES_METADATA_SOURCE=ELASTICSEARCH,PIO_STORAGE_REPOSITORIES_MODELDATA_SOURCE=LOCALFS,PIO_STORAGE_REPOSITORIES_EVENTDATA_NAME=predictionio_eventdata,PIO_STORAGE_SOURCES_ELASTICSEARCH_HOME=/home/wern/elasticsearch-1.4.4,PIO_FS_TMPDIR=/home/wern/.pio_store/tmp,PIO_STORAGE_REPOSITORIES_MODELDATA_NAME=pio_,PIO_STORAGE_SOURCES_LOCALFS_HOSTS=/home/wern/.pio_store/models,PIO_STORAGE_REPOSITORIES_EVENTDATA_SOURCE=HBASE,PIO_CONF_DIR=/home/wern/PredictionIO-0.9.1/conf,PIO_STORAGE_SOURCES_LOCALFS_PORTS=0,PIO_STORAGE_SOURCES_ELASTICSEARCH_PORTS=9300,PIO_STORAGE_SOURCES_LOCALFS_TYPE=localfs --engine-id RTn3BZbRfxOlOkDQCHBmOaMBHTP1gmOg --engine-version 92c46ac3197f8bf4696281a1f76eaaa943495d3f --engine-variant /home/wern/RecommendationApp/engine.json --verbosity 0 Spark assembly has been built with Hive, including Datanucleus jars on classpath [WARN] [NativeCodeLoader] Unable to load native-hadoop library for your platform... using builtin-java classes where applicable [INFO] [Engine] Extracting datasource params... [INFO] [WorkflowUtils$] No 'name' is found. Default empty String will be used. [INFO] [Engine] Datasource params: (,DataSourceParams(3)) [INFO] [Engine] Extracting preparator params... [INFO] [Engine] Preparator params: (,Empty) [INFO] [Engine] Extracting serving params... [INFO] [Engine] Serving params: (,Empty) [WARN] [Utils] Your hostname, fraukojiro resolves to a loopback address: 127.0.1.1; using 192.168.254.105 instead (on interface wlan0) [WARN] [Utils] Set SPARK_LOCAL_IP if you need to bind to another address [INFO] [Remoting] Starting remoting [INFO] [Remoting] Remoting started; listening on addresses :[akka.tcp://[email protected]:37397] [INFO] [Engine$] EngineWorkflow.train [INFO] [Engine$] DataSource: com.wern.DataSource@653fb8d1 [INFO] [Engine$] Preparator: com.wern.Preparator@93501be [INFO] [Engine$] AlgorithmList: List(com.wern.ALSAlgorithm@3c25cfe1) [INFO] [Engine$] Data santiy check is on. [ERROR] [HBPEvents] The appId 3 does not exist. Please use valid appId. Exception in thread "main" java.lang.Exception: HBase table not found for appId 3. at io.prediction.data.storage.hbase.HBPEvents.checkTableExists(HBPEvents.scala:54) at io.prediction.data.storage.hbase.HBPEvents.find(HBPEvents.scala:70) at com.wern.DataSource.readTraining(DataSource.scala:32) at com.wern.DataSource.readTraining(DataSource.scala:18) at io.prediction.controller.PDataSource.readTrainingBase(DataSource.scala:41) at io.prediction.controller.Engine$.train(Engine.scala:518) at io.prediction.controller.Engine.train(Engine.scala:147) at io.prediction.workflow.CoreWorkflow$.runTrain(CoreWorkflow.scala:61) at io.prediction.workflow.CreateWorkflow$.main(CreateWorkflow.scala:258) at io.prediction.workflow.CreateWorkflow.main(CreateWorkflow.scala) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:358) at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75) at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) Basically it doesn't recognize the appId which I supplied. Executing `pio app list` however shows that the ID is indeed 3. [INFO] [App$] Name | ID | Access Key | Allowed Event(s) [INFO] [App$] TestRecommendation | 2 | GJBuFYODWTwFBVQ2D2nbBFW5C0iKClNLEMbYGGhDGoZGEtLre62BLwLJlioTEeJP | (all) [INFO] [App$] MyGenericRecommendationApp | 3 | C7vfcipXd0baQcZYzqr73EwSPT2Bd0YW1OTLgEdlUA9FOeBja6dyBVIKaYnQbsUO | (all) [INFO] [App$] Finished listing 2 app(s). Any ideas? Answer: Looks like your question is already answered here <https://groups.google.com/forum/#!topic/predictionio-user/W1P4T2tTreQ>
Django error: relation "users_user" does not exist Question: I'm getting the following error during migration: > django.db.utils.ProgrammingError: relation "users_user" does not exist File "/Users/user/Documents/workspace/api/env/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Users/user/Documents/workspace/api/env/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/user/Documents/workspace/api/env/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/user/Documents/workspace/api/env/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) This is my model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from ..managers.user import UserManager class User(AbstractBaseUser, PermissionsMixin): # Email identifier, primary key, unique identifier for the user. email = models.EmailField(verbose_name='email address', max_length=254, unique=True, db_index=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = 'User' app_label = "users" def __unicode__(self): return self.email @property def get_full_name(self): return self.email @property def get_short_name(self): return self.email def has_module_perms(self, app_label): """ Does the user have permissions to view the app `app_label` """ # Simplest possible answer: Yes, always return True @property def is_staff(self): # Simplest possible answer: All admins are staff return self.is_admin Settings: AUTH_USER_MODEL = 'users.User' Anything I have missed? Answer: Inside your user app, you should have a folder `migrations`. It should only contain `0001_initial.py` and `__init__.py`. Is that correct? Try running `./manage.py sqlmigrate user 0001_initial` and see what it does, because thats where the error comes from
Best algorithm to compare two lists in python Question: I have two lists (list1 and list2) in python filled with an own datatype. I want to compare these to lists and give all elements of these lists to stdout(or somewhere else), but in a specific order(without sorting the lists in any way). List1 and List2 can have elements which are not in the other list, but can also have elements which be in the other list. These elements, beeing in both lists, should output at the same line. But the elements beeing only in one list, should be in the right order too, at the end. Example: List1 = [A,B,C,D,F,H,G]; List2 = [A,C,D,E,H]; output should be: List1 |List2 A A B C C D D E F H H G How can I "sort" in these way? Answer: import difflib, re list_a = ['A', 'B', 'C', 'D', 'F', 'H', 'G'] list_b = ['A', 'C', 'D', 'E', 'H'] for i in difflib.Differ().compare(list_a, list_b): differ_char, letter = re.match(r'([\s\-+]) ([A-Z])', i).groups() choices = [' ' + letter, letter + ' ', letter + ' ' + letter] print choices[['+', '-', ' '].index(differ_char)] # print lines
Algorithm to choose number of random numbers from list in python? Question: I am looking for an efficient way (pseudocode will do) to choose a given number of values randomly from the list preferably "Pythonic way". Values have to come from unique indexes of the list So for example: list = [0,1,2,3,4,5,24] def choose(number_of_values, list): # method return_val = choose(3, list) # return_val = [2, 4, 3] Answer: Its what that [`random.sample`](https://docs.python.org/2/library/random.html#random.sample) is for. >>> import random >>> random.sample([0,1,2,3,4,5,24],3) [2, 24, 5]
Ignore additional keyword arguments in python Question: Imagine I have a function like def foo(x): ... When I call it with the dictionary `{ 'x': 42, 'y': 23 }` as keyword arguments I get an `TypeError`: >>> foo(**{ 'x': 42, 'y': 23 }) ... TypeError: foo() got an unexpected keyword argument 'y' Is there a good way to make a function call with keyword arguments where additional keyword arguments are just ignored? **My solution so far:** I can define a helper function: import inspect def call_with_kwargs(func, kwargs): params = inspect.getargspec(func).args return func(**{ k: v for k,v in kwargs.items() if k in params}) Now I can do >>> call_with_kwargs(foo, { 'x': 42, 'y': 23 }) 42 Is there a better way? Answer: If altering your functions is fine, then just add a catch-all `**kw` argument to it: def foo(x, **kw): # ... and ignore whatever `kw` captured in the function.
File does not exist: /var/www/polls Question: Content of example.wsgi file in /var/www import os import sys import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('~/.virtualenvs/menv/local/lib/python2.7/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('/var/www/example') sys.path.append('/var/www/example/example') os.environ['DJANGO_SETTINGS_MODULE'] = 'example.settings' # Activate your virtual env activate_env=os.path.expanduser("~/.virtualenvs/menv/bin/activate_this.py") execfile(activate_env, dict(__file__=activate_env)) from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Content of example.conf <VirtualHost *:80> ServerAdmin [email protected] ServerName example.redirectme.net ServerAlias www.example.redirectme.net WSGIScriptAlias / /var/www/example.wsgi <Directory /var/www/polls> Order deny,allow Allow from all </Directory> </VirtualHost> polls is the name of the app inside example project Answer: If polls is the name of the app within the example project, your example.conf file should probably have this line: <Directory /var/www/example/polls> instead of this one: <Directory /var/www/polls>
How to find 6 digits in a string in python? Question: An example string is `"CPLR_DUK10_772989_2"`. I want to pick out `"772989"` specifically. I would imagine using `re.findall` is a good way to go about it, however, I don't have a very good grasp on regular expression so I find myself stumped on this one. Here is a sample of code that I thought would work, until I looked at the full list of strings, and saw that it definitely doesn't. I suppose I'm looking for some more robustness! for ad in Ads: num = ''.join(re.findall(numbers,ad)[1:7]) ID.append(num) ID = pd.Series(ID) Other sample strings: `"Teb1_110765"`, `"PAN1_111572_5"`. Answer: The regex you are looking for is p = re.findall(r'_(\d{6})', ad) This will match a six-digit number preceded by an underscore, and give you a list of all matches (_should there be more than one_) **Demo:** >>> import re >>> stringy = 'CPLR_DUK10_772989_2' >>> re.findall(r'_(\d{6})', stringy) ['772989']
python:assignment of list item as true and false Question: I have a Python list and I want to assign all possible combinations of `True` and `False` values to all the elements of the list. Suppose I have list `list1 = ['a', 'b']`, so I want a new list as `[['t','t'],['t','f'],['f','t'],['f','f']]`, which are all the possible combinations of `True` and `False` value of the given list item. If I have `n` element in the given list then I should `2^n` element in my new list and each of the inner lists should contain `n` element either as 't' or 'f'. How can I achieve this? Answer: Use `itertools.product`. >>> import itertools >>> list(itertools.product(["t", "f"], repeat=2)) [('t', 't'), ('t', 'f'), ('f', 't'), ('f', 'f')] >>> list(itertools.product(["t", "f"], repeat=3)) [('t', 't', 't'), ('t', 't', 'f'), ('t', 'f', 't'), ('t', 'f', 'f'), ('f', 't', 't'), ('f', 't', 'f'), ('f', 'f', 't'), ('f', 'f', 'f')] >>> #etc
reduce datetime list by timedelta Question: in python, how I can reduce a datetime list by a timedelta neighborhood? If I have dates = [ dt.datetime(1970, 1, 1, 0, 2), dt.datetime(1970, 1, 1, 0, 3), dt.datetime(1970, 1, 1, 0, 7), dt.datetime(1970, 1, 1, 0, 8) ] and a timedelta delta = dt.timedelta(minutes=2) How I can get this ? expected = [ dt.datetime(1970, 1, 1, 0, 2, 30), dt.datetime(1970, 1, 1, 0, 7, 30) ] # EDIT A example with numbers, if I have this number list numbers = [1,2,6,7] delta = 1 I try to group the nearly values and get a characteristic value (a central value) of the group. The delta is the max distance between the values. for the numbers, the characteristic value is [1.5, 6.5] Because the values are grouped in [1,2] and [6,7] and calculated the average value. Answer: The problem description already gives it away: you want to use the `groupby()` function from `itertools` All that is needed is a slightly smarter `key` function, one that remembers the last state and keeps on giving the same `key` value as long as successive time stamps are closer closer than `delta`. After grouping, transform the found groups to average times, taking care of single time stamps (example included). import datetime as dt from itertools import groupby dates = [ dt.datetime(1970, 1, 1, 0, 2), dt.datetime(1970, 1, 1, 0, 3), dt.datetime(1970, 1, 1, 0, 7), dt.datetime(1970, 1, 1, 0, 8), dt.datetime(1970, 1, 1, 0, 13) ] delta = dt.timedelta(minutes=2) class grouper: def __init__(self, delta): self.delta= delta self.last = None def __call__(self, tm): # we keep on returning the same key as long as successive time # stamps are within the last time stamp + delta self.last = tm if (self.last is None) or (tm - self.last)>self.delta \ else self.last return self.last # transform the result of groupby into average times def avgtm(item): (key, tms) = item tms = list(tms) # transform generator into list so we can index it return tms[0] + (tms[-1]-tms[0])/2 if len(tms)>1 else tms[0] timestamps = map(avgtm, groupby(dates, key=grouper(delta))) print "Time stamps: ",timestamps Yields output: Time stamps: [datetime.datetime(1970, 1, 1, 0, 2, 30), datetime.datetime(1970, 1, 1, 0, 7, 30), datetime.datetime(1970, 1, 1, 0, 13)]
Python selenium is_displayed method Question: I want to be able to reach the else statement and not get an exceptions when the element is not displayed. for example: if driver.find_element_by_xpath("/html/body/main/div/article[2]/div[4]/header/div[2]/div/div[3]/a[4]").is_displayed(): print("yeah found it") else: print("not found") Answer: You CANNOT call is_displayed() or any other property on an element that **does not exist**. is_displayed() only would work if the element present in the DOM but hidden or displayed. your program is failing before even reaching the code to check if it is displayed or not. So the possible fix is probably to use some kind of try catch instead from selenium.common.exceptions import NoSuchElementException found = False while not found: try: link = driver.find_element_by_xpath(linkAddress) found = True except NoSuchElementException: time.sleep(2) Example code taken from [here](http://stackoverflow.com/questions/22741591/python-selenium-webdriver- try-except-loop)