text
stringlengths
226
34.5k
Rock, Paper, Scissor, Spock, Lizard in python, Player 2 automatically wins Question: for an exercise we need to recreate the game played by the members of the bigbang theory: Rock, Paper, Scissor, Spock, Lizard. I managed to recreate it almost completely, the only problem is: Player 2 automatically wins. Can someone tell me where I need to change the code and also explain why? import sys t = len(sys.argv) if(t < 2 or t > 3): print("Usage: rpsls.py symbool1 symbool2") exit() i = 1 while (i > 0): a = sys.argv[1] b = sys.argv[2] a = a.lower() b = b.lower() if(a != "rock" and a != "paper" and a != "scissor" and a != "lizard" and a != "spock"): print("What's that? please use a real symbol!") elif(b != "rock" and b != "paper" and b != "scissor" and b != "lizard" and b != "spock"): print("What's that? please use a real symbol!") else: if (a == "paper" and b == "scissor"): s = True i = 0 else: s = False i = 0 if(a == "paper" and b == "rock"): s = True i = 0 else: s = False i = 0 if(a == "rock" and b == "lizard"): s = True i = 0 else: s = False i = 0 if(a == "lizard" and b == "spock"): s = True i = 0 else: s = False i = 0 if(a == "spock" and b == "scissors"): s = True i = 0 else: s = False i = 0 if(a == "scissor" and b == "lizard"): s = True i = 0 else: s = False i = 0 if(a == "lizard" and b == "paper"): s = True i = 0 else: s = False i = 0 if(a == "paper" and b == "spock"): s = True i = 0 else: s = False i = 0 if(a == "spock" and b == "rock"): s = True i = 0 else: s = False i = 0 if(a == "rock" and b == "scissor"): s = True i = 0 else: s = False i = 0 if(a == b): print("It's a tie!") i = 0 exit() if(s == True): print("Player 1 wins!") if(s == False): print("Player 2 wins!") Answer: Each of your if statements has an else. Only one of the if statements can be true, so that means that all the other else statements are evaluated. The result of that is that the last else statement - which sets s to False - will "win", so player 2 wins. You should drop all your else statements, and restructure your code as a series of `if...elif...` blocks: if a == "paper" and b == "scissor": s = True i = 0 elif a == "paper" and b == "rock": (Note, if conditions don't need parentheses.)
Linking library in python Question: I want to use the Cantera library in python. I have been using it for C++ and I am linking my adding these couple lines to my makefile: CANT_LIB = $HOME/usr/local/Cantera201/lib/ CANT_INC = $HOME/usr/local/Cantera201/include/ -I $HOME/usr/local/Cantera201/include/cantera \ with `CANT_LIB` and `CANT_INC` being called when compiling. I have very limited experience with python. Is there an equivalent to linking libraries in python? I have tried adding the cantera path to `PYTHONPATH` but it did not work. I am working on a Linux server on which I do not have access to super user and `python 2.6.6`. Answer: You need to install Cantera's Python module to use it, the raw C/C++ libraries aren't enough. If you install using [the directions on their website](http://www.cantera.org/docs/sphinx/html/install.html) it should be installed to the appropriate Python `site-packages` directory automatically, and [available for use with just `import cantera`](http://www.cantera.org/docs/sphinx/html/cython/migrating.html#importing- the-python-module).
Broke Python on Mac by uninstalling Python wrong, how to get Modules to work again? Question: I'm trying to use Python with the Twisted framework, and have been struggling to get it running. I've got some dirt simple python code: from twisted.internet import reactor reactor.run() Buy when I run `python server.py` I get back: > > File "server.py", line 1, in <module> > from twisted.internet import reactor File > "/Library/Python/2.7/site-packages/twisted/__init__.py", line 53, in > <module> > _checkRequirements() File "/Library/Python/2.7/site- > packages/twisted/__init__.py", line 37, in > _checkRequirements > raise ImportError(required + ": no module named zope.interface.") > ImportError: Twisted requires zope.interface 3.6.0 or later: no module > named zope.interface. > My first assumption was to run `pip install zope.interface` Unfortunately, all I get from this is: > > Requirement already satisfied (use --upgrade to upgrade): > zope.interface in > > /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python > Requirement already satisfied (use --upgrade to upgrade): setuptools > in > > /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python > (from zope.interface) > I also tried `easy_install zope.interface` But that yields similar results: > > Searching for zope.interface > Best match: zope.interface 4.1.1 > zope.interface 4.1.1 is already the active version in easy-install.pth > > Using > /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python > Processing dependencies for zope.interface > Finished processing dependencies for zope.interface > Since apparently zope is installed on my machine, I'm thinking that the problem could possibly be with the python I've got installed. I installed Python3 with brew earlier this year, and I think I may have messed up the python configuration. Any ideas? **Update** The default python that is on mac should work for everything I was trying to do above, I verified this on another mac computer. The problem I was having was that I had corrupted my default python image that came with my mac. By following the post below I was able to create working virtualenv again for my python. Answer: You should do all of your Python work in a [virtualenv](https://virtualenv.readthedocs.org/en/latest/). If you were to make a fresh virtualenv for your Twisted development, and always activate it before working on it, you would have much tighter control over what gets installed and it would be a lot easier to diagnose problems. So please make a new virtualenv and `pip install twisted` in it, and then this problem should go away.
Finding the mode of a list using ONLY loops and creating lists in python Question: I have been trying to figure out how to find the mode of a list **WITHOUT** using sorting functions nor importing any modules for quite awhile now... Here's what I have so far: d = {} def mode(): for i in mode: if i in d: d[i] += 1 else: d[i] = 1 return How do I find the output such as the following: print(mode([1, 5, 6, 1, 1, 2])) [1] print(mode([5, 6, 7, 8, 9])) [5, 6, 7, 8, 9] Thanks a bunch! Answer: You need to count the occurrences in your dict and extract the `max` based on the value returning the list itself if there is no mode. def mode(l): d= {} for i in l: d.setdefault(i, 0) d[i] += 1 mx = max(d,key=d.get) return d[mx] if d[mx] > 1 else l
BioPython AlignIO ValueError says strings must be same length? Question: Input fasta-format text file: <http://www.jcvi.org/cgi- bin/tigrfams/DownloadFile.cgi?file=/opt/www/www_tmp/tigrfams/fa_alignment_PF00205.txt> #!/usr/bin/python from Bio import AlignIO seq_file = open('/path/to/fa_alignment_PF00205.txt') alignment = AlignIO.read(seq_file, "fasta") Error: ValueError: Sequences must all be the same length The input sequences shouldn't have to be the same length since on ClustalOmega you can align sequences of differing lengths. This also doesn't work...gets the same error: alignment = AlignIO.parse(seq_file,"fasta") for record in alignment: print(record.id) **Does anybody who is familiar with BioPython know how to get around this to align sequences from fasta files?** Answer: Pad the sequence that is too short and write the records to to a temporary FASTA file. Than your alignments works as expected: from Bio import AlignIO from Bio import SeqIO from Bio import Seq import os input_file = '/path/to/fa_alignment_PF00205.txt' records = SeqIO.parse(input_file, 'fasta') records = list(records) # make a copy, otherwise our generator # is exhausted after calculating maxlen maxlen = max(len(record.seq) for record in records) # pad sequences so that they all have the same length for record in records: if len(record.seq) != maxlen: sequence = str(record.seq).ljust(maxlen, '.') record.seq = Seq.Seq(sequence) assert all(len(record.seq) == maxlen for record in records) # write to temporary file and do alignment output_file = '{}_padded.fasta'.format(os.path.splitext(input_file)[0]) with open(output_file, 'w') as f: SeqIO.write(records, f, 'fasta') alignment = AlignIO.read(output_file, "fasta") print alignment This outputs: SingleLetterAlphabet() alignment with 104 rows and 275 columns TKAAIELIADHQ.......LTVLADLLVHRLQ..AVKELEALLA...QAL SP|A2VGF0.1/208-339 LQELASVINQHE...KV..MLFCGHGCR...Y..AVEEVMALAK...EDL SP|A3D4X6.1/190-319 IKKIAQAIEKAK...KP..VICAGGGVINS.N..ASEELLTLSR...KEL SP|A3DID9.1/192-327 IDEAAEAINKAE...RP..VILAGGGVSIA.G..ANKELFEFAT...QLL SP|A3DIY4.1/192-327 IEKAIELINSSQ...RP..FICSGGGVISS.E..ASEELIQFAE...KIL SP|A4XHS0.1/191-326 IKRAVEAIENSQ...RP..VICSGGGVIAS.R..ASDELKILVE...SEI SP|A4XIL5.1/194-328 VRQAARIIMESE...RP..VIYAGGGVRIS.G..AAPELLELSE...RAL SP|A5D4V9.1/192-327 LQALAQRILRAQ...RP..VIITGDEIVKS.D..ALQAAADFAS...LQL SP|A5ECG1.1/192-328 VEKAVELLWSAR...RV..LVISGRGAR...G..AGPELIGLLD...RAM SP|A5EDH4.1/198-324 IQKAARLIETAE...KP..VIIAGHGVNIS.G..ANEELKTLAE...KSL SP|A5FR34.1/193-328 LDALARDLDSAA...RV..TIYAGIGAR...G..AAARVVQLAG...EAL SP|A5FTR0.1/189-317 VADVAALLRAAR...RP..VIVAGGGVIHSG...AEERLATFAA...DAL SP|A5G0X6.1/217-351 IAEAVSALKGAK...RP..IIYTGGGLINS.GPESAELIVQLAK...RAL SP|A5G2E1.1/199-336 LKKAAEIINRAK...RP..LIYAGGGITLA.G..ASAELRALAA...ALL SP|A5GC69.1/192-327 CRDIVGKLLQSH...RP..VVLGGTGVRLS.R..TEQRLLALVE...DVF SP|A5W0I1.1/200-336 LDQAALKLAAAE...RP..MIIAGGGA..L.H..AAEQLAQLSA...AGL SP|A5W220.1/196-326 LQRAADILNTGH...KV..AILVGAGAL...Q..ATEQVIAIAE...RAL SP|A5W364.1/198-328 IRKAAEMLLAAK...RP..VVYSGGGVILG.G..GSEALTEIAK...SEM SP|A5W954.1/196-331 ... LTELQERLANAQ...RP..VVILGGSRWSD.A..AVQQFTRFAE...... SP|Q220C3.1/190-328
GAE/P transaction using static method Question: I'm trying to figure out how to organize app engine code with transactions. Currently I have a separate python file with all my transaction functions. For transactions that are closely related to entities, I was wondering if it made sense to use a `@staticmethod` for the transaction. Here is a simple example: class MyEntity(ndb.Model): n = ndb.IntegerProperty(default=0) @staticmethod @ndb.transactional # does the order of the decorators matter? def increment_n(my_entity_key): my_entity = my_entity_key.get() my_entity.n += 1 my_entity.put() def do_something(self): MyEntity.increment_n(self.key) It would be nice to have `increment_n` associated with the entity definition, but I have never seen anyone do this so I was wondering if this would be a bad idea. MY SOLUTION: Following Brent's answer, I've implemented this: class MyEntity(ndb.Model): n = ndb.IntegerProperty(default=0) @staticmethod @ndb.transactional def increment_n_transaction(my_entity_key): my_entity = my_entity_key.get() my_entity.increment_n() def increment_n(self): self.n += 1 self.put() This way I can keep entity related code all in one place and I can easily use the transactional version or not as needed. Answer: Yes, it makes sense to use a `@staticmethod` in this case, since the function doesn't use a class or an instance (`self`). And yes, the order of decorators is important, as noted in @Kekito's later answer.
Time Looping Python Question: How can I write code to loop in time python? I want this code loop 10 minutes in python. msList =[] msg = str(raw_input('Input Data :')) msgList.append(msg) I do not wanna use `crontab` because I want this code looping in my program. Answer: Use the `sleep` function from the `time` module. This should do what you're asking: from time import sleep msList =[] while True: msg = str(raw_input('Input Data :')) msgList.append(msg) sleep(600)
Insert into MySQl database after reading csv file? Question: I have a csv file like this: [email protected], 01-05-2014 [email protected], 01-05-2014 [email protected], 01-05-2014 [email protected], 01-05-2014 I need to read the above csv file and extract domain name and also the count of emails address by domain name and date as well. All these things I need to insert into MySQL database but somehow I am stuck how to insert into MySQL database after iterating the list I got. Query will be like this: INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES (%s, %s, %s); Below is the code #!/usr/bin/python import fileinput import csv import os import sys import MySQLdb from collections import defaultdict lst = defaultdict(list) d_lst = defaultdict(list) # ======================== Defined Functions ====================== def get_file_path(filename): currentdirpath = os.getcwd() # get current working directory path filepath = os.path.join(currentdirpath, filename) return filepath # =========================================================== def read_CSV(filepath): domain_list = [] domain_date_list = [] sorted_domain_list_bydate = defaultdict(list) with open(filepath, 'rb') as csvfile: reader = csv.reader(csvfile) for row in reader: # insert the 1st & 2nd column of the CSV file into a set called input_list email = row[0].strip().lower() date = row[1].strip() domain_date_list.append([date, email[ email.find("@") : ]]) domain_list.append(email[ email.find("@") : ]) for k, v in domain_date_list: sorted_domain_list_bydate[k].append(v) # remove duplicates from domain list domain_list = list(set(domain_list)) return sorted_domain_list_bydate, domain_list # =========================================================== def update_DB(lst): # open a database connection db = MySQLdb.connect(host="localhost", # your host, usually localhost user="root", # your username passwd="abcdef1234", # your password db="test") # name of the data base cur = db.cursor() a = [] for k, v in lst.items(): # now what should I do here? # this is what I am confuse db.commit() db.close() # ========================================================== # ======================= main program ======================================= path = get_file_path('emails.csv') [lst, d_lst] = read_CSV(path) # read the input file update_DB(lst) # insert data into domains table I am confuse in `update_DB` method. Answer: I am not sure why you have such a complicated program for a simple task. Lets start from the top: 1. You need to first organize your data correctly by domain, date and then count. import csv from collections import defuaultdict, Counter domain_counts = defaultdict(Counter) with open('somefile.csv') as f: reader = csv.reader(f) for row in reader: domain_counts[row[0].split('@')[1].strip()][row[1]] += 1 2. Next, you need to insert each _row_ correctly in the database: db = MySQLdb.connect(...) cur = db.cursor() q = 'INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, %s)' for domain, data in domain_counts.iteritems(): for email_date, email_count in data.iteritems(): cur.execute(q, (domain, email_count, email_date)) db.commit() * * * As your dates are not being inserted correctly, try this updated query instead: q = """INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, STR_TO_DATE(%s, '%d-%m-%Y'))"""
Python connection to Oracle database Question: I am writing a Python script to fetch and update some data on a remote oracle database from a Linux server. I would like to know how can I connect to remote oracle database from the server. Do I necessarily need to have an oracle client installed on my server or any connector can be used for the same? And also if I use `cx_Oracle` module in Python, is there any dependency that has to be fulfilled for making it work? Answer: You have to Install Instance_client for cx_oracle driver to interact with remote oracle server <http://www.oracle.com/technetwork/database/features/instant- client/index-097480.html>. Use SQLAlchemy (Object Relational Mapper) to make the connection and interact with Oracle Database. The below code you can refer for oracle DB connection. > > > from sqlalchemy import create_engine >>> >>> from sqlalchemy.orm import sessionmaker >>> >>> engine = create_engine('oracle+cx_oracle://test_user:test_user@ORACSG') >>> >>> session_factory = sessionmaker(bind=engine, autoflush=False) >>> >>> session = session_factory() >>> >>> res = session.execute("select * from emp"); >>> >>> print res.fetchall()
Why Response.Cookies is empty? Question: When I run this python script import requests main_page_request = requests.get("http://carkit.kg/") cookie = main_page_request.cookies.get("csrftoken", "") I'm getting proper result, but when I run this code at C#: string url = @"http://carkit.kg"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Debug.Log(response.Cookies["csrftoken"]); // prints "Null" it says that response.Cookies is empty. What is the problem? Answer: You have to add a cookie container to the request. Then it returns the cookie: CookieContainer c = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = c; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Console.WriteLine(response.Cookies["csrftoken"]); // prints "csrftoken=E1iRIi7cQvxvJcnSgOgaEP3XPxTHRUfT"
sending data using post in python to php with variable Question: I have this script and I want to replace the date `2015-05-01` (from and to) with the current date. I am thinking of using **import datetime** and something like this (I am new to python): from StringIO import StringIO import urllib import urllib2 url = 'http://fme.discomap.eea.europa.eu/fmedatastreaming/AirQuality/AirQualityUTDExport.fmw' data = "POSTDATA=FromDate=2015-05-01&ToDate=2015-06-01&Countrycode=&InsertedSinceDate=&UpdatedSinceDate=&Pollutant=PM10&Namespace=&Format=XML&UserToken= " req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() print the_page **New script** from StringIO import StringIO import urllib import urllib2 import datetime i = datetime.datetime.now() // gets the date url = 'http://fme.discomap.eea.europa.eu/fmedatastreaming/AirQuality/AirQualityUTDExport.fmw' data = "POSTDATA=FromDate="i&ToDate="i"&Countrycode=&InsertedSinceDate=&UpdatedSinceDate=&Pollutant=PM10&Namespace=&Format=XML&UserToken=" //i replaced the fixed date with the variable i req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() print the_page Answer: I don't mean to sound harsh, but being new to a language is no excuse for not learning the language's syntax (quite on the contrary). This line: data = "POSTDATA=FromDate="i&ToDate="i"&Countrycode=&InsertedSinceDate=&UpdatedSinceDate=&Pollutant=PM10&Namespace=&Format=XML&UserToken=" is obviously broken and raises a SyntaxError: bruno@bigb:~/Work/playground$ python Python 2.7.3 (default, Jun 22 2015, 19:33:41) >>> data = "POSTDATA=FromDate="i&ToDate="i"&Countrycode=&InsertedSinceDate=&UpdatedSinceDate=&Pollutant=PM10&Namespace=&Format=XML&UserToken=" File "<stdin>", line 1 data = "POSTDATA=FromDate="i&ToDate="i"&Countrycode=&InsertedSinceDate=&UpdatedSinceDate=&Pollutant=PM10&Namespace=&Format=XML&UserToken=" ^ SyntaxError: invalid syntax >>> In this statement the rhs expression actually begins with : * `"POSTDATA=FromDate="` which is a legal literal string * `i&ToDate` which is parsed as "`i`" (identifier) "`&`" (operator) "`ToDate`" (identifier) The mere juxtaposition of a literal string and an identifier (without an operator) is actually illegal: bruno@bigb:~/Work/playground$ python Python 2.7.3 (default, Jun 22 2015, 19:33:41) >>> i = 42 >>> "foo" i File "<stdin>", line 1 "foo" i ^ SyntaxError: invalid syntax >>> Obviously what you want here is string concatenation, which is expressed by the `add` ("`+`") operator, so it should read: "POSTDATA=FromDate=" + i Then since "&ToDate" is supposed to be a string literal instead of an operator and a variable you'd have to quote it: "POSTDATA=FromDate=" + i + "&ToDate=" Then concatenate the current date again: "POSTDATA=FromDate=" + i + "&ToDate=" + i + "etc..." Now in your code `i` (not how I would have named a date BTW but anyway) is a `datetime` object, not a string, so now you'll get a `TypeError` because you cannot concatenate a string with anything else than a string (hopefully - it wouldn't make any sense). FWIW what you want here is not a `datetime` object but the textual ("string") representation of the date in the "YYYY-MM-DD" format. You can get this from the `datetime` object using it's `strftime()` method: today = datetime.datetime.now().strftime("%Y-%m-%d) Now you have a string that you can concatenate: data = "POSTDATA=FromDate=" + today + "&ToDate=" + today + "etc..." This being said: * this kind of operation is usually done using [string formatting](https://docs.python.org/2/library/string.html#string-formatting) * and as Ekrem Dogan mentionned, the simplest solution here is to use a higher-level package that will take care of all the boring details of HTTP requests - `requests` being the de facto standard.
Killing a Python program using ctrl C Question: I have an assignment in school which i can't get around and i'm stuck with. the assignment is to build a program that infinitly spews out random numbers in a EasyGUI messagebox ( Yeah i know EasyGUI is old xD ) this is my source code: import easygui while True: easygui.msgbox(random.randint(-100, 100)) The problem is that when i run this i can't get out of it. I should be allowed to use ctrl+C but that doesn't work. Am i missing something? Thank you in advance! Answer: using signalhandlers does not seem to be a trivial task when it comes to easygui, if you can work with quitting when `x` is pressed you can do the following: while True: e = easygui.msgbox(random.randint(-100, 100)) if e is None: break `e` will either be a string `"OK"` if you press ok or None if `x` is pressed so it is probably the simplest way to quit and end the loop.
Unable to run python script from shell but able to run it from eclipse(PyDev) Question: Python version:2.7 OS: CentOS I have a python project with multiple files spread across different directories. I am able to run this through Eclipse(PyDev). However I am unable to run it from linux shell. The directory structure looks like this: Projectrepo | | __|__ src conf | | | | buildexec.py | | script_variables, list_of_scripts `buildexec.py` is my main script. `script_variables` and `list_of_scripts` are two modules which I am referencing from buildexec.py. I have included `from conf.script_variables import *` in my main script and it is working fine when I run it on eclipse. But, when I try to run it on shell, I get an error `'Traceback (most recent call last): File "buildexec.py", line 6, in <module> from conf.script_variables import * ImportError: No module named conf.script_variables'` I have added PYTHONPATH=/usr/bin/python2.7 and have exported it.. Also, in the main script, I have added `sys.path.append('/home/tejas/Projectrepo/conf')` before importing the modules. Answer: Was a simple solution! My pythonpath was pointing to the default directory /usr/bin/python2.7. I added the location of the user defined modules also in the python path using `export PYTHONPATH=/usr/bin/python2.7:/home/tejas/Projectrepo/conf`
write chinese words in csv file using python2.7 Question: I am trying to write Chinese words like 花花公子昊天鞋类专营店 in a CSV file in python, but not able to do it. I tried solution given here("[issues with writing Chinese to csv file in Python](http://stackoverflow.com/questions/29442448/issues-with-writing- chinese-to-csv-file-in-python)"). Any help will be appreciated. Answer: The module `unicodecsv` helps with that (you can install that with **pip**): import unicodecsv w = unicodecsv.writer(open("test.csv", "w")) w.writerow((u"花花公子昊天鞋类专营店", 78.10)) del w The resulting csv file opens succesfully in OpenOffice. You can also read it back in Python: r = unicodecsv.reader(open("test.csv", "rb")) for row in r: print row[0], row[1] And when run, it should print: (user@motoom) ~/Prj/python $ python chinesecsv.py 花花公子昊天鞋类专营店 78.1
Parse lines into individual segments - python Question: I'm new to python and having issues working with a text file. The text file structure being used is shown. What I'm trying to do is first split the two polylines into their own variable and then split each variable into individual coordinates. The end goal is to have it structured as: polyline 1: [###, ###] [###, ###] polyline 2: [###, ###] [###, ###] Text file structure: Polyline; 1: ###,###; ###,### 2: ###,###; ###,###; ###,### The code I've tried is just working with a single line. While I've been able to split the single line, I have not been able to move to the next step which is to split the line further. f=open('txt.txt', 'r') pl = [] for line in f.read().split('\n'): if (line.find('1: ') !=-1): ln = line.split('1: ') print ln f.close() What is the best way to split the line to the end state? Answer: First of all you can use `with ... as` statement to open a file which will close the file at the end of block , secondly you don't have to read the file and split with `\n` just use a for loop to loop over your file object. Also for checking the start with digit number you can us regex and in this case you can use `re.match` function, then you can split the line with `;` and using a list comprehension split another parts with `,` : import re with open('txt.txt') as f: for line in f: if re.match(r'\d:.*',line): ln = [var.split(',') for var in line.split(';')] print ln
Mongodb lack of precision incrementing floats Question: I have a problem because Mongodb doesn't seem to maintain precision when incrementing floats. For example, the following should yield `2.0`: from decimal import Decimal # for python precision for i in range(40): db.test.update({}, {'$inc': {'count': float(Decimal(1) / 20)}}, upsert=True) print db.test.find_one()['count'] 2.000000000000001 How can I get around this issue? Answer: Unfortunately, you can't -- at least not directly. Mongo stores floating-point numbers as double-precision IEEE floats (<https://en.wikipedia.org/wiki/IEEE_floating_point>), and those rounding errors are inherent to the format. I'm noticing you're using Decimals in your code -- they're converted to Python floats (which are doubles) before being sent to the DB. If you want to keep your true decimal precision, you'll have to store your numbers as stringified Decimals, which means you'll also have to give up Mongo's number-handling facilities such as `$inc`. It is, sadly, a tradeoff you'll be confronted to in most databases and programming languages: IEEE floating-point numbers is the format CPUs natively deal with, and any attempts to stray away from them (to use arbitrary- precision decimals like `decimal.Decimal`) come with a big performance and usability penalty.
how to fetch all the documents of the mongodb collection in python Question: I want to fetch all the documents of the some collection of MongoDB and print certain attributes within each document. But I am unable to do so. My code: import csv from pymongo import MongoClient db_client = MongoClient() db = db_client.pg_new_sw_cur db_collection_users = db.pg_new_sw #with open("pg_details_new.csv",'w') as f: for post in db_collection_users.find(): print post['user_name'] print "===========================" It is printing nothing on the screen after running it when the collection consists of thousands of objects/documents when viewed using robomongo. I am new to MongoDB. So, please help me. Answer: It would be a wild guess, but I suspect that you have specified an incorrect collection name: db_collection_users = db.pg_new_sw Recheck that `pg_new_sw` actually exists in your local `MongoDB` server instance and contains documents inside.
Unique Template Class without __LINE__ or __COUNTER__ Macros Question: First, let me start with what I'm trying to do. I'm working on a library that makes embedding a Python interpreter in C++ code a bit easier, and I'd like to leverage some C++11 features. I'm using std::functions quite heavily, which is a problem since Python makes heavy use of classic function pointers. I've been using fredbaba's solution found at <http://stackoverflow.com/a/18422878> which may not be a good idea, but the reasoning seems sound; for every std::function you'd like a pointer too, you need to create some class or struct with a static function that invokes the std::function of interest, and any class function pointers can point to the static function. However, that means you've got to ensure every struct created is unique; the poster from that thread uses a unique integer as an identifier, which is cumbersome. In my code I use the LINE macro (COUNTER never seems to work), but that of courses forces me to put everything in one file to avoid line number conflicts. I've found similar questions asked but none of them really do it; in order for this to work the identifier has to be a compile time constant, and many of the solutions I've found fail in this regard. Is this possible? Can I cheat the system and get pointers to my std::functions? If you're wondering why I need to... I take a std::function that wraps some C++ function, capture it in yet another function, then store that in a std::list. Then I create a function pointer to each list element and put them in a Python Module I create. // Store these where references are safe using PyFunc = std::function<PyObject *(PyObject *, PyObject *)>; std::list<PyFunc> lst_ExposedFuncs; ... // Expose some R fn(Args...){ ... return R(); } template <size_t idx, typename R, typename ... Args> static void Register_Function(std::string methodName, std::function<R(Args...)> fn, std::string docs = "") { // Capture the function you'd like to expose in a PyFunc PyFunc pFn = [fn](PyObject * s, PyObject * a) { // Convert the arguments to a std::tuple std::tuple<Args...> tup; convert(a, tup); // Invoke the function with a tuple R rVal = call<R>(fn, tup); // Convert rVal to some PyObject and return return alloc_pyobject(rVal); }; // Use the unique idx here, where I'll need the function pointer lst_ExposedFunctions.push_back(pFn); PyCFunction fnPtr = get_fn_ptr<idx>(lst_ExposedFunctions.back()); } From there on I actually do something with fnPtr, but it's not important. Is this crazy? Can I even capture a function like that? John Answer: I do something vaguely similar for a similar use case (actually a class factory for use with a JNI). My technique is to use a `template struct` on an `unsigned` with a specialisation for 0: Each `struct` contains a function - you could adapt this to a `static` member for which a pointer would be valid. I also show how you could call a function `foo` with a parameter dependent on a particular specialisation (not sure you need this, but included just in case). extern bar* foo(const unsigned& id); // The function that gets called template<unsigned N> struct Registrar { static bar* func() { return foo(N - 1); } private: Registrar<N - 1> m_next; // Instantiate the next one. }; template<> struct Registrar<0> // To block the recursion { }; namespace { Registrar</*ToDo - total number here*/> TheRegistrar; } `TheRegistrar` is pretty much a metasyntactic variable which ensures that a given number of specialisations, and hence `static` functions are created. (For various technical reasons I have to instantiate my templates in reverse order: if you don't need that then you can adjust accordingly.) I imagine it's the interplay between `func` and `foo` that you'll need to adapt to your needs. Each `N`, of course, is that _compile-time_ constant that you seek.
Python - Control window with pywinauto while the window is minimized or hidden Question: **What I'm trying to do:** I'm trying to create a script in python with pywinauto to automatically install notepad++ in the background (hidden or minimized), notepad++ is just an example since I will edit it to work with other software. **Problem:** The problem is that I want to do it while the installer is hidden or minimized, but if I move my mouse the script will stop working. **Question:** How can I execute this script and make it work, while the notepad++ installer is hidden or minimized. **This is my code so far** : import sys, os, pywinauto pwa_app = pywinauto.application.Application() app = pywinauto.Application().Start(r'npp.6.8.3.Installer.exe') Wizard = app['Installer Language'] Wizard.NextButton.Click() Wizard = app['Notepad++ v6.8.3 Setup'] Wizard.Wait('visible') Wizard['Welcome to the Notepad++ v6.8.3 Setup'].Wait('ready') Wizard.NextButton.Click() Wizard['License Agreement'].Wait('ready') Wizard['I &Agree'].Click() Wizard['Choose Install Location'].Wait('ready') Wizard.Button2.Click() Wizard['Choose Components'].Wait('ready') Wizard.Button2.Click() Wizard['Create Shortcut on Desktop'].Wait('enabled').CheckByClick() Wizard.Install.Click() Wizard['Completing the Notepad++ v6.8.3 Setup'].Wait('ready', timeout=30) Wizard['CheckBox'].Wait('enabled').Click() Wizard.Finish.Click() Wizard.WaitNot('visible') Answer: The problem is here: Wizard['Create Shortcut on Desktop'].Wait('enabled').CheckByClick() `CheckByClick()` uses `ClickInput()` method that moves real mouse cursor and performs a realistic click. Use `Check()` method instead. [EDIT] If the installer doesn't handle BM_SETCHECK properly the workaround may look so: checkbox = Wizard['Create Shortcut on Desktop'].Wait('enabled') if checkbox.GetCheckState() != pywinauto.win32defines.BST_CHECKED: checkbox.Click() I will fix it in the next pywinauto release by creating methods `CheckByClick` and `CheckByClickInput` respectively. * * * [EDIT 2] I tried your script with my fix and it works perfectly (and very fast) with and without mouse moves. Win7 x64, 32-bit Python 2.7, pywinauto 0.5.3, run as administrator. import sys, os, pywinauto app = pywinauto.Application().Start(r'npp.6.8.3.Installer.exe') Wizard = app['Installer Language'] Wizard.Minimize() Wizard.NextButton.Click() Wizard = app['Notepad++ v6.8.3 Setup'] Wizard.Wait('visible') Wizard.Minimize() Wizard['Welcome to the Notepad++ v6.8.3 Setup'].Wait('ready') Wizard.NextButton.Click() Wizard.Minimize() Wizard['License Agreement'].Wait('ready') Wizard['I &Agree'].Click() Wizard.Minimize() Wizard['Choose Install Location'].Wait('ready') Wizard.Button2.Click() Wizard.Minimize() Wizard['Choose Components'].Wait('ready') Wizard.Button2.Click() Wizard.Minimize() checkbox = Wizard['Create Shortcut on Desktop'].Wait('enabled') if checkbox.GetCheckState() != pywinauto.win32defines.BST_CHECKED: checkbox.Click() Wizard.Install.Click() Wizard['Completing the Notepad++ v6.8.3 Setup'].Wait('ready', timeout=30) Wizard.Minimize() Wizard['CheckBox'].Wait('enabled').Click() Wizard.Finish.Click() Wizard.WaitNot('visible')
scipy.io.savemat How to save global variables? Question: I'm trying to use Python like one would do in Matlab. Basically I have some Python code for which I have run and it has generated some global variables. Say, a = 5 b = 3 I would like to save these to a .mat file , that will be openable by Matlab. The goal is to be able to see the global variables in Matlab, just as one would when saving to a .mat file in Matlab. I've seen examples where savemat is used to save dictionaries/arrays, but not where it saves the global variables. How may I do so? Is this something that scipy just cannot do? Thanks. Answer: You most probably don't want to save globals, but locals (though the variables are local to the interpreter). You can access and update them through the `locals()` and `globals()` functions. From there you can use your preferred method of storage, such as [pickle](https://docs.python.org/3/library/pickle.html), [marshal](https://docs.python.org/3/library/marshal.html), [json](https://docs.python.org/3/library/json.html) or others, depending on which level of security you want and which object types you have at hand. However, be wary that messing with those functions may get you into some trouble, since they also report functions and some internal variables. However, if you intend to (like Matlab) just load and store variables through the GUI, you may want to check the **[Spyder IDE](http://pythonhosted.org/spyder/)** ([GitHub project](https://github.com/spyder-ide/spyder)). It is a very nice IDE, geared toward scientific usage and very similar (in appearance) to Matlab's old interface. Most importantly, it offers a tab/pane named "**Variable explorer** " which tracks what you want to store, and have both a "**Save data as...** " and "**Import data** " buttons and the "Save data as..." dialog supports saving to Spyder data files (_.spydata), Matlab files (_.mat) and HDF5 (*.h5). If you want to do this programatically, you may check how Spyder does it.
randint in Python 3.5 doesn't work Question: I am a new to Python, and I ran into some issues when developing a _D &D Dice_ program. import random print("Hi,here you can roll all D´n´D Dice´s!") dice=input("What dice do u want?D4,D6,D8,D10,D12,D20 or D100?") if dice=="D4" or "d4": print(random.randint(1,4)) elif dice=="D6" or "d6": print(random.randint(1,6)) elif dice=="D8" or "d8": print(random.randint(1,8)) elif dice=="D10"or"d10": print(random.randint(1,10)) elif dice=="D12"or"d12": print(random.randint(1,12)) elif dice=="D20"or"d20": print(random.randint(1,20)) elif dice=="D100"or"d100": print(random.randint(1,100)) else: print("No?Ok!") When I run the program and enter the number of dice, it always enter the first `if` statement. Answer: You want to write: if dice=="D4" or dice=="d4": instead of: if dice=="D4" or "d4": `"d4"` by itself has a (true) boolean value because it isn't an empty string.
Select option from dynamic dropdown list using selenium Question: I am trying to fill out the dropdown menus found on this [homepage](http://www.tirerack.com/content/tirerack/desktop/en/homepage.html) using Python and the selenium package. To Select Make I am using the following code from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.support.select import Select driver = webdriver.Firefox() driver.implicitly_wait(5) driver.get('http://www.tirerack.com/content/tirerack/desktop/en/homepage.html') button = driver.find_element_by_tag_name('button') ActionChains(driver).click(button).perform() select_make = driver.find_element_by_id('vehicle-make') Select(select_make).select_by_value("BMW") However this does not seem to actually "Select the BMW" option. I tried to follow the method explained in [this](http://sqa.stackexchange.com/questions/1355/what-is-the-correct-way-to- select-an-option-using-seleniums-python-webdriver) post. Can someone show me what I am doing wrong? Answer: From the question you linked to the accepted answer iterates over the options and finds the matching text. select_make = driver.find_element_by_id('vehical-make') for option in select_make.find_elements_by_tag_name('option'): if option.text == 'BMW': option.click() # select() in earlier versions of webdriver break Running this in Java I got the message that the element is not visible, so I forced it: WebDriver driver = new FirefoxDriver(); driver.get("http://www.tirerack.com/content/tirerack/desktop/en/homepage.html"); Thread.sleep(3000); driver.findElement(By.tagName("button")).click(); WebElement select_make = driver.findElement(By.id("vehicle-make")); select_make.click(); JavascriptExecutor js = (JavascriptExecutor) driver; String jsDisplay = "document.getElementById(\"vehicle-make\").style.display=\"block\""; js.executeScript(jsDisplay, select_make); for (WebElement option : select_make.findElements(By.tagName("option"))) { System.out.println(option.getText()); if ("BMW".equals(option.getText())) { option.click(); break; } } If you add the JavascriptExecutor lines (in python) I think it will work.
Python Tkinter: Reading Serial Values Question: I would like to read serial values into my Tkinter GUI. Either into a text window or eventually to a text label widget which updates every second or so. The issue I am having is with the queue class. The error I am getting is: AttributeError: 'Applcation' object has no attribute 'queue' Here is my code: #!/usr/bin/env python from tkinter import * from tkinter import messagebox from time import sleep import picamera import os import serial import sys import RPi.GPIO as GPIO import _thread import threading import random import queue # Setup GPIO pin(s) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18, GPIO.OUT) GPIO.output(18, False) #============================================================== # Declaration of Constants # none used #============================================================== class SerialThread(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue.Queue() def read_sensor_values(self): ser = serial.Serial('/dev/ttyUSB0', 9600) while True: if ser.inWaiting: text = ser.readline(s.inWaiting) self.queue.put(text) self.pressures_txt.insert(0.0,values) class Application(Frame): """ GUI Application for taking photos. """ def __init__(self, master): super(Application, self).__init__(master) self.grid() self.create_widgets() self.setup_camera() def create_widgets(self): Checkbutton( self, text = "Read Pressure Values", variable = self.mode2, command = self.process_serial, bg = 'white').grid(row = 4, column = 0, sticky = W+E+N+S) # create text field to display pressure values from arduino self.pressures_txt = Text(self, height = 3, wrap = WORD) self.pressures_txt.grid(row=9, column = 0, columnspan =3) def process_serial(self): #self.text.delete(1.0, END) while self.queue.qsize(): try: self.text.insert(END, self.queue.get()) self.pressures_txt.insert(0.0, self.queue.get()) except queue.Empty: pass self.after('1000', self.process_serial) #................. end of method: read_sensor_values ................ #================================================================= # main #================================================================= root = Tk() # Create the GUI root object root.title("Control V1.0") app = Application(root) # Create the root application window root.mainloop() The code I have posted is an abbreviated version of the entire program. I have removed sections that are supposedly irrelevant. I am running in python3. I suspect I may have an error in indentation but I am not certain. I am using the code from the following link for my serial reading class: <https://www.daniweb.com/programming/software- development/threads/496499/using-a-checkbutton-to-import-serial-data-into- python-tkinter> Answer: The problem is that the `self.queue` in `read_sensor_values` belongs to a `SerialThread` object. When you say `self.queue` in the `process_serial` method of your `Application` object, it refers to a non-existent `queue` attribute of the `Application` object. Perhaps you ought to make the `SerialThread` object an attribute of your `Application` object. Then `process_serial` could refer to `self.serial.queue` or whatever you name it.
generic scoring module using python pandas Question: Hi I'm trying to develop a generic scoring module for grading students based on variety of attributes. I'm trying to develop a generic method using python pandas Input: An input data frame with student ID and UG Major and attributes for scoring (I called df_input) An input ref. data frame that contains scoring params Process: Based on the variable type, developing a process to calculate scores for each attribute Output: Input data frame with added cols that capture the attribute score Example: df_input + ------------+-----------+----+------------+-----+------+ | STUDENT_ID | UG_MAJOR | C1 | C2 | C3 | C4 | +------------+-----------+----+------------+-----+------+ | 123 | MATH | A | 8000-10000 | 12% | 9000 | | 234 | ALL_OTHER | B | 1500-2000 | 10% | 1500 | | 345 | ALL_OTHER | A | 2800-3000 | 8% | 2300 | | 456 | ALL_OTHER | A | 8000-10000 | 12% | 3200 | | 980 | ALL_OTHER | C | 1000-2500 | 15% | 2700 | +------------+-----------+----+------------+-----+------+ df_ref + ---------+---------+---------+ | REF_COL | REF_VAL | REF_SCR | +---------+---------+---------+ | C1 | A | 10 | | C1 | B | 20 | | C1 | C | 30 | | C1 | NULL | 0 | | C1 | MISSING | 0 | | C1 | A | 20 | | C1 | B | 30 | | C1 | C | 40 | | C1 | NULL | 10 | | C1 | MISSING | 10 | | C2 | <1000 | 0 | | C2 | >1000 | 20 | | C2 | >7000 | 30 | | C2 | >9500 | 40 | | C2 | MISSING | 0 | | C2 | NULL | 0 | | C3 | <3% | 5 | | C3 | >3% | 10 | | C3 | >5% | 100 | | C3 | >7% | 200 | | C3 | >10% | 300 | | C3 | NULL | 0 | | C3 | MISSING | 0 | | C4 | <5000 | 10 | | C4 | >5000 | 20 | | C4 | >10000 | 30 | | C4 | >15000 | 40 | +---------+---------+---------+ +------------+-----------+----+------------+-----+------+--------+--------+--------+---------+ | Req.Output | | | | | | | | | | +------------+-----------+----+------------+-----+------+--------+--------+--------+---------+ | STUDENT_ID | UG_MAJOR | C1 | C2 | C3 | C4 | C1_SCR | C2_SCR | C3_SCR | TOT_SCR | | 123 | MATH | A | 8000-10000 | 12% | 9000 | | | | | | 234 | ALL_OTHER | B | 1500-2000 | 10% | 1500 | | | | | | 345 | ALL_OTHER | A | 2800-3000 | 8% | 2300 | | | | | | 456 | ALL_OTHER | A | 8000-10000 | 12% | 3200 | | | | | | 980 | ALL_OTHER | C | 1000-2500 | 15% | 2700 | | | | | +------------+-----------+----+------------+-----+------+--------+--------+--------+---------+ I want to see if any thing like a function be developed to accomplish this Thank you Pari Answer: If I understand the question correctly, you are trying to store a collection of rules in `df_ref` that are to be applied to `df_input` to generate scores. While this certainly can be done, you should make sure that your rules are well defined. This would also guide you in writing the corresponding scoring function. For instance, suppose one of the students gets a value of `10000` in column `C3`. `10000` is larger than `1000`, `7000` and `9500`. This means that the score is ambiguous. Suppose you want to choose the highest of all scores from this particular column. Then, you need another table specifying the choice rule for each column when multiple scores are selected. Second, you should think about the type of Python variable stored in 'REF_VAL' column. If `>7000` is a string, you would have to do extra work to determine the score. Consider storing this as `7000` instead and specifying comparison operator elsewhere. Finally, looking at your current rules, there seems to be a pattern. Each score is associated with `NULL`, `MISSING` or a range cutoff. This can be captured as follows: import pandas as pd import numpy as np from itertools import dropwhile # stores values and scores for special values and cutoff values sample_range_rule = { 'MISSING' : 0, 'NULL' : 0, 'VALS' : [ (0, 0), (10, 50), (70, 75), (90, 100), (100, 100) ] } # takes a dict with rules and produces a scoring function def getScoringFunction(range_rule): def score(val): if val == 'MISSING': return range_rule['MISSING'] elif val == 'NULL': return range_rule['NULL'] else: return dropwhile(lambda (cutoff, score): cutoff < val, range_rule['VALS']).next()[1] return score sample_scoring_function = getScoringFunction(sample_range_rule) for test_value in ['MISSING', 'NULL', 0, 12, 55, 66, 99]: print 'Input', test_value, print 'Output', sample_scoring_function(test_value) After you have a dict specifying a rule for every column, you can do the following: `df['Ck_SCR'] = df['Ck'].apply(getScoringFunction(Ck_dct))` Converting pandas DataFrame with two columns to a dict of this form should not be to difficult.
MySQL special chars lost when queried in Python. (But works with Django.) Question: I have a MySQL database that is utf8 encoded. It contains a row with a value "sauté". Note the accent over the e. When I select this data using a Django application then it correctly detects the é. However, when I execute it as a Python program then this information (the special e) seems to be lost. I've tried various combinations of encode and decode and "from **future** import unicode_literals" and putting a "u" in front of the sauté string and putting a u in front of the query string. No luck. How can I get this info correctly out of my database (with Python) and test for it? # Connection when excute as .py: (Django is usual in settings.py) cursor = MySQLdb.connect(host='<xxx>',user="<xxx>", passwd="<xxx>", db="<xxx>", unix_socket = 'path/mysql.sock' ).cursor() # Same code in Django and Python execution: cursor.execute(select line from my_table where id = 27) results = cursor.fetchall() for r in results: line = r[0] if re.search("sauté", line): do_something() # Should get here, but only with Django Answer: Thanks to JD Vangsness (in the comments) for the answer. I needed to add charset='utf8' to the connection parameters. cursor = MySQLdb.connect(host='<xxx>',user="<xxx>", charset='utf8', passwd="<xxx>", db="<xxx>", unix_socket = 'path/mysql.sock').cursor() And then I also needed to make the comparison string unicode: u"sauté"
IGNORECASE errors in Python's re.Scanner? Question: There is hidden but well known [functionality](http://code.activestate.com/recipes/457664-hidden-scanner- functionality-in-re-module/) in re module import re def s_ident(scanner, token): return token def s_operator(scanner, token): return "op%s" % token def s_float(scanner, token): return float(token) def s_int(scanner, token): return int(token) scanner = re.Scanner([ (r"[a-zA-Z]\w*", s_ident), (r"\d+\.\d*", s_float), (r"\d+", s_int), (r"=|\+|-|\*|/", s_operator), (r"\s+", None), ]) print scanner.scan("Sum = 3*foo + 312.50 + bar") # (['Sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], '') I want to use IGNORECASE flag here but it seems it does not work: import re def s_ident(scanner, token): return token def s_operator(scanner, token): return "op%s" % token def s_float(scanner, token): return float(token) def s_int(scanner, token): return int(token) scanner = re.Scanner([ (r"(?i)[a-z]\w*", s_ident), (r"\d+\.\d*", s_float), (r"\d+", s_int), (r"=|\+|-|\*|/", s_operator), (r"\s+", None), ]) print scanner.scan("Sum = 3*foo + 312.50 + bar") # ([], 'Sum = 3*foo + 312.50 + bar') Is it a issue of the Scanner or error in my code? Is it possible to implement non-case-sensitive matching using Scanner? This issue was initially reproduced on Python 2.7.9. Expected value: (['Sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], '') Actual value: ([], 'Sum = 3*foo + 312.50 + bar') Answer: You can pass the `flags` parameter to the constructor. scanner = re.Scanner([ (r"[a-z]\w*", s_ident), (r"\d+\.\d*", s_float), (r"\d+", s_int), (r"=|\+|-|\*|/", s_operator), (r"\s+", None), ], flags=re.IGNORECASE) Source for `Scanner`: <https://github.com/python/cpython/blob/master/Lib/re.py#L345>
Django - Autocomplete_Light's "Add Another" popup declares: "'initial' is an invalid keyword argument for this function" Question: I am working on getting the "add another" popup to work with `django- autocomplete_light`. Following along in the docs: <http://django-autocomplete-light.readthedocs.org/en/latest/addanother.html> I have set up my URLs: import autocomplete_light.shortcuts as al from AlmondKing.FinancialLogs import models from AlmondKing.FinancialLogs import forms urlpatterns = [ url(r'^branches/autocreate/$', al.CreateView.as_view( model=models.CompanyBranch, form_class=forms.CompanyBranch), name='branch_autocreate'), ] and my autocomplete_light_registry.py al.register(CompanyBranch, search_fields=['^branch_name'], attrs={ 'placeholder': 'Branch', 'data-autocomplete-minimum-characters': 1, }, widget_attrs={ 'data-widget-maximum-values': 1, 'class': 'modern-style', }, add_another_url_name='company:branch_autocreate', ) However, when I click the plus sign to add a new related object, I get the following error: > TypeError at /company/branches/autocreate/ > > 'initial' is an invalid keyword argument for this function I've been trying to find a way to do this for a while and I'm so close! Now, I am hoping someone can read the traceback and help me understand what went wrong: Environment: Request Method: GET Request URL: http://localhost:8000/company/branches/autocreate/?_popup=1&winName=id_branch Django Version: 1.8.2 Python Version: 3.4.3 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'AlmondKing.InventoryLogs', 'AlmondKing.FinancialLogs', 'AlmondKing.AKGenius', 'autocomplete_light') Installed Middleware: ('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', 'django.middleware.security.SecurityMiddleware', 'AlmondKing.AKGenius.middleware.RequireLoginMiddleware') Traceback: File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\base.py" in dispatch 89. return handler(request, *args, **kwargs) File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\edit.py" in get 245. return super(BaseCreateView, self).get(request, *args, **kwargs) File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\edit.py" in get 205. form = self.get_form() File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\edit.py" in get_form 74. return form_class(**self.get_form_kwargs()) File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\db\models\base.py" in __init__ 480. raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) Exception Type: TypeError at /company/branches/autocreate/ Exception Value: 'initial' is an invalid keyword argument for this function Answer: Try this: add_another_url_name='company:branch_autocreate', add_another_url_name='branch_autocreate',
Python File handling: standard input and output Question: import sys fileobject=open('file.txt','w') fileobject.write(sys.stdin.readline()) Cat In the above code, shouldn't cat be in file after execution? However, when I run it, I find file empty. If my code is wrong, can someone explain how `sys.stdin.read()` and `sys.stdout.write()` work and their uses? Answer: You need to close the file import sys fileobject = open('file.txt', 'w') fileobject.write(sys.stdin.readline()) Cat fileobject.close() If you want to see the updated file content before closing the file or exiting the program you can use flush(): fileobject.flush() Check this [StackOverflow Question](http://stackoverflow.com/questions/14555402/understanding-stdin- stdout-stderr%20question) for standard input/output
DHT Sensor Python script error Question: I have a sensor type DHT22 connected to a raspberry. I have written a script in python but when I run it I get errors #!/usr/bin/python import MySQLdb import subprocess import re import sys import time import datetime import Adafruit_DHT conn = MySQLdb.connect("localhost","zeus","gee3g673r","logi") while(True): date = time.strftime("%d/%m/%Y") clock = time.strftime("%H:%M") #output = subprocess.check_output(["/usr/bin/AdafruitDHT.py 2302", "4"]); output = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 4) matches = re.search("Temp =\s+([0-9.]+)", output) if (not matches): time.sleep(0) continue temp = float(matches.group(1)) matches = re.search("Hum =\s+([0-9.]+)", output) if (not matches): time.sleep(0) continue humidity = float(matches.group(1)) # MYSQL DATA Processing c = conn.cursor() c.execute("INSERT INTO data_th (date, clock, temp, hum) VALUES (%s, %s,%s, %s)",(date, clock, temp, humidity)) #print "DB Loaded" time.sleep(360) This is the error encountered on running the script: root@raspberrypi:/home# ./hdt.py Traceback (most recent call last): File "./dht.py", line 22, in <module> matches = re.search("Temp =\s+([0-9.]+)", output) File "/usr/lib/python2.7/re.py", line 142, in search return _compile(pattern, flags).search(string) TypeError: expected string or buffer Answer: Adafruit_DHT.read_retry() does not return string. re.search expects string as second parameter. Please have a look at code below (taken from [Adafruit_Python_DHT/examples](https://github.com/adafruit/Adafruit_Python_DHT/blob/master/examples/AdafruitDHT.py)): # Try to grab a sensor reading. Use the read_retry method which will retry up # to 15 times to get a sensor reading (waiting 2 seconds between each retry). humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) # Un-comment the line below to convert the temperature to Fahrenheit. # temperature = temperature * 9/5.0 + 32 # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). # If this happens try again! if humidity is not None and temperature is not None: print 'Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity) else: print 'Failed to get reading. Try again!' sys.exit(1)
a "Pygame error", not able to open .wav file Question: I have a problem with my Pygame program. I need help. The wav file is in the same directory as the python file. I run It in terminal- Python3: import pygame.mixer sounds = pygame.mixer sounds.init() def wait_finish(channel): while channel.get_busy(): pass asked = 0 true = 0 false = 0 choice = str(input("Push 1 for true, 2 for false, 0 to end")) while choice != '0': if choice == '1': asked = asked + 1 true = true + 1 s = sounds.Sound("correct.wav") wait_finish(s.play()) if choice == '2': asked = asked + 1 false = false + 1 s = sounds.Sound("wrong.wav") wait_finish(s.play()) choice = str(input("Push 1 for true, 2 for false, 0 to end")) print ("you asked" +str(asked) + "questions") print ("there were" +str(false) + "wrong answers") print ("and" + str(true) + "correct answers") ...it throws- pygame.error: Unable to open file 'correct.wav' Answer: Rather than have a discussion in the comments section I'll post this. Once `def wait_finish(channnel):` has been altered to `def wait_finish(channel):` and the issue with `sounds.Sound` rather than `sounds.Sounds` has been resolved, the program works fine with normal .wav files on my machine. I am convinced that the error of Sound or Sounds for calling the wrong.wav file to be played would explain the "unable to open file wrong.wav" message. If pygame doesn't like something about the file it may well not play it and this is where a line like: sounds.pre_init(frequency=22050, size=-16, channels=2, buffer=4096) (called before `sounds.init()`) might come into play. (NB you might have to use a different buffer option as I am testing with pygame for python 2.7) On my box, if pygame doesn't like or cannot find the file, I get no error at all but the speakers click when the call to play is made. All I can suggest at this point is that you try an entirely different wav file to the current one you are using for wrong answers and see if it makes a difference. Just for the record, I changed your wait_finish function to : def wait_finish(channel): while channel.get_busy(): pygame.time.Clock().tick(10)
Merging tables from two different databases (Python) Question: I have two databases `Database1.db` and `Database2.db`. The databases contain tables with **matching names and matching columns** (and the Primary key is the 'Date' column in both). The only difference between the two is that the entries in Database1 are from 2013 and the entries in Database2 are from 2014. I would like to merge these two databases so that all the 2013 and 2014 data ends up **in one table** in a third database (let's call it Database3.db). To be clear, here is what the databases I'm working with currently contain and what I want the third resulting database to contain: Database1.db: Table Name: GERMANY_BERLIN Date Morning Day Evening Night 01.01.2013 0.5 0.2 0.2 0.1 02.01.2013 0.4 0.3 0.1 0.2 ... Database2.db: Table Name: GERMANY_BERLIN Date Morning Day Evening Night 01.01.2014 0.6 0.2 0.1 0.1 02.01.2014 0.5 0.2 0.3 0.0 ... I would like to have create a resulting Database3 with the following data: Database2.db: Table Name: GERMANY_BERLIN Date Morning Day Evening Night 01.01.2013 0.5 0.2 0.2 0.1 02.01.2013 0.4 0.3 0.1 0.2 01.01.2014 0.6 0.2 0.1 0.1 02.01.2014 0.5 0.2 0.3 0.0 ... I haven't been able to find anything directly helpful on this online yet (perhaps JOINS could be used somehow? bhttp://www.tutorialspoint.com/sqlite/sqlite_using_joins.htm) so any suggestions would be greatly appreciated! PS. SQLite has been used to create the existing databases and is the database- related Python library that I'm most familiar with Answer: You can easly export a .db into a csv ([How to export sqlite to CSV in Python without being formatted as a list?](http://stackoverflow.com/questions/10522830/how-to-export-sqlite-to- csv-in-python-without-being-formatted-as-a-list)) and import it again into .db ([Importing a CSV file into a sqlite3 database table using Python](http://stackoverflow.com/questions/2887878/importing-a-csv-file-into- a-sqlite3-database-table-using-python)) for the step 1 just append the result to the same cvs file.
Python 3 CSV not writing Question: When I open my csv file I see nothing. Is this the right way to build a csv file? Just trying to learn it all. Thanks for all your help. import csv from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://shop.nordstrom.com/c/designer-handbags?dept=8000001&origin=topnav#category=b60133547&type=category&color=&price=&brand=&stores=&instoreavailability=false&lastfilter=&sizeFinderId=0&resultsmode=&segmentId=0&page=1&partial=1&pagesize=100&contextualsortcategoryid=0") nordHandbags = BeautifulSoup(html) bagList = nordHandbags.findAll("a", {"class":"title"}) f = csv.writer(open("./nordstrom.csv", "w")) f.writerow(["Product Title"]) for title in bagList: productTitles = title.contents[0] f.writerow([productTitles]) Answer: Really hard to see how you could fail to have at least a `"Product Title"` header in that file. Are you checking the file _after_ you have tgerminated the Python interpreter? This, because there is no explicit close of the file in that code, and until it is closed, its contents may be cached in memory. More Pythonic, and avoiding this problem, is with open("./nordstrom.csv", "w") as csvfile: f = csv.writer( csvfile) f.writerow(["Product Title"]) # etc. pass # close the with block, csvfile is now closed. Also (grasping at straws) are you opening the file with a text editor to check it, or just using the `type` command in Windows cmd.exe? Because, if the file doesn't contain an explicit LF, the `C:\wherever\ >`prompt may overwrite the header before you see it.
How to authenticate in django app via C#? Question: I have a python script: import requests main_page_request = requests.get("http://carkit.kg/") csrf_cookie = main_page_request.cookies.get("csrftoken", "") r = requests.post("http://carkit.kg/", data={u'username': u'admin', u'password': u'admin', 'csrfmiddlewaretoken': csrf_cookie }, cookies={'csrftoken': csrf_cookie}) print r.url carkit.kg/ - is a login url in django app. Script prints one url if authentication succeed and another in other case. I tried to rewrite this script in C# (Unity3D game): //get token string url = "http://carkit.kg"; HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create(url); tokenRequest.CookieContainer = new CookieContainer(); HttpWebResponse tokenResponse = (HttpWebResponse)tokenRequest.GetResponse(); String token = tokenResponse.Cookies["csrftoken"].ToString().Split('=')[1]; //login HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(url); loginRequest.Method = "POST"; loginRequest.CookieContainer = new CookieContainer(); loginRequest.ContentType = "application/x-www-form-urlencoded"; loginRequest.CookieContainer.Add(new Cookie("csrftoken", token, "/", "carkit.kg")); String postData = "username=" + tempEmail; postData += "&password=" + tempPass; postData += "&csrfmiddlewaretoken=" + token; byte[] data = Encoding.ASCII.GetBytes(postData); loginRequest.ContentLength = data.Length + 1; Debug.Log(data.Length); loginRequest.Timeout = 3000; String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(tempEmail + ":" + tempPass)); loginRequest.Headers.Add("Authorization", "Basic " + encoded); loginRequest.GetRequestStream().Write(data, 0, data.Length); loginRequest.PreAuthenticate=true; HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse(); But I'm getting error 411 or timed out request. How to get the same result in C# code as in python? Answer: I setted [django rest api url](http://www.django-rest-framework.org/api- guide/authentication/) as simple post request destination and django returned token in data.
How to tell python to reload module whenever it sees import statement Question: I'm writing a program to manage the flow of processing data. User can write code of several method to process data, called 'flow code', and tell my program to compare the result of each method. The code is executed by `exec`. There's also a git repo containing functions to call, and user can import them in the 'flow code'. My question is, because user can change repo between each execution, how to tell python to reload modules when it sees an import statement in 'flow code'? My current solution is that, before executing a line, check type of all local variable of 'flow code' and reload it if the type is `ModuleType`. However, this is very inefficient. Is there any better solution, like hooks? Someone said `imputil` can make hooks, but the documentation says: > Deprecated since version 2.6: The imputil module has been removed in Python > 3. And I'm using python 2.7 Answer: Use reload method. e.g. >>> import test >>> test.a 1 >>> test.a = 3 >>> test.a 3 >>> reload(test) <module 'test' from 'test.pyc'> >>> test.a 1 >>>
a simple python code that astonishingly ignores if condition & statement Question: I have a really simple code here. But the problem is really bothering me. In line no 7, there is a if-condition; astonishingly this if condition is never addressed! I ran the program and checked multiple times using python version 2.7. It behaves as if the if-condition and its statements (along with break) is inside the comment and is simply ignored. from random import randint random_number = randint(1, 10) guesses_left = 3 while (guesses_left>=1): print (random_number) guess = raw_input('Guess ?') if guess == random_number: #this statement is never checked? print ('You win!') break guesses_left -= 1 else: print ('You lose.') Answer: if guess == random_number: #this statement is never checked? It _is_ being checked, but it’s just _always_ false. `guess` is a _string_ since it comes from `raw_input` but `random_number` is an int coming from `randint`. Since a string can never be equal to an int, the expression is always false. You need to convert the input into an int first: `int(guess)`. But make sure you check for errors when the user does not enter a number.
creating daemon using Python libtorrent for fetching meta data of 100k+ torrents Question: I am trying to fetch meta data of around 10k+ torrents per day using python libtorrent. This is the current flow of code 1. Start libtorrent Session. 2. Get total counts of torrents we need metadata for uploaded within last 1 day. 3. get torrent hashes from DB in chunks 4. create magnet link using those hashes and add those magnet URI's in the session by creating handle for each magnet URI. 5. sleep for a second while Meta Data is fetched and keep checking whether meta data s found or not. 6. If meta data is received add it in DB else check if we have been looking for meta data for around 10 minutes , if yes then remove the handle i.e. dont look for metadata no more for now. 7. do above indefinitely. and save session state for future. so far I have tried this. #!/usr/bin/env python # this file will run as client or daemon and fetch torrent meta data i.e. torrent files from magnet uri import libtorrent as lt # libtorrent library import tempfile # for settings parameters while fetching metadata as temp dir import sys #getting arguiments from shell or exit script from time import sleep #sleep import shutil # removing directory tree from temp directory import os.path # for getting pwd and other things from pprint import pprint # for debugging, showing object data import MySQLdb # DB connectivity import os from datetime import date, timedelta session = lt.session(lt.fingerprint("UT", 3, 4, 5, 0), flags=0) session.listen_on(6881, 6891) session.add_extension('ut_metadata') session.add_extension('ut_pex') session.add_extension('smart_ban') session.add_extension('metadata_transfer') session_save_filename = "/magnet2torrent/magnet_to_torrent_daemon.save_state" if(os.path.isfile(session_save_filename)): fileread = open(session_save_filename, 'rb') session.load_state(lt.bdecode(fileread.read())) fileread.close() print('session loaded from file') else: print('new session started') session.add_dht_router("router.utorrent.com", 6881) session.add_dht_router("router.bittorrent.com", 6881) session.add_dht_router("dht.transmissionbt.com", 6881) session.add_dht_router("dht.aelitis.com", 6881) session.start_dht() session.start_lsd() session.start_upnp() session.start_natpmp() alive = True while alive: db_conn = MySQLdb.connect( host = '', user = '', passwd = '', db = '', unix_socket='/mysql/mysql.sock') # Open database connection #print('reconnecting') #get all records where enabled = 0 and uploaded within yesterday subset_count = 100 ; yesterday = date.today() - timedelta(1) yesterday = yesterday.strftime('%Y-%m-%d %H:%M:%S') #print(yesterday) total_count_query = ("SELECT COUNT(*) as total_count FROM content WHERE upload_date > '"+ yesterday +"' AND enabled = '0' ") #print(total_count_query) try: total_count_cursor = db_conn.cursor()# prepare a cursor object using cursor() method total_count_cursor.execute(total_count_query) # Execute the SQL command total_count_results = total_count_cursor.fetchone() # Fetch all the rows in a list of lists. total_count = total_count_results[0] print(total_count) except: print "Error: unable to select data" total_pages = total_count/subset_count #print(total_pages) current_page = 1 while(current_page <= total_pages): from_count = (current_page * subset_count) - subset_count #print(current_page) #print(from_count) hashes = [] get_mysql_data_query = ("SELECT hash FROM content WHERE upload_date > '" + yesterday +"' AND enabled = '0' ORDER BY record_num DESC LIMIT "+ str(from_count) +" , " + str(subset_count) +" ") #print(get_mysql_data_query) try: get_mysql_data_cursor = db_conn.cursor()# prepare a cursor object using cursor() method get_mysql_data_cursor.execute(get_mysql_data_query) # Execute the SQL command get_mysql_data_results = get_mysql_data_cursor.fetchall() # Fetch all the rows in a list of lists. for row in get_mysql_data_results: hashes.append(row[0].upper()) except: print "Error: unable to select data" #print(hashes) handles = [] for hash in hashes: tempdir = tempfile.mkdtemp() add_magnet_uri_params = { 'save_path': tempdir, 'duplicate_is_error': True, 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } magnet_uri = "magnet:?xt=urn:btih:" + hash.upper() + "&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.ccc.de%3A80" #print(magnet_uri) handle = lt.add_magnet_uri(session, magnet_uri, add_magnet_uri_params) handles.append(handle) #push handle in handles list #print("handles length is :") #print(len(handles)) while(len(handles) != 0): for h in handles: #print("inside handles for each loop") if h.has_metadata(): torinfo = h.get_torrent_info() final_info_hash = str(torinfo.info_hash()) final_info_hash = final_info_hash.upper() torfile = lt.create_torrent(torinfo) torcontent = lt.bencode(torfile.generate()) tfile_size = len(torcontent) try: insert_cursor = db_conn.cursor()# prepare a cursor object using cursor() method insert_cursor.execute("""INSERT INTO dht_tfiles (hash, tdata) VALUES (%s, %s)""", [final_info_hash , torcontent] ) db_conn.commit() #print "data inserted in DB" except MySQLdb.Error, e: try: print "MySQL Error [%d]: %s" % (e.args[0], e.args[1]) except IndexError: print "MySQL Error: %s" % str(e) shutil.rmtree(h.save_path()) # remove temp data directory session.remove_torrent(h) # remove torrnt handle from session handles.remove(h) #remove handle from list else: if(h.status().active_time > 600): # check if handle is more than 10 minutes old i.e. 600 seconds #print('remove_torrent') shutil.rmtree(h.save_path()) # remove temp data directory session.remove_torrent(h) # remove torrnt handle from session handles.remove(h) #remove handle from list sleep(1) #print('sleep1') #print('sleep10') #sleep(10) current_page = current_page + 1 #save session state filewrite = open(session_save_filename, "wb") filewrite.write(lt.bencode(session.save_state())) filewrite.close() print('sleep60') sleep(60) #save session state filewrite = open(session_save_filename, "wb") filewrite.write(lt.bencode(session.save_state())) filewrite.close() I tried kept above script running overnight and found only around 1200 torrent's meta data is found in the overnight session. so I am looking for improve the performance of the script. I have even tried Decoding the `save_state` file and noticed there are 700+ `DHT nodes` I am connected to. so its not like `DHT` is not running, What I am planning to do is, `keep the handles active` in session indefinitely while meta data is not fetched. and not going to remove the handles after 10 minutes if no meta data is fetched in 10 minutes, like I am currently doing it. I have few questions regarding the lib-torrent python bindings. 1. How many handles can I keep running ? is there any limit for running handles ? 2. will running 10k+ or 100k handles slow down my system ? or eat up resources ? if yes then which resources ? I mean RAM , NETWORK ? 3. I am behind firewall , can be a blocked incoming port causing the slow speed of metadata fetching ? 4. can DHT server like router.bittorrent.com or any other BAN my ip address for sending too many requests ? 5. Can other peers BAN my ip address if they find out I am making too many requests only fot fetching meta data ? 6. can I run multiple instances of this script ? or may be multi-threading ? will it give better performance ? 7. if using multiple instances of the same script, each script will get unique node-id depending on the ip and port I am using , is this viable solution ? Is there any better approach ? for achieving what I am trying ? Answer: I can't answer questions specific to libtorrent's APIs, but some of your questions apply to bittorrent in general. > will running 10k+ or 100k handles slow down my system ? or eat up resources > ? if yes then which resources ? i mean RAM , NETWORK ? Metadata-downloads shouldn't use much resources since they are not full torrent-downloads yet, i.e. they can't allocate the actual files or anything like that. But they will need some ram/disk space for the metadata itself once they grab the first chunk of those. > I am behind firewall , can be a blocked incoming port causing the slow speed > of metadata fetching ? yes, by reducing the number of peers that can establish connections it becomes more difficult to fetch metadata (or establish any connection at all) on swarms with a low peer count. NATs can cause the same issue. > can DHT server like router.bittorrent.com or any other BAN my ip address for > sending too many requests ? router.bittorrent.com is a bootstrap node, not a server per se. Lookups don't query a single node, they query many different (among millions). But yes, individual nodes can ban, or more likely rate-limit, you. This can be mitigated by looking for randomly distributed IDs to spread the load across the DHT keyspace. > can i run multiple instances of this script ? or may be multi-threading ? > will it give better performance ? AIUI libtorrent is sufficiently non-blocking or multi-threaded that you can schedule many torrents at once. I don't know if libtorrent has a rate-limit for outgoing DHT requests. > if using multiple instances of the same script, each script will get unique > node-id depending on the ip and port i am using , is this viable solution ? If you mean the DHT node ID, then they're derived from the IP (as per [BEP 42](http://bittorrent.org/beps/bep_0042.html)), not the port. Although some random element is included, so a limited amount of IDs can be obtained per IP. And some of this might also might be applicable for your scenario: <http://blog.libtorrent.org/2012/01/seeding-a-million-torrents/> And another option is [my own DHT implementation](https://github.com/the8472/mldht) which includes a CLI to bulk-fetch torrents.
Cannot import pathos in Python Question: import pathos import pathos.multiprocessing as mp import dill print pool.map(pow, [1,2,3,4], [5,6,7,8]) when i run the above code it throws a error > cannot find pathos.multiprocessing > > cannot import pathos i tried all the possible ways but i could not find any solution. I was trying to work on a developing a code which takes more than 10 inputs and process them using multiprocessing instead of waiting in queue and generates output. For that i have tried multiprocessing, but it throws pickling error, so i tried to use pathos, but it says cannot import pathos. Can any one tell me the possible solution for this??? Answer: You need to **install** the software you use, otherwise you can't use it. So, go ahead and install pathos.
StackOverflowError when using getattr in Jython Question: I'm writing a text editor in Jython. This text editor has a toolbar which is displayed with a `ToolbarView` class and handled by a `ToolbarController` class. Some actions can't be dealt with by the `ToolbarController` on its own, so these are delegated to the `MainController` class. To avoid repeating code since there are many actions delegated from the `ToolbarController` to the MainController, I've used getattr as suggested in a previous question I asked [here](http://stackoverflow.com/questions/32828305/setattr-and-getattr-with- methods). I have also realised I can use the same mechanism in the `ToolbarView` code for the actions of the buttons, but I can't get it to work and I end up getting an infinite loop and a `Java StackOverflowError`. This is an extract of the relevant code: **ToolbarView** class: from javax.swing import JToolBar, ImageIcon, JButton class ToolbarView(JToolBar): def __init__(self, controller): #Give reference to controller to delegate action response self.controller = controller options= ['NewFile', 'OpenFile', 'SaveFile', 'CloseFile'] for option in options: methods[option] = "on" + option + "Click" print methods[option] for name, method in methods.items(): button = JButton(name, actionPerformed=getattr(self, method)) self.add(button) def __getattr__(self, name): return getattr(self.controller, name) **ToolbarController** class: from .ToolbarView import ToolbarView class ToolbarController(object): def __init__(self, mainController): #Create view with a reference to its controller to handle events self.view = ToolbarView(self) #Will also need delegating to parent presenter self.mainController = mainController def __getattr__(self, name): return getattr(self.mainController, name) **MainController** class: from .ToolbarController import ToolbarController class MainController(object): def __init__(self): self.toolbarController = ToolbarController(self) def onNewFileClick(self, event): print("MainController: Creating new file...") def onEditFileClick(self, event): print("MainController: Editting new file...") def onSaveFileClick(self, event): print("MainController: Saving new file...") def onCloseFileClick(self, event): print("MainController: Closing new file...") So what I expect is when I click the button, `MainController.onNewFileClick` gets executed and prints out that message in console. It works if I want to delegate from the `ToolbarView` to the `ToolbarController`, but it doesn't work when I pass that delegation from the `ToolbarController` to the MainController. It seems to call itself on an infinite loop. The error I get is: Traceback (most recent call last): File "main.py", line 3, in <module> MainController() File "/home/training/Jython/controller/MainController", line 8, in __init__ self.toolbarController = ToolbarController(self) File "/home/Jython/controller/ToolbarController.py", line 8, in __init__ self.view = ToolbarView(self) File "/home/Jython/controller/ToolbarView.py", line 44, in __init__ button = JButton(name, actionPerformed=getattr(self, method)) File "/home/Jython/controller/ToolbarView.py", line 54, in __getattr__ return getattr(self.controller, name) File "/home/Jython/controller/ToolbarController.py", line 15, in __getattr__ return getattr(self.mainController, name) File "/home/Jython/controller/ToolbarController.py", line 15, in __getattr__ return getattr(self.mainController, name) [...] File "/home/Jython/controller/ToolbarController.py", line 15, in __getattr__ return getattr(self.mainController, name) RuntimeError: maximum recursion depth exceeded (Java StackOverflowError) What am I doing wrong? I've tried something similar in python (delegating from a class to another class to another class) and it works if a put `()` after the getattr, but here I get confused because of the `actionPerformed` in the JButton. I've tried it but results are the same. Answer: it seems you are using `Jython`, which i don't really know. anyways, in python, you override `__getattr__`, then you should expect `getattr` to use your overridden hook instead. so i think you really mean: class ToolbarView(JToolBar): def __init__(self, controller): #Give reference to controller to delegate action response self.controller = controller options= ['NewFile', 'OpenFile', 'SaveFile', 'CloseFile'] for option in options: methods[option] = "on" + option + "Click" print methods[option] for name, method in methods.items(): button = JButton(name, actionPerformed=super(ToolbarView, self).__getattr__(method)) self.add(button) def __getattr__(self, name): return getattr(self.controller, name) watch how buttons are created. in terms of why you have a SO problem, it is because how `getattr` is handled. if you override `__getattr__`, this hook will only get called if you try to reference to a undefined field: >>> class A(object): defined = True def __getattr__(self, name): print "referenced :" + name >>> a = A() >>> a.defined True >>> a.undefined referenced :undefined hope it's clear how the hook work now. so the SO is actually caused by you were referencing something that does not belong to `MainController`. in your `MainController`, only `onNewFileClick` is defined, but you defined 3 other options: options= ['NewFile', 'OpenFile', 'SaveFile', 'CloseFile'] so, this will happen at the second round of iteration. since `MainController` has no `onOpenFileClick`, an `AttributeError` will be raised, but captured by `ToolbarController`, and therefore the overridden `__getattr__` is invoked and on and on. that's why your call stack explodes.
Print list without space in i python-notebook Question: a="alizafar" b=len(a) lis=[1]*b d=b sep="" c=0 while b>0: lis[c]=a[c] c=c+1 b=b-1 c=0 while d>0: new=lis[c] print new, c=c+1 d=d-1 result: a l i z a f a r while I want to print: alizafar Answer: You can use `sys.stdout.write` instead of `print` import sys a="alizafar" b=len(a) lis=[1]*b d=b sep="" c=0 while b>0: lis[c]=a[c] c=c+1 b=b-1 c=0 while d>0: new=lis[c] sys.stdout.write(new) c=c+1 d=d-1 will print out alizafar
Path manipulation Question: Consider you are launching a script in the following linux path: `/home/chris/sources/a/b/c/d/e/test.py` I want to be able to check whether folder named `sources` is in path and then return the path `/home/chris/sources/` Do you think I should do it using simple string manipulation, or do we have in python some xpath library that can help me do it? Answer: inb4Padraic path = '/home/chris/sources/a/b/c/d/e/test.py'.split('/') if 'sources' in path: print '/'.join(path[:path.index('sources') + 1]) another way import os path = '/home/chris/sources/a/b/c/d/e/test.py'.split('sources') if len(path) > 1: print os.path.join(path[0], 'sources')
On Centos Linux, how to install Python package 'readline' using pip? Question: Using the regular command `sudo pip install readline` I got an error Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-Ax57Qh/readline/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-KRvGg7-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-Ax57Qh/readline The complete console output is sudo pip install readline [sudo] password for qazwsx: Collecting readline Using cached readline-6.2.4.1.tar.gz Installing collected packages: readline Running setup.py install for readline Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-Ax57Qh/readline/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-KRvGg7-record/install-record.txt --single-version-externally-managed --compile: readline-6.2/ readline-6.2/doc/ readline-6.2/doc/Makefile.in readline-6.2/doc/texinfo.tex readline-6.2/doc/version.texi readline-6.2/doc/fdl.texi readline-6.2/doc/rlman.texi readline-6.2/doc/rltech.texi readline-6.2/doc/rluser.texi readline-6.2/doc/rluserman.texi readline-6.2/doc/history.texi readline-6.2/doc/hstech.texi readline-6.2/doc/hsuser.texi readline-6.2/doc/readline.3 readline-6.2/doc/history.3 readline-6.2/doc/texi2dvi readline-6.2/doc/texi2html readline-6.2/doc/readline.ps readline-6.2/doc/history.ps readline-6.2/doc/rluserman.ps readline-6.2/doc/readline.dvi readline-6.2/doc/history.dvi readline-6.2/doc/rluserman.dvi readline-6.2/doc/readline.info readline-6.2/doc/history.info readline-6.2/doc/rluserman.info readline-6.2/doc/readline.html readline-6.2/doc/history.html readline-6.2/doc/rluserman.html readline-6.2/doc/readline.0 readline-6.2/doc/history.0 readline-6.2/doc/readline_3.ps readline-6.2/doc/history_3.ps readline-6.2/doc/history.pdf readline-6.2/doc/readline.pdf readline-6.2/doc/rluserman.pdf readline-6.2/examples/ readline-6.2/examples/autoconf/ readline-6.2/examples/autoconf/BASH_CHECK_LIB_TERMCAP readline-6.2/examples/autoconf/RL_LIB_READLINE_VERSION readline-6.2/examples/autoconf/wi_LIB_READLINE readline-6.2/examples/rlfe/ readline-6.2/examples/rlfe/ChangeLog readline-6.2/examples/rlfe/Makefile.in readline-6.2/examples/rlfe/README readline-6.2/examples/rlfe/config.h.in readline-6.2/examples/rlfe/configure readline-6.2/examples/rlfe/configure.in readline-6.2/examples/rlfe/extern.h readline-6.2/examples/rlfe/os.h readline-6.2/examples/rlfe/pty.c readline-6.2/examples/rlfe/rlfe.c readline-6.2/examples/rlfe/screen.h readline-6.2/examples/Makefile.in readline-6.2/examples/excallback.c readline-6.2/examples/fileman.c readline-6.2/examples/manexamp.c readline-6.2/examples/readlinebuf.h readline-6.2/examples/rl-fgets.c readline-6.2/examples/rlcat.c readline-6.2/examples/rlevent.c readline-6.2/examples/rltest.c readline-6.2/examples/rl.c readline-6.2/examples/rlptytest.c readline-6.2/examples/rlversion.c readline-6.2/examples/histexamp.c readline-6.2/examples/Inputrc readline-6.2/examples/rlwrap-0.30.tar.gz readline-6.2/support/ readline-6.2/support/config.guess readline-6.2/support/config.rpath readline-6.2/support/config.sub readline-6.2/support/install.sh readline-6.2/support/mkdirs readline-6.2/support/mkdist readline-6.2/support/mkinstalldirs readline-6.2/support/shobj-conf readline-6.2/support/shlib-install readline-6.2/support/wcwidth.c readline-6.2/shlib/ readline-6.2/shlib/Makefile.in readline-6.2/COPYING readline-6.2/README readline-6.2/MANIFEST readline-6.2/INSTALL readline-6.2/CHANGELOG readline-6.2/CHANGES readline-6.2/NEWS readline-6.2/USAGE readline-6.2/aclocal.m4 readline-6.2/config.h.in readline-6.2/configure readline-6.2/configure.in readline-6.2/Makefile.in readline-6.2/ansi_stdlib.h readline-6.2/chardefs.h readline-6.2/history.h readline-6.2/histlib.h readline-6.2/keymaps.h readline-6.2/posixdir.h readline-6.2/posixjmp.h readline-6.2/readline.h readline-6.2/posixselect.h readline-6.2/posixstat.h readline-6.2/rlconf.h readline-6.2/rldefs.h readline-6.2/rlmbutil.h readline-6.2/rlprivate.h readline-6.2/rlshell.h readline-6.2/rlstdc.h readline-6.2/rltty.h readline-6.2/rltypedefs.h readline-6.2/rlwinsize.h readline-6.2/tcap.h readline-6.2/tilde.h readline-6.2/xmalloc.h readline-6.2/bind.c readline-6.2/callback.c readline-6.2/compat.c readline-6.2/complete.c readline-6.2/display.c readline-6.2/emacs_keymap.c readline-6.2/funmap.c readline-6.2/input.c readline-6.2/isearch.c readline-6.2/keymaps.c readline-6.2/kill.c readline-6.2/macro.c readline-6.2/mbutil.c readline-6.2/misc.c readline-6.2/nls.c readline-6.2/parens.c readline-6.2/readline.c readline-6.2/rltty.c readline-6.2/savestring.c readline-6.2/search.c readline-6.2/shell.c readline-6.2/signals.c readline-6.2/terminal.c readline-6.2/text.c readline-6.2/tilde.c readline-6.2/undo.c readline-6.2/util.c readline-6.2/vi_keymap.c readline-6.2/vi_mode.c readline-6.2/xfree.c readline-6.2/xmalloc.c readline-6.2/history.c readline-6.2/histexpand.c readline-6.2/histfile.c readline-6.2/histsearch.c readline-6.2/patchlevel patching file vi_mode.c patching file callback.c patching file support/shobj-conf patching file patchlevel patching file input.c patching file patchlevel patching file vi_mode.c patching file patchlevel checking build system type... x86_64-unknown-linux-gnu checking host system type... x86_64-unknown-linux-gnu Beginning configuration for readline-6.2 for x86_64-unknown-linux-gnu checking whether make sets $(MAKE)... yes checking for gcc... gcc checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking how to run the C preprocessor... gcc -E checking for grep that handles long lines and -e... /usr/bin/grep checking for egrep... /usr/bin/grep -E checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking minix/config.h usability... no checking minix/config.h presence... no checking for minix/config.h... no checking whether it is safe to define __EXTENSIONS__... yes checking whether gcc needs -traditional... no checking for a BSD-compatible install... /usr/bin/install -c checking for ar... ar checking for ranlib... ranlib checking for an ANSI C-conforming const... yes checking for function prototypes... yes checking whether char is unsigned... no checking for working volatile... yes checking return type of signal handlers... void checking for size_t... yes checking for ssize_t... yes checking for ANSI C header files... (cached) yes checking whether stat file-mode macros are broken... no checking for dirent.h that defines DIR... yes checking for library containing opendir... none required checking for fcntl... yes checking for kill... yes checking for lstat... yes checking for memmove... yes checking for putenv... yes checking for select... yes checking for setenv... yes checking for setlocale... yes checking for strcasecmp... yes checking for strpbrk... yes checking for tcgetattr... yes checking for vsnprintf... yes checking for isascii... yes checking for isxdigit... yes checking for getpwent... yes checking for getpwnam... yes checking for getpwuid... yes checking for working strcoll... yes checking fcntl.h usability... yes checking fcntl.h presence... yes checking for fcntl.h... yes checking for unistd.h... (cached) yes checking for stdlib.h... (cached) yes checking varargs.h usability... no checking varargs.h presence... no checking for varargs.h... no checking stdarg.h usability... yes checking stdarg.h presence... yes checking for stdarg.h... yes checking for string.h... (cached) yes checking for strings.h... (cached) yes checking limits.h usability... yes checking limits.h presence... yes checking for limits.h... yes checking locale.h usability... yes checking locale.h presence... yes checking for locale.h... yes checking pwd.h usability... yes checking pwd.h presence... yes checking for pwd.h... yes checking for memory.h... (cached) yes checking termcap.h usability... no checking termcap.h presence... no checking for termcap.h... no checking termios.h usability... yes checking termios.h presence... yes checking for termios.h... yes checking termio.h usability... yes checking termio.h presence... yes checking for termio.h... yes checking sys/pte.h usability... no checking sys/pte.h presence... no checking for sys/pte.h... no checking sys/stream.h usability... no checking sys/stream.h presence... no checking for sys/stream.h... no checking sys/select.h usability... yes checking sys/select.h presence... yes checking for sys/select.h... yes checking sys/file.h usability... yes checking sys/file.h presence... yes checking for sys/file.h... yes checking for sys/ptem.h... no checking for special C compiler options needed for large files... no checking for _FILE_OFFSET_BITS value needed for large files... no checking for type of signal functions... posix checking if signal handlers must be reinstalled when invoked... no checking for presence of POSIX-style sigsetjmp/siglongjmp... present checking for lstat... yes checking whether or not strcoll and strcmp differ... no checking whether the ctype macros accept non-ascii characters... yes checking whether getpw functions are declared in pwd.h... yes checking whether termios.h defines TIOCGWINSZ... no checking whether sys/ioctl.h defines TIOCGWINSZ... yes checking for sig_atomic_t in signal.h... yes checking whether signal handlers are of type void... yes checking for TIOCSTAT in sys/ioctl.h... no checking for FIONREAD in sys/ioctl.h... yes checking for speed_t in sys/types.h... no checking for struct winsize in sys/ioctl.h and termios.h... sys/ioctl.h checking for struct dirent.d_ino... yes checking for struct dirent.d_fileno... yes checking for tgetent... no checking for tgetent in -ltermcap... no checking for tgetent in -ltinfo... no checking for tgetent in -lcurses... no checking for tgetent in -lncurses... no checking which library has the termcap functions... using gnutermcap checking wctype.h usability... yes checking wctype.h presence... yes checking for wctype.h... yes checking wchar.h usability... yes checking wchar.h presence... yes checking for wchar.h... yes checking langinfo.h usability... yes checking langinfo.h presence... yes checking for langinfo.h... yes checking for mbrlen... yes checking for mbscasecmp... no checking for mbscmp... no checking for mbsnrtowcs... yes checking for mbsrtowcs... yes checking for mbschr... no checking for wcrtomb... yes checking for wcscoll... yes checking for wcsdup... yes checking for wcwidth... yes checking for wctype... yes checking for wcswidth... yes checking whether mbrtowc and mbstate_t are properly declared... yes checking for iswlower... yes checking for iswupper... yes checking for towlower... yes checking for towupper... yes checking for iswctype... yes checking for nl_langinfo and CODESET... yes checking for wchar_t in wchar.h... yes checking for wctype_t in wctype.h... yes checking for wint_t in wctype.h... yes checking configuration for building shared libraries... supported configure: creating ./config.status config.status: creating Makefile config.status: creating doc/Makefile config.status: creating examples/Makefile config.status: creating shlib/Makefile config.status: creating config.h config.status: executing default commands rm -f readline.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O readline.c rm -f vi_mode.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O vi_mode.c rm -f funmap.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O funmap.c rm -f keymaps.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O keymaps.c rm -f parens.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O parens.c rm -f search.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O search.c rm -f rltty.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O rltty.c rm -f complete.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O complete.c rm -f bind.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O bind.c rm -f isearch.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O isearch.c rm -f display.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O display.c rm -f signals.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O signals.c rm -f util.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O util.c rm -f kill.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O kill.c rm -f undo.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O undo.c rm -f macro.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O macro.c rm -f input.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O input.c rm -f callback.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O callback.c rm -f terminal.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O terminal.c rm -f text.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O text.c rm -f nls.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O nls.c rm -f misc.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O misc.c rm -f compat.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O compat.c rm -f xfree.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O xfree.c rm -f xmalloc.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O xmalloc.c rm -f history.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O history.c rm -f histexpand.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O histexpand.c rm -f histfile.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O histfile.c rm -f histsearch.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O histsearch.c rm -f shell.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O shell.c rm -f mbutil.o gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O mbutil.c rm -f tilde.o gcc -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I. -DRL_LIBRARY_VERSION='"6.2"' -g -O -DREADLINE_LIBRARY -c ./tilde.c rm -f libreadline.a ar cr libreadline.a readline.o vi_mode.o funmap.o keymaps.o parens.o search.o rltty.o complete.o bind.o isearch.o display.o signals.o util.o kill.o undo.o macro.o input.o callback.o terminal.o text.o nls.o misc.o compat.o xfree.o xmalloc.o history.o histexpand.o histfile.o histsearch.o shell.o mbutil.o tilde.o test -n "ranlib" && ranlib libreadline.a rm -f libhistory.a ar cr libhistory.a history.o histexpand.o histfile.o histsearch.o shell.o mbutil.o xmalloc.o xfree.o test -n "ranlib" && ranlib libhistory.a test -d shlib || mkdir shlib ( cd shlib ; make all ) make[1]: Entering directory `/tmp/pip-build-Ax57Qh/readline/rl/readline-lib/shlib' rm -f readline.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o readline.o ../readline.c mv readline.o readline.so rm -f vi_mode.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o vi_mode.o ../vi_mode.c mv vi_mode.o vi_mode.so rm -f funmap.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o funmap.o ../funmap.c mv funmap.o funmap.so rm -f keymaps.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o keymaps.o ../keymaps.c mv keymaps.o keymaps.so rm -f parens.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o parens.o ../parens.c mv parens.o parens.so rm -f search.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o search.o ../search.c mv search.o search.so rm -f rltty.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o rltty.o ../rltty.c mv rltty.o rltty.so rm -f complete.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o complete.o ../complete.c mv complete.o complete.so rm -f bind.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o bind.o ../bind.c mv bind.o bind.so rm -f isearch.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o isearch.o ../isearch.c mv isearch.o isearch.so rm -f display.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o display.o ../display.c mv display.o display.so rm -f signals.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o signals.o ../signals.c mv signals.o signals.so rm -f util.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o util.o ../util.c mv util.o util.so rm -f kill.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o kill.o ../kill.c mv kill.o kill.so rm -f undo.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o undo.o ../undo.c mv undo.o undo.so rm -f macro.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o macro.o ../macro.c mv macro.o macro.so rm -f input.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o input.o ../input.c mv input.o input.so rm -f callback.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o callback.o ../callback.c mv callback.o callback.so rm -f terminal.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o terminal.o ../terminal.c mv terminal.o terminal.so rm -f text.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o text.o ../text.c mv text.o text.so rm -f nls.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o nls.o ../nls.c mv nls.o nls.so rm -f misc.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o misc.o ../misc.c mv misc.o misc.so rm -f xmalloc.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o xmalloc.o ../xmalloc.c mv xmalloc.o xmalloc.so rm -f xfree.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o xfree.o ../xfree.c mv xfree.o xfree.so rm -f history.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o history.o ../history.c mv history.o history.so rm -f histexpand.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o histexpand.o ../histexpand.c mv histexpand.o histexpand.so rm -f histfile.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o histfile.o ../histfile.c mv histfile.o histfile.so rm -f histsearch.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o histsearch.o ../histsearch.c mv histsearch.o histsearch.so rm -f shell.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o shell.o ../shell.c mv shell.o shell.so rm -f mbutil.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o mbutil.o ../mbutil.c mv mbutil.o mbutil.so rm -f tilde.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -DREADLINE_LIBRARY -c -o tilde.o ../tilde.c mv tilde.o tilde.so rm -f compat.so gcc -c -DHAVE_CONFIG_H -DNEED_EXTERN_PC -fPIC -I. -I.. -I.. -DRL_LIBRARY_VERSION='"6.2"' -g -O -fPIC -o compat.o ../compat.c mv compat.o compat.so rm -f libreadline.so.6.2 gcc -shared -Wl,-soname,libreadline.so.6.2 -L./lib/termcap -Wl,-rpath,/usr/local/lib -Wl,-soname,`basename libreadline.so.6.2 .2` -o libreadline.so.6.2 readline.so vi_mode.so funmap.so keymaps.so parens.so search.so rltty.so complete.so bind.so isearch.so display.so signals.so util.so kill.so undo.so macro.so input.so callback.so terminal.so text.so nls.so misc.so xmalloc.so xfree.so history.so histexpand.so histfile.so histsearch.so shell.so mbutil.so tilde.so compat.so rm -f libhistory.so.6.2 gcc -shared -Wl,-soname,libhistory.so.6.2 -L./lib/termcap -Wl,-rpath,/usr/local/lib -Wl,-soname,`basename libhistory.so.6.2 .2` -o libhistory.so.6.2 history.so histexpand.so histfile.so histsearch.so shell.so mbutil.so xmalloc.so xfree.so make[1]: Leaving directory `/tmp/pip-build-Ax57Qh/readline/rl/readline-lib/shlib' ============ Building the readline library ============ ============ Building the readline extension module ============ running install running build running build_ext building 'readline' extension creating build creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/Modules creating build/temp.linux-x86_64-2.7/Modules/2.x gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DHAVE_RL_CALLBACK -DHAVE_RL_CATCH_SIGNAL -DHAVE_RL_COMPLETION_APPEND_CHARACTER -DHAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK -DHAVE_RL_COMPLETION_MATCHES -DHAVE_RL_COMPLETION_SUPPRESS_APPEND -DHAVE_RL_PRE_INPUT_HOOK -I. -I/usr/include/python2.7 -c Modules/2.x/readline.c -o build/temp.linux-x86_64-2.7/Modules/2.x/readline.o -Wno-strict-prototypes Modules/2.x/readline.c:8:20: fatal error: Python.h: No such file or directory #include "Python.h" ^ compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-Ax57Qh/readline/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-KRvGg7-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-Ax57Qh/readline **Update** : adding path to `$CPATH` does NOT help -bash-4.2$ locate Python.h /usr/include/python2.7/Python.h -bash-4.2$ echo $CPATH -bash-4.2$ export CPATH=/usr/include/python2.7/ -bash-4.2$ echo $CPATH /usr/include/python2.7/ and I still get the _same_ error running `sudo pip install readline`: Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-NP1WUS/readline/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-9Uamrv-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-NP1WUS/readline Then the said file no longer exist in tmp/: -bash-4.2$ ls -la /tmp/pip-build-* ls: cannot access /tmp/pip-build-*: No such file or directory Answer: Don't know for sure but: Try installing `sudo yum install python-devel` EDIT: Can you check if the directory /usr/include/python2.7 actually exists? Looks like gcc can't find the libraries for Python.
Certain Amount of Time to Input in Python? Question: I'm making a simple Python Text Adventure Game, and I want to know a way how to make a simple function that asks for a user input; however, I want the program to ONLY accept the input before a certain duration (in my program I'm using 3 seconds). Furthermore, I want the function to check the correctness of the input before accepting it as right. My attempt is as follows: lvl1 = [ 'Hi', 'Friend', 'Say', 'Smelly', 'Made', 'Tree', 'Python', 'Freak' ] one = raw_input("You have 3 seconds to type: " + random.choice(lvl1)) endtime = time.time() + 3 while time.time() <= endtime and lvl1[0:]: print("Wrong!") one = raw_input("Try again: ") print("Correct") Basically what I want this code to do is to get an input from the user in (less than or equal to) a 3 second time duration, but before congratulating the user, make sure that their input is the same as one of the strings in the 'lvl1' array. Thanks! Answer: You were very close. One thing that you missed was that you need to start the timer before you prompt the user for input. If you do not do this, the program will wait for the users input before starting the timer, which will always cause the "in less than 3 seconds" condition to be true. Another change I made was storing the value of the randomly selected word so that you can display it and, later in the program, verify that the user's input matches later. import random import time lvl1 = [ 'Hi', 'Friend', 'Say', 'Smelly', 'Made', 'Tree', 'Python', 'Freak' ] word = random.choice(lvl1) start_time = time.time() one = raw_input("You have 3 seconds to type: {}\n".format(word)) while time.time() - start_time > 3 or one != word: print("Wrong!") start_time = time.time() one = raw_input("Try again: ") print("Correct") Hope this helps!
Privlege error trying to create symlink using python on windows 10 Question: I am attempting to create a symlink using python on windows 10 (home version) with the foll. code: import ctypes kdll = ctypes.windll.LoadLibrary("kernel32.dll") kdll.CreateSymbolicLinkW(src_dir, dst_dir, 1) but I get the foll. error: *** error: (1314, 'CreateSymbolicLink', 'A required privilege is not held by the client.') How to fix this? Answer: If UAC is enabled and your user is an administrator, then the Local Security Authority (LSA, hosted in lsass.exe) logs your user on with a restricted access token. For this token, the `BUILTIN\Administrators` group is used only for denying access; the integrity-level label is medium instead of high; and the privileges typically granted to an administrator have been filtered out. To create a symbolic link, you need to create the process using your unrestricted/elevated access token (i.e. elevated from medium to high integrity level). Do this by right-clicking and selecting "Run as administrator". This elevated token will be inherited by child processes, so it suffices to run your Python script from an elevated command prompt, which you can open via the keyboard shortcut `Win+X` `A`. You can verify that the cmd shell is elevated by running `whoami /priv` and checking for the presence of `SeCreateSymbolicLinkPrivilege`. Don't be alarmed if the state is disabled. The Windows [`CreateSymbolicLink`](https://msdn.microsoft.com/en- us/library/aa363866) function automatically enables this privilege. That said, since you're creating a _directory_ symbolic link, then perhaps a junction will work just as well. No special privilege is required to create a junction. You can create a junction using cmd's `mklink` command. For example: subprocess.check_call('mklink /J "%s" "%s"' % (link, target), shell=True)
Import JSON to MONGODB Question: I have a Python script that generates a huge JSON. When I put the program to run, it generates a file in Notepad with JSON. I wanted to put this JSON in MongoDB database and let stored, and then be able to search this JSON using MongoDB commands to search for espercificas things. But could not find anywhere how can I get this JSON file in the Notepad, and put in the database. If anyone can help. tanks Answer: Go to file directory using cmd, outside mongoshell. Then, mongoimport --db dbName --collection collectionName <fileName.json Example, mongoimport --db foo --collection myCollections < /Users/file.json connected to: *.*.*.* Sat Mar 2 15:01:08 imported 11 objects
I got stuck on Python error TypeError: unhashable type: 'slice' Question: from informedSearch import * from search import * class EightPuzzleProblem(InformedProblemState): """ Inherited from the InformedProblemState class. To solve the eight puzzle problem. """ def __init__(self, myList, list = {}, operator = None): self.myList = list self.operator = operator def __str__(self): ## Method returns a string representation of the state. result = "" if self.operator != None: result += "Operator: " + self.operator + "" result += " " + ' '.join(self.myList[0:3]) + "\n" result += " " + ' '.join(self.myList[3:6]) + "\n" result += " " + ' '.join(self.myList[6:9]) + "\n" return result def illegal(self): ## Tests whether the state is illegal. if self.myList < 0 or self.myList > 9: return 1 return 0 def equals(self, state): ## Method to determine whether the state instance ## and the given state are equal. return ' '.join(self.myList) == ' '.join(state.myList) ## The five methods below perform the tree traversing def move(self, value): nList = self.myList[:] # make copy of the current state position = nList.index('P') # P acts as the key val = nList.pop(position + value) nList.insert(position + value, 'P') nList.pop(position) nList.insert(position, val) return nList def moveleft(self): n = self.move(-1) return EightPuzzleProblem(n, "moveleft") def moveright(self): n = self.move(1) return EightPuzzleProblem(n, "moveright") def moveup(self): n = self.move(-3) return EightPuzzleProblem(n, "moveup") def movedown(self): n = self.move(+3) return EightPuzzleProblem(n, "movedown") def operatorNames(self): return ["moveleft", "moveright", "moveup", "movedown"] def enqueue(self): q = [] if (self.myList.index('P') != 0) and (self.myList.index('P') != 3) and (self.myList.index('P') != 6): q.append(self.moveleft()) if (self.myList.index('P') != 2) and (self.myList.index('P') != 5) and (self.myList.index('P') != 8): q.append(self.moveright()) if self.myList.index('P') >= 3: q.append(self.moveup()) if self.myList.index('P') >= 5: q.append(self.movedown()) def applyOperators(self): return [self.moveleft(), self.moveright(), self.moveup(), self.movedown()] def heuristic(): counter = 0 for i in range(len(self.myList)): if ((self.myList[i] != goal.myList[i]) and self.myList[i] != 'P'): ## Position of current: current = goal.myList.index(self.myList[i]) if current < 3: goalRow = 0 elif current < 6: goalRow = 1 else: goalRow = 2 if i < 3: initRow = 0 elif i < 6: initRow = 1 else: startRow = 2 initColumn = i % 3 goalColumn = current % 3 counter += (abs(goalColumn - initColumn) + abs(goalRow - initRow)) return counter #Uncomment to test the starting states: init = ['1','3','P','8','2','4','7','6','5'] #A #init = ['1','3','4','8','6','2','P','7','5'] #B #init = ['P','1','3','4','2','5','8','7','6'] #C #init = ['7','1','2','8','P','3','6','5','4'] #D #init = ['8','1','2','7','P','4','6','5','3'] #E #init = ['2','6','3','4','P','5','1','8','7'] #F #init = ['7','3','4','6','1','5','8','P','2'] #G #init = ['7','4','5','6','P','3','8','1','2'] #H goal = ['1','2','3','8','P','4','7','6','5'] #goal state InformedSearch(EightPuzzleProblem(init), EightPuzzleProblem(goal)) I run it and it shows error **line 34, in __str__ result += " " + ' '.join(self.myList[0:3]) + "\n" TypeError: unhashable type: 'slice'** Can anyone help please? I think there are a lot of other problems in this class too. Answer: You're setting the "list" to a dictionary as a default value: `list = {}` in: def __init__(self, myList, list = {}, operator = None): and then assigning it to `myList` with: self.myList = list A dictionary cannot be sliced like a list. So when you try to slice it: self.myList[0:3] it fails.
Using Python and external programs Question: By using python, how do I use cmd.exe supported commands and get the output to be viewed back in python? The reason I am doing this is to get the Microsoft .NET framework version. At the moment I could only find it through the cmd.exe by using the following command: wmic product where "Name like 'Microsoft .Net%'" get Name, Version So I was thinking to get python to execute the above command and get the results back and write them to a file. Answer: Here is a way about how to execute cmd command from python using the [subprocess](https://docs.python.org/2/library/subprocess.html#module- subprocess) module. **Code** : The following code is just pinging the loopback address using `ping 127.0.0.1` command and then writing the results to a file. [Docs](https://docs.python.org/2/tutorial/inputoutput.html#reading-and- writing-files) for file handling in python could be found [here](https://docs.python.org/2/tutorial/inputoutput.html#reading-and- writing-files). import subprocess def myFunc(): p = subprocess.Popen("ping 127.0.0.1", stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() print out print err with open('myOutputFile.txt', 'w') as f: f.write(out) #Write the output to a file myFunc() Replace the `ping 127.0.0.1` with other cmd command and it should work. For eg: `netstat -a`. Note: It might take a while before you see the output in console, because the output will be returned to the console when the cmd command has finished the execution! The following code should do your job: import subprocess def myFunc(): p = subprocess.Popen("wmic product where \"Name like 'Microsoft .Net%'\" get Name, Version", stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() print out print err with open('myOutputFile.txt', 'w') as f: f.write(out) #Write the output to a file myFunc() Hope it helps!
Python itertools.product() get item index Question: I have a given tuple `my_tuple` and I know it is in the return object of itertools.product(). How could I find the index of `my_tuple` without iterating over the itertools.product() object? import itertools permutations = itertools.product(my_sorted_list, repeat = perm_length) Expected output similar of `any_list.index(interesting_pattern)` **Edit** Note that I cannot use list() on the object because of memory constraints Using Python 2.7 Answer: You don't want to use `itertools.product` in this case. If you only want the index, than you should calculate it with math. Like others said before, this one is slow and needs a lot of memory: import itertools print list(itertools.product([0, 2, 3, 5], repeat=3)).index((3, 0, 2)) Much better is: def product_index(sorted_list, repeat, interesting_pattern): result = 0 for index, number in enumerate(interesting_pattern): result += sorted_list.index(number) * len(sorted_list)**(repeat - 1 - index) return result print product_index([0, 2, 3, 5], 3, (3, 0, 2)) ### Explanation: Just look at the output of `list(itertools([0, 2, 3, 5], repeat=3))`: [(0, 0, 0), (0, 0, 2), (0, 0, 3), (0, 0, 5), (0, 2, 0), (0, 2, 2), (0, 2, 3), (0, 2, 5), (0, 3, 0), (0, 3, 2), (0, 3, 3), (0, 3, 5), (0, 5, 0), (0, 5, 2), (0, 5, 3), (0, 5, 5), (2, 0, 0), (2, 0, 2), (2, 0, 3), (2, 0, 5), (2, 2, 0), (2, 2, 2), (2, 2, 3), (2, 2, 5), (2, 3, 0), (2, 3, 2), (2, 3, 3), (2, 3, 5), (2, 5, 0), (2, 5, 2), (2, 5, 3), (2, 5, 5), (3, 0, 0), (3, 0, 2), (3, 0, 3), (3, 0, 5), (3, 2, 0), (3, 2, 2), (3, 2, 3), (3, 2, 5), ...] Since the input list is sorted, the generated tuples are also sorted. At first `itertools.product` generates all tuples of length `3`, that start with `0`. Then there are all tuples of length `3` that start with `2`. And so on. So the algorithm goes through each element of `interesting_pattern` and determines, how many of these tuples start with a number smaller. So for `interesting_pattern = (3, 0, 2)` we have: * How many tuples of length `3` are there, where the first element is smaller than `3`? For the first element there are 2 possibilities (`0` and `2`) and all the other elements can be everything (4 possibilities). So there are `2*4*4 = 2*4^2 = 32`. Now we have the first digit 3, and only have to look at the subtuple `(0, 2)`. * How many tuples of length `2` are there, where the first element is smaller than `0`? There is no possibility for the first element, but 4 possibilities for the second element, so `0*4 = 0*4^1 = 0`. * And at last. How many tuples of length `1` are there, where the first element is smaller than `2`? There is 1 possibility for the first element (`0`), so `1 = 1*4^0 = 1`. In total we get `32 + 0 + 1 = 33`. The index is `33`. ### edit: This algorithm is probably even faster, since you don't have to compute any powers. def product_index2(sorted_list, interesting_pattern): result = 0 for number in interesting_pattern: result = result * len(sorted_list) + sorted_list.index(number) return result
array - float64 to array - ndarray Question: I am new to python, am not aware of data types. I want the output to be in the form [[ 0.3120883 ] [ 0.36910208] [ 0.99886361] ..., [-0.10729821] [ 0.08311962] [ 1.67302086]] But currently my output is the form [-0.13562086 -0.11107482 0.1600553 ..., -0.3161786 -0.23419835 0.45029903] How to convert it? Answer: You can [`numpy.reshape`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html) it to `(-1,1)` to get the result in the form you want. Example - narray = narray.reshape((-1,1)) Demo - In [19]: import numpy as np In [20]: narray = np.arange(10) In [21]: narray Out[21]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [22]: narray.reshape((-1,1)) Out[22]: array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]) Basically what you are doing is to change the shape of the array from something like - `(n,)` to `(n,1)` , you do this by using [`reshape()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy.reshape) , in it you can pass `-1` as one of the arguments. As given in documentation - > `newshape` : int or tuple of ints > > The new shape should be compatible with the original shape. If an integer, > then the result will be a 1-D array of that length. **One shape dimension > can be -1. In this case, the value is inferred from the length of the array > and remaining dimensions.**
concatenating python strings in a loop Question: I am using enums and string.join() method to form a help string in Python: I have the following code segment: from enum import Enum class Estimators(Enum): rsac = 1 msac = 2 Now, I create a help string as follows: est_help = 'Valid options are: [' + (str(i.name) + ', ' for i in Estimators) + ']' This throws a TypeError exception as: TypeError: cannot concatenate 'str' and 'generator' objects I was wondering what I am doing wrong. The `i.name` is of string type. Answer: The error message tells you what you are doing wrong - attempting to concatenate a string and a generator. What you want to do is to make a list using list comprehension based on the generator, then use that est_help = 'Valid options are: [{}]'.format( ', '.join( i.name for i in Estimators)) Let's decompose this into individual steps: 1. Create the list `[rsac,msac]`: `est_list = [str(i.name) for i in Estimators]` 2. Create a string with the list elements separated by a comma `'rsac, msac'`: `est_str = ', '.join( est_list )` 3. Insert the string into your text template: `est_help = 'Valid options are: [{}]'.format( est_str )`, and get the resulting string `Valid options are: [rsac, msac]'` **edit: modified code incorporating suggestions from comments** est_help = 'Valid options are: [{}]'.format( ', '.join( i.name for i in Estimators ) )
Moving Mouse in Python on VM Question: I am trying to move my mouse using this simple code. import win32api, win32con def click(x,y): win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0) click(10,10) My machine is running MacOS, and I run a Virtual Machine on my computer with windows 7. When I run this code on my Virtual Machine, it doesnt move the actual mouse, but rather uses a "ghost mouse" to make the click. When I try to use this code to make the mouse move on a windows desktop machine, you can see the cursor moving (unlike on my VM). Are there any ideas to making the actual mouse cursor move on my virtual machine through python? Thanks! Answer: From what I can tell, I don't really believe it's possible. For all the VM knows, the host doesn't really even exist (for the most part). One major thing VMs do is sandbox the client from the host. (See [security.SE](http://security.stackexchange.com/questions/9011/does-a-virtual- machine-stop-malware-from-doing-harm)). The other thing is, that would be a massive security issue. If I had access to your machine from the VM, then I could ostensibly click through and install malware. Now for the catch: You probably can. VMS can communicate to their host through the network, so if you had a server listening on the host for the communication, and the host moves the cursor after reading the comms, then yes. Note that this method requires explicitly setting up the host to listen to the client. No method I am aware of allows the VM to directly interact with the host without the host "listening".
Python - plot a NxN matrix as a gradient colors grid Question: I want to visualize the correlation between columns that I get with `datafrome.corr()` method. The result looks like: [![enter image description here](http://i.stack.imgur.com/MRqmL.png)](http://i.stack.imgur.com/MRqmL.png) What I am trying to do here is to draw that matrix with gradient colors based on the values of the data frame. Something like (Just an example from the web): [![enter image description here](http://i.stack.imgur.com/48dVc.png)](http://i.stack.imgur.com/48dVc.png) Answer: If you can import your data into numpy here is a simple solution using matplotlib and should produce a heatmap similar to what you posted. You will just need to replace the dummy data with your data. import numpy as np import matplotlib.pyplot as plt # Generate some test data data = np.arange(100).reshape((10,10)) plt.title('Actual Function') heatmap = plt.pcolor(data) plt.show() **Edit:** Here is a bit fancier version with your x and y axis labels. I chose to put them into two lists so that you could change each one independently. import numpy as np import matplotlib.pyplot as plt # Generate some test data data = np.arange(100).reshape((10,10)) xlabels = ['capacity', 'failure_rate', 'id', 'margin', 'price', 'prod_cost', 'product_type', 'quality', 'warranty', 'market_share', 'attractiveness'] ylabels = ['capacity', 'failure_rate', 'id', 'margin', 'price', 'prod_cost', 'product_type', 'quality', 'warranty', 'market_share', 'attractiveness'] fig, ax = plt.subplots() ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) ax.xaxis.tick_top() plt.xticks(rotation=90) ax.set_xticklabels(xlabels, minor=False) ax.set_yticklabels(ylabels, minor=False) heatmap = ax.pcolor(data) ax = plt.gca() for t in ax.xaxis.get_major_ticks(): t.tick1On = False t.tick2On = False for t in ax.yaxis.get_major_ticks(): t.tick1On = False t.tick2On = False plt.show()
capturing only certain characters in regular expression by python Question: I'm trying to create pattern that detects certain strings. Basically, the purpose is if detect 'ABCDEF' in a string then return "true". but between 'ABC' and 'DEF', there would be (L+count) or (number) or not like examples below. BTW all examples below return "true". It would be really appreciate if some one can advise how to ignore those combo of number and characters between "ABC" and "DEF"? ABC(L30)(345)DEF, ABC(L2)(45)DEF, ABCDEF, ABC(L10)DEF, ABC(2)DEF Answer: Regex compose thinking path: * Start with ABC * Ends with DEF * Either (L[0-9]+) or ([0-9]+) or empty > > #!/usr/bin/python > import re > r=re.compile("ABC(\(L[0-9]+\)|\([0-9]+\)|)*DEF"); > lines = [ > "ABC(L30)(345)DEF", > "ABC(L2)(45)DEF", > "ABC(L30)DEF", > "ABC(345)DEF", > "ABCDEF", > "ABCxyzDEF", > "ABC(L)DEF", > "ABC(A)DEF", > "ABC()DEF", > ] > for str in lines: > if r.match(str): > print " match : %s" % str > else: > print "not match : %s" % str > Output: > > match : ABC(L30)(345)DEF > match : ABC(L2)(45)DEF > match : ABC(L30)DEF > match : ABC(345)DEF > match : ABCDEF > not match : ABCxyzDEF > not match : ABC(L)DEF > not match : ABC(A)DEF > not match : ABC()DEF >
Error during pip install ldavis Question: I have been attempting to install a Python package by the name of 'pyLDAvis' from cmd with no success since over a day now! I ran the following command from cmd - pip install pyldavis I have already installed Microsoft Visual C++ 2010. Further, I have also performed the steps mentioned at <http://stackoverflow.com/a/26513378/3228300> (Installing Win SDK 7.1, change the redistributable pkgs and create a vcvars64.bat file). Sadly, I do not know how to proceed further. I am pasting the ending snippet of code that is thrown back at me when the installation stops below - c:\users\ABC\anaconda3\lib\site-packages\numpy\core\include\num py\npy_1_7_deprecated_api.h(12) : Warning Msg: Using deprecated NumPy API, disab le it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\Bin\amd64\link.exe /D LL /nologo /INCREMENTAL:NO "/LIBPATH:C:\Users\ABC\Anaconda3\libs" " /LIBPATH:C:\Users\ABC\Anaconda3\PCbuild\amd64" /EXPORT:PyInit___sub sample build\temp.win-amd64-3.4\Release\skbio/stats/__subsample.obj /OUT:build\l ib.win-amd64-3.4\skbio\stats\__subsample.pyd /IMPLIB:build\temp.win-amd64-3.4\Re lease\skbio/stats\__subsample.lib /MANIFESTFILE:build\temp.win-amd64-3.4\Release \skbio/stats\__subsample.pyd.manifest __subsample.obj : warning LNK4197: export 'PyInit___subsample' specified mul tiple times; using first specification Creating library build\temp.win-amd64-3.4\Release\skbio/stats\__subsample .lib and object build\temp.win-amd64-3.4\Release\skbio/stats\__subsample.exp building 'skbio.alignment._ssw_wrapper' extension creating build\temp.win-amd64-3.4\Release\skbio\alignment creating build\temp.win-amd64-3.4\Release\skbio\alignment\_lib C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\Bin\amd64\cl.exe /c / nologo /Ox /MD /W3 /GS- /DNDEBUG "-IC:\Users\ABC\Anaconda3\lib\site -packages\numpy\core\include" "-IC:\Users\ABC\Anaconda3\include" "- IC:\Users\ABC\Anaconda3\include" /Tcskbio/alignment/_ssw_wrapper.c /Fobuild\temp.win-amd64-3.4\Release\skbio/alignment/_ssw_wrapper.obj -Wno-error= declaration-after-statement cl : Command line error D8021 : invalid numeric argument '/Wno-error=declara tion-after-statement' error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\B in\\amd64\\cl.exe' failed with exit status 2 ---------------------------------------- Command ""C:\Users\ABC\Anaconda3\python.exe" -c "import setuptools, tokenize;__file__='C:\\Users\\ABC1\\AppData\\Local\\Temp\\pip-build-cp30pok 9\\scikit-bio\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__). read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\ABC1\AppData\Local\Temp\pip-hto4uniu-record\install-record.txt --single-version- externally-managed --compile" failed with error code 1 in C:\Users\ABC1\AppD ata\Local\Temp\pip-build-cp30pok9\scikit-bio Any suggestions helping me out of this situation are welcome. P.S. I run Python 3.4 on a Windows 7 desktop (6 GB ram). Answer: pyldavis does not work for windows machines because sci-kit bio package is not compiled for windows binaries... it seems this will be available mid 2016. You will need to use Linux or OSX to get pyldavis working.
How to verify if indexes of letter from word matches index of letter from words from list in python? Question: I have multiple functions which return a list of words (each function contains words that start with the same letter): def get_a(): # ..some code return words_a # words_a contain a list with some words that begin with a ... # and so on def get_y(): # ..some code return words_y # words_y contain a list with some words that begin with y Output example: `['yahoo', 'yep', 'yellow']` Now, I have a random word ( I know its `len` and only some letters which are located at specific indexes - I also know these ) Supposing that I have the following `partial_word` (I have `0` instead of the empty spaces): `partial_word = 00LL0W` What is the best way of getting a list with words(from all my functions) that will satisfy the following condition: * all known index letters(in my example `L(position2) L(position3) W(position5`) from the `partial_word` will match at the exact same positions the letters from the words from my functions ? * another important detail is that each function returns a list with 3-4k words. Answer: You may make use of the build-in regular expression library import re partial_word = '00LL0W' pattern = '^' + partial_word + '$' pattern = pattern.replace('0', '\w') example_word = 'YELLOW' m = re.match(pattern, example_word) print m.group(0)
Create a list of lists / matrices from a text file in Python 3.4 Question: I need to create a set of matrices from the file below, the lines/rows with the same value of Z will go in a matrix together. Below is a shortened version of my txt file: X Y Z -1 10 0 1 20 5 2 15 10 2 50 10 2 90 10 3 15 11 4 50 11 5 90 11 6 13 14 7 50 14 8 70 14 8 95 14 8 75 14 So for example my first matrix will be [-1, 10, 0], my second one will be [1, 20, 5], my third will be ([2, 15, 10], [2, 50, 10], [2, 90, 10]) etc I've looked at a few questions related to this but nothing seems to be quite right. I started by making each column an array. I was thinking a for loop might work well. So far I have f = open("data.txt", "r") header1 = f.readline() for line in f: line = line.strip() columns = line.split() x = columns[0] y = columns[1] z = columns[2] i = line in f z.old = line(i-1,4) i=1 for line in f: f.readline(i) if z(0) == [i,3]: line(i) = matrix[i,:] else z(0) != [i,3]: store line(i) as M continue i = i+1 however, I'm getting 'invalid syntax' for line, else z(0) != line(4): By this else clause, I mean that `if z(0)/(z initial) is not equal to line(4)` then this line will then get stored as the first line of the next matrix we will check under this code. However, I'm not sure how well this would work. Any help would be greatly appreciated! Answer: The following should work for your data, it assumes the columns in your text file are tab delimited: import csv import operator with open('input.txt', 'rb') as f_input: csv_input = csv.reader(f_input, delimiter='\t') headers = next(csv_input) row_number = 1 for k, g in itertools.groupby(csv_input, key=operator.itemgetter(0)): row = [] for entry in g: entry = [float(e) for e in entry] row.append([row_number] + entry) row_number += 1 print row This would print the following output: [[1, -1, 10, 0]] [[2, 1, 20, 5]] [[3, 2, 15, 10], [4, 2, 50, 10], [5, 2, 90, 10]] [[6, 3, 15, 11]] [[7, 4, 50, 11]] [[8, 5, 90, 11]] [[9, 6, 13, 14]] [[10, 7, 50, 14]] [[11, 8, 70, 14], [12, 8, 95, 14], [13, 8, 75, 14]] If your CSV file is exactly as you have it shown, i.e. with spaces separating the columns, then you will need to change the `csv.reader` line as follows: csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True)
search for pattern in string Question: I need to find a pattern ATG[any number of any characters triplets][TGA or TAG or TGA], where I need only the first ATG, further up to [TGA or TAG or TAA] do not matter. And this should be interrupted at [TGA or TAG or TAA]. In string there could be several such, they do not need to overlap. For example search on 'ATGcccATGgggTAGgATGtttTAA' should give 'ATGcccATGgggTAG' and 'ATGtttTAA' as a result. Is there any way to do this in Python? Answer: This is a job for a regex. (Note that your expected result does not seem to match your specification; you originally say you want to match up to TGA, TAG or TGA, but then in the result you match up to TAA. I'll assume the end of the string is meant to be TGA.) import re target = 'ATGcccATGgggTAGgATGtttTGA' results = re.findall(r'(ATG.*?(?:TAG|TGA|TGA))', target) # ['ATGcccATGgggTAG', 'ATGtttTGA']
Why Python splits read function into multiple syscalls? Question: I tested this: strace python -c "fp = open('/dev/urandom', 'rb'); ans = fp.read(65600); fp.close()" With the following partial output: read(3, "\211^\250\202P\32\344\262\373\332\241y\226\340\16\16!<\354\250\221\261\331\242\304\375\24\36\253!\345\311"..., 65536) = 65536 read(3, "\7\220-\344\365\245\240\346\241>Z\330\266^Gy\320\275\231\30^\266\364\253\256\263\214\310\345\217\221\300"..., 4096) = 4096 There are two calls for read syscall with different number of requested bytes. When I repeat the same using dd command, dd if=/dev/urandom bs=65600 count=1 of=/dev/null just one read syscall is triggered using the exact number of bytes requested. read(0, "P.i\246!\356o\10A\307\376\2332\365=\262r`\273\"\370\4\n!\364J\316Q1\346\26\317"..., 65600) = 65600 I have googled this without any possible explanation. Is this related to page size or any Python memory management? Why does this happen? Answer: I did some research on exactly why this happens. Note: I did my tests with Python 3.5. Python 2 has a different I/O system with the same quirk for a similar reason, but this was easier to understand with the new IO system in Python 3. As it turns out, this is due to Python's BufferedReader, not anything about the actual system calls. You can try this code: fp = open('/dev/urandom', 'rb') fp = fp.detach() ans = fp.read(65600) fp.close() If you try to strace this code, you will find: read(3, "]\"\34\277V\21\223$l\361\234\16:\306V\323\266M\215\331\3bdU\265C\213\227\225pWV"..., 65600) = 65600 Our original file object was a BufferedReader: >>> open("/dev/urandom", "rb") <_io.BufferedReader name='/dev/urandom'> If we call `detach()` on this, then we throw away the BufferedReader portion and just get the FileIO, which is what talks to the kernel. At this layer, it'll read everything at once. So the behavior that we're looking for is in BufferedReader. We can look in `Modules/_io/bufferedio.c` in the Python source, specifically the function `_io__Buffered_read_impl`. In our case, where the file has not yet been read from until this point, we dispatch to `_bufferedreader_read_generic`. Now, this is where the quirk we see comes from: while (remaining > 0) { /* We want to read a whole block at the end into buffer. If we had readv() we could do this in one pass. */ Py_ssize_t r = MINUS_LAST_BLOCK(self, remaining); if (r == 0) break; r = _bufferedreader_raw_read(self, out + written, r); Essentially, this will read as many full "blocks" as possible directly into the output buffer. The block size is based on the parameter passed to the `BufferedReader` constructor, which has a default selected by a few parameters: * Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`. On many systems, the buffer will typically be 4096 or 8192 bytes long. So this code will read as much as possible without needing to start filling its buffer. This will be 65536 bytes in this case, because it's the largest multiple of 4096 bytes less than or equal to 65600. By doing this, it can read the data directly into the output and avoid filling up and emptying its own buffer, which would be slower. Once it's done with that, there might be a bit more to read. In our case, `65600 - 65536 == 64`, so it needs to read at least 64 more bytes. But yet it reads 4096! What gives? Well, the key here is that the point of a BufferedReader is to minimize the number of kernel reads we actually have to do, as each read has significant overhead in and of itself. So it simply reads another block to fill its buffer (so 4096 bytes) and gives you the first 64 of these. Hopefully, that makes sense in terms of explaining why it happens like this. As a demonstration, we could try this program: import _io fp = _io.BufferedReader(_io.FileIO("/dev/urandom", "rb"), 30000) ans = fp.read(65600) fp.close() With this, strace tells us: read(3, "\357\202{u'\364\6R\fr\20\f~\254\372\3705\2\332JF\n\210\341\2s\365]\270\r\306B"..., 60000) = 60000 read(3, "\266_ \323\346\302}\32\334Yl\ry\215\326\222\363O\303\367\353\340\303\234\0\370Y_\3232\21\36"..., 30000) = 30000 Sure enough, this follows the same pattern: as many blocks as possible, and then one more. `dd`, in a quest for high efficiency of copying lots and lots of data, would try to read up to a much larger amount at once, which is why it only uses one read. Try it with a larger set of data, and I suspect you may find multiple calls to read. TL;DR: the BufferedReader reads as many full blocks as possible (64 * 4096) and then one extra block of 4096 to fill its buffer. EDIT: The easy way to change the buffer size, as @fcatho pointed out, is to change the `buffering` argument on `open`: > > open(name[, mode[, buffering]]) > > > ( ... ) > > The optional buffering argument specifies the file’s desired buffer size: 0 > means unbuffered, 1 means line buffered, any other positive value means use > a buffer of (approximately) that size (in bytes). A negative buffering means > to use the system default, which is usually line buffered for tty devices > and fully buffered for other files. If omitted, the system default is used. This works on both [Python 2](https://docs.python.org/2/library/functions.html#open) and [Python 3](https://docs.python.org/3/library/functions.html#open).
Replace sequences between files using Biopython Question: I have two protein sequences FASTA files: nsp.fasta --> original file wsp.fasta --> output file from a signal peptide predictor tool, which returned the proteins in nsp.fasta with the signal stripped. For example: record in nsp.fasta: >gi|564250271|ref|XP_006264203.1| PREDICTED: apolipoprotein D [Alligator mississippiensis] MRGMLALLAALLGLLGLVEGQTFHMGQCPNPPVQEDFDPSKYLGKWYEIEKLPSGFEQER CVQANYSLKANGKIKVLTKMVRSAQHLTCLQHRMMLLVSSPVMPASPYWVVATDYENYAL VYSCTSFFWLFHVDYAWIRSRTPQLHPETVEHLKSVLRSYRIQTGMMLPTDQMNCPSDM record in wsp.fasta: >gi|564250271|ref|XP|006264203.1| PREDICTED: apolipoprotein D [Alligator mississippiensis]; MatureChain: 21-179 QTFHMGQCPNPPVQEDFDPSKYLGKWYEIEKLPSGFEQERCVQANYSLKANGKIKVLTKM VRSAQHLTCLQHRMMLLVSSPVMPASPYWVVATDYENYALVYSCTSFFWLFHVDYAWIRS RTPQLHPETVEHLKSVLRSYRIQTGMMLPTDQMNCPSDM However, not all the proteins in nsp.fasta contained a signal peptide, so wsp.fasta is a subset of the proteins in nsp.fasta that contains the signal. What I need is a unique file that contains all the protein records, both proteins with no signal peptide found and the mature chains with the signal peptide stripped. I have tried the following: from Bio import SeqIO file1 = SeqIO.parse(r"c:\Users\Sergio\Desktop\nsp.fasta", "fasta") file2 = SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.fasta", "fasta") for seq1 in file1: for seq2 in file2: if seq2.id == seq1.id: seq1.seq = seq2.seq SeqIO.write(seq1, r"c:\Users\Sergio\Desktop\nuevsp.fasta", "fasta") But there's no output at all. I have tried putting the SeqIO.write out of the loops, and it returns a blank file. What am I doing wrong? There already exist any method to merge two files or to replace sequences in one file with sequences in other file? Thank you in advance!! Sergio Edited code, I added an elif clause in an attempt to also add the records in nsp.fasta that doesn't match wsp.fasta, but it doesn't work: to_write = [] for seq1 in SeqIO.parse(r"c:\Users\Sergio\Desktop\nsp.txt", "fasta"): for seq2 in SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.txt", "fasta"): if seq1.id == seq2.id: seq1.seq = seq2.seq to_write.append(seq1) elif seq1.id != seq2.id: to_write.append(seq1) SeqIO.write(to_write, r"c:\Users\Sergio\Desktop\nuevsp.txt", "fasta") Answer: As you have written it, every time you write a new sequence, you're overwriting the previous one. Try storing your records in a list and then writing out the list when the loop is completed. to_write = [] for seq1 in SeqIO.parse(r"c:\Users\Sergio\Desktop\nsp.fasta", "fasta"): for seq2 in SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.fasta", "fasta"): if seq2.id == seq1.id: seq1.seq = seq2.seq to_write.append(seq1) SeqIO.write(to_write, r"c:\Users\Sergio\Desktop\nuevsp.fasta", "fasta") Edit to suggest another approach using list comprehensions: ids_to_save = [x.id for x in SeqIO.parse(r"c:\Users\Sergio\Desktop\nsp.fasta", "fasta")] records_to_save = [x for x in SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.fasta", "fasta") if (x.id in ids_to_save)] SeqIO.write(records_to_save, r"c:\Users\Sergio\Desktop\nuevsp.fasta", "fasta") Edit to address the "add the records in nsp.fasta that doesn't match wsp.fasta" need - general approach, not necessarily exact code: ids_not_wanted = [x.id for x in SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.fasta", "fasta")] records_to_save_2 = [x for x in SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.fasta", "fasta") if (x.id not in ids_not_wanted)] records_to_save.append(records_to_save_2) # If duplicate records are a problem, eliminate them using "set" records_to_save = list(set(records_to_save)) SeqIO.write(records_to_save, r"c:\Users\Sergio\Desktop\nuevsp.fasta", "fasta")
How do I add a 'google' module for protocol buffers in Python in Visual Studio 2013? Question: I'm following the tutorial at <https://developers.google.com/protocol- buffers/docs/pythontutorial> . I've managed to create the `addressbook_pb2.py` from the proto file. I added `addressbook_pb2.py` to my project, and when I do `import addressbook_pb2` the .py file pops up as I type the name, so I know the program recognizes it. When I try to run the program, which consists of only the line `import addressbook_pb2`, I receive the error `No module named 'google'`. I am extremely new to Python, how would I go about fixing this error? I am running Python 3.4 in Visual Studio 2013 The error is caused at each `importing google.protobuf` line in my 'addressbook_pb2.py' file # Generated by the protocol buffer compiler. DO NOT EDIT! # source: addressbook.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 Answer: This problem is often caused by having multiple Pythons installed. Solutions to this is explained [here](http://stackoverflow.com/questions/21196648/how- can-i-use-protocol-buffers-for-python-on-windows) and [here](http://stackoverflow.com/questions/31308812/no-module-named-google- protobuf).
Python regex: Remove a pattern at the end of string Question: Input: `blah.(2/2)` Desired Output: `blah` Input can be "blah.(n/n)" where n can be any single digit number. How do I use regex to achieve "blah"? This is the regex I currently have which doesn't work: m = re.sub('[.[0-9] /\ [0-9]]{6}$', '', m) Answer: You need to use regex `\.\(\d/\d\)$` >>> import re >>> str = "blah.(2/2)" >>> re.sub(r'\.\(\d/\d\)$', '',str) 'blah' **[Regex explanation here](https://regex101.com/r/uB8vX3/2)** ![Regular expression visualization](https://www.debuggex.com/i/0OCKYmNVzwWQbubU.png)
Python tkinter update_idletasks is blanking the window Question: [This has been fairly significantly edited in the light of comments to the original post, and to make the context - 2 modules - clearer and to summarise what I think is the key underlying issue. The code is also updated. I have a working version but am not at all sure its done the right way.] (Disclaimer ... Im learning Tkinter as I go along!) Im attempting to display a progress bar while an app is running (eg walking a music library folder tree but that doesnt matter here). I'd like to implement this as a class in a separate module from the main app so I can use it elsewhere (also the app itself is actually in 2 modules). For that reason, and also because I don't want to upset the app's main window design Id like the progress bar to appear in a separate window. I've tried this two ways ... my own crudely drawn progress bar using a text widget, and - once I discovered it - ttk.Progressbar. Im now focusing on using ttk.Progressbar. Note however I had essentially the same problem with either approach, which is getting the contents of the progress window to display properly without preventing control reverting back to the calling module. My class for this (ProgressBar) has methods to start, update, and stop the progress bar. As I understand it there are three ways to force refreshing of the status window in the class methods. All three seem to have drawbacks. * root.master.mainloop() keeps control in the progress window and the app stops executing. This basically defeats the purpose. * root.master.update_idletasks() gives control back to the calling app but the status window is blanked out. Also defeats the purpose, for a different reason. * root.master.update() seems to work perfectly, the status window is updated with visible contents and control goes back to the calling app. HOWEVER Ive read in several places this is a dangerous method to use. So the basic questions are - What is the correct way to force the window to update (eg the Set method); and why is update_idletasks() blanking the progress window. I believe the following code reflects the suggestions made but I have adapted it to reflect the intended import class. # dummy application importing the StatusBar class. # this reflects app is itslef using tkinter from ProgressBar12 import ProgressBar import tkinter as Tk import time import os def RunAppProcess(): print('App running') Bar = ProgressBar(tkroot) # '' arg to have ProgressBar create its tkroot Bar.start('Progress...', 0) # >0 determinate (works) / 0 for indeterminate (doesnt!) print('starting process') # this simulates some process, (eg for root, dirs, files = os.walk(lib)) for k in range(10): Bar.step(5) # (should be) optional for indeterminate time.sleep(.2) Bar.stop('done') # '' => kill the window; or 'message' to display in window def EndAppProcess(): tkroot.withdraw() tkroot.destroy() # Application init code, the application is using tkinter # (should probably be in an init procedure etc, but this will serve) tkroot = Tk.Tk() tkroot.title("An Application") tkroot.geometry("100x100") tkroot.configure(bg='khaki1') # a 2 button mini window: [Start] and [Quit] Tk.Button(tkroot, text='Start', bg='orange', command=RunAppProcess).grid(sticky=Tk.W) Tk.Button(tkroot, text="Quit", bg="orange", command=EndAppProcess).grid(sticky=Tk.W) tkroot.mainloop() ProgressBar Module # determinate mode import tkinter as Tk import tkinter.font as TkF from tkinter import ttk import time # print statements are for tracing execution # changes from the sample code previsouly given reflect: # - suggestions made in the answer and in comments # - to reflect the actual usage with the class imported into a calling module rather than single module solution # - consistent terminology (progress not status) # - having the class handle either determinate or indeterminate progress bar class ProgressBar(): def __init__(self, root): print('progress bar instance init') if root == '': root = tkInit() self.master=Tk.Toplevel(root) # Tk.Button(root, text="Quit all", bg="orange", command=root.quit).grid() A bit rude to mod the callers window self.customFont2 = TkF.Font(family="Calibri", size=12, weight='bold') self.customFont5 = TkF.Font(family="Cambria", size=16, weight='bold') self.master.config(background='ivory2') self.create_widgets() self.N = 0 self.maxN = 100 # default for % def create_widgets(self): self.msg = Tk.Label(self.master, text='None', bg='ivory2', fg='blue4') #, font=self.customFont2) self.msg.grid(row=0, column=0, sticky=Tk.W) self.bar = ttk.Progressbar(self.master, length=300, mode='indeterminate') self.bar.grid(row=1, column=0, sticky=Tk.W) #self.btn_abort = Tk.Button(self.master, text=' Abort ', command=self.abort, font=self.customFont2, fg='maroon') #self.btn_abort.grid(row=2,column=0, sticky=Tk.W) #self.master.rowconfigure(2, pad=3) print('progress bar widgets done') def start(self, msg, maxN): if maxN <= 0: #indeterminate self.msg.configure(text=msg) self.bar.configure(mode='indeterminate') self.maxN = 0 self.bar.start() self.master.update() else: # determinate self.msg.configure(text=msg) self.bar.configure(mode='determinate') self.maxN = maxN self.N = 0 self.bar['maximum'] = maxN self.bar['value'] = 0 def step(self, K): #if self.maxN == 0: return # or raise error? self.N = min(self.maxN, K+self.N) self.bar['value'] = self.N self.master.update() # see set(..) def set(self, K): #if self.maxN == 0: return self.N = min(self.maxN, K) self.bar['value'] = self.N #self.master.mainloop() # <<< calling module does not regain control. Pointless. #self.master.update_idletasks # <<< works, EXCEPT statusbar window is blank! Also pointless. But calling module regains control self.master.update() # <<< works in all regards, BUT I've read this is dangerous. def stop(self, msg): print('progress bar stopping') self.msg.configure(text=msg) if self.maxN <= 0: self.bar.stop() else: self.bar['value'] = self.maxN #self.bar.stop() if msg == '': self.master.destroy() else: self.master.update() def abort(self): # eventually will raise an error to the calling routine to stop the process self.master.destroy() def tkInit(): print('progress bar tk init') tkroot = Tk.Tk() tkroot.title("Progress Bar") tkroot.geometry("250x50") tkroot.configure(bg='grey77') tkroot.withdraw() return tkroot if (__name__ == '__main__'): print('start progress bar') tkroot = tkInit() tkroot.configure(bg='ivory2') Bar = ProgressBar(tkroot) Bar.start('Demo', 10) for k in range(11): Bar.set(k) time.sleep(.2) Bar.stop('done, you can close me') else: # called from another module print('progress bar module init. (nothing) done.') This is based on the first of the solutions in the answer; as an alternative I will try the second using after() .... I first have to understand exactly what that does. Answer: First, you don't call mainloop() anywhere. The following code displays a moving progress bar until you hit the abort button. The for() loop in your code above serves no purpose as it does nothing except stop program execuption for 0.3*20 seconds. If you want to update the progress bar yourself, then see the 2nd example and how it uses "after" to call an update function until the progress bar completes. And note that everything associated with it is contained in the class, which is one of the reasons you would use a class. You could also call the update function from outside the class, but the update function would still be in the same class that created the progress bar. import Tkinter as Tk import tkFont as TkF import ttk import time class StatusBar(): def __init__(self, root): self.master=Tk.Toplevel(root) Tk.Button(root, text="Quit all", bg="orange", command=root.quit).grid() self.customFont2 = TkF.Font(family="Calibri", size=12, weight='bold') self.customFont5 = TkF.Font(family="Cambria", size=16, weight='bold') self.master.config(background='ivory2') self.ctr=0 self.create_widgets() def create_widgets(self): self.msg = Tk.Label(self.master, text='None', bg='ivory2', fg='blue4', font=self.customFont2, width=5) self.msg.grid(row=0, column=0, sticky=Tk.W) self.bar = ttk.Progressbar(self.master, length=300, mode='indeterminate') self.bar.grid(row=1, column=0, sticky=Tk.W) self.btn_abort = Tk.Button(self.master, text=' Abort ', command=self.abort, font=self.customFont2, fg='maroon') self.btn_abort.grid(row=2,column=0, sticky=Tk.W) self.master.rowconfigure(2, pad=3) print('widgets done') def Start(self, msg): self.msg.configure(text=msg) self.bar.start() def Stop(self, msg): self.msg.configure(text=msg) self.bar.stop() def abort(self): # eventually will raise an error to the calling routine to stop the process self.master.destroy() if (__name__ == '__main__'): print('start') tkroot = Tk.Tk() tkroot.title("Status Bar") tkroot.geometry("500x75") tkroot.configure(bg='ivory2') Bar = StatusBar(tkroot) Bar.Start('Demo') tkroot.mainloop() Uses after() to update the progress bar try: import Tkinter as tk ## Python 2.x except ImportError: import tkinter as tk ## Python 3.x import ttk class TestProgress(): def __init__(self): self.root = tk.Tk() self.root.title('ttk.Progressbar') self.increment = 0 self.pbar = ttk.Progressbar(self.root, length=300) self.pbar.pack(padx=5, pady=5) self.root.after(100, self.advance) self.root.mainloop() def advance(self): # can be a float self.pbar.step(5) self.increment += 5 if self.increment < 100: self.root.after(500, self.advance) else: self.root.quit() TP=TestProgress()
How to remove connecting area in fill_between() using Python and MatPlot Question: I am graphing +-2 standard deviations from the mean on my graph (the green points). However, I would rather have straight vertical lines on top of each x-mean, because currently there is a connecting shade area between states that is misleading. How can I do this? I've tried everything and can't figure it out. Thanks in advance. (Since I'm new to Stack Overflow I can't post an image of my graph unfortunately.) plt.scatter(x= joined.index.values, y = joined.poll_mean, color = "g") plt.scatter(x= joined.index.values, y = joined.spread,color = joined.color) plt.fill_between(joined.index,(joined.poll_mean + 2*joined.poll_std).values, (joined.poll_mean - 2*joined.poll_std).values, color='g', alpha = .3) plt.xticks(joined.index.values, joined.state.values, rotation='vertical') Answer: Are you trying to do error bars? There is a matplotlib package for that. An example piece of code to do this (from [here](http://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html)): import numpy as np import matplotlib.pyplot as plt # example data x = np.arange(0.1, 4, 0.5) y = np.exp(-x) # example variable error bar values yerr = 0.1 + 0.2*np.sqrt(x) xerr = 0.1 + yerr # First illustrate basic pyplot interface, using defaults where possible. plt.figure() plt.errorbar(x, y, xerr=0.2, yerr=0.4) plt.title("Simplest errorbars, 0.2 in x, 0.4 in y") Also as a tip, for people to better help you, provide code that can reproduce your problem in full.
Combine functions to later use in map Question: I have a list of items, coming from one object which are of type A, and a library that operates on object of type B. I would like to convert A to B, and later call B's function in a pythonic way. What I have come up with so far: def convert_A_to_B(A): return B(A.something, A.something_else) def doStuff(a_list): converted_to_b = list(map(convert_A_to_B, a_list) return list(map(B.function, converted_to_b)) I could create a lambda to combine these functions, but I feel like there should be an easier way. Something like: return list(map(combine(convert_A_to_B, B.function))) Answer: from functools import partial, reduce combine = lambda *xs: partial (reduce, lambda v,x: x(v), xs) The function is usable such as `combine (A.foo, A.bar) (x)` with is equivalent to `A.bar(A.foo (x))`. `combine` will accept a variadic number of functions, and return a new function that accepts a single value. This value will then be passed through every previously mentioned function (in chain) until a final result is yield. * * * ### Sample usage map (combine (convert_A_to_B, B.function), a_list)
incrementing key,value pair inside for loop iterating over dictionary Question: How can I increment key value pair inside a for loop while iterating over dictionary in python? for key,value in mydict.iteritems(): if condition: #inc key,value #something to do I have tried using `next(mydict.iteritems())` and `mydict.iteritems().next()` but in vain. I am using python2.7. EDIT - I know that forloop automatically increments the key,value pair. I want to manually increment to next pair ( Thus resulting in 2 increments). Also I can't use continue because I want both the key value pair to be accessible at same time. So that when I increment, I have the current key value pair as well as the next. If I use continue, I lose access to current and only get next key,value pair. Answer: If you need simultaneous access to two key-value pairs use pairwise from [itertools recipes](https://docs.python.org/2/library/itertools.html). from itertools import izip, tee def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return izip(a, b)
Stepsize control of dopri5 integrator Question: I am trying to solve a simple example with the `dopri5` integrator in `scipy.integrate.ode`. As the documentation states > This is an explicit runge-kutta method of order (4)5 due to Dormand & Prince > (with stepsize control and dense output). this should work. So here is my example: import numpy as np from scipy.integrate import ode import matplotlib.pyplot as plt def MassSpring_with_force(t, state): """ Simple 1DOF dynamics model: m ddx(t) + k x(t) = f(t)""" # unpack the state vector x = state[0] xd = state[1] # these are our constants k = 2.5 # Newtons per metre m = 1.5 # Kilograms # force f = force(t) # compute acceleration xdd xdd = ( ( -k*x + f) / m ) # return the two state derivatives return [xd, xdd] def force(t): """ Excitation force """ f0 = 1 # force amplitude [N] freq = 20 # frequency[Hz] omega = 2 * np.pi *freq # angular frequency [rad/s] return f0 * np.sin(omega*t) # Time range t_start = 0 t_final = 1 # Main program state_ode_f = ode(MassSpring_with_force) state_ode_f.set_integrator('dopri5', rtol=1e-6, nsteps=500, first_step=1e-6, max_step=1e-3) state2 = [0.0, 0.0] # initial conditions state_ode_f.set_initial_value(state2, 0) sol = np.array([[t_start, state2[0], state2[1]]], dtype=float) print("Time\t\t Timestep\t dx\t\t ddx\t\t state_ode_f.successful()") while state_ode_f.t < (t_final): state_ode_f.integrate(t_final, step=True) sol = np.append(sol, [[state_ode_f.t, state_ode_f.y[0], state_ode_f.y[1]]], axis=0) print("{0:0.8f}\t {1:0.4e} \t{2:10.3e}\t {3:0.3e}\t {4}".format( state_ode_f.t, sol[-1, 0]- sol[-2, 0], state_ode_f.y[0], state_ode_f.y[1], state_ode_f.successful())) The result I get is: Time Timestep dx ddx state_ode_f.successful() 0.49763822 4.9764e-01 2.475e-03 -8.258e-04 False 0.99863822 5.0100e-01 3.955e-03 -3.754e-03 False 1.00000000 1.3618e-03 3.950e-03 -3.840e-03 False with a warning: > c:\python34\lib\site-packages\scipy\integrate_ode.py:1018: UserWarning: > dopri5: larger nmax is needed self.messages.get(idid, 'Unexpected idid=%s' % > idid)) The result is incorect. If I run the same code with `vode` integrator, I get the expected result. **Edit** A similar issue is described here: [Using adaptive step sizes with scipy.integrate.ode](http://stackoverflow.com/questions/12926393/using- adaptive-step-sizes-with-scipy-integrate-ode) The suggested solution recommends setting `nsteps=1`, which solves the ODE correctly and with step-size control. However the integrator returns `state_ode_f.successful()` as `False`. Answer: No, there is nothing wrong. You are telling the integrator to perform an integration step to `t_final` and it performs that step. Internal steps of the integrator are not reported. * * * The sensible thing to do is to give the desired sampling points as input of the algorithm, set for example `dt=0.1` and use state_ode_f.integrate( min(state_ode_f.t+dt, t_final) ) There is no single-`step` method in `dopri5`, only `vode` has it defined, see the source code <https://github.com/scipy/scipy/blob/v0.14.0/scipy/integrate/_ode.py#L376>, this could account for the observed differences. As you found in [Using adaptive step sizes with scipy.integrate.ode](http://stackoverflow.com/questions/12926393/using- adaptive-step-sizes-with-scipy-integrate-ode), one can force single-step behavior by setting the iteration bound `nsteps=1`. This will produce a warning every time, so one has to suppress these specific warnings to see a sensible result. * * * You should not use a parameter (which is a constant for the integration interval) for a time-dependent force. Use inside `MassSpring_with_force` the evaluation `f=force(t)`. Possibly you could pass the function handle of `force` as parameter.
Why does a query invoke a auto-flush in SQLAlchemy? Question: The code you see above is just a sample but it works to reproduce this error: sqlalchemy.exc.IntegrityError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely) (sqlite3.IntegrityError) NOT NULL constraint failed: X.nn [SQL: 'INSERT INTO "X" (nn, val) VALUES (?, ?)'] [parameters: (None, 1)] A mapped instance is still added to a session. The instance wants to know (which means query on the database) if other instances its own type exists having the same values. There is a second attribute/column (`_nn`). It is specified to `NOT NULL`. But by default it is `NULL`. When the instance (like in the sample) is still added to the session a call to `query.one()` invoke a auto-flush. This flush create an `INSERT` which tries to store the instance. This fails because `_nn` is still null and violates the `NOT NULL` constraint. That is what I understand currently. But the question is why does it invoke an auto-flush? Can I block that? #!/usr/bin/env python3 import os.path import os import sqlalchemy as sa import sqlalchemy.orm as sao import sqlalchemy.ext.declarative as sad from sqlalchemy_utils import create_database _Base = sad.declarative_base() session = None class X(_Base): __tablename__ = 'X' _oid = sa.Column('oid', sa.Integer, primary_key=True) _nn = sa.Column('nn', sa.Integer, nullable=False) # NOT NULL! _val = sa.Column('val', sa.Integer) def __init__(self, val): self._val = val def test(self, session): q = session.query(X).filter(X._val == self._val) x = q.one() print('x={}'.format(x)) dbfile = 'x.db' def _create_database(): if os.path.exists(dbfile): os.remove(dbfile) engine = sa.create_engine('sqlite:///{}'.format(dbfile), echo=True) create_database(engine.url) _Base.metadata.create_all(engine) return sao.sessionmaker(bind=engine)() if __name__ == '__main__': session = _create_database() for val in range(3): x = X(val) x._nn = 0 session.add(x) session.commit() x = X(1) session.add(x) x.test(session) Of course a solution would be to _not_ add the instance to the session before `query.one()` was called. This work. But in my real (but to complex for this question) use-case it isn't a nice solution. Answer: How to turn off [autoflush](http://docs.sqlalchemy.org/en/latest/orm/session_api.html?highlight=autoflush#sqlalchemy.orm.session.Session.params.autoflush) feature: * Temporary: you can use [no_autoflush](http://docs.sqlalchemy.org/en/latest/orm/session_api.html?highlight=autoflush#sqlalchemy.orm.session.Session.params.autoflush) context manager on snippet where you query the database, i.e. in `X.test` method: def test(self, session): with session.no_autoflush: q = session.query(X).filter(X._val == self._val) x = q.one() print('x={}'.format(x)) * Session-wide: just pass `autoflush=False` to your sessionmaker: return sao.sessionmaker(bind=engine, autoflush=False)()
Atom Editor: CMD + R => No Symbols Found Question: For some reason, Atom doesn't seem to recognize function tags properly with the default plugin it has mapped to CMD + r. I've tried completely uninstalling and deleting Atom and it's files and reinstalling to get the function detection to work properly, but to no avail. Function detection does not work in C++ or Python, for me. Instead of just recognizing functions in my Python scripts, it will even list my numpy imports etc. Somethings pretty wacky with it. Does anyone know how to deal with this? [![The result of hitting CMD+r in the Atom.io application.](http://i.stack.imgur.com/VGkU4.png)](http://i.stack.imgur.com/VGkU4.png) Answer: I found the solution from an atom github [issue comment](https://github.com/atom/symbols- view/issues/173?#issuecomment-222352841) about the same problem, launching Atom from command line will make it work. `cmd+r` maps to `symbols-view:toggle-file-symbols` command, which using `ctags` to generate language-specific symbols. `ctags` will generate temporary symbol list file inside your `$TMPDIR` directory , but that environment variable is not known when Atom launched from Finder.
django - ZeroDivisionError when using thumbnail low-level API Question: I implemented thumbnails for images that are displayed in an inline form, by creating my custom form ([like this](http://blog.glaucocustodio.com/2014/04/08/display-thumbnails-in-django- admin-with-sorl-thumbnail/)). However, in one case (that I noticed) so far, I get a ZeroDivisionError when trying to edit a project, and this is apparently caused by [this line](https://github.com/python- pillow/Pillow/blob/master/PIL/TiffImagePlugin.py#L482) in TiffImagePlugin, which is called by get_thumbnail. Here's the error traceback [![enter image description here](http://i.stack.imgur.com/L0dmq.png)](http://i.stack.imgur.com/L0dmq.png) [![enter image description here](http://i.stack.imgur.com/7QCtZ.png)](http://i.stack.imgur.com/7QCtZ.png) And here's my code (note I'm also using admin-sortable but I don't think that's related): from django.contrib.admin.widgets import AdminFileWidget from django.utils.safestring import mark_safe from django.forms import ModelForm from sorl.thumbnail import get_thumbnail from models import Image class AdminImageWidget(AdminFileWidget): def render(self, name, value, attrs=None): output = [] if value and getattr(value, "url", None): t = get_thumbnail(value,'80x80') output.append('<img src="{}">'.format(t.url)) output.append(super(AdminFileWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output)) class ImageForm(ModelForm): class Meta: fields = '__all__' model = Image widgets = { 'img': AdminImageWidget, } class ImageInline(SortableStackedInline): model = Image extra = 3 form = ImageForm class ProjectAdmin(NonSortableParentAdmin): list_display = ('name', 'description') inlines = [ImageInline] list_filter = ('type',) search_fields = ('name', 'description') Note this doesn't happen all the time, it only happens when trying to edit a _specific_ project (and I'm assuming it might happen with others as well, but so far couldn't find more examples). Any ideas? Thanks in advanced! Answer: Got same error, update Pillow, it helps. $ pip install pillow --upgrade
to clustter the floating point data into suitable buckets in python Question: I have a csv file which has thousands of floating point values arranged in ascending order. I want to bunch/cluster those values into suitable clusters. for example : 0.001 0.002 0.013 0.1 0.101 0.12 0.123 0.112 0.113 0.2 so the clusters should be like 0 - 0.1 with count 4 0.1 - 0.2 with count 6 How can I do this clustering task automatically in python ? Do I need to keep some initial parameters? I have no clue in this regard. Please help. Answer: You can `bisect.bisect_left` to find where the element would land in a list of keys with the correct increment, then simply use that index to get the element from the list of keys and increment its count using a dict. from bisect import bisect_left with open("test.txt") as f: keys = [0.1, 0.2] d = dict.fromkeys(keys, 0) for line in f: ind = bisect_left(keys, float(line)) d[keys[ind]] += 1 print(d) {0.1: 4, 0.2: 6} Another way would be to round by an appropriate amount: with open("test.txt") as f: keys = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] d = dict.fromkeys(keys, 0) for flt in map(float, f): k = round(flt + .05, 1) if flt > .05 else .1 if flt not in d: d[k] += 1 else: d[flt] += 1
Can monads do what this OOP can't? Question: Trying to understand monads and wondering if they'd be useful for data transformation programming in Python, I looked at many introductory explanations. But I don't understand why monads are important. Is the following Python code a good representation of the Maybe monad? class Some: def __init__(self, val): self.val=val def apply(self, func): return func(self.val) class Error: def apply(self, func): return Error() a = Some(1) b = a.apply(lambda x:Some(x+5)) Can you give an example of a monad solution, which cannot be transformed into such OOP code? (Do you think monads for data transformation in OOP languages can be useful?) Answer: Here is a post that discusses monads using Swift as the language that might help you make more sense of them: <http://www.javiersoto.me/post/106875422394> The basic point is that a monad is an object that has three components. 1. A constructor that can take some other object, or objects, and create a monad wrapping that object. 2. A method that can apply a function _that knows nothing about the monad_ to its contents and return the result wrapped in a monad. 3. A method that can apply a function that takes the raw object and returns a result wrapped in the monad, and return that monad. Note that this means even an Array class can be a monad if the language treats methods as first class objects, and the necessary methods exist. If the language doesn't treat methods as first class objects, _even if it's an OO language_ , it will not able able to implement Monads. I think your confusion may be coming from the fact that you are using a multi-paradigm language (Python) and assuming it is a pure OO language.
how to pass python json object to django template Question: I want to pass some data(dict format) from views to template. And then in the template I want to transform it to json format, so that it can be used in javascript. But I tried to use json filter, it turns out it is not a valid filter in django. I also tried to use pass a json data in the context dictionary like this, but I get an error in the template, it says the data is not JSON serializable. i know there is a way to make a another ajax call just to get json data. But I want to get the data in the initial call. items = models.Model1.objects.all() itmes = json.dumps(items) return render(request, "index.html", {"items":items}) The template I try to use is <script type="text/javascript"> var data = {{ items}}; $('#table').DataTable( { data: data,}); </script> # model class Model1(models.Model): token = models.CharField(max_length=100) flag = models.BooleanField(default = False) Answer: You don't have to pass it to template and then transform it to json. You can directly return a string response. import json return HttpResponse(json.dumps({"item":items}))
Python version check Question: When I did like this for checking python version installed python -version the result was like this- Python 2.7.6 when I checked like this- python -v result was like this- # installing zipimport hook import zipimport # builtin # installed zipimport hook # /usr/lib/python2.7/site.pyc matches /usr/lib/python2.7/site.py import site # precompiled from /usr/lib/python2.7/site.pyc # /usr/lib/python2.7/os.pyc matches /usr/lib/python2.7/os.py import os # precompiled from /usr/lib/python2.7/os.pyc import errno # builtin import posix # builtin # /usr/lib/python2.7/posixpath.pyc matches /usr/lib/python2.7/posixpath.py import posixpath # precompiled from /usr/lib/python2.7/posixpath.pyc # /usr/lib/python2.7/stat.pyc matches /usr/lib/python2.7/stat.py import stat # precompiled from /usr/lib/python2.7/stat.pyc # /usr/lib/python2.7/genericpath.pyc matches /usr/lib/python2.7/genericpath.py import genericpath # precompiled from /usr/lib/python2.7/genericpath.pyc # /usr/lib/python2.7/warnings.pyc matches /usr/lib/python2.7/warnings.py import warnings # precompiled from /usr/lib/python2.7/warnings.pyc # /usr/lib/python2.7/linecache.pyc matches /usr/lib/python2.7/linecache.py import linecache # precompiled from /usr/lib/python2.7/linecache.pyc # /usr/lib/python2.7/types.pyc matches /usr/lib/python2.7/types.py import types # precompiled from /usr/lib/python2.7/types.pyc # /usr/lib/python2.7/UserDict.pyc matches /usr/lib/python2.7/UserDict.py import UserDict # precompiled from /usr/lib/python2.7/UserDict.pyc # /usr/lib/python2.7/_abcoll.pyc matches /usr/lib/python2.7/_abcoll.py import _abcoll # precompiled from /usr/lib/python2.7/_abcoll.pyc # /usr/lib/python2.7/abc.pyc matches /usr/lib/python2.7/abc.py import abc # precompiled from /usr/lib/python2.7/abc.pyc # /usr/lib/python2.7/_weakrefset.pyc matches /usr/lib/python2.7/_weakrefset.py import _weakrefset # precompiled from /usr/lib/python2.7/_weakrefset.pyc import _weakref # builtin # /usr/lib/python2.7/copy_reg.pyc matches /usr/lib/python2.7/copy_reg.py import copy_reg # precompiled from /usr/lib/python2.7/copy_reg.pyc # /usr/lib/python2.7/traceback.pyc matches /usr/lib/python2.7/traceback.py import traceback # precompiled from /usr/lib/python2.7/traceback.pyc # /usr/lib/python2.7/sysconfig.pyc matches /usr/lib/python2.7/sysconfig.py import sysconfig # precompiled from /usr/lib/python2.7/sysconfig.pyc # /usr/lib/python2.7/re.pyc matches /usr/lib/python2.7/re.py import re # precompiled from /usr/lib/python2.7/re.pyc # /usr/lib/python2.7/sre_compile.pyc matches /usr/lib/python2.7/sre_compile.py import sre_compile # precompiled from /usr/lib/python2.7/sre_compile.pyc import _sre # builtin # /usr/lib/python2.7/sre_parse.pyc matches /usr/lib/python2.7/sre_parse.py import sre_parse # precompiled from /usr/lib/python2.7/sre_parse.pyc # /usr/lib/python2.7/sre_constants.pyc matches /usr/lib/python2.7/sre_constants.py import sre_constants # precompiled from /usr/lib/python2.7/sre_constants.pyc # /usr/lib/python2.7/_sysconfigdata.pyc matches /usr/lib/python2.7/_sysconfigdata.py import _sysconfigdata # precompiled from /usr/lib/python2.7/_sysconfigdata.pyc # /usr/lib/python2.7/plat-x86_64-linux-gnu/_sysconfigdata_nd.pyc matches /usr/lib/python2.7/plat-x86_64-linux-gnu/_sysconfigdata_nd.py import _sysconfigdata_nd # precompiled from /usr/lib/python2.7/plat-x86_64-linux-gnu/_sysconfigdata_nd.pyc # /usr/lib/python2.7/sitecustomize.pyc matches /usr/lib/python2.7/sitecustomize.py import sitecustomize # precompiled from /usr/lib/python2.7/sitecustomize.pyc import encodings # directory /usr/lib/python2.7/encodings # /usr/lib/python2.7/encodings/__init__.pyc matches /usr/lib/python2.7/encodings/__init__.py import encodings # precompiled from /usr/lib/python2.7/encodings/__init__.pyc # /usr/lib/python2.7/codecs.pyc matches /usr/lib/python2.7/codecs.py import codecs # precompiled from /usr/lib/python2.7/codecs.pyc import _codecs # builtin # /usr/lib/python2.7/encodings/aliases.pyc matches /usr/lib/python2.7/encodings/aliases.py import encodings.aliases # precompiled from /usr/lib/python2.7/encodings/aliases.pyc # /usr/lib/python2.7/encodings/utf_8.pyc matches /usr/lib/python2.7/encodings/utf_8.py import encodings.utf_8 # precompiled from /usr/lib/python2.7/encodings/utf_8.pyc Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. dlopen("/usr/lib/python2.7/lib-dynload/readline.x86_64-linux-gnu.so", 2); import readline # dynamically loaded from /usr/lib/python2.7/lib-dynload/readline.x86_64-linux-gnu.so >>> It looks like I have multiple versions of python installed which are causing problems while installing modules using pip. Even after installing django manage.py runserver shows error regarding unable to find django.core something something. How to solve this problem? Please help!! Answer: python -v is for 'verbose': -v : verbose (trace import statements); also PYTHONVERBOSE=x can be supplied multiple times to increase verbosity Note it is **lowercase** `python -V` will give you the version. (uppercase v)
Find included range from a range given excluded range in python Question: I have a range say (0,1000). My another input will be excluded range [(200,400), (600,800)]. I need as output included range [(0,199), (401,599), (801,1000)]. How do I implement this in python? Answer: You can [chain iterables](https://docs.python.org/2/library/itertools.html#itertools.chain) together: from itertools import chain for i in chain(range(1,200), range(401, 600), range(801, 1001)): # etc Also, if you've been given the range and can only iterate over it once, you can use [**`tee`**](https://docs.python.org/2/library/itertools.html#itertools.tee) and [**`islice`**](https://docs.python.org/2/library/itertools.html#itertools.islice): def excluded(sequence): first, second, third = tee(sequence, 3) yield from chain(islice(first, 1, 200), islice(second, 401, 600), islice(third, 801, 1001)) for i in excluded(range(0, 1000)): # etc.
Proper use of sep in print Question: I am new at python, and I am having problems with the use of sep=. What I want to do is to not have a space between the number `25` and the `.` Here is my code and the error I get. I am running this code on MAC OSX El Capitan's Terminal. code: side = 5 area = side * side print "The area of a square with side ",side,"is ",area,".",sep=" " Output: print "The area of a square with side ",side,"is ",area,".",sep=" " ^ SyntaxError: invalid syntax Answer: `sep` is an argument to the [`print()` _function_](https://docs.python.org/3/library/functions.html#print), which requires you use Python 3 or use a special `from __future__ import print_function` statement in Python 2 (see the [`print()` function documentation](https://docs.python.org/2/library/functions.html#print). The normal plain vanilla [Python 2 `print` _statement_](https://docs.python.org/2/reference/simple_stmts.html#the-print- statement) (which is what you appear to be using) does not support altering the separator used. Since the separator is _always_ a space, you don't need to specify it here at all: print "The area of a square with side ", side, "is ", area, "." If you wanted to print _without_ spaces, use string formatting instead: print "The area of a square with side {} is {}.".format(side, area) If you are using a Python 3 tutorial using `print(foo, bar, baz sep='')` or similar similar syntax, get yourself Python 3 installed, or get yourself a Python 2 specific tutorial instead.
Numbers in a Matrix Question: I tried to solve the following problem with Python: [![enter image description here](http://i.stack.imgur.com/TK8zK.png)](http://i.stack.imgur.com/TK8zK.png) But I got stuck at generating a single valid table. I was expecting the program to display a valid matrix, but in order for the program to continue and not print `None`, I had to assign a `7` for a square that has no possibles. What should be fixed? My code so far: from pprint import pprint import sys import random sys.setrecursionlimit(10000) def getPossiblesForSquare(sqx,sqy,matrix): '''Gets the possible entries of matrix[sqy][sqx]. Assumes it equals 0.''' assert matrix[sqy][sqx]==0 # get the row that it is on rowon=matrix[sqy] # columns are a little trickier colon=[matrix[row][sqx] for row in range(5)] # find the possibilities! possibles=list(range(1,7)) for item in list(set(rowon+colon)): # remove duplicates if not (item == 0) and (item in possibles): del possibles[possibles.index(item)] random.shuffle(possibles) return possibles def getPossiblesForMatrix(matrix): '''Gets all the possible squares for a matrix.''' possiblesdict={} for y in range(6): for x in range(6): if matrix[y][x]==0: possiblesdict[(y,x)]=getPossiblesForSquare(x,y,MATRIX) return possiblesdict def flattenList(matrix): result=[] for i in matrix: if not isinstance(i,list): result+=[i] else: result+=flattenList(i) return result def getPossibleMatrix(startMatrix, iteration=0, yon=1, prevZeroInd=None): if 0 not in flattenList(startMatrix): print('RESULT:\n\n') return startMatrix else: # find&fill in the first blank one ind=flattenList(startMatrix).index(0) y=ind//6 x=ind%6 if (x,y)==prevZeroInd: startMatrix[y][x]=7 else: possibles=getPossiblesForSquare(x,y,startMatrix) if len(possibles)==0: startMatrix[y][x]=7 else: startMatrix[y][x]=possibles[0] if iteration <= 6: return getPossibleMatrix(startMatrix, iteration+1, yon, (x,y)) # <<BUG else: if yon!=4: return getPossibleMatrix(startMatrix, 0, yon+1, (x,y)) MATRIX=[[1,2,3,4,5,6], [2,0,0,0,0,5], [3,0,0,0,0,4], [4,0,0,0,0,3], [5,0,0,0,0,2], [6,5,4,3,2,1]] result=getPossibleMatrix(MATRIX) pprint(result) Answer: ## Why your script hangs: * * * Essentially your script encounters problems here: for item in list(set(rowon + colon)): # remove duplicates if not (item == 0) and (item in possibles): del possibles[possibles.index(item)] * At the third iteration, for the third cell your if condition is evaluated as true for all possible values `[1 to 6]` (if you output the matrix you will see that the `set()` you are creating contains all elements), so you always return zero, re-check the values, return zero [**_ad infinitum_**](https://en.wikipedia.org/wiki/Ad_infinitum). If you're looking to brute-force a solution out of this, you might want to update the `sqx` and `sqy` to go to a different cell when possibles is empty. Another additional small mistake I located was: # you are checking values 1-5 and not 1-6! possibles = list(range(1, 6)) # should be range(7) [exclusive range] * Don't forget that range is exclusive, it doesn't include (excludes) the upper limit. There exist of course, different ways to tackle this problem. * * * ## A possible -alternate- solution: > Read this for the general, alternate view of how to solve this. If you do > not want to see a possible solution, skip the 'code' part. * * * The solution matrix (one of the possible ones) has this form (unless I am making a horrible mistake): MATRIX = [[1, 2, 3, 4, 5, 6], [2, 3, 6, 1, 4, 5], [3, 1, 5, 2, 6, 4], [4, 6, 2, 5, 1, 3], [5, 4, 1, 6, 3, 2], [6, 5, 4, 3, 2, 1]] The Logic is as follows: You must observe the symmetry present in the matrix. Specifically, every row and every column displays a 'flip and reverse' symmetry. For example, the first and last rows are connected by this equation : row[0] = REV(flip(row[n])) Similarly, all additional rows (or columns) have their corresponding counterpart: row[1] = REV(flip(row[n-1])) and so on. So, for `n=6` this essentially boils down to finding the `(n / 2) -1` (because we already know the first and last row!) and afterwards flipping them (not the finger), reversing them and assigning them to their corresponding rows. In order to find these values we can observe the matrix as a combination of smaller matrices: These make the first two (unknown) rows of the matrix: sub_matrix = [[1, 2, 3, 4, 5, 6], [2, 0, 0, 0, 0, 5], [3, 0, 0, 0, 0, 4], [6, 5, 4, 3, 2, 1]] and the other two rows can be made by finding the correct values for these two. Observe the restrictions in hand: In column `[1][1]` and `[1][m-1]` we cannot: * place a `2` or a `5` In columns `[1][2]` and `[1][m-2]` we cannot: * place the previous values (`[2, 5]`) along with (`[3, 4]`) so, we cannot have a value `in` `[2,3,4,5]` For the inner columns we're left with the set `set(1-6) - set(2-5) = [1, 6]` and since we get a normal row and a **_single_** inverted and flipped row for this, we can arbitrarily select a value and add it as a column value. By using another list we can keep track of the values used and fill out the rest of the cells. * * * ### Coding this: (Spoilers) * * * **Note** : I did not use `numpy` for this. You **can** and **should** though. (Also, `Python 2.7`) Also, I did not use recursion for this (you can try to, by finding the same matrix for bigger values of `n` [I believe it's a good fit for a recursive function]. First, in order to not type this all the time, you can create a `n x n` matrix as follows: (This isn't much of a spoiler.) # our matrix must be n x n with n even. n = 6 # Create n x n matrix. head = [i for i in xrange(1, n + 1)] # contains values from 1 to n. zeros = [0 for i in xrange(1, n-1)] # zeros tail = [i for i in xrange(n, 0, -1)] # contains values from n to 1. # Add head and zeros until tail. MATRIX = [([j] + zeros + [(n+1)-j]) if j != 1 else head for j in xrange(1, n)] # Add tail MATRIX.append(tail) Then, create the smaller `(n/2 + 1) x n` array: # Split matrix and add last row. sub_matrix = MATRIX[:(n / 2)] + [tail] Afterwards, a small function called `sub = fill_rows(sub_matrix)` comes in and takes care of business: def fill_rows(mtrx): # length of the sub array (= 4) sub_n = len(mtrx) # From 1 because 0 = head # Until sub_n -1 because the sub_n - 1 is = tail (remember, range is exclusive) for current_row in xrange(1, sub_n - 1): print "Current row: " + str(current_row) # -- it gets messy here -- # get values of inner columns and filter out the zeros (matrix[row][n / 2] == 0 evaluates to False) col_vals_1 = [mtrx[row][n / 2] for row in xrange(0, sub_n) if mtrx[row][(n / 2)]] col_vals_2 = [mtrx[row][(n / 2) - 1] for row in xrange(0, sub_n) if mtrx[row][(n / 2) - 1]] col_vals = col_vals_1 + col_vals_2 # print "Column Values = " + str(col_vals) row_vals = [mtrx[current_row][col] for col in xrange(0, n) if mtrx[current_row][col]] # print "Row Values = " + str(row_vals) # Find the possible values by getting the difference of the joined set of column + row values # with the range from (1 - 6). possible_values = list(set(xrange(1, n + 1)) - set(row_vals + col_vals)) print "Possible acceptable values: " + str(possible_values) # Add values to matrix (pop to remove them) # After removing add to the list of row_values in order to check for the other columns. mtrx[current_row][(n-1)/2] = possible_values.pop() row_vals.append(mtrx[current_row][(n - 1) / 2]) mtrx[current_row][(n-1)/2 + 1] = possible_values.pop() row_vals.append(mtrx[current_row][(n-1) / 2 + 1]) # New possible values for remaining columns of the current row. possible_values = list(set(xrange(1, n + 1)) - set(row_vals)) print "Possible acceptable values: " + str(possible_values) # Add values to the cells. mtrx[current_row][(n - 2)] = possible_values.pop() mtrx[current_row][1] = possible_values.pop() # return updated sub-matrix. return mtrx The only thing left to do now is take those two rows, flip them, reverse them and add the head and tail to them: print '=' * 30 + " Out " + "=" * 30 # Remove first and last rows. del sub[0] sub.pop() # reverse values in lists temp_sub = [l[::-1] for l in sub] # reverse lists in matrix. temp_sub.reverse() # Add them and Print. pprint([head] + sub + temp_sub + [tail]) This outputs what, I hope, is the right matrix: ============================== Out ============================== [[1, 2, 3, 4, 5, 6], [2, 3, 6, 1, 4, 5], [3, 1, 5, 2, 6, 4], [4, 6, 2, 5, 1, 3], [5, 4, 1, 6, 3, 2], [6, 5, 4, 3, 2, 1]] * * * ### Additionally * * * By using this way of solving it the answer to the problem in hand becomes more easy. Viewing the matrix as a combination of these sub-matrices you can tell how many of these combinations might be possible. As a closing note, it would be a good work-out to modify it a bit in order to allow it to find this array for an arbitrary (**_but even_**) number of `n`.
Add an image in a specific position in the document (.docx) with Python? Question: I use Python-docx to generate Microsoft Word document.The user want that when he write for eg: "Good Morning every body,This is my %(profile_img)s do you like it?" in a HTML field, i create a word document and i recuper the picture of the user from the database and i replace the key word %(profile_img)s by the picture of the user **NOT at the END OF THE DOCUMENT**. With Python-docx we use this instruction to add a picture: document.add_picture('profile_img.png', width=Inches(1.25)) The picture is added to the document but the problem that it is added at the end of the document. Is it impossible to add a picture in a specific position in a microsoft word document with python? I've not found any answers to this in the net but have seen people asking the same elsewhere with no solution. Thanks (note: I'm not a hugely experiance programmer and other than this awkward part the rest of my code will very basic) Answer: Quoting [the python-docx documentation](https://python- docx.readthedocs.org/en/latest/user/shapes.html): > The Document.add_picture() method adds a specified picture to the end of the > document in a paragraph of its own. However, by digging a little deeper into > the API you can place text on either side of the picture in its paragraph, > or both. When we "dig a little deeper", we discover the [`Run.add_picture()`](https://python- docx.readthedocs.org/en/latest/api/text.html#docx.text.run.Run.add_picture) API. Here is an example of its use: from docx import Document from docx.shared import Inches document = Document() p = document.add_paragraph() r = p.add_run() r.add_text('Good Morning every body,This is my ') r.add_picture('/tmp/foo.jpg') r.add_text(' do you like it?') document.save('demo.docx')
Error while installing PyGraphviz (Mac OS X, Anaconda) Question: I'm having trouble while installing PyGraphviz. I'm using Anaconda in Mac OS X. Error messages indicates some reasons, but I already checked out it is installed in anaconda directory. Sundongui-MacBook-Pro:site-packages sundong$ pwd /Users/sundong/anaconda/lib/python2.7/site-packages Sundongui-MacBook-Pro:site-packages sundong$ pip install graphviz --upgrade Requirement already up-to-date: graphviz in /Users/sundong/anaconda/lib/python2.7/site-packages According to the error messages, How can I change the the include_dirs and library_dirs variables in setup.py?? Here is the error message that I meet Sundongui-MacBook-Pro:anaconda sundong$ pip install pygraphviz Collecting pygraphviz Using cached pygraphviz-1.3.1.tar.gz Building wheels for collected packages: pygraphviz Running setup.py bdist_wheel for pygraphviz Complete output from command /Users/sundong/anaconda/bin/python -c "import setuptools;__file__='/private/var/folders/p6/rjy4tf353bzfy7gsl5jn_yvc0000gn/T/pip-build-bLb4AR/pygraphviz/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /var/folders/p6/rjy4tf353bzfy7gsl5jn_yvc0000gn/T/tmpwR_08Dpip-wheel-: running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.5-x86_64-2.7 creating build/lib.macosx-10.5-x86_64-2.7/pygraphviz copying pygraphviz/__init__.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz copying pygraphviz/agraph.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz copying pygraphviz/graphviz.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz copying pygraphviz/release.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz copying pygraphviz/version.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz creating build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/__init__.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_attribute_defaults.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_attributes.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_clear.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_drawing.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_edge_attributes.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_graph.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_html.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_layout.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_node_attributes.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_readwrite.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_string.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_subgraph.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests copying pygraphviz/tests/test_unicode.py -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz/tests running egg_info writing pygraphviz.egg-info/PKG-INFO writing top-level names to pygraphviz.egg-info/top_level.txt writing dependency_links to pygraphviz.egg-info/dependency_links.txt warning: manifest_maker: standard file '-c' not found reading manifest file 'pygraphviz.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no previously-included files matching '*~' found anywhere in distribution warning: no previously-included files matching '*.pyc' found anywhere in distribution warning: no previously-included files matching '.svn' found anywhere in distribution no previously-included directories found matching 'doc/build' writing manifest file 'pygraphviz.egg-info/SOURCES.txt' copying pygraphviz/graphviz.i -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz copying pygraphviz/graphviz_wrap.c -> build/lib.macosx-10.5-x86_64-2.7/pygraphviz running build_ext building 'pygraphviz._graphviz' extension creating build/temp.macosx-10.5-x86_64-2.7 creating build/temp.macosx-10.5-x86_64-2.7/pygraphviz gcc -fno-strict-aliasing -I/Users/sundong/anaconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/sundong/anaconda/include/python2.7 -c pygraphviz/graphviz_wrap.c -o build/temp.macosx-10.5-x86_64-2.7/pygraphviz/graphviz_wrap.o pygraphviz/graphviz_wrap.c:2954:10: fatal error: 'graphviz/cgraph.h' file not found #include "graphviz/cgraph.h" ^ 1 error generated. error: command 'gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for pygraphviz Failed to build pygraphviz Installing collected packages: pygraphviz Running setup.py install for pygraphviz Complete output from command /Users/sundong/anaconda/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/p6/rjy4tf353bzfy7gsl5jn_yvc0000gn/T/pip-build-bLb4AR/pygraphviz/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/p6/rjy4tf353bzfy7gsl5jn_yvc0000gn/T/pip-qgosXm-record/install-record.txt --single-version-externally-managed --compile: running install Trying pkg-config Failed to find pkg-config Trying dotneato-config Failed to find dotneato-config Failed to find dotneato-config Your Graphviz installation could not be found. 1) You don't have Graphviz installed: Install Graphviz (http://graphviz.org) 2) Your Graphviz package might incomplete. Install the binary development subpackage (e.g. libgraphviz-dev or similar.) 3) You are using Windows There are no PyGraphviz binary packages for Windows but you might be able to build it from this source. See http://networkx.lanl.gov/pygraphviz/reference/faq.html If you think your installation is correct you will need to manually change the include_dirs and library_dirs variables in setup.py to point to the correct locations of your graphviz installation. The current setting of library_dirs and include_dirs is: library_dirs=None include_dirs=None error: Error locating graphviz. ---------------------------------------- Command "/Users/sundong/anaconda/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/p6/rjy4tf353bzfy7gsl5jn_yvc0000gn/T/pip-build-bLb4AR/pygraphviz/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/p6/rjy4tf353bzfy7gsl5jn_yvc0000gn/T/pip-qgosXm-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/p6/rjy4tf353bzfy7gsl5jn_yvc0000gn/T/pip-build-bLb4AR/pygraphviz Answer: try the following (make sure to have anaconda-client installed and updated): conda install --channel https://conda.anaconda.org/garylschultz pygraphviz
Python time.sleep() does not work in linux and multi thread Question: I write a simple multiprocess and multi-thread code in python which works in windows but doesn't work in linux (i tested it on freebsd and ubuntu) import threading import time from multiprocessing import Process class Test(threading.Thread): def run(self): print('before sleep') time.sleep(1) print('after sleep') def run_test(): Test().start() if __name__ == "__main__": Process(target=run_test, args=()).start() this program only print "before sleep" and then exit. why sleep doesn't work here? (it works on windows) UPDATE: I used join() in my process like this, but still not work. ... if __name__ == "__main__": pr = Process(target=run_test, args=()) pr.start() pr.join() Answer: The join() should be used in the calling thread to wait for another thread: def run_test(): t = Test() t.start() t.join()
Django custom auth backend doesn't seem to be being called? Question: I'm using Django 1.8.4 on Python 3, and attempting to create an auth backend which validates a cookie from a legacy ColdFusion web site and create / log the Django user in after checking the value in a database. In settings, I am including the backend: AUTHENTICATION_BACKENDS = ( 'site_classroom.cf_auth_backend.ColdFusionBackend', ) And the code for the backend itself; SiteCFUser is a model against the SQL Server database user model which contains the active cookie token value: from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from users.models import SiteCFUser class ColdFusionBackend(ModelBackend): """ Authenticates and logs in a Django user if they have a valid ColdFusion created cookie. ColdFusion sets a cookie called "site_web_auth" Example cookie: authenticated@site+username+domain+8E375588B1AAA9A13BE03E401A02BC46 We verify this cookie in the MS SQL database 'site', table site_users, column user_last_cookie_token """ def authenticate(self, request): User = get_user_model() print('Hello!') token=request.COOKIES.get('site_web_auth', None) print('Token: ' + token) cookie_bites = token.split('+') if cookie_bites[0] != "authenticated@site": # Reality check: not a valid site auth cookie return None username = cookie_bites[1] cf_token = cookie_bites[3] try: site_user = SiteCFUser.objects.using('mssqlsite').filter(cf_username=username) except: # No user found; redirect to login page return None if site_user[0].cftoken == cf_token: try: # Does the user exist in Django? user = User.objects.get(username=username) except: # User does not exist, has a valid cookie, create the User. user = User(username=username) user.first_name = site_user[0].cf_first_name user.last_name = site_user[0].cf_last_name user.email = site_user[0].cf_email user.save() else: return None def get_user(self, user_id): User = get_user_model() try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None The problem is, the backend doesn't seem to be called when hitting a URL with a view with `@login_required`, or even trying to log in through a form with username and password. If I force an error by changing the name of the class in settings, or change the name of the class in cf_auth_backend.py, I do get an error. However, none of the print statements show up in the console. I'm clearly missing something here: any idea what I'm not doing right? Answer: Authentication backends doesn't work that way. They won't be called on each request or on requests where authentication is required. If you want to log in user based on some cookie, you should call authentication in middleware.
Issue to play a mp3 file with a Python script from Arduino data Question: I am trying to perform the following action with an Arduino Uno and a Python script: if the length calculated by the ultrawave sensor of Arduino is below 36 then play a music which is on my hard drive. My Python code is the following one: import serial, webbrowser arduino = serial.Serial('/dev/ttyACM0', 9600) data = arduino.readline() while (1==1): if (arduino.inWaiting()>0) and data < 36: webbrowser.open("/home/path/my-music.mp3") But nothing is happening when I am launching it, the script kept running in my shell. If I perform a print data I noticed that the value of data is different from the Arduino console and it seems that the Arduino console is not working properly (the length value of the ultrawave sensor seem truncated) when the Python script is running at the same time. when I run the following Python script: import serial, webbrowser webbrowser.open("/home/path/my-music.mp3") My mp3 is played properly. Any ideas? Answer: I modified your script to tell you what is happening. I can not test it out. # import the modules import serial import webbrowser # open a serial connection to the Arduino to read data from arduino = serial.Serial('/dev/ttyACM0', 9600) # we want to read everything the Arduino tells us while True: # read one line (a str) that the Arduino wrote with Serial.println() line = arduino.readline() # convert the line into a string that contains only the numbers # by stripping away the line break characters and spaces string_with_number_in_it = line.strip() # convert the string into a number that can be compared number = float(string_with_number_in_it) if number < 36: webbrowser.open("/home/path/my-music.mp3") Also, I suggest you install [mplayer](https://en.wikipedia.org/wiki/MPlayer) and use it instead of the webbrowser. import subprocess def play_music_file(filename): subprocess.call(('mplayer', filename))
parse a file for a line with specific text, then logic to determine next steps Question: I am trying to scan a textfile for a specific keyword. When this keyword is found there's a numeric value on the line that I need to compare to see if it's less than a set value. If it is, the following lines in the file need to be printed/saved until the next keyword is reached. I hope this makes sense. Example of the textfile: "saleAmount","500", text text text etc etc etc text text text "saleAmount","1200", text text text etc etc etc text text text My python file is as follows: import re info = open("results.txt", "r") for line in info: if re.match("(.*)saleAmount(.*)", line): for s in line: result=re.findall('\d+', s) if (result < 1000) print (result) In this case the line with the amount of 500 should be compared to 1000 and printed, as should the following 2 lines. The line with the amount of 1200 and it's following lines will be ignored. I can get this to print out the values in a weird one digit a line result but when I add in the comparison I can't get that. I'm sure this is simple but I'm new to python. Thanks Answer: Here's one possible solution: import re ls=[] with open('results.txt') as f: for line in f: if "saleAmount" in line: ls.append(line.strip('\n')) for num in range(len(ls)): for amnt in re.findall('\d+',ls[num]): if int(amnt) < 1000: print(amnt) What I did is added the file that contain `saleAmount` to a list `ls`, then extracted the numbers and from that list and compared to see if they are less than 1000. In your case, `result` is obtaining the values whether it contains a number (splits up that number into single digit) or if it contains a string (becomes empty list). In your original code, try `print(result)` right after you define it without the `if` statement and what's below it. Then you'll get a clearer understanding as to why you can't compare it to 1000 Edit: Include "saleAmount" and following lines import re ls=[] with open('data.csv') as f: for line in f: ls.append(line) for w in ls: if "saleAmount" in w and int(re.findall('\d+',w)[0]) < 1000: print(w) for i in range(1,4): print(ls[ls.index(w)+i])
Incrementally and statistically measuring samples with Python (Numpy, Pandas, etc) and performance Question: Let's say I take a stream of incoming data (very fast) and I want to view various stats for a window (std deviation, (say, the last N samples, N being quite large). What's the most efficient way to do this with Python? For example, df=ps.DataFrame(np.random.random_sample(200000000)) df2 = df.append([5]) Is crashing my REPL environment in visual studio. Is there a way to append to an array without this happening? Is there a way to tell which operations on the dataframe are computed incrementally other than by doing timeit on them? Answer: I recommend building a circular buffer out of a numpy array. This will involve keeping track of an index to your last updated point, and incrementing that when you add a new value. import numpy as np circular_buffer = np.zeros(200000000, dtype=np.float64) head = 0 # stream input circular_buffer[head] = new_value if head == len(circular_buffer) - 1: head = 0 else: head += 1 Then you can compute the statistics normally on circular_buffer. ### If You Don't Have Enough RAM Try implementing something similar in [bquery](https://github.com/visualfabriq/bquery) and [bcolz](https://github.com/Blosc/bcolz). These store your data more efficiently than numpy (using compression) and offer similar performance. Bquery now has mean and standard deviation. _Note: I'm a contributer to bquery_
How to fake javascript enabled in Python requests/beautifulsoup Question: I'm trying to crawl a website which return an error message that your js is disabled and you might be a bot. I tried to see same behaviour in web browser and yes the same response, however if JavaScript is enabled it will not affect the original response, I mean original response is not dependent on JS. So I was thinking if I can tell the web/http server that my JS is enabled and I'm not a BOT. is this possible in Python requests library, or any other python library for that matter? And yeah I've set the `User-Agent` header, even all other headers, like `host`, `language`, `connection`, etc Answer: If the site is just checking whether javascript can be executed or not through executing some js, use selenium to get the page, and then use BeautifulSoup to parse the page that selenium got. from bs4 import BeautifulSoup from selenium import webdriver driver = webdriver.Firefox() driver.get('http://your-site/url') html = driver.page_source soup = BeautifulSoup(html) ...
Python Dictionary of States Question: I am writing a program that uses a dictionary of 50 states. This program. will ask users about 8 questions and after the user answer the questions, it will out some thing like 'based on your answer, you should live in this state'. it is a randomized output of state. The questions will loop around until the user decided to stop. This is what I have thus far. Can you help? Thank you import random def main(): states = { 'Alabama','Alaska','Arizona','Arkansas','California','Colorado', 'Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho', 'Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana', 'Maine' 'Maryland','Massachusetts','Michigan','Minnesota', 'Mississippi', 'Missouri','Montana','Nebraska','Nevada', 'New Hampshire','New Jersey','New Mexico','New York', 'North Carolina','North Dakota','Ohio', 'Oklahoma','Oregon','Pennsylvania','Rhode Island', 'South Carolina','South Dakota','Tennessee','Texas','Utah', 'Vermont','Virginia','Washington','West Virginia', 'Wisconsin','Wyoming' } print('What city are you from') city = input() print('What is your favorite team?') team = input() print('What state is close to you?') state = input() print('What is the name of your Governor?') governor = input() print('What is the name of your Senator?') senator = input() print('what is the name of your Sherif?') sherif = input() print('What is your favorite baseball team?') baseball = input() print('What is your favorite basketball team?') basketball = input() print('What is your favorite hockey team?') hockey = input() print ('Base on your answer the state you should live in is:' + states) Answer: First the states you provide is not a dictionary but a set. Try: type(states) For having a random choice. First convert if to a list and then choose as below. import random states_list = list(states) choice = random.choice(states_list) So in final line include print ('Base on your answer the state you should live in is: ' + choice)
Setup.py woes: WARNING: '' not a valid package name Question: For my Python project, I keep my source code in the directory `src`. Thus, for my project's setup.py script: from setuptools import setup setup(name='pyIAST', ... package_dir={'':'src'}, packages=['']) so that it looks for `src/IAST.py`, where my code resides. e.g. there is a function `plot_isotherms()` in my `IAST.py` script so the user can, after installation, call it: import IAST IAST.plot_isotherms() Everything works great, but there is an annoying warning when I `python setup.py install` or use `pip install pyIAST` from PyPi: WARNING: '' not a valid package name; please use only.-separated package names in setup.py How do I make this go away? My project is [here](https://github.com/CorySimon/pyIAST). I'm also a bit confused as to why I name my package `pyIAST`, yet the user still types `import IAST` for my package to import. Answer: One way to clear that warning is to change your first line to: `from setuptools import setup, find_packages` and then change your packages line to: `packages=find_packages(),` The setup install will no longer generate a warning. You can run the following two commands to see your isotherm method is now available: `import pyiast` #(<==notice this is not IAST) `dir(pyiast)` > `['BETIsotherm', 'InterpolatorIsotherm', 'LangmuirIsotherm', > 'ModelIsotherm', 'QuadraticIsotherm', 'SipsIsotherm', '_MODELS', > '_MODEL_PARAMS', '_VERSION', '__author__', '__builtins__', '__doc__', > '__file__', '__name__', '__package__', 'iast', 'np', 'plot_isotherm', > 'print_selectivity', 'reverse_iast', 'scipy']` It can be called using `pyiast.plot_isotherm()` You may need to update your setuptools. You can check what version you have with: `import setuptools; print "setup version: ", setuptools.__version__` Can update it with: `sudo pip install --upgrade setuptools`
Testing in Python whether one glyph is a reflection of another in the same font Question: Inspired by [List of all unicode's open/close brackets?](http://stackoverflow.com/questions/13535172/list-of-all-unicodes- open-close-brackets) I'm trying to find a list of all unicode glyphs in a given font that are reflections of each other. First I just need to be able to test whether one glyph is a reflection of another. Below I have two different attempts (two different implementations of my `render_char` function) but I'm not able to identify '(' and ')' as mirror images using either one. How can I do this? from PIL import Image,ImageDraw,ImageFont import freetype import numpy as np def render_char0(c): # Based on https://github.com/rougier/freetype-py/blob/master/examples/hello-world.py # Needs numpy (blech) and the image comes out the inverse of the way I expect face = freetype.Face("/Library/Fonts/Verdana.ttf") face.set_char_size( 48*64 ) face.load_char(c) bitmap = face.glyph.bitmap w,h = bitmap.width, bitmap.rows Z = np.array(bitmap.buffer, dtype=np.ubyte).reshape(h,w) return Image.fromarray(Z, mode='L').convert('1') def render_char1(c): # Based on http://stackoverflow.com/a/14446201/2829764 verdana_font = ImageFont.truetype("/Library/Fonts/Verdana.ttf", 20, encoding="unic") text_width, text_height = verdana_font.getsize(c) canvas = Image.new('RGB', (text_width+10, text_height+10), (255, 255, 255)) draw = ImageDraw.Draw(canvas) draw.text((5,5), c, font = verdana_font, fill = "#000000") return canvas for render_char in [render_char0, render_char1]: lparen = render_char('(') rparen = render_char(')') mirror = lparen.transpose(Image.FLIP_LEFT_RIGHT) mirror.show() rparen.show() print mirror.tobytes() == rparen.tobytes() # False Answer: There is a text file called `BidiMirroring.txt` in the Unicode plain-text database with a list of all mirrored characters. That file is easy to parse by programs. Current url is <http://www.unicode.org/Public/UNIDATA/BidiMirroring.txt> I don't think using the rendered glyphs can work reliably. There's a lot of reasons why eg. `(` and `)` are no exact mirror images, like spacing around the character, hinting and anti-aliasing, maybe the font is slightly slanted, or maybe the font designer has just make the two brackets a bit different etc. Other characters are rotated, rather than mirrored, like `“` and `”` in some fonts, and the Chinese quotation marks `「` and `」`.
Memory Error when using float32 in dask array Question: I am trying to import a 1.25 GB dataset into python using **`dask.array`** The file is a 1312*2500*196 Array of **`uint16`** 's. I need to convert this to a **`float32`** array for later processing. I have managed to stitch together this Dask array in `uint16`, however when I try to convert to `float32` I get a **memory error**. It doesn't matter what I do to the chunk size, I will always get a memory error. I create the array by concatenating the array in lines of 100 (breaking the 2500 dimension up into little pieces of 100 lines, since `dask` can't natively read `.RAW` imaging files I have to use **`numpy.memmap()`** to read the file and then create the array. Below I will supply a "as short as possible" code snippet: I have tried two methods: 1) Create the full `uint16` array and then try to convert to `float32`: (note: the `memmap` is a 1312x100x196 array and lines ranges from 0 to 24) for i in range(lines): NewArray = da.concatenate([OldArray,Memmap],axis=0) OldArray = NewArray return NewArray and then I use Float32Array = FinalArray.map_blocks(lambda FinalArray: FinalArray * 1.,dtype=np.float32) In method 2: for i in range(lines): NewArray = da.concatenate([OldArray,np.float32(Memmap)],axis=0) OldArray = NewArray return NewArray Both methods result in a memory error. **Is there any reason for this?** I read that `dask` array is capable of doing up to 100 GB dataset calculations. I tried all chunk sizes (from as small as 10x10x10 to a single line) Answer: You can create a dask.array from a numpy memmap array directly with the `da.from_array` function x = load_memmap_numpy_array_from_raw_file(filename) d = da.from_array(x, chunks=...) You can change the dtype with the `astype` method d = d.astype(np.float32)
Printing contents in particular section of configuration file in Python Question: Lets imagine i have an config file by name sample.ini, let there be two section in that. [section1] Name1 = Url_1 Name2 = Url_2 [Section2] Name3 = Url_3 Name4 = Url_4 Now if I want to print Url_3 & Url_4, is there a way in Python that I can only print those two Url. I tried looking about this, but they provide solution which print every section contents in config file. Please help me with that. Answer: Could you try giving this a shot? Using python's config parser sample.ini [section1] Name1=Url_1 Name2=Url_2 [Section2] Name3=Url_3 Name4=Url_4 Script: import ConfigParser as configparser parser = configparser.ConfigParser() parser.read("sample.ini") section_2 = dict(parser.items("Section2")) print section_2["name3"] print section_2["name4"] Output: Url_3 Url_4
import clr ImportError: No module named clr Question: I have an Ubuntu 12.04. I tried import clr in my python code and I have this error. I went through the links. But all in vain. Is there a way to check 'clr' present? How do I see that the module is present? Answer: You need to install Mono framework to run .NET on Ubuntu. Please refer the below link which helps you to install .NET framework. Then the CLR will be available for your code OR you can reference the CLR in your code after installation of Mono. <http://askubuntu.com/questions/497358/how-to-install-mono-on- ubuntu-64-bit-v14-04>
Python 3 SQLite3 - Incorrect number of bindings Question: I understand there are MANY questions on Stack Overflow about this error but I have tried MANY solutions and obviously they have all failed. Here's a list: [sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied](http://stackoverflow.com/questions/16856647/sqlite3-programmingerror- incorrect-number-of-bindings-supplied-the-current-sta) [SQLite parameter substitution problem](http://stackoverflow.com/questions/228912/sqlite-parameter- substitution-problem) [sqlite3.ProgrammingError: Incorrect number of bindings supplied](http://stackoverflow.com/questions/19473281/sqlite3-programmingerror- incorrect-number-of-bindings-supplied) [Reading from database with SQLite and Python: Incorrect number of binding supplied](http://stackoverflow.com/questions/9986578/reading-from-database- with-sqlite-and-python-incorrect-number-of-binding-suppli) [SQLite Python Insert - Incorrect Number of Bindings Supplied](http://stackoverflow.com/questions/4654513/sqlite-python-insert- incorrect-number-of-bindings-supplied) I am trying to store a username and hashed password (created by PassLib - <https://pythonhosted.org/passlib/> ) in a SQLite3 database. These are stored in the variables "targetusername" and "password" respectively. My problem is that when I actually try to insert these 2 variables into a table of a database called "Passwords", it gives this error: Incorrect number of bindings supplied. The current statement uses 1, and there are 11 supplied. Here's an example of what targetusername and password would store: targetusername = "user4884072" password = "$5$rounds=535000$ySH31paWMjEDCUUY$jdrBVGsoYnSMkdVBtjCaxQy2f0g3MX1Wts4vSYz7m.4" This line gives the error: c.executemany("INSERT INTO {tn} ({idf}, {cn}) VALUES(targetusername, %s" % str(password).\ format(tn="Passwords")) It has been changed multiple times to try and fix the issue (which apparently is caused by how Python stores variables), but here is what it was originally: c.execute("INSERT OR IGNORE INTO {tn} ({idf}, {cn}) VALUES (targetusername, password)".\ format(tn="Passwords", idf="Username", cn="Password")) Answer: Use `c.execute()`, not `c.executemany()`, to insert a single row of data. This is the immediate cause of the error that you experience. In addition to that, don't use string substitution, use parameterised queries. Here is a complete working example: import sqlite3 connection = sqlite3.connect(':memory:') # in memory database c = connection.cursor() c.execute('create table Passwords (Username text, Password text)') targetusername = "user4884072" password = "$5$rounds=535000$ySH31paWMjEDCUUY$jdrBVGsoYnSMkdVBtjCaxQy2f0g3MX1Wts4vSYz7m.4" c.execute('insert into Passwords (Username, Password) values (?, ?)', (targetusername, password)) print c.execute('select * from Passwords').fetchall() Output: [(u'user4884072', u'$5$rounds=535000$ySH31paWMjEDCUUY$jdrBVGsoYnSMkdVBtjCaxQy2f0g3MX1Wts4vSYz7m.4')] In the code that you have posted there is no point in substituting values for the table or column names, so just put them in the query string as shown. This uses a parameterised query where the API inserts the values for username and password into the query at the places denoted by `?`. This is safer than using string substitution because the DB API knows how to properly and safely escape the values passed to it, and this avoids SQL injection attacks on your code. And it uses `execute()` rather than `executemany()` since there is only one row of data being inserted.
PyDAQmx importing confusion Question: I'm trying to use PyDAQmx. If I try to import like from PyDAQmx.DAQmxFunctions import * ... DAQmxResetDevice(ch) #unresolved the function call is not recognized. However the following works just fine: import PyDAQmx.DAQmxFunctions as daq ... daq.DAQmxResetDevice(ch) #fine Any idea why that might be? I'd like to use the first case just to avoid unnecessary clutter in my code since there will be a lot of function calls from that library. I know importing has been discussed to death and I looked at quite a few threads, but couldn't really find anything explaining my issue. FYI, python 2.7, PyCharm 4.5.3 Community Edition, NI-DAQ 14.5.1, PyDAQmx 1.3.1. Answer: PyDAQmx doesn't have an `__all__` definition in its `__init__.py`: <https://github.com/clade/PyDAQmx/blob/master/PyDAQmx/__init__.py> Without an `__all__`, Python doesn't know what to [import](https://docs.python.org/2/tutorial/modules.html#importing-from-a- package).
How to load script when wsadmin shell is used Question: A system administrator has created a Python script called globalScript. py. What should the administrator do to ensure globalScript. py is loaded when the wsadmin shell is used? A. Compile globalScript.py to a Java class in the bin directory. B. Invoke wsadmin with the argument-profileName globalScript.py. C. Modify the configureCustomProperty script to import globalScript. py. D. D. Set the script profiles in the wsadmin.properties file to load globalScript .py. Answer: wsadmin.properties has this entry **com.ibm.ws.scripting.profiles** where we can add the scripting files to be loaded So D should be the answer #------------------------------------------------------------------------- # The profiles property is a list of profiles to be run before # running user commands, scripts, or an interactive shell. # securityProcs is included here by default to make security # configuration easier. #------------------------------------------------------------------------- com.ibm.ws.scripting.profiles=/hosting/products/WebSphereD24/bin/securityProcs.jacl;/hosting/products/WebSphereD24/bin/LTPA_LDAPSecurityProcs.jacl
Python loop to get data from every line of file and convert it to dec Question: I'm kinda lost at the moment: I have text file with lines looking like that: /dev/input/event0: 0003 0035 000002ac /dev/input/event0: 0003 0036 000008fb There are many lines like that, and I want to make script that gets the last hex value from every line and then writes them in file with output looking like this: something someting hex_from_line_1 hex_from_line_2 something someting hex_from_line_3 hex_from_line_4 And so on. As I'm new to Python I have some trouble with making loop which would do this. Can You give me any guidance? (I'm not asking for whole loop, only guidance - I'd love to learn that, not use some finished code) Answer: A fun thing about Python's `zip` is that it will happily take the same iterator multiple times as arguments, allowing you to pair up inputs easily. For example: # For efficiency, if you're on Python 2, include this line so zip is a generator that produces pairs on demand, rather than eagerly slurping the whole file from future_builtins import zip with open('myinput') as f: # Creates a generator that produces only the final space separated value for each line (could be anything; not checking for hex) final_hex = (line.rsplit(None, 1)[-1] for line in f) # By using the same generator twice, we get the 1st, 3rd, 5th, etc. from one # and the 2nd, 4th, 6th, etc. from the other. for hexa, hexb in zip(final_hex, final_hex): print("something something", hexa, hexb) # Python 3 print function print "something something", hexa, hexb # Python 2 print statement Note: If the input data isn't an even number of lines, this will drop the final unpaired input. You can use `itertools.zip_longest` (`izip_longest` on Python 2) if you want the unpaired value.
How do I get the current path of the file executing the current thread? Question: In python, I can do this to get the current file's path: os.path.dirname(os.path.abspath(__file__)) But if I run this on a thread say: def do_stuff(): class RunThread(threading.Thread): def run(self): print os.path.dirname(os.path.abspath(__file__)) a = RunThread() a.start() I get this error: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner self.run() File "readrss.py", line 137, in run print os.path.dirname(os.path.abspath(__file__)) NameError: global name '__file__' is not defined Answer: import inspect print(inspect.stack()[0][1]) [inspect](https://docs.python.org/2/library/inspect.html)
Diff output from two commands quickly in vim Question: I have two hosts that should be running the same version of squid. To verify that this was indeed true, I ran `squid -v` on each of the hosts and collected the output from them. Is there a quick way in vim to compare these text blobs and print the diff? I was able to do this in python, but was wondering if someone could show me a few tricks in vim. host1 # squid3 -v Squid Cache: Version 3.3.8 Ubuntu configure options: '--build=x86_64-linux-gnu' '--prefix=/usr' '--includedir=${prefix}/include' '--mandir=${prefix}/share/man' '--infodir=${prefix}/share/info' '--sysconfdir=/etc' '--localstatedir=/var' '--libexecdir=${prefix}/lib/squid3' '--srcdir=.' '--disable-maintainer-mode' '--disable-dependency-tracking' '--disable-silent-rules' '--datadir=/usr/share/squid3' '--sysconfdir=/etc/squid3' '--mandir=/usr/share/man' '--enable-inline' '--enable-async-io=8' '--enable-storeio=ufs,aufs,diskd,rock' '--enable-removal-policies=lru,heap' '--enable-delay-pools' '--enable-cache-digests' '--enable-underscores' '--enable-icap-client' '--enable-follow-x-forwarded-for' '--enable-auth-basic=DB,fake,getpwnam,LDAP,MSNT,MSNT-multi-domain,NCSA,NIS,PAM,POP3,RADIUS,SASL,SMB' '--enable-auth-digest=file,LDAP' '--enable-auth-negotiate=kerberos,wrapper' '--enable-auth-ntlm=fake,smb_lm' '--enable-external-acl-helpers=file_userip,kerberos_ldap_group,LDAP_group,session,SQL_session,unix_group,wbinfo_group' '--enable-url-rewrite-helpers=fake' '--enable-eui' '--enable-esi' '--enable-icmp' '--enable-zph-qos' '--enable-ecap' '--disable-translation' '--with-swapdir=/var/spool/squid3' '--with-logdir=/var/log/squid3' '--with-pidfile=/var/run/squid3.pid' '--with-filedescriptors=65536' '--with-large-files' '--with-default-user=proxy' '--enable-ssl' '--with-open-ssl=/etc/ssl/openssl.cnf' '--enable-linux-netfilter' 'build_alias=x86_64-linux-gnu' 'CFLAGS=-g -O2 -fPIE -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wall' 'LDFLAGS=-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' 'CPPFLAGS=-D_FORTIFY_SOURCE=2' 'CXXFLAGS=-g -O2 -fPIE -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security' host2 # squid3 -v Squid Cache: Version 3.3.8 Ubuntu configure options: '--build=x86_64-linux-gnu' '--prefix=/usr' '--includedir=${prefix}/include' '--mandir=${prefix}/share/man' '--infodir=${prefix}/share/info' '--sysconfdir=/etc' '--localstatedir=/var' '--libexecdir=${prefix}/lib/squid3' '--srcdir=.' '--disable-maintainer-mode' '--disable-dependency-tracking' '--disable-silent-rules' '--datadir=/usr/share/squid3' '--sysconfdir=/etc/squid3' '--mandir=/usr/share/man' '--enable-inline' '--enable-async-io=8' '--enable-storeio=ufs,aufs,diskd,rock' '--enable-removal-policies=lru,heap' '--enable-delay-pools' '--enable-cache-digests' '--enable-underscores' '--enable-icap-client' '--enable-follow-x-forwarded-for' '--enable-auth-basic=DB,fake,getpwnam,LDAP,MSNT,MSNT-multi-domain,NCSA,NIS,PAM,POP3,RADIUS,SASL,SMB' '--enable-auth-digest=file,LDAP' '--enable-auth-negotiate=kerberos,wrapper' '--enable-auth-ntlm=fake,smb_lm' '--enable-external-acl-helpers=file_userip,kerberos_ldap_group,LDAP_group,session,SQL_session,unix_group,wbinfo_group' '--enable-url-rewrite-helpers=fake' '--enable-eui' '--enable-esi' '--enable-icmp' '--enable-zph-qos' '--enable-ecap' '--disable-translation' '--with-swapdir=/var/spool/squid3' '--with-logdir=/var/log/squid3' '--with-pidfile=/var/run/squid3.pid' '--with-filedescriptors=65536' '--with-large-files' '--with-default-user=proxy' '--enable-linux-netfilter' 'build_alias=x86_64-linux-gnu' 'CFLAGS=-g -O2 -fPIE -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wall' 'LDFLAGS=-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' 'CPPFLAGS=-D_FORTIFY_SOURCE=2' 'CXXFLAGS=-g -O2 -fPIE -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security' I assigned the output from each host to two variables in python and computed the diff as below: >>> import re >>> re.findall("('\S+')", x) >>> x='''configure options: '--build=x86_64-linux-gnu' '--prefix=/usr' '--includedir=${prefix}/include' '--mandir=${prefix}/share/man' '--infodir=${prefix}/share/info' '--sysconfdir=/etc' '--localstatedir=/var' '--libexecdir=${prefix}/lib/squid3' '--srcdir=.' '--disable-maintainer-mode' '--disable-dependency-tracking' '--disable-silent-rules' '--datadir=/usr/share/squid3' '--sysconfdir=/etc/squid3' '--mandir=/usr/share/man' '--enable-inline' '--enable-async-io=8' '--enable-storeio=ufs,aufs,diskd,rock' '--enable-removal-policies=lru,heap' '--enable-delay-pools' '--enable-cache-digests' '--enable-underscores' '--enable-icap-client' '--enable-follow-x-forwarded-for' '--enable-auth-basic=DB,fake,getpwnam,LDAP,MSNT,MSNT-multi-domain,NCSA,NIS,PAM,POP3,RADIUS,SASL,SMB' '--enable-auth-digest=file,LDAP' '--enable-auth-negotiate=kerberos,wrapper' '--enable-auth-ntlm=fake,smb_lm' '--enable-external-acl-helpers=file_userip,kerberos_ldap_group,LDAP_group,session,SQL_session,unix_group,wbinfo_group' '--enable-url-rewrite-helpers=fake' '--enable-eui' '--enable-esi' '--enable-icmp' '--enable-zph-qos' '--enable-ecap' '--disable-translation' '--with-swapdir=/var/spool/squid3' '--with-logdir=/var/log/squid3' '--with-pidfile=/var/run/squid3.pid' '--with-filedescriptors=65536' '--with-large-files' '--with-default-user=proxy' '--enable-ssl' '--with-open-ssl=/etc/ssl/openssl.cnf' '--enable-linux-netfilter' 'build_alias=x86_64-linux-gnu' 'CFLAGS=-g -O2 -fPIE -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wall' 'LDFLAGS=-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' 'CPPFLAGS=-D_FORTIFY_SOURCE=2' 'CXXFLAGS=-g -O2 -fPIE -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security' ''' # Similarly, assign output from host2 to x1 >>> s1 = set(re.findall("('\S+')", x)) >>> s2 = set(re.findall("('\S+')", x1)) >>> s1-s2 set(["'--enable-ssl'", "'--with-open-ssl=/etc/ssl/openssl.cnf'"]) Answer: To compare the 2 results you need to get each output in a file on the same machine (`squid3 -v >> yourFile` and a basic file transfer should do the trick). Once you have your two files open them in vim `vim file1 file2`. This will load both files in vim buffers. Then you'll need to have two split windows to compare your files: If you are currently on the `file1` buffer use `:vsplit file2` to open the second buffer in a vertical split window. Then you can enter diff mode with `:windo diffthis` and leave it with `:diffoff`. As stated by @romanarmy in the comments of your question [vimcast](http://vimcasts.org/episodes/comparing-buffers-with-vimdiff/) is an excellent resource to learn more about Vim.
Post data as an array in Django Rest Framework Question: I'm implementing an API using Django Rest framework. I wonder Python can send POST params as an array like Ruby does? For example: POST /api/end_point/ params = { 'user_id': [1,2,3] } # In controller, we get an array of user_id: user_ids = params[:user_id] # [1,2,3] Answer: There are a number of ways to deal with this in `django-rest-framework`, depending on what you are actually trying to do. If you are planning on passing this data through `POST` data then you should use a `Serializer`. Using a serializer and `django-rest-framework`s `Serializer` you can provide the `POST` data through `json` or through a `form`. `Serializer` documentation: <http://www.django-rest-framework.org/api- guide/serializers/> `Serializer Field` documentation: <http://www.django-rest- framework.org/api-guide/fields/> Specifically you will want to look at the `ListField`. It's not tested, but you will want something along the lines of: from rest_framework import serializers from rest_framework.decorators import api_view class ItemSerializer(serializers.Serializer): """Your Custom Serializer""" # Gets a list of Integers user_ids = serializers.ListField(child=serializers.IntegerField()) @api_view(['POST']) def item_list(request): item_serializer = ItemSerializer(data=request.data) item_serializer.is_valid(raise_exception=True) user_ids = item_serializer.data['user_ids'] # etc ...
CRITICAL: Unhandled error in Deferred: Question: I am developing spider project and I have moved to a new computer. Now I am installing everything and I encounter problem with Twisted. I have read about this bug and I have installed pywin32 and then also WinPython, but it doesn't help. I have tried to update Twisted with this command pip install Twisted --update as advised in the forum, but it says that pip install doesn't have --update option. I have also run python python27\scripts\pywin32_postinstall.py -install but with no success. This is my error: G:\Job_vacancies\Python\vacancies>scrapy crawl jobs 2015-10-06 09:12:53 [scrapy] INFO: Scrapy 1.0.3 started (bot: vacancies) 2015-10-06 09:12:53 [scrapy] INFO: Optional features available: ssl, http11 2015-10-06 09:12:53 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'va cancies.spiders', 'SPIDER_MODULES': ['vacancies.spiders'], 'DEPTH_LIMIT': 3, 'BO T_NAME': 'vacancies'} 2015-10-06 09:12:53 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsol e, LogStats, CoreStats, SpiderState Unhandled error in Deferred: 2015-10-06 09:12:53 [twisted] CRITICAL: Unhandled error in Deferred: Traceback (most recent call last): File "c:\python27\lib\site-packages\scrapy\cmdline.py", line 150, in _run_comm and cmd.run(args, opts) File "c:\python27\lib\site-packages\scrapy\commands\crawl.py", line 57, in run self.crawler_process.crawl(spname, **opts.spargs) File "c:\python27\lib\site-packages\scrapy\crawler.py", line 153, in crawl d = crawler.crawl(*args, **kwargs) File "c:\python27\lib\site-packages\twisted\internet\defer.py", line 1274, in unwindGenerator return _inlineCallbacks(None, gen, Deferred()) --- <exception caught here> --- File "c:\python27\lib\site-packages\twisted\internet\defer.py", line 1128, in _inlineCallbacks result = g.send(result) File "c:\python27\lib\site-packages\scrapy\crawler.py", line 71, in crawl self.engine = self._create_engine() File "c:\python27\lib\site-packages\scrapy\crawler.py", line 83, in _create_en gine return ExecutionEngine(self, lambda _: self.stop()) File "c:\python27\lib\site-packages\scrapy\core\engine.py", line 66, in __init __ self.downloader = downloader_cls(crawler) File "c:\python27\lib\site-packages\scrapy\core\downloader\__init__.py", line 65, in __init__ self.handlers = DownloadHandlers(crawler) File "c:\python27\lib\site-packages\scrapy\core\downloader\handlers\__init__.p y", line 23, in __init__ cls = load_object(clspath) File "c:\python27\lib\site-packages\scrapy\utils\misc.py", line 44, in load_ob ject mod = import_module(module) File "c:\python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "c:\python27\lib\site-packages\scrapy\core\downloader\handlers\s3.py", li ne 6, in <module> from .http import HTTPDownloadHandler File "c:\python27\lib\site-packages\scrapy\core\downloader\handlers\http.py", line 5, in <module> from .http11 import HTTP11DownloadHandler as HTTPDownloadHandler File "c:\python27\lib\site-packages\scrapy\core\downloader\handlers\http11.py" , line 15, in <module> from scrapy.xlib.tx import Agent, ProxyAgent, ResponseDone, \ File "c:\python27\lib\site-packages\scrapy\xlib\tx\__init__.py", line 3, in <m odule> from twisted.web import client File "c:\python27\lib\site-packages\twisted\web\client.py", line 42, in <modul e> from twisted.internet.endpoints import TCP4ClientEndpoint, SSL4ClientEndpoin t File "c:\python27\lib\site-packages\twisted\internet\endpoints.py", line 34, i n <module> from twisted.internet.stdio import StandardIO, PipeAddress File "c:\python27\lib\site-packages\twisted\internet\stdio.py", line 30, in <m odule> from twisted.internet import _win32stdio File "c:\python27\lib\site-packages\twisted\internet\_win32stdio.py", line 7, in <module> import win32api exceptions.ImportError: DLL load failed: The specified module could not be found . 2015-10-06 09:12:53 [twisted] CRITICAL: And this is my code: #!/usr/bin/python # -*- coding: utf-8 -*- # encoding=UTF-8 import scrapy, urlparse from scrapy.http import Request from scrapy.utils.response import get_base_url from urlparse import urlparse, urljoin from vacancies.items import JobItem #We need that in order to force Slovenian pages instead of English pages. It happened at "http://www.g-gmi.si/gmiweb/" that only English pages were found and no Slovenian. #from scrapy.conf import settings #settings.overrides['DEFAULT_REQUEST_HEADERS'] = {'Accept':'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8','Accept-Language':'sl',} #settings.overrides['DEFAULT_REQUEST_HEADERS'] = {'Accept':'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8','Accept-Language':'sl','en':q=0.8,} class JobSpider(scrapy.Spider): name = "jobs" #Test sample of SLO companies start_urls = [ "http://www.g-gmi.si/gmiweb/", ] #Result of the programme is this list of job vacancies webpages. jobs_urls = [] def parse(self, response): response.selector.remove_namespaces() #We take all urls, they are marked by "href". These are either webpages on our website either new websites. urls = response.xpath('//@href').extract() #Base url. base_url = get_base_url(response) #Loop through all urls on the webpage. for url in urls: #If url represents a picture, a document, a compression ... we ignore it. We might have to change that because some companies provide job vacancies information in PDF. if url.endswith(( #images '.jpg', '.jpeg', '.png', '.gif', '.eps', '.ico', '.svg', '.tif', '.tiff', '.JPG', '.JPEG', '.PNG', '.GIF', '.EPS', '.ICO', '.SVG', '.TIF', '.TIFF', #documents '.xls', '.ppt', '.doc', '.xlsx', '.pptx', '.docx', '.txt', '.csv', '.pdf', '.pd', '.XLS', '.PPT', '.DOC', '.XLSX', '.PPTX', '.DOCX', '.TXT', '.CSV', '.PDF', '.PD', #music and video '.mp3', '.mp4', '.mpg', '.ai', '.avi', '.swf', '.MP3', '.MP4', '.MPG', '.AI', '.AVI', '.SWF', #compressions and other '.zip', '.rar', '.css', '.flv', '.php', '.ZIP', '.RAR', '.CSS', '.FLV', '.PHP', )): continue #If url includes characters like ?, %, &, # ... it is LIKELY NOT to be the one we are looking for and we ignore it. #However in this case we exclude good urls like http://www.mdm.si/company#employment if any(x in url for x in ['?', '%', '&', '#']): continue #Ignore ftp. if url.startswith("ftp"): continue #We need to save original url for xpath, in case we change it later (join it with base_url) url_xpath = url #If url doesn't start with "http", it is relative url, and we add base url to get absolute url. # -- It is true, that we may get some strange urls, but it is fine for now. if not (url.startswith("http")): url = urljoin(base_url,url) #We don't want to go to other websites. We want to stay on our website, so we keep only urls with domain (netloc) of the company we are investigating. if (urlparse(url).netloc == urlparse(base_url).netloc): #The main part. We look for webpages, whose urls include one of the employment words as strings. # -- Instruction. # -- Users in other languages, please insert employment words in your own language, like jobs, vacancies, career, employment ... -- if any(x in url for x in [ 'zaposlovanje', 'Zaposlovanje', 'zaposlitev', 'Zaposlitev', 'zaposlitve', 'Zaposlitve', 'zaposlimo', 'Zaposlimo', 'kariera', 'Kariera', 'delovna-mesta', 'delovna_mesta', 'pridruzi-se', 'pridruzi_se', 'prijava-za-delo', 'prijava_za_delo', 'oglas', 'Oglas', 'iscemo', 'Iscemo', 'careers', 'Careers', 'jobs', 'Jobs', 'employment', 'Employment', ]): #This is additional filter, suggested by Dan Wu, to improve accuracy. We will check the text of the url as well. texts = response.xpath('//a[@href="%s"]/text()' % url_xpath).extract() #1. Texts are empty. if texts == []: print "Ni teksta za url: " + str(url) #We found url that includes one of the magic words and also the text includes a magic word. #We check url, if we have found it before. If it is new, we add it to the list "jobs_urls". if url not in self.jobs_urls: self.jobs_urls.append(url) item = JobItem() #item["text"] = text item["url"] = url #We return the item. yield item # 2. There are texts, one or more. else: #For the same partial url several texts are possible. for text in texts: if any(x in text for x in [ 'zaposlovanje', 'Zaposlovanje', 'zaposlitev', 'Zaposlitev', 'zaposlitve', 'Zaposlitve', 'zaposlimo', 'Zaposlimo', 'ZAPOSLIMO', 'kariera', 'Kariera', 'delovna-mesta', 'delovna_mesta', 'pridruzi-se', 'pridruzi_se', 'oglas', 'Oglas', 'iscemo', 'Iscemo', 'ISCEMO', 'careers', 'Careers', 'jobs', 'Jobs', 'employment', 'Employment', ]): #We found url that includes one of the magic words and also the text includes a magic word. #We check url, if we have found it before. If it is new, we add it to the list "jobs_urls". if url not in self.jobs_urls: self.jobs_urls.append(url) item = JobItem() item["text"] = text item["url"] = url #We return the item. yield item #We don't put "else" sentence because we want to further explore the employment webpage to find possible new employment webpages. #We keep looking for employment webpages, until we reach the DEPTH, that we have set in settings.py. yield Request(url, callback = self.parse) # We run the programme in the command line with this command: # scrapy crawl jobs -o jobs.csv -t csv --logfile log.txt # We get two output files # 1) jobs.csv # 2) log.txt # Then we manually put one of employment urls from jobs.csv into read.py I would be glad if you could give some advice on how to run this thing. Thank you, Marko Answer: You should always install stuff into a [virtualenv](http://virtualenv.readthedocs.org/en/latest/). Once you've got a virtualenv and it's active, do: pip install --upgrade twisted pypiwin32 and you should get the depenendency that makes Twisted support stdio on the Windows platform. To get _all_ the goodies you might try pip install --upgrade twisted[windows_platform] but you may run into problems with `gmp.h` if you try that, and you don't need most of it to do what you're trying to do.
How to extend the space for y ticks in barh - python matplotlib Question: Please see attached image [![enter image description here](http://i.stack.imgur.com/gL2A0.jpg)](http://i.stack.imgur.com/gL2A0.jpg) I have the source code as follows in python def plotBarChartH(self,data): LogManager.logDebug('Executing Plotter.plotBarChartH') if type(data) is not dict: LogManager.logError('Input data parameter is not in right format. Need a dict') return False testNames = [] testTimes = [] for val in data: testNames.append(val) testTimes.append(data[val]) matplotlib.rcParams.update({'font.size': 8}) yPos = np.arange(len(testNames)) plt.barh(yPos, testTimes, height=0.4, align='center', alpha=0.4) plt.yticks(yPos, testNames) plt.xlabel('time (seconds)') plt.title('Test Execution Times') savePath = os.path.join(ConfigurationManager.applicationConfig['robotreportspath'],'bar.jpg') plt.savefig(savePath) plt.clf() return True The bar looks fine but I have two issues 1. How can the text in y-axis can be shown in full? I mean some text are cut-off and i want to extend the space in occupies so that it can be displayed in full. 2. Can I Increase the whole plot area on which the charts are drawn? I want to increase the width of of plot area so that image looks bit bigger thanks Answer: You can set the figure size (in inches) explicitly when you create a `Figure` object with `plt.figure(figsize=(width,height)), and call`plt.tight_layout()` to make room for your tick labels as follows: import matplotlib.pyplot as plt names = ['Content Channels','Kittens for Xbox Platform','Tigers for PS Platform', 'Content Series', 'Wombats for Mobile Platform'] values = [260, 255, 420, 300, 270] fig = plt.figure(figsize=(10,4)) ax = fig.add_subplot(111) yvals = range(len(names)) ax.barh(yvals, values, align='center', alpha=0.4) plt.yticks(yvals,names) plt.tight_layout() plt.show() [![enter image description here](http://i.stack.imgur.com/PYiI8.png)](http://i.stack.imgur.com/PYiI8.png)
Run Python script from another and pass the variables and output Question: When looking for a tutorial on passing variables and output between Python scripts I couldn't find any example that would work with the WSGI Server in my example. I want the **output (and variables)** returned in HTML instead of seeing it only in the console. The best solution for calling python script from another I found is **subprocess** , but I still can't see the merged output of Script 1 and Script 2 of in my web browser and only in console. Script 1: #!/usr/bin/env python # -*- coding: UTF-8 -*- from cgi import escape import sys, os from flup.server.fcgi import WSGIServer import subprocess def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) yield '<h1>Test - Python pass output and variables</h1>' yield '<p>Script 1</p>' yield subprocess.check_output(["python", "script2.py"]) WSGIServer(app).run() Script 2: #!/usr/bin/env python # -*- coding: UTF-8 -*- print "<p>Script 2</p>"; Answer: If you want to pass variables between scripts in python, do something like this: Script1.py: def passVars(): variable = "bla" return variable Script2.py: import Script1 as sc1 var = sc1.passVars()
Validating Log In funtionality in website using Selenium webdriver with Python Question: I am trying to click the "Log In" element present in webpage. "Log In" element is visible , when you click on ACCOUNT element on website. code is : import unittest from selenium import webdriver class registernewuser(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome() cls.driver.implicitly_wait(10) cls.driver.maximize_window() cls.driver.get("http://demo.magentocommerce.com/") def test_register_new_user(self): driver = self.driver account_click = driver.find_element_by_link_text("ACCOUNT").click() driver.implicitly_wait(3) self.driver.find_element_by_link_text('Log In').click() @classmethod def tearDownClass(cls): cls.driver.quit() Answer: Added [account_click = driver.find_element_by_link_text("ACCOUNT").click() driver.implicitly_wait(3) ] in code and it worked . If you want to click an element which is a part of dropdown of main element , click main element--> implicitily wait command ---> Click dropdown element.