input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
What was the first foreign ruling dynasty of Egypt? | Semitic Hyksos |
breadth first search traversal in python I know there are a few questions already up about this and I have already looked through them and tried to use those answers for a solution but I am still having problems For some reason my breadth search either gets stuck in an infinite loop or it says that it cannot `dequeue` from an empty list Here is the code ````def enqueue(self data): self queue_list append(data def dequeue(self): return self queue_list pop(0) def breadth(self): string = "" queue = q Queue() root = self root queue enqueue(root data) string = str(queue dequeue()) while queue != None: if root left != None: queue enqueue(root left data) root = root left if root right != None: queue enqueue(root right data) root = root right data = queue dequeue() string = str(data) return string ```` | Your check in the `while` loop should not be `queue != None` You should be checking for when the queue is empty It is never going to be `None` As coded you queue something then dequeue it so the queue is empty then you go into the `while` loop since although queue is empty it is <them>not</them> `None` You then try to deque near the end of the while loop which is causing your error |
How to determine the maximum read buffer size for file I/O I am trying to optimize a binary reader for the Stata filetype and the current implementation is lazily evaluated for each record in the file The reader loses speed very quickly as the size of the file increases When I asked the person who initially wrote it why he used a generator he said it to be memory-careful What advice I have been given is read and process larger chunks of the file at a time and I would like to know how to tell what the largest chunk I can read without going into virtual memory is A few side notes - why is reading and processing large chunks faster than doing so with small chunks Does the cost of overhead being called many times add up that quickly? - I am interested in seeing if I can get even greater speed gains by trying my hand at Cython Does anyone know of any modules with binary file readers I could take a look at (other than the scipy stats matlab file reader)? | - I would like to know how to tell what the largest chunk I can read without going into virtual memory is I am not sure what you mean by "without going into virtual memory" but this is highly dependent on details such as the file format the storage medium and the filesystem/OS It is best determined empirically If you can implement a parameter `chunk_size` (or `n_records` or whatever) that determines how many records to read at a time - why is reading and processing large chunks faster than doing so with small chunks Depends on the code that is doing the reading It might be due to system call overhead or because Python code has to executed in between reads - Does anyone know of any modules with binary file readers I could take a look I co-wrote a <a href="https://github com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_svmlight_format pyx" rel="nofollow">loader for the LibSVM/SVMlight file format</a> a simple text format for sparse matrices in Cython It is distributed as part of scikit-learn |
How to get this thread waiting on a queue to quit? I have got two threads in my application One that puts values in a <a href="http://docs python org/library/queue html" rel="nofollow">`Queue`</a> and another that pulls them from the `Queue` and processes them I am faced with a dilemma when shutting the application down The thread that processes items in the `Queue` is stuck on: ````item = request_queue get() # this call blocks until an item is available ```` The only thing that will terminate the thread is if another item is added to the `Queue` - and since the main thread does not add anything (because it is shutting down) the application locks So how can I instruct `Queue get()` to somehow return even if there is nothing on the `Queue`? | The answer it turns out is quite simple Pick a value that would be invalid for the code that processes the `Queue` (`None` is ideal for that) and push that into the `Queue` Then have the `Queue` processing thread quit when it gets the value: ````while True: item = request_queue get() if item is None: break # process the Queue as per normal ```` |
How to maintain LDAP authentication across Django views? Here is the current situation: I created a <them>login html</them> page where I enter my username and password in a form In my `views py` I get the POST data and use the username and password to authenticate against my LDAP server (mechanism works) If the username/password is wrong I am redirected back to the login page with an error message Otherwise I am redirected to a landing page where I will have a message like: "<them>Hello Lastname Firstname</them>" I am able to get the first and last names from the LDAP query <strong>The problem:</strong> When I go to the new view i e the landing page I lose my authentication When I trace `request user` I get the admin user I used while creating my Django project I would expect the Django_auth ecosystem to do all this for me but maybe I am wrong I am not sure whether I should place the user in a session because I could not find anywhere on Google where people use Django's LDAP and Session together I would appreciate any help from the gurus out there Thanks Edit with actual code: ````def login(request): error = False DN = 'None' user = 'None' user_attr = 'None' if request method == 'POST': #if form has been submitted DN = request POST['login'] PWD = request POST['password'] DN_FULL_EMAIL = DN '@'+user_domain+' mysite com' print 'DN_FULL_EMAIL' DN_FULL_EMAIL try: l = ldap initialize('ldap://mysite com:3268') print 'bind_res = ' l simple_bind_s(DN_FULL_EMAIL PWD) BASE_DN = 'DC=eng DC=mysite DC=com' SCOPE = ldap SCOPE_SUBTREE Filter = '(&(objectClass=person)(sAMAccountName='+DN+'*)(objectClass=organizationalPerson)(objectClass=user))' Attrs = ['displayName' 'employeeID'] #The only data we need r= l search_ext(BASE_DN SCOPE Filter Attrs) Type user = l result(r 10) if user : Name Attrs = user[0] if hasattr(Attrs 'has_key') and Attrs has_key('displayName') and Attrs has_key('employeeID'): displayName = Attrs['displayName'][0] WWID = Attrs['employeeID'][0] request user = user user_attr = Attrs return HttpResponseRedirect('/' { 'user' : user 'user_attr' : user_attr }) except ImportError: error = True pass except ldap INVALID_CREDENTIALS: error = True pass return render_to_response( 'login html' { 'error' : error 'user' : user 'user_attr' : user_attr } context_instance = RequestContext(request)) ```` | You almost certainly want to use an LDAP authentication backend like <a href="https://pypi python org/pypi/django-auth-ldap/1 1 4" rel="nofollow">django-auth-ldap</a> If the backend is installed and configured properly your views should not require any LDAP-specific code If you have gotten tangled up do not be afraid to start over and follow the backend's documentation from the beginning |
What is an example of skilled professionals? | physicians |
psycopg2 returns numbers as string Every time I try to return numbers with psycopg2(saved as numeric) they end up being of string data type How can I return them as int float or double? | The <a href="http://initd org/psycopg/docs/faq html#faq-float" rel="nofollow">FAQ</a> describes a method for doing this You basically register a type handler Search for `Numeric` on that page According to the FAQ you do this: ````DEC2FLOAT = psycopg2 extensions new_type( psycopg2 extensions DECIMAL values 'DEC2FLOAT' lambda value curs: float(value) if value is not None else None) psycopg2 extensions register_type(DEC2FLOAT) ```` |
Going down columns using xlrd Let us say I have a cell (9 3) I want to get the values from (9 3) to (9 99) How do I go down the columns to get the values I am trying to write the values into another excel file that starts from (13 3) and ends at (13 99) How do I write a loop for that in xlrd? ````def write_into_cols_rows(are c): for num in range (0 96): c = 1 return (r c) ```` | `worksheet row(int)` will return you the row and to get the value of certain columns you need to run `row[int] value` to get the value For more information you can read <a href="http://www simplistix co uk/presentations/python-excel pdf" rel="nofollow">this</a> pdf file (Page 9 Introspecting a sheet) ````import xlrd workbook = xlrd open_workbook(filename) # This will get you the very first sheet in the workbook worksheet = workbook sheet_by_name(workbook sheet_names()[0]) for index in range(worksheet nrows): try: row = worksheet row(index) row_value = [col value for col in row] # now row_value is a list contains all the column values print row_value[3:99] except: pass ```` To write data to Excel file you might want to check out `xlwt` package BY THE WAY seems like you are doing something like reading from excel do some work write to excel I would also recommend you take a look at `numpy` `scipy` or `R` When I usually do data munging I use `R` and it saves me so much time |
What was the average family size? | 2.97 persons. |
Murmured consonants are uncommon in which language of which country? | null |
closing hanging zmq socket from another thread Is there some way to close a specific hanging recv zmq socket from another thread in Python without clobbering other sockets that may be in use? The following code does not seem to exit; replacing the `sock close()` with `ctx destroy()` causes it to exit but that would obviously destroy all sockets in the context: ````import zmq import time import threading as th ctx = zmq Context() sock = ctx socket(zmq ROUTER) sock bind('tcp://*:6000') def shutdown(): time sleep(5) print 'closing' sock close() t = th Thread(target=shutdown) t start() try: sock recv() except zmq ZMQError: print 'closed' ```` | One possibility is to perform the socket operations within a context manager that shuts down sockets using a signal handler that raises an exception when a signal is detected: ````import zmq import signal time import threading as th from contextlib import contextmanager @contextmanager def ZMQErrorOnAlarm(): def handler(signum frame): raise Exception('ALARM detected') signal signal(signal SIGALRM handler) yield ctx = zmq Context() sock = ctx socket(zmq ROUTER) sock bind('tcp://*:6000') def shutdown(): signal alarm(5) print 'closing' t = th Thread(target=shutdown) t start() with ZMQErrorOnAlarm(): try: sock send('x') sock recv() except: print 'closed' ```` |
Restore postrgres without ending connections I run a number of queries for adhoc analysis against a postgres database Many times I will leave the connection open through the day instead of ending after each query I receive a postgres dump over scp through a she will script every five minutes and I would like to restore the database without cutting the connections Is this possible? | One of the few activities that you cannot perform while a user is connected is dropping the database So – if that is what you are doing during restore – you will have to change your approach Do not drop the database (do not use the `-C` option in `pg_dump` or `pg_restore`) but rather drop and recreate the schemas and objects that do not depend on a schema (like large objects) You can use the `-c` flag of `pg_dump` or `pg_restore` for that The other problem you might run into is connections with open transactions (state “idle in transaction”) Such connections can hold locks that keep you from dropping and recreating objects and you will have to use `pg_terminate_backend()` to get rid of them |
How to find the minimum value in a numpy matrix? Hey this is a quick and easy question How would i find the minimum value of this matrix excluding 0? As in 8 ````arr = numpy array([[ 0 56 20 44 ] [ 68 0 56 8 ] [ 32 56 0 44 ] [ 68 20 56 0 ]]) ```` | As you are using `numpy` you could use ````arr[arr>0] min() ```` for the case you posted but if your array could have negative values then you should use ````arr[arr != 0] min() ```` |
Cannot for the life of me get rpy2 installed - gcc error I have gotten so many different install/build errors in trying to setup rpy2 on my Ubuntu 14 04 server in a virtual environment that I have lost track This is the last step I have in setting up my iPython server but I have been stuck on the rpy2 install for several days now I have tried many different things some of which I am sure are conflicting with each other and making my life harder (such as the dual R version installs) but I am giving up trying to do this without outside help Various things I have done: - Installed python-dev and setuptools - Installed and updated pip - Installed and updated gcc - Build and install the newest version of R from source - Build and install the development version of ARE (r-devel) from source using <a href="https://registry hub docker com/you/rocker/r-devel/dockerfile/" rel="nofollow">Dirk Eddelbuetel's Docker file</a> - [sudo] pip install rpy2 with stable ARE <them>and</them> development ARE - build rpy2 from source with stable ARE <them>and</them> development ARE (with <a href="http://rpy sourceforge net/rpy2/doc-dev/html/overview html" rel="nofollow">--ignore-check-rversion</a> option set) - easy_install rpy2 - pip install and source install with and without R_HOME set to stable ARE (current default R is the unstable development verison) If anyone has any idea what I can do to get this working besides starting from scratch in a clean environment then please let me know - it will be greatly appreciated Thank you!! The current error that I am getting is as follows: ````( venv)zacp@contentvalue:~/rpy2-2 6 0$ python setup py build_ext --ignore-check-rversion install R Under development (unstable) (2015-06-16 r68524) -- "Unsuffered Consequences" setup py:196: UserWarning: R did not seem to have the minimum required version number warnings warn("R did not seem to have the minimum required version number") /usr/local/lib/R/bin/R CMD config --ldflags R was not built as a library /usr/local/lib/R/bin/R CMD config --cppflags R was not built as a library setup py:211: UserWarning: No include specified warnings warn('No include specified') setup py:222: UserWarning: No libraries as -l arguments to the compiler warnings warn('No libraries as -l arguments to the compiler ') Compilation parameters for rpy2's C components: include_dirs = [] library_dirs = [] libraries = [] extra_link_args = [] running build_ext R Under development (unstable) (2015-06-16 r68524) -- "Unsuffered Consequences" setup py:77: UserWarning: R did not seem to have the minimum required version number warnings warn("R did not seem to have the minimum required version number") building 'rpy2 rinterface _rinterface' extension gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DR_INTERFACE_PTRS=1 -DHAVE_POSIX_SIGJMP=1 -DRIF_HAS_RSIGHAND=1 -DCSTACK_DEFNS=1 -DHAS_READLINE=1 -I /rpy/rinterface -I/usr/local/lib/python2 7 9/include/python2 7 -c /rpy/rinterface/_rinterface c -o build/temp linux-x86_64-2 7/ /rpy/rinterface/_rinterface o In file included from /usr/local/lib/python2 7 9/include/python2 7/Python h:8:0 from /rpy/rinterface/_rinterface c:55: /usr/local/lib/python2 7 9/include/python2 7/pyconfig h:1182:0: warning: "_POSIX_C_SOURCE" redefined [enabled by default] #define _POSIX_C_SOURCE 200112L ^ In file included from /usr/include/signal h:28:0 from /rpy/rinterface/_rinterface c:51: /usr/include/features h:230:0: note: this is the location of the previous definition # define _POSIX_C_SOURCE 200809L ^ In file included from /rpy/rinterface/_rinterface c:58:0: /rpy/rinterface/_rinterface h:8:15: fatal error: R h: No such file or directory #include <R h> ^ compilation terminated error: command 'gcc' failed with exit status 1 ```` | I guess the version of R that I installed with apt-get was out-of-date R 3 0 is "probably OK" according to the <a href="http://rpy sourceforge net/rpy2/doc-2 5/html/overview html" rel="nofollow">documentation</a> and I guess I misinterpreted the warnings Whoops! |
PicklingError when using multiprocessing I am having trouble when using the Pool map_async() (and also Pool map()) in the multiprocessing module I have implemented a parallel-for-loop function that works fine as long as the function input to Pool map_async is a "regular" function When the function is e g a method to a class then I get a PicklingError: ````cPickle PicklingError: Cannot pickle <type 'function'>: attribute lookup __builtin__ function failed ```` I use Python only for scientific computing so I am not so familiar with the concept of pickling have just learned a bit about it today I have looked at a couple of previous answers like <a href="http://stackoverflow com/questions/1816958/cannot-pickle-type-instancemethod-when-using-pythons-multiprocessing-pool-map">Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool map()</a> but I cannot figure out how to make it work even when following the link provided in the answer My code were the objective is to simulate a vector of Normal r v's with the use of multiple cores Note that this is just an example and maybe it does not even payoff to run on multiple cores ````import multiprocessing as mp import scipy as sp import scipy stats as spstat def parfor(func args static_arg = None nWorkers = 8 chunksize = None): """ Purpose: Evaluate function using Multiple cores Input: func - Function to evaluate in parallel arg - Array of arguments to evaluate func(arg) static_arg - The "static" argument (if any) i e the variables that are constant in the evaluation of func nWorkers - Number of Workers to process computations Output: func(i static_arg) for i in args """ # Prepare arguments for func: Collect arguments with static argument (if any) if static_arg != None: arguments = [[arg] static_arg for arg in list(args)] else: arguments = args # Initialize workers pool = mp Pool(processes = nWorkers) # Evaluate function result = pool map_async(func arguments chunksize = chunksize) pool close() pool join() return sp array(result get()) flatten() # First test-function Freeze location and scale for the Normal random variates generator # This returns a function that is a method of the class Norm_gen Methods cannot be pickled # so this will give an error def genNorm(loc scale): def subfunc(a): return spstat norm rvs(loc = loc scale = scale size = a) return subfunc # Second test-function The same as above but does not return a method of a class This is a "plain" function and can be # pickled def test(fargs): x a b = fargs return spstat norm rvs(size = x loc = a scale = b) # Try it out N = 1000000 # Set arguments to function args1 = [1 1 1 1] the purpose is just to generate a random variable of size 1 for each # element in the output vector args1 = sp ones(N) static_arg = [0 1] # standarized normal # This gives the PicklingError func = genNorm(*static_arg) sim = parfor(func args1 static_arg = None nWorkers = 12 chunksize = None) # This is OK: func = test sim = parfor(func args1 static_arg = static_arg nWorkers = 12 chunksize = None) ```` Following the link provided in the answer to the question in <a href="http://stackoverflow com/questions/1816958/cannot-pickle-type-instancemethod-when-using-pythons-multiprocessing-pool-map">Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool map()</a> Steven Bethard (almost at the end) suggests using the copy_reg module His code is: ````def _pickle_method(method): func_name = method im_func __name__ obj = method im_self cls = method im_class return _unpickle_method (func_name obj cls) def _unpickle_method(func_name obj cls): for cls in cls mro(): try: func = cls __dict__[func_name] except KeyError: pass else: break return func __get__(obj cls) import copy_reg import types copy_reg pickle(types MethodType _pickle_method _unpickle_method) ```` I do not really understand how I can make use of this The only thing I could come up with was putting it just before my code but it did not help A simple solution is of course to just go with the one that works and avoid getting involved with copy_reg I am more interested in getting copy_reg to work properly to take fully advantage of multiprocessing without having to go around the problem each time Thank you for your help it is much appreciated Matias | The problem here is less of the "pickle" error message than conceptual: multiprocess does fork your code in "worker" different processes in order to perform its magic It then sends data to and from the different process by seamlessly serializing and de-serializing the data (that is the part that uses the pickle) When part of the data passed back and forth is a function - it assumes a function with the same name exists in the callee process and (I guess) passes the function name as a string Since functions are stateless the called worker-process just calls that same function with the data it has received (Python functions cannot be serialized through pickle so just the reference is passed between the master and the worker processes) When your function is a method in an instance - although when we code python it is much like the same thing as a function with an "automatic" `self` variable it is not the same underneath Because instances (objects) are stateful That means the worker process does not have a copy of the object that is the owner of the method you want to call on the other side Working around ways of passing your method as a function to the map_async call will not work either - as multiprocess just uses a function reference not the actual function when passing it around So you should (1) either change your code so that you do pass a function - and not a method - to the worker processes converting whatever states the object keeps to new parameters to be called (2) Create a "target" function for the map_async call that reconstructs the needed object on the worker-process side and then calls the function inside it Most straightforward classes in Python are pickable themselves so you could pass the object that is the function owner itself on the map_async call - and the "target" function would call the appropriate method itself on the worker side (2) may sound "difficult" but it is probably just something like this - unless your object's class cannot be pickled: ````import types def target(object *args **kw): method_name = args[0] return getattr(object method_name)(*args[1:]) ( ) #And add these 3 lines prior to your map_async call: # Evaluate function if isinstance (func types MethodType): arguments insert(0 func __name__) func = target result = pool map_async(func arguments chunksize = chunksize) ```` *disclaimer: I have not tested this |
How to add lib directory to sys path when installed with custom prefix I come from a C background with Autotools ( /configure make make install) but have recently started to use Python With Autotools I can install a program more or less anywhere on the system by doing a ` /configure --prefix=/foo/bar` I have found that most Python programs uses a similar system based on distutils usually in a file called setup py However I have noticed that if I install the project in a non-standard directory for example by doing a `python setup py install --prefix /foo/bar` then the script in `/foo/bar/bin` will not be able to pick up packages which are installed into `/foo/bar/lib/pythonx y/site-packages` I assume that somehow I have to add that directory to `sys path` when the script is executed How do I do that in a stable cross-platform manner? Or should I do something else? | If your custom installdir is "foo" your python-root is "bar" and your package-root is "lib" you might add this to your script: ````import sys from os path import join foo = "foo" bar = "bar" lib = "lib" newbase = join(foo bar lib) sys path append(newbase) ```` in your example: ````foo ='foo' bar = 'bar' lib = '/lib/pythonx y/site-packages' ```` |
how to change a function in existing 3rd party library in python This was an interview question which was asked to me Please do not penalize me if it does not make sense She asked: "I have an existing 3rd party lib in python and there is a function foo() in it How do I modify that function after importing in my existing module?" | This is called monkey-patching In short you can just assign to the variable holding the function: ````import existingmodule existingmodule foo = lambda *args **kwargs: "You fail it" ```` This is rarely the right answer in practice It is much better to wrap something with your own function or provide your own implementation elsewhere or use inheritance (if a method on a class) The only reason to do this is if you need the altered behaviour to be reflected in the library's own code (or other third party code); if so test well It is usually a better approach than just creating your own fork; that said it might be a good idea to submit your code as a patch so it is not just you supporting it if it is accepted by the project |
Python: how to make two lists from a dictionary I have a dictionary ````{1 : [1 2 2 3 4 9 2 0] 2 : [4 1 5 1 6 3] 3 : [4 9 6 8 9 5 1 1 7 1]} ```` I want to pass each key:value pair to an instance of `matplotlib pyplot` as two lists: x values and y values Each key is an x value associated with each item in its value So I want two lists for each key: ````[1 1 1 1] [1 2 2 3 4 9 2 0] [2 2 2] [4 1 5 1 6 3] [3 3 3 3 3] [4 9 6 8 9 5 1 1 7 1] ```` Is there an elegant way to do this? Or perhaps there is a way to pass a dict to `matplotlib pyplot`? | Maybe something like: ````d = {1 : [1 2 2 3 4 9 2 0] 2 : [4 1 5 1 6 3] 3 : [4 9 6 8 9 5 1 1 7 1]} result = [] for key values in d items(): result append(([key]*len(values) values)) ```` |
How soon after did another series start after the Digimon Adventure 02? | three years |
pymysql fetchall() results as dictionary? Is there any way to get the results from a fetchall() as a dictionary using pymysql? | Use a <a href="http://mysql-python sourceforge net/MySQLdb-1 2 2/public/MySQLdb cursors DictCursor-class html" rel="nofollow">dictcursor</a> |
Best non-regex way to remove all characters after and including the first non-digit in Python Assume a string of 5 chars The title I think is clear but here are some examples: ````'716-0' -> '716' '77820' -> '77820' ```` Regex works fine ````import re re findall(r'\d+' '716-0')[0] ```` but how about a good non-regex way? | Regex is probably the best way to do it but if for whatever reason you want to avoid it you can make use of <a href="https://docs python org/3/library/stdtypes html#str isdigit" rel="nofollow">`str isdigit()`</a> and <a href="https://docs python org/3/library/itertools html#itertools takewhile" rel="nofollow">`itertools takewhile()`</a>: ````from itertools import takewhile string = "716-0" number = "" join(takewhile(str isdigit string)) ```` |
export data from csv file containing unicode characters I would like to export data from a csv file which contains unicode strings Previously I tried a Python script which works fine for ASCII data only But it will not support unicode stuff either: ````#! /usr/bin/env python import csv csv register_dialect('custom' delimiter=' ' doublequote=True escapechar=None quotechar='"' quoting=csv QUOTE_MINIMAL skipinitialspace=False) with open('input csv') as ifile: data = csv reader(ifile dialect='custom') for record in data: for i field in enumerate(record): print (" <field%s>" % i field "</field%s>" % i) ```` <blockquote> Traceback (most recent call last): for record in data: _csv Error: line contains NULL byte </blockquote> | use this unicode-csv library instead <a href="https://github com/jdunck/python-unicodecsv" rel="nofollow">https://github com/jdunck/python-unicodecsv</a> ````import unicodecsv as csv with open('input csv') as ifile: rows = [row for row in csv reader(ifile encoding='utf-8')] print rows ```` |
ctypes - call library function passing a struct resulted from an other library call A shared-library function results a struct that I try to pass to a second function from the same lib: ````struct rohc_comp* rohc_alloc_compressor(int a int b int c int d) void rohc_activate_profile( struct rohc_comp * comp int p ) ```` I do not want to manipulate the struct in my python code but i need the proper way to store a refence to it and pass it if needed: ````librc = CDLL("librohc_comp so") comp = librc rohc_alloc_compressor(15 0 0 0) librc rohc_activate_profile(comp 1) ```` It worked when I tested it as a very dummy example but when I put it in my complex Class it causes segmentation fault Which ctype should I use for comp? | Handle it as a `void *` i e set ````librc rohc_alloc_compressor restype = c_void_p librc rohc_activate_profile argtypes = [c_void_p c_int] ```` |
According to the Constitution what is rule of human leader superior to? | null |
The HRF measured target distance and what else? | elevation angle |
cgi module FieldStorage() function not receiving arguments I am trying to get a Python cgi module to work Python file runs well for example then I try to print out but once it comes to recive a GET or POST argument the cgi FieldStorage() function does not receive any input The print statement for FieldStorage output: ````FieldStorage(None None []) ```` You can find all the necessary code below I have simplified my script to the bare minimum trying to made it work It will not work either via GET nor POST ````#!/usr/bin/env python print "Content-type: text/html\n\n" import cgi cgitb cgitb enable() form = cgi FieldStorage() subMail = form getfirst("mail") print form print subMail ```` The HTML page (nor POST nor GET are working) ````<form action="cgi-bin/mail py" method="post" id="frm-landingPage1" class="form"> <div class="input-group"> <input type="text" class="form-control" placeholder="Indirizzo email" name="mail" id="frm-landingPage1-email" required value=""> <span class="input-group-btn"> <input class="btn btn-default" type="submit" value="Invia" name="_submit" id="frm-landingPage1-submit"> </span> </div> </form> ```` | Make sure you have all pre-settings proper like CGI Environment and make sure the CGI Script is in correct path Please read this: <a href="https://www tutorialspoint com/python/python_cgi_programming htm" rel="nofollow">https://www tutorialspoint com/python/python_cgi_programming htm</a> |
By mid November of 1940 how many incendiaries were dropped on London? | 1,000,000 |
arrange values in a python 2D array I am new to python and I am having a problem that I am not able to solve I have the following 2D array: ````valuearray = [['A' '21' '45'] ['A' '12' '23'] ['A' '54' '21'] ['A' '15' '54'] ['B' '23' '53'] ['B' '34' '53'] ['B' '32' '54'] ['B' '24' '13'] ['C' '31' '43'] ['C' '42' '54'] ['C' '35' '54'] ['C' '12' '11']] A 21 45 A 12 23 A 54 21 A 15 54 B 23 53 B 34 53 B 32 54 B 24 13 C 31 43 C 42 54 C 35 54 C 12 11 ```` I need to generate from this array another array that have the unique values of `valuearray[0]` the maximum of `valuearray[1`] for each `valuearray[0]` and the minimum `valuearray[2]` for each `valuearray[0]` The result would be: ````resarray[] A 54 21 B 34 13 C 42 11 ```` <them><strong>EDIT: sorry for not presenting what I tried</them></strong> ```` uniquenames = [] un = [] for i in range(len(valuearray)): un append(valuearray[i][0]) uniquenames=uniq(un) test = [] for ci in range(len(valuearray)): for gn in range(len(uniquenames)): if(valuearray[ci][0] == uniquenames[gn]): # i do not know what to do here i tried append(valuearray[ci][0] max(valuearray[ci][1]) min( valuearray[ci][2])) ```` but append only take one parametre so I do not know how to continue And uniq is a function that gives me the unique values from a list | We can do this pretty easily with <a href="http://docs python org/library/itertools html#itertools groupby" rel="nofollow">`itertools groupby`</a> and <a href="http://docs python org/library/functions html#zip" rel="nofollow">`zip()`</a>: ````data = [ ['A' '21' '45'] ['A' '12' '23'] ['A' '54' '21'] ['A' '15' '54'] ['B' '23' '53'] ['B' '34' '53'] ['B' '32' '54'] ['B' '24' '13'] ['C' '31' '43'] ['C' '42' '54'] ['C' '35' '54'] ['C' '12' '11'] ] from itertools import groupby from operator import itemgetter for name values in groupby(data itemgetter(0)): _ first second = zip(*values) print(name max(first) min(second)) ```` What we are doing here is using `groupby()` to group the list items by the first item This gives us three lists - a list for the records beginning with A then a list for B then C It is also worth noting that `groupby()` does not require your list to be sorted We then extract the values from these lists by using `zip()` to unzip the values from a list of triplets into three lists of single values We throw away the first column as it is just A B or C as is relevant and then take the maximum and minimum of the other columns to get the values you wanted Which gives us: ````A 54 21 B 34 13 C 42 11 ```` <h1>Edit:</h1> If you have your values as text then you can use a <a href="https://www youtube com/watch?v=t85uBptTDYY" rel="nofollow">list comprehension</a> and <a href="http://docs python org/library/stdtypes html#str split" rel="nofollow">`str split()`</a> to make a list out of it: ````data = """\ A 21 45 A 12 23 A 54 21 A 15 54 B 23 53 B 34 53 B 32 54 B 24 13 C 31 43 C 42 54 C 35 54 C 12 11\ """ data = [value split() for value in data split("\n")] ```` <h1>Another Edit:</h1> As per the chat you can discard extra columns like so: Python 3 x: ````for name values in groupby(data itemgetter(0)): _ first second *_ = zip(*values) print(name max(first) min(second)) ```` Python 2 x: ````for name values in groupby(data itemgetter(0)): first second = zip(*values)[1:3] print name max(first) min(second) ```` <h1>And to make the output a list rather than printing the values:</h1> ````def max_min_by_group(group): for name values in group: _ first second *_ = zip(*values) yield [name max(first) min(second)] new = [item for item in max_min_by_group(groupby(data itemgetter(0)))] ```` We simply use a list comprehension and a generator (we could do this in one big line but it would be unwieldy and unreadable) This gives us: ````[['A' '54' '21'] ['B' '34' '13'] ['C' '42' '11']] ```` |
Page is not always rendered In Google App Engine I have the following code which shows a simple HTML page ````import os from google appengine ext webapp import template from google appengine ext import webapp class IndexHandler(webapp RequestHandler): def get(self): template_values = { } path = os path join(os path dirname(__file__) ' /templates/index html') self response out write(template render(path template_values)) ```` The issue is that the page is not always rendered The index html is a simple "Hello World!" After a couple of page refresh the page is displayed properly (i e the index html file is found ) I tried to call flush at the end but it did not help I am able to repro this with the SDK and on their server Am I missing something? Does someone have an idea of what is going on? Thanks | Cannot reproduce -- with directory changed to ` /templates` (do not have a ` /templates` in my setup) and the usual `main` function added and this script assigned in `app yaml` to some arbitrary URL it serves successfully "Hello World" every time Guess we need more info to help -- log entries (maybe add `logging info` calls here?) `app yaml` where is `main` etc etc |
Running a Perl script and entering commands into it from Python I am a week into learning Python and am trying to write a piece of code that allows me to run a text-based Perl script in LXTerminal automatically I have a couple of questions regarding some specifics I need my code to start the Perl script with a user-inputted environment file enter a few specific settings into the Perl script and then read in many txt files one at a time into the Perl script It also needs to restart the process for every single txt file and capture each individual output (it would help if every output could be written to a single csv file) To call the Perl script I am starting with the following: ````alphamelts="/home/melts/Desktop/alphamelts" pipe=subprocess Popen(["perl" "/home/Desktop/melts/alphaMELTS" "run_alphamelts command -f %s"]) % raw_input("Enter an environment file:") stdout=PIPE ```` Assuming that is correct I now need it to read in a txt file enter number-based commands have my code wait for the Perl script to finish its calculations and I need it to write the output to a csv file If it helps the Perl script I am running automatically generates a space delimited file containing the results of its calculations once the program exists but it would be super helpful if only a few of its outputs were written onto a single seperate csv file for each txt file processed No idea where to go from here but I absolutely have to get this working Sorry for the complexity Thank you! | you can do some really cool stuff in ipython Check out <a href="https://github com/nagordon/technotes/blob/master/ipython-perl-octave ipynb" rel="nofollow">this notebook</a> for some specific examples As far as waiting for a subprocess to finish I think you need to put a `pause` in your script Also for data handling and export to csv and excel I would recommend <a href="http://pandas pydata org/pandas-docs/stable/" rel="nofollow">pandas</a> Just something to get you started |
Issue on Matching the string and replacing the hex in python ````st = """ What kind of speCialist would we see for this?He also seems to have reactions to the red dye cochineal/carmine cialist I like Cialist much """ ```` here I need to replace only the Cialist string(exact match) also it may has comma at the end The word "spe*cialist*" should not be thrown i tried with this regex ```` bold_string = "<b>"+"Cialist"+"</b>" insensitive_string = re compile(re escape("cialist") re IGNORECASE) comment = insensitive_string sub(bold_string st) ```` but it throws the string <strong>specialist</strong> also Could you suggest me to fix this? One more issue with replacing the hexadecimal character in python ```` date_str = "28-06-2010\xc3\x82\xc2\xa008:48 PM" date_str = date_str replace("\n" "") replace("\t" "") replace("\r" "") replace("\xc3\x82\xc2\xa" " ") date_obj = datetime strptime(date_str "%d-%m-%Y %H:%M %p") Error: time data '08-09-2005\xc3\x82\xc2\xa010:18 PM' does not match format '%d-%m-%Y %H:%M %p' ```` Here I am not able to replace the hex characters with space for matching with datetime pattern Could you please help out of this issue? | Use \b to match a word boundary Then it becomes simples :) ````import re st = """ What kind of speCialist would we see for this?He also seems to have reactions to the red dye cochineal/carmine cialist I like Cialist much """ print re sub(r'\bCialist\b' "<b>Cialist</b>" st) ```` For the second question you are missing a 0 at the end of your last replace string Just add 0 and it works :) ````date_str = "28-06-2010\xc3\x82\xc2\xa008:48 PM" print date_str date_str = date_str replace("\n" "") replace("\t" "") replace("\r" "") replace("\xc3\x82\xc2\xa0" " ") print repr(date_str) ```` |
Django ModelChoiceField - use something other than id? Say I have an `address` table and it has a `postal_code` field -- ModelChoiceField does not allow me to use something other than PKs to validate existence correct? What would be the way to go? Normal input and use `clean_*()`? | ModelChoiceFields are meant to be used to select between a choice of existing model instances This is almost always best represented by some form of Select field That said do you really have a FK from address to postal_code as you are implying What are you storing on a PostalCode table to justify the extra table that will need to be joined in for every address related query? For most cases postal_code should simply be a CharField and in that case if you want to validate that the value is valid you can use the `choices` attribute with a list of valid postal codes Keep in mind that maintaining a list of valid postal codes by hand is a huge hassle If you really have a PostalCode table and think it is a good idea (which in some cases it could be) you may want to consider actually using the postal_code as the primary key rather than the default autoincrement since it is necessarily unique makes your data more exportable and solves your issue with validation |
Searching python lists with loops and conditionals ````def ListCreate(*args): items = none for i in range(len(args)-1 -1 -1): items = join(args[i] items) return items a = ListCreate(1 2 3 4 5 6) b = ListCreate(20150602 20150603 20150604 20150605 20150606 20150607) ```` Lists in python are ordered so I would like `element 0` in list a to correspond with `element 0` in list b i e ```` (1 20150602)(2 20150603)(3 20150604) #etc ```` Now I would like to create a search loop that asks `if a(n)==a(n+1) and b(n+1) - b(n) <= 3` print all elements where conditions remain true | It is difficult to understand your desired output but this is my best guess: ```` In [39]: a = [1 1 3 4 4 6] b = [20150602 20150603 20150604 20150605 20150606 20150607] c = zip(a b) print c for i in range(0 len(c)-1): if c[i][0] == c[i+1][0] and c[i+1][1] - c[i][1] <= 3: print c[i] [(1 20150602) (1 20150603) (3 20150604) (4 20150605) (4 20150606) (6 20150607)] (1 20150602) (4 20150605) ```` |
NameError: global name 'Twitter' is not defined I installed the twitter wrapper for python installed it and running it but getting this error ````Traceback (most recent call last): File "/home/siddhartha/workspace/trouveunappart/src/test py" line 35 in <module> sid() File "/home/siddhartha/workspace/trouveunappart/src/test py" line 12 in sid t = Twitter( NameError: global name 'Twitter' is not defined ```` the code is: ````from twitter import * CONSUMER_KEY = '' CONSUMER_SECRET = '' OAUTH_TOKEN = '' OAUTH_SECRET = '' t = Twitter( auth=OAuth(OAUTH_TOKEN OAUTH_SECRET CONSUMER_KEY CONSUMER_SECRET) ) since_ID = -1 max_ID = 0 while(since_ID != max_ID): search = t search tweets(q = k count = 100 since_id = max_ID) print len(search['statuses']) if len(search['statuses']) == 0: print 'end' break since_ID = search['search_metadata']['since_id_str'] max_ID = search['search_metadata']['max_id_str'] ```` | Just a guess Is it possible that you have got another twitter library installed? I mean `import twitter` works for you but there is not `twitter Twitter` which should be there if you are really using <them>python twitter tools</them> For example <a href="https://code google com/p/python-twitter/" rel="nofollow"><them>python-twitter</them></a> does not have `twitter Twitter` but has `twitter Api` which does not exist in <them>python twitter tools</them> It seems that you have got <them>python-twitter</them> not <them>python twitter tools</them> |
Interest Calculator In Python <strong>Interest Calculator</strong> Let the user calculate the amount of money they will have in the bank after their interest has compounded for a certain number of years Note: A = P(1+r)^t where A = total amount P = principal are = rate and t = time This is what I tried: ````principal = input("How much money do you currently have in the bank?") rate = input("What is your interest rate?") time = input("Over how many years is the interest compounded?") actual_principal = float(principal) actual_rate = float(rate) actual_time = int(time) #TODO: Calculate the total amount and print the result A = (actual_principal(1 actual_rate) ^ actual_time) print(A) ```` I used actual_principal actual_rate and actual_time to convert the strings into (exact) integers I used float instead of int because float will maintain an input with decimals right? But I got an error message on line 9 ````TypeError: 'float' object is not callable on line 9 ```` I am assuming that the 'float' object refers to either actual_principal or actual_rate or both since those are the two values that I converted Why then are not they callable? How can I fix this program to calculate interest correctly? Thank you! <strong>EDIT</strong> Learning that the power function in python is ** and that implied multiplication operators do not exist in python syntax I reworked my equation to look like this: ````final_actual_rate = actual_rate 1 B = actual_principal * final_actual_rate A = B ** actual_time print(A) ```` When entering 13 58 for "How much money do you currently have in the bank?" 0 3 for "What is your interest rate?" and 5 for "Over how many years is the interest compounded?" I got the answer 1714808 43561 - so the calculator works! <strong>EDIT 2</strong> Replacing my way with this equation is the better / cleaner way to create the interest calculator - both will get you the same result: ````A = math pow(actual_principal*(1 actual_rate) actual_time) print(A) ```` | ````import math principal = input("How much money do you currently have in the bank?") rate = input("What is your interest rate?") time = input("Over how many years is the interest compounded?") actual_principal = float(principal) actual_rate = float(rate) actual_time = int(time) #TODO: Calculate the total amount and print the result A = math pow(actual_principal*(1 actual_rate) actual_time) print(A) ```` A few things wrong with what you have `^` is not what you think it is in Python `^` is an XOR binary operator not power If you want power you use <a href="https://docs python org/3/library/math html#math pow" rel="nofollow">math pow() module </a> Also using `action_principal(1 actual_rate)` is wrong You are trying to call the function `action_principal` with the argument `1 actual_rate` instead of multiplying it Try `*` instead |
set value to 99 percentile for each column in a dataframe I am working with the data which looks like a dataframe described by ````df = pd DataFrame({'AAA' : [1 1 1 2 2 2 3 3] 'BBB' : [2 1 3 4 6 1 2 3]}) ```` what i would like to do is to set value to roundup(90%) if value exceeds 90 percentile So its like capping max to 90 percentile This is getting trickier for me as every column is going to have different percentile value I am able to get 90 percentile value using ````df describe(percentiles=[ 9]) ```` so for column BBB 6 is greater than 4 60 (90 percentile) hence it needs to be changed to 5 (roundup 4 60) In actual problem I am doing this for large matrix so I would like to know if there is any simple solution to this rather than creating an array of 90 percentile of columns first and then checking elements in for a column and setting those to roundup of 90 percentile | One way to do this apply `clip_upper()` on 90 percentile value `np percentile(x 90)` for each column ````In [242]: df apply(lambda x: x clip_upper(np percentile(x 90))) Out[242]: AAA BBB 0 1 2 0 1 1 1 0 2 1 3 0 3 2 4 0 4 2 4 6 5 2 1 0 6 3 2 0 7 3 3 0 ```` <hr> I had imagined @ajcr elegant solution would faster than `apply` <strong>But </strong> Below benchmarks for `len(df) ~ 130K` ````In [245]: %timeit df apply(lambda x: x clip_upper(np percentile(x 90))) 100 loops best of 3: 7 49 ms per loop In [246]: %timeit np minimum(df df quantile(0 9)) 100 loops best of 3: 11 1 ms per loop ```` And for `len(df) ~ 1M` ````In [248]: %timeit df apply(lambda x: x clip_upper(np percentile(x 90))) 10 loops best of 3: 54 5 ms per loop In [249]: %timeit np minimum(df df quantile(0 9)) 10 loops best of 3: 73 9 ms per loop ```` |
Attempting to update a single Django form/model field is failing because user-id (foreign key) is not provided I have this horrible-looking-but-good enough-for-the-moment page that displays the user's profile picture (this user has none) and the "year they became a fan" Both are also forms so they can be updated <img src="http://i stack imgur com/Hwpsz jpg" alt="enter image description here"> So these two forms have <them>exactly one element</them> Here is the year-became-a-fan form (full forms py below): ````YEAR_CHOICES = ((x str(x)) for x in range(DISCOVERED_MIN_YEAR DISCOVERED_MAX_YEAR+1)) YEAR_DISCOVERED = forms IntegerField(label="Year discovered Billy Joel's music/became a fan" required=False min_value=DISCOVERED_MIN_YEAR max_value=DISCOVERED_MAX_YEAR widget=forms Select(choices=YEAR_CHOICES)) class UserProfileFormYearDiscOnly(forms ModelForm): global YEAR_DISCOVERED year_discovered = YEAR_DISCOVERED class Meta: model = UserProfile fields = ('year_discovered' ) ```` I have this function ````def _update_form_on_favs(user_profile_form): """ Submit the profile picture OR year_discovered form as found on the "my favorites" page RETURNS - None: If the form is valid - The form if any errors are detected """ if(user_profile_form is_valid()): profile = user_profile_form save(commit=False) profile save() return None; return user_profile_form; ```` Which is called by this view: ````@login_required def my_favorites(request form_name=None): context = RequestContext(request) context["fav_albums"] = request user album_set all() context["fav_songs"] = request user song_set all() profile_pic_form = None year_disc_form = None if(request POST and form_name is not None): if(form_name == "profile_pic"): profile_pic_form = _update_form_on_favs(UserProfileFormProfilePicOnly(request POST)) elif(form_name == "year_disc"): year_disc_form = _update_form_on_favs(UserProfileFormYearDiscOnly(request POST)) else: raise ValueError("Unknown value for 'form_name': '%s'" % str(form_name)) if(profile_pic_form is None): #The form was either successfully submitted or not submitted at all context["profile_pic_form"] = UserProfileFormProfilePicOnly() if(year_disc_form is None): #The form was either successfully submitted or not submitted at all context["year_disc_form"] = UserProfileFormYearDiscOnly(initial={ "year_discovered": request user profile year_discovered}) return render(request "billyjoel/my_favorites html" context_instance=context) ```` But when submitting the fan-year form the `profile save()` line (in the top function) is causing this error: `null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (26 null 1964 ) ` How do I associate this single field-value (which is a field in the UserProfile model) to the user it is meant for--the currently-logged-in user? <hr> models py: ````from datetime import datetime from django contrib auth models import User from django core exceptions import ValidationError from django db import models from time import time def get_upload_file_name(instance filename): return "uploaded_files/%s_%s" % (str(time()) replace(" " "_") filename) class Album(models Model): OFFICIALITY = ( ('J' 'Major studio release') ('I' 'Non-major official release') ('YOU' 'Unofficial') ) title = models CharField(max_length=70) description = models TextField(max_length=500 default="" null=True blank=True) pub_date = models DateField('release date') officiality = models CharField(max_length=1 choices=OFFICIALITY) is_concert = models BooleanField(default=False) main_info_url = models URLField(blank=False) thumbnail = models FileField(upload_to=get_upload_file_name blank=True null=True) #virtual field to skip over the through table songs = models ManyToManyField("Song" through="AlbumSong") users_favorited_by = models ManyToManyField('auth User') def __str__(self): return self title class Meta: #Default ordering is by release date ascending ordering = ['pub_date'] class Song(models Model): name = models CharField(max_length=100) description = models TextField(max_length=500 default="" null=True blank=True) length_seconds = models IntegerField() lyrics_url = models URLField(default="" blank=True null=True) albums = models ManyToManyField("Album" through="AlbumSong") users_favorited_by = models ManyToManyField(User) def get_length_desc_from_seconds(self): if(self length_seconds == -1): return "-1" m s = divmod(self length_seconds 60) h m = divmod(m 60) if(h): return "%d:%02d:%02d" % (h m s) else: return "%d:%02d" % (m s) def __str__(self): return self name class AlbumSong(models Model): song = models ForeignKey(Song) album = models ForeignKey(Album) sequence_num = models IntegerField() class Meta: unique_together = ('album' 'sequence_num' ) unique_together = ('album' 'song' ) def __str__(self): return str(self album) ": " str(self sequence_num) ": " str(self song) DISCOVERED_MIN_YEAR = 1960 DISCOVERED_MAX_YEAR = datetime now() year def validate_discovered_year(value): intval = -1 try: intval = int(str(value) strip()) except TypeError: raise ValidationError(you'"%s" is not an integer' % value) global DISCOVERED_MAX_YEAR global DISCOVERED_MIN_YEAR if(intval < DISCOVERED_MIN_YEAR or intval > DISCOVERED_MAX_YEAR): raise ValidationError(you'%s is an invalid "discovered Billy Joel year" Must be between %s and %s inclusive' % value DISCOVERED_MAX_YEAR DISCOVERED_MIN_YEAR) #It is all good ```` The bottom of models py containing the UserProfile model: ````class UserProfile(models Model): """ select id from auth_user where username='jeffy7'; select * from billyjoel_userprofile where user_id=XXX; """ # This line is required Links UserProfile to a User model instance user = models OneToOneField(User related_name="profile") # The additional attributes we wish to include year_discovered = models IntegerField(blank=True verbose_name="Year you discovered Billy Joel's music/became a fan" validators=[validate_discovered_year]) profile_picture = models ImageField(upload_to=get_upload_file_name blank=True null=True) #https://github com/mfogel/django-simple-email-confirmation #activation_key = models CharField(maxlength=40) #key_expires = models DateTimeField() # Override the __unicode__() method to return out something meaningful! def __unicode__(self): return self user username ```` forms py: ````from django import forms from django contrib auth models import User from models import UserProfile DISCOVERED_MIN_YEAR DISCOVERED_MAX_YEAR class UserForm(forms ModelForm): password1 = forms CharField(label="Password" widget=forms PasswordInput()) password2 = forms CharField(label="Password confirmation" widget=forms PasswordInput()) class Meta: model = User fields = ('username' 'email' 'password1' 'password2') def clean_password2(self): # Check that the two password entries match password1 = self cleaned_data get("password1") password2 = self cleaned_data get("password2") if password1 and password2 and password1 != password2: raise forms ValidationError("Passwords do not match") return password2 def save(self commit=True): # Save the provided password in hashed format user = super(UserForm self) save(commit=False) user set_password(self cleaned_data["password2"]) if commit: user save() return user #Should be implemented as an abstract base class with Meta or Meta fields passed into the constructor START YEAR_CHOICES = ((x str(x)) for x in range(DISCOVERED_MIN_YEAR DISCOVERED_MAX_YEAR+1)) YEAR_DISCOVERED = forms IntegerField(label="Year discovered Billy Joel's music/became a fan" required=False min_value=DISCOVERED_MIN_YEAR max_value=DISCOVERED_MAX_YEAR widget=forms Select(choices=YEAR_CHOICES)) #With no bounds: #YEAR_DISCOVERED = forms IntegerField(min_value=DISCOVERED_MIN_YEAR max_value=DISCOVERED_MAX_YEAR) class UserProfileForm(forms ModelForm): global YEAR_DISCOVERED year_discovered = YEAR_DISCOVERED class Meta: model = UserProfile fields = ('year_discovered' 'profile_picture' ) class UserProfileFormProfilePicOnly(forms ModelForm): class Meta: model = UserProfile fields = ('profile_picture' ) class UserProfileFormYearDiscOnly(forms ModelForm): global YEAR_DISCOVERED year_discovered = YEAR_DISCOVERED class Meta: model = UserProfile fields = ('year_discovered' ) #Should be implemented as an abstract base class with Meta or Meta fields passed into the constructor END ```` | If you just want update you need to pass the UserProfile instance like this: ````_update_form_on_favs(UserProfileFormProfilePicOnly(instance=request user profile request POST)) ```` Then call it as usual ````def _update_form_on_favs(profile_form_w_user_set_into_cnstr): if(profile_form_w_user_set_into_cnstr is_valid()): profile = profile_form_w_user_set_into_cnstr save(commit=False) profile save() return profile_form_w_user_set_into_cnstr ```` Good luck! |
Python define an action for an randomly chosen word I have written a script which chooses a random letter from a tuple and places it in a tkinter label Now I want to define specific actions for each letter so for example `"E"` might play a song How can I accomplish this? ````# -*- coding: cp1252 -*- import pygame import Tkinter as tk from Tkinter import * from functools import partial import random pygame init() label=tk Label() label pack() def knopf(label): WORDS=("A" "B" "C" "D" "E") label['text']=random choice(WORDS) button=tk Button(text='Knopf' command=partial(knopf label)) button pack() mainloop() ```` I tried to do it like Adam Smith but I always get an Error ````# -*- coding: cp1252 -*- import Tkinter as tk from Tkinter import * from functools import partial import random import pygame pygame init() label=tk Label() label pack() def knopf(label): def do_a(): pass def do_b(): pass def do_c(): pass def do_d(): pass def do_e(): print("E") WORDS={"A":do_a "B":do_b "C":do_c "D":do_d "E":do_e} choice = random choice(WORDS) label['text']=choice WORDS[choice]() button=tk Button(text='Knopf' command=partial(knopf label)) button pack() mainloop() ```` And here is the error: ````Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter py" line 1470 in __call__ return self func(*args) File "C:\Python27\tester py" line 20 in knopf choice = random choice(WORDS) File "C:\Python27\lib\random py" line 273 in choice return seq[int(self random() * len(seq))] # raises IndexError if seq is empty KeyError: 3 ```` | Write a function for each and dispatch to the various functions using a dictionary as with `WORDS[choice]()` below ````def knopf(label): def do_a(): pass def do_b(): pass def do_c(): pass def do_d(): pass def do_e(): play_song() WORDS={"A":do_a "B":do_b "C":do_c "D":do_d "E":do_e} choice = random choice(list(WORDS)) # make the choice label['text']=choice # set the label WORDS[choice]() # do the action ```` |
Dictionary that counts occurrences of its items I would like to create a <a href="http://docs python org/2/tutorial/datastructures html#dictionaries" rel="nofollow">`dictionary`</a> in python that automatically counts the repetitions of its elements: when an element that is not contained is added it should insert it with corresponding value `1` if the same element is inserted again it will increment its counter Is there a more elegant / compact way to implement this dictionary rather than the following? ````if var in myList: myDictionary[var] = 1 else: myDictionary[var] = 1 ```` | ````from collections import defaultdict d = defaultdict(int) d[var] = 1 ```` |
RPi3 connecting to WEP router using Python I have been trying to connect to WiFi networks using Python but hitting a dead end I am using the wireless module in Python: <a href="https://github com/joshvillbrandt/wireless" rel="nofollow">https://github com/joshvillbrandt/wireless</a> ````from wireless import Wireless wireless = Wireless() wireless connect(ssid password) ```` However this seems to only work for WPA and WPA2 routers I have also looked to see if I can do it via the terminal (so then I could call it in Python): <a href="http://askubuntu com/questions/16584/how-to-connect-and-disconnect-to-a-network-manually-in-terminal">http://askubuntu com/questions/16584/how-to-connect-and-disconnect-to-a-network-manually-in-terminal</a> ````iwconfig wlan0 essid SSID key PASSWORD ```` However this does not seem to connect to the router either So I was wondering whether anyone knows how to connect to a WEP router or if I am doing something wrong? | What O/S are you using? Can you connect to it from the RaspPi3 built-in wireless options? If so - what are settings in wpa_supplicant? From the library notes - this might be an answer: <blockquote> To use wpa_supplicant network-manager (the backend for nmcli) must not be running This is because network-manager runs an instance of wpa_supplicant behind the scenes which will conflict with the wpa_supplicant instance that this library would create If you have a network-manager on your machine but would prefer to use wpa_supplicant (not recommended) run sudo service network-manager stop before using wireless </blockquote> |
Benford's Law number generator inequality I created a small Python program that will calculate the probability of various 'random' numbers and see if they follow Benford's Law My algorithms may not be the most efficient for this but it still does the job My question is why does numGen1 not follow the rule where as numGen2 and numGen3 follow the rule? Is it something to do with the way that computers generate numbers? Sample Output (with n = 5000): NumGen1: ````Occurance of starting with 1 is 0 112 Occurance of starting with 2 is 0 104 Occurance of starting with 3 is 0 117 Occurance of starting with 4 is 0 117 ```` NumGen2: ````Occurance of starting with 1 is 0 327 Occurance of starting with 2 is 0 208 Occurance of starting with 3 is 0 141 Occurance of starting with 4 is 0 078 ```` NumGen3: ````Occurance of starting with 1 is 0 301 Occurance of starting with 2 is 0 176 Occurance of starting with 3 is 0 125 Occurance of starting with 4 is 0 097 ```` Here is my code: ````import random def numGen1(n): '''random randint choses an integer from [1 n]''' L = [] start1 = 0 start2 = 0 start3 = 0 start4 = 0 for i in range(n): L append(str(random randint(1 10000000))) for numbers in L: x = eval(numbers[0]) if x == 1: start1 = 1 if x == 2: start2 = 1 if x == 3: start3 = 1 if x == 4: start4 = 1 print ("Occurance of starting with 1 is % 3f \n" "Occurance of starting with 2 is % 3f \n" "Occurance of starting with 3 is % 3f \n" "Occurance of starting with 4 is % 3f ") % (start1/float(n) start2/float(n) start3/float(n) start4/float(n)) def numGen2(n): '''random random() takes a number x such that 0 <= x < 1 ''' L = [] start1 = 0 start2 = 0 start3 = 0 start4 = 0 for i in range(n): L append(str(random random()*i)) for numbers in L: x = eval(numbers[0]) if x == 1: start1 = 1 if x == 2: start2 = 1 if x == 3: start3 = 1 if x == 4: start4 = 1 print ("Occurance of starting with 1 is % 3f \n" "Occurance of starting with 2 is % 3f \n" "Occurance of starting with 3 is % 3f \n" "Occurance of starting with 4 is % 3f ") % (start1/float(n) start2/float(n) start3/float(n) start4/float(n)) def numGen3(n): '''Fibonnaci sequence generator''' a = 0 b = 1 c = 0 L=[] start1 = 0 start2 = 0 start3 = 0 start4 = 0 for i in range(n): c = a b a = b b = c L append(str(c)) for numbers in L: x = eval(numbers[0]) if x == 1: start1 = 1 if x == 2: start2 = 1 if x == 3: start3 = 1 if x == 4: start4 = 1 print ("Occurance of starting with 1 is % 3f \n" "Occurance of starting with 2 is % 3f \n" "Occurance of starting with 3 is % 3f \n" "Occurance of starting with 4 is % 3f ") % (start1/float(n) start2/float(n) start3/float(n) start4/float(n)) ```` | You are mixing things up here Bendford's law applies to sources of data and you can say it is something they adhere to You have essentially defined three random number generators; which have their own rules governing how they create the numbers There are many types of random number generation with the two main ones being <them>uniform</them> and <them>Gaussian</them> where they generate numbers <them>uniformly</them> spaced between the minimum and maximum and distributed normally about a mean with a stdard deviation (respectively) Only your third random number generator can be said to satisfy Benford's law the second is <them>similar</them> but it does not obey the law (it does not match log(d+1) - log(d)) These are just characteristics of your random number generators it is a maths thing Your third one obeys the law since the Fibonacci numbers obey the rule You would get the same result if you did the same with factorials and the powers of most numbers as they happen to obey Benford's law The second PRNG is dependant on N for example if N is some value like 80000 then you will miss out on the 8XXXX and 9XXXX entries and skew the results Presumably the best bet is to only have N as powers of 10 i will test this How this behaves for N = \infty though i am not sure either i will try and extrapolate Here is a plot of the distribution for different values of N note the cusps and how they appear for different colours (sorry about the legend i was not thinking when i plotted it and it tooko a fair while to plot ) <img src="http://i stack imgur com/z0DOi png" alt="enter image description here"> If you only look at powers of ten then you lose the cusps; <img src="http://i stack imgur com/i5Buv png" alt="enter image description here"> I ran each value of N enough times so that they all have the same number of samples - i e the line for 1000 was run 1000 times and the line for 1000000 was run once That should have removed most of the randomness I would say this is not following Benford's law There might be some magic number you can select to get it to work but that is not really in the spirit of Benford's law which is normally taken to be the behaviour in the limit of all of the data There is a chance that as N increases further it shifts towards the correct distribution i will think up an analytic formula for it and then try and plot that As for unutbu's comment about Benford distributions absorbing the properties of other distributions I think that is a bit of a confusion If you <them>uniformly randomly select values from another distribution</them> - which is what this code is doing - then you will end up with the original distribution again In this vein if you uniformly randomly select variables from <them>any</them> other distribution you will recover the original distribution as your sample size grows I completely agree that taking numbers uniformly (i e ala `random random()`) will give back a Benford distribution <them>if the original set of numbers follows Benford's law</them> so the problem boils down to deciding if then average of the probabilities of numbers starting with each digit in each of the sets: ````1 1 2 1 2 3 1 2 3 4 ```` has a Benford distribution The thing to notice here is that at each multiple of 10 the distribution is equal for all numbers it is uneven for non multiples of ten giving more bias to earlier numbers in the sequence Whether or not the amount of additional bias given to the numbers follows Benford's law though i do not know This plot from wikipedia: <img src="http://i stack imgur com/cgVgh jpg" alt="enter image description here"> Claims that it does but does not offer anything other than that The probability for each number being included in any sample is: <img src="http://i stack imgur com/PemkL png" alt="enter image description here"> Where N is the maximum (or in the original question `n` in the function call) and `i` is the number That then needs to be converted to give the probability of the number having `X` as it is first digit I am not sure how to do that in some easy way yet will take a bit more digging I will call it B(i) for now though where if something is truely benfordly distributed it has B(1) = 30 1% (etc ) I can plot it though; Here it is for N=100: <img src="http://i stack imgur com/rpxk8 png" alt="enter image description here"> At every power of ten there is a ripple like feature which spreads out to the next power of ten which you can easily relate to an increased probability of numbers starting with X (i e for N=119 B(i) will be higher than for N=99 since we have had 20 extra iterations through the loop wherein there are an increased number of numbers starting with 1 i e all of the extra ones) Each of the ripples is longer as it is spread out across the whole of the domain 10^m -> 10^{m+1} Here it is for N=1000 <img src="http://i stack imgur com/n2hWq png" alt="enter image description here"> And here is B_i(N) for each `i` I will add plots with larger N as i create them These plots are every `[i * 10 ** j for j in range(lowPower highPower) for i in range(1 10)] [10 ** (highPower)]` with cubic spline interpolation so that i did not have to do as many data points The interpolation makes very little difference though <img src="http://i stack imgur com/4khV6 png" alt="enter image description here"> it makes a little more sense to view it on a log scale though; <img src="http://i stack imgur com/JPqll png" alt="enter image description here"> Note that you do not have to average these lines to get the average of the whole distribution these are the expected values for B_i(N) for the second PRNG in the question |
Sort list B by the sort of list A? Let us say I have some list A with k elements and list B with k elements as well I want to sort list A but I also want to permute list B in the same way For example ````A = [2 3 1 4] B = [5 6 7 8] ```` after sorting A: ````A = [1 2 3 4] B = [7 5 6 8] ```` | You can try something like this: ````>>> A = [2 3 1 4] >>> B = [5 6 7 8] >>> >>> AB = zip(A B) >>> AB sort() >>> A[:] = [t[0] for t in AB] >>> B[:] = [t[1] for t in AB] >>> A [1 2 3 4] >>> B [7 5 6 8] ```` All we are doing here is "zipping" the list (i e in your example: `[(2 5) (3 6) (1 7) (4 8)]`) and sorting <them>that</them> list by the first element of each tuple Then from this sorted list we retrieve the desired `A` and `B` |
Setting variable as returned list does not seem to be doing anything Setting variables as returned lists from functions that contain variables as a returned list does not seem to give me any output: ````def get_wordlist(num s): items_in_wordlist = database_get(num) print "Trying to get wordlist " print items_in_wordlist items = [] if s == 0: for item in items_in_wordlist: items append((item[1]) decode("hex")) return items elif s == 1: for item in items_in_wordlist: items append((item[2]) decode("hex")) return items def get_wordlist_set(self speed): global main_wordlist main_wordlist_e print "Getting wordlist set " #try: main_wordlist = get_wordlist(speed 1) print "Check (1) - Passed" main_wordlist_e = get_wordlist(speed 0) print "Check (2) - Passed" return main_wordlist ```` "Check (*) - Passed" should be printed to the screen However All I am getting is "Getting wordlist set " Any ideas as to what I am doing wrong? | As sandinmyjoints says if you are seeing `Getting wordlist set ` But not `Trying to get wordlist ` It looks like ````database_get(num) ```` is not returning It could also be that the same function name is used for a different function elsewhere It might be a good idea to put a print <them>before</them> the call to `database_get` |
Python: list manipulation using del or list remove I am trying to write a function This function takes a list of numbers as input finds the largest sequence of consecutive numbers in this list and returns a list containing only this largest sequence of numbers of the original list Example: ````In [2]: largestSeq([1 2 3 4 1 2 3]) Out[2]: [1 2 3 4] ```` It works as long as the input list has 0 or more than 1 elements in it I included print statements in my code to see where the error is Here is the code and the result of calling `largestSeq([1])`and `largestSeq([1 2])`: <h2>Code:</h2> ````def findSeq(seq): #this finds a sequence of consecutive numbers i = 0 #in a list and returns it if len(seq) <= 1: #it stops when the next number in the list return seq #is smaller than the former s =[seq[0]] while seq[i] < seq[i+1]: i = 1 s append(seq[i]) if i == len(seq)-1: break return s def largestSeq(seq a=[]): b = findSeq(seq) #find the first consecutive sequence if len(seq) == 0: return a print 'Length of b is ' str(len(b)) if len(b) > len(a): #check if found sequence is bigger than print 'seq is now ' str(seq)#the last found sequence print 'b is now ' str(b) i = len(b) print 'now deleting elements of seq' for d in range (i): seq remove(seq[0]) #remove found sequence from the original #del seq[0:i] #list print 'seq is now ' str(seq) print 'b is now ' str(b) return largestSeq(seq b) #start over else: del seq[0:len(b)] return largestSeq(seq a) ```` <h2>And now the calls:</h2> ````In [14]: largestSeq([1]) Length of b is 1 seq is now [1] b is now [1] now deleting elements of seq seq is now [] b is now [] Out[14]: [] largestSeq([1 2]) Length of b is 2 seq is now [1 2] b is now [1 2] now deleting elements of seq seq is now [] b is now [1 2] Out[15]: [1 2] ```` Please note that in the first call the element in `b` is also deleted after deleting element of `seq` althoug I did not change it! In the second call with `[1 2]` `b` is behaving like I want it while `seq` is deleted I tried manipulating the list with `list remove` and with `del` (which is commented out and yields the same error) What is going on in there? I do not understand it I want `b` remaining unchanged in the first call like it does in the second call This is a very specific question I would be grateful for any suggestions! | In the first case you are returning the same list you have to return a copy of the list Try: ````def findSeq(seq): #this finds a sequence of consecutive numbers i = 0 #in a list and returns it if len(seq) <= 1: #it stops when the next number in the list return list(seq) #is smaller than the former s =[seq[0]] while seq[i] < seq[i+1]: i = 1 s append(seq[i]) if i == len(seq)-1: break return s ```` |
Reminder Using Tkinter I use Windows 7 32bit As a programming exercise I have to make a reminder using tkinter To be more specified : My main project is to help people who suffer from alzheimer disease So one of my targets is to make a reminder for helping them do the necessary activities/things For example At 14:00 of the clock Create a messagebox (and if it possible play a sound) saying "It is time to eat" Then at 18:00 of the clock Create a messagebox (and if it possible play a sound) saying "It is time for a walk" etc How I can do this? Is there a special module or some tools in python(or in tkinter) that can help me ? Before coding in Visual Basic as remember I used something like "Timer" But I cannot remember more about this :P Thanks in advance | At first thought you can have a tk config dialog where you can add new rules edit messagebox strings etc Then you will have in which you will use the `time` module From there you can access the system time If you want to display windows messageboxes you can find them in the ctypes libary |
Who lost the election in 1980? | null |
sqlalchemy: distinct only on one column My table looks like this: ```` title | slug ------------------------------ The Title | the-title Another Title | another-title another title | another-title ```` I want to select by distinct slug but also want the title returned as part of the results Which title gets returned for multiple matches I do not care So my results look like this: ````[('The Title' 'the-title') ('Another Title' 'another-title')] ```` | You probably want to do something like: ````session query(func max(Table title) Table slug) group_by(Table slug) all() ```` |
How to display more than one image in pygame? I want to make something that you can compare images and choose the one you like the best in pygame how can I display multiple images in one screen? | Load a second image and reposition it next to the first image object Here is a tip on how to work with positioning: <a href="http://stackoverflow com/questions/20165686/pygame-image-position">Pygame Image position</a> |
Display 'readable' list for output of MultipleChoiceField in email subject I would like to display the form output of a `MultipleChoiceField` in an email subject and message via Django's mail module Currently the subject lists data like this: <blockquote> Order placed for [you'cake' you'cheesecake'] by Patrick Beeson </blockquote> Here is the portion of my form accepting the input: ````class OrderForm(forms Form): ORDER_TYPE_CHOICES = ( ('cake' 'Cake') ('cheesecake' 'Cheesecake') ('coffee catering' 'Coffee catering') ('breakfast platter' 'Breakfast platter') ('cookie platter' 'Cookie platter') ('gourmet desserts platter' 'Gourmet desserts platter') ) order_type = forms MultipleChoiceField(required=False choices=ORDER_TYPE_CHOICES widget=forms CheckboxSelectMultiple) ```` And here is my view: ````from django shortcuts import render from django http import HttpResponseRedirect from django core urlresolvers import reverse from order_form forms import OrderForm def order(request): if request method == 'POST': form = OrderForm(request POST) if form is_valid(): name = form cleaned_data['name'] order_description = form cleaned_data['order_description'] phone_number = form cleaned_data['phone_number'] email_address = form cleaned_data['email_address'] date_needed = form cleaned_data['date_needed'] order_type = form cleaned_data['order_type'] subject = "Order placed for %s by %s" % (order_type name) message = "Name: %s\nPhone number: %s\nEmail address: %s\nOrder type: %s\nOrder description: %s\nDate needed: %s" % (name phone_number email_address order_type order_description date_needed) from django core mail import send_mail send_mail(subject message 'orders@business com' ['name@gmail com' email_address]) return HttpResponseRedirect('thanks/') else: form = OrderForm() return render(request 'order_form/order html' { 'form': form }) ```` | The <a href="https://docs djangoproject com/en/dev/ref/forms/fields/#multiplechoicefield" rel="nofollow">MultipleChoiceField resolves to a list of unicode objects</a> One possible way to make them "human readable" is to simply map that to a str: ````# map applies str to the outputted list order_type = map(str form cleaned_data['order_type']) if len(order_type) > 1: delineated = ' a ' join(order_type[0:-1]) # You are free to include or omit the oxford comma # unless you feel otherwise order_type = 'a {0} and a {1}' format(delineated order_type[-1]) else: order_type = 'a {0}' format(order_type[0]) ```` |
Why is not my PHP exec() working when trying to call a Python function? I am writing a web app that will use HTML to display a form Then the user completes the form and on submit the form is sent to PHP In the PHP file I have it set up to call and exec() command to a Python file that will return data But for some reason I am not getting anything back When I execute the command in terminal it works great but no response we ran in the web browser HTML: ````<form id ="nameForm" action="python php" method="post" target="_blank"> <label>First Name:</label><input type="text" id="firstName" name="firstName"><br> <label>Last Name:</label><input type="text" id="lastName" name="lastName"><br> <input type="submit" id="submitName" value="Submit"> </form> ```` PHP: ````$firstName = $_REQUEST['firstName']; $lastName = $_REQUEST['lastName']; exec("/opt/http/PythonWeb/web/python pythonName py " $firstName " " $lastName $response); echo $response; ```` Python: ````import sys def main(): firstName = sys argv[1] lastName = sys argv[2] output = "" output = "<html>\n" output = " <head><title></title></head>\n" output = " <body>\n" output = " <p>Hi " firstName " " lastName "</p>\n" output = " </body>\n" output = "</html>\n" print output if __name__ == '__main__': main() ```` Please give me some suggestions as to what may be wrong I am new to Python but it is what the boss man wants so I am going to make this work Thanks! | According to this <a href="http://www php net/manual/en/function passthru php" rel="nofollow">http://www php net/manual/en/function passthru php</a> you are using passthrough in a wrong way It is for binary data <blockquote> This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser </blockquote> Try Exec() Hope I was helpful |
Adding the items in a list within a list to find the average Okay so I have a list within a list(inception like madness) and it looks like this ````list = [[62 0 0 07427184466019418 9 0 6058252427184466 0 07455501618122977 0 0634304207119741 0 12637540453074433 0 4357200647249191 0 0 45] [98 0 0 32406580793266165 16 1 9099604642265018 0 5279938783318454 0 19997449304935594 3 547506695574544 1 3736768269353399 0 0 35]] ```` What I am trying to do is find the average of each item So in the above lists i would add 62 0 98 0(62 98 are the first items in each list) and divide by two to find the average I was thinking something like this ````for row in list: counter = 1 row[0] = row[0] row[0] / under_total ```` Any suggestions would be very welcome I hope this makes sense thanks for looking | ````L = [[62 0 0 07427184466019418 9 0 6058252427184466 0 07455501618122977 0 0634304207119741 0 12637540453074433 0 4357200647249191 0 0 45] [98 0 0 32406580793266165 16 1 9099604642265018 0 5279938783318454 0 19997449304935594 3 547506695574544 1 3736768269353399 0 0 35]] answer = [] for col in zip(*L): answer append(sum(col)/len(col)) print(answer) ```` Output: ````[80 0 0 1991688262964279 12 5 1 2578928534724743 0 30127444725653757 0 131702456880665 1 8369410500526442 0 9046984458301295 0 0 0 0 40 0] ```` If you have non-numeric entries in your lists: ````answer = [] for col in zip(*L): col = [c for c in col if isinstance(c int) or isinstance(c float)] answer append(sum(col)/len(col)) print(answer) ```` If it is indeed possible to have a column full of non-numeric values then it is possible for you to run into a ZerDivisionError So let us say that in those cases you want to say that the average is `0` Then this should do the trick: ````answer = [] for col in zip(*L): col = [c for c in col if isinstance(c int) or isinstance(c float)] if col: answer append(sum(col)/len(col)) else: answer append(0) print(answer) ```` |
Opening a Quickly dialog using a button I have created a window using quickly add dialog But I cannot figure out how to simply open the dialog from a button I have already set up a button in my main window and set up the code for it This is the code for the button: ````def on_quicksitesbutton_clicked(self widget): dialog = QuicksitesDialog QuicksitesDialog() result = dialog run() ```` I also imported the dialog with this line of code: ````from brandsonicweb QuicksitesDialog import QuicksitesDialog ```` The program runs fine but when I click the button I get in the terminal: ````Traceback (most recent call last): File "/home/brandon/brandsonicweb/brandsonicweb/BrandsonicwebWindow py" line 71 in on_quicksitesbutton_clicked dialog = QuicksitesDialog QuicksitesDialog() AttributeError: type object 'QuicksitesDialog' has no attribute 'QuicksitesDialog' ```` What am I doing wrong? How can I make this work? | Either write this in the function: ````dialog = QuicksitesDialog() ```` Or import like that: ````from brandsonicweb import QuicksitesDialog ```` In your code you finally get this: ````dialog = brandsonicweb QuicksitesDialog QuicksitesDialog QuicksitesDialog() ```` which is a little too much |
Problem using MySQLdb on OSX: symbol not found _mysql_affected_rows This is related to <a href="http://stackoverflow com/questions/1299013/problem-using-mysqldb-symbol-not-found-mysql-affected-rows">a previous question</a> However the main posted solution there is not working for me I am on Snow Leopard using the 32-bit 5 1 49 MySQL dmg install <strike>I am using the built in python</strike> (apparently as noted in the comments my Python version is different) which appears to be 2 6 5 32-bit: ``` Python 2 6 5 (r265:79359 Mar 24 2010 01:32:55) [GCC 4 0 1 (Apple Inc build 5493)] on darwin Type "help" "copyright" "credits" or "license" for more information >>> import sys >>> sys maxint 2147483647 ``` I have downloaded MySQL-python 1 2 3 from <a href="http://sourceforge net/projects/mysql-python/" rel="nofollow">the usual location</a> and changed site cfg so that mysql_config points to the right place and the registry_key directive is commented out The packages seems to build and install just fine: ``` caywork:MySQL-python-1 2 3 carl$ python setup py clean running clean caywork:MySQL-python-1 2 3 carl$ python setup py build running build running build_py copying MySQLdb/release py -> build/lib macosx-10 3-fat-2 6/MySQLdb running build_ext caywork:MySQL-python-1 2 3 carl$ sudo python setup py install running install running bdist_egg running egg_info writing MySQL_python egg-info/PKG-INFO writing top-level names to MySQL_python egg-info/top_level txt writing dependency_links to MySQL_python egg-info/dependency_links txt reading manifest file 'MySQL_python egg-info/SOURCES txt' reading manifest template 'MANIFEST in' warning: no files found matching 'MANIFEST' warning: no files found matching 'ChangeLog' warning: no files found matching 'GPL' writing manifest file 'MySQL_python egg-info/SOURCES txt' installing library code to build/bdist macosx-10 3-fat/egg running install_lib running build_py copying MySQLdb/release py -> build/lib macosx-10 3-fat-2 6/MySQLdb running build_ext creating build/bdist macosx-10 3-fat/egg copying build/lib macosx-10 3-fat-2 6/_mysql so -> build/bdist macosx-10 3-fat/egg copying build/lib macosx-10 3-fat-2 6/_mysql_exceptions py -> build/bdist macosx-10 3-fat/egg creating build/bdist macosx-10 3-fat/egg/MySQLdb copying build/lib macosx-10 3-fat-2 6/MySQLdb/__init__ py -> build/bdist macosx-10 3-fat/egg/MySQLdb copying build/lib macosx-10 3-fat-2 6/MySQLdb/connections py -> build/bdist macosx-10 3-fat/egg/MySQLdb creating build/bdist macosx-10 3-fat/egg/MySQLdb/constants copying build/lib macosx-10 3-fat-2 6/MySQLdb/constants/__init__ py -> build/bdist macosx-10 3-fat/egg/MySQLdb/constants copying build/lib macosx-10 3-fat-2 6/MySQLdb/constants/CLIENT py -> build/bdist macosx-10 3-fat/egg/MySQLdb/constants copying build/lib macosx-10 3-fat-2 6/MySQLdb/constants/CR py -> build/bdist macosx-10 3-fat/egg/MySQLdb/constants copying build/lib macosx-10 3-fat-2 6/MySQLdb/constants/ER py -> build/bdist macosx-10 3-fat/egg/MySQLdb/constants copying build/lib macosx-10 3-fat-2 6/MySQLdb/constants/FIELD_TYPE py -> build/bdist macosx-10 3-fat/egg/MySQLdb/constants copying build/lib macosx-10 3-fat-2 6/MySQLdb/constants/FLAG py -> build/bdist macosx-10 3-fat/egg/MySQLdb/constants copying build/lib macosx-10 3-fat-2 6/MySQLdb/constants/REFRESH py -> build/bdist macosx-10 3-fat/egg/MySQLdb/constants copying build/lib macosx-10 3-fat-2 6/MySQLdb/converters py -> build/bdist macosx-10 3-fat/egg/MySQLdb copying build/lib macosx-10 3-fat-2 6/MySQLdb/cursors py -> build/bdist macosx-10 3-fat/egg/MySQLdb copying build/lib macosx-10 3-fat-2 6/MySQLdb/release py -> build/bdist macosx-10 3-fat/egg/MySQLdb copying build/lib macosx-10 3-fat-2 6/MySQLdb/times py -> build/bdist macosx-10 3-fat/egg/MySQLdb byte-compiling build/bdist macosx-10 3-fat/egg/_mysql_exceptions py to _mysql_exceptions pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/__init__ py to __init__ pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/connections py to connections pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/constants/__init__ py to __init__ pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/constants/CLIENT py to CLIENT pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/constants/CR py to CR pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/constants/ER py to ER pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/constants/FIELD_TYPE py to FIELD_TYPE pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/constants/FLAG py to FLAG pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/constants/REFRESH py to REFRESH pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/converters py to converters pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/cursors py to cursors pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/release py to release pyc byte-compiling build/bdist macosx-10 3-fat/egg/MySQLdb/times py to times pyc creating stub loader for _mysql so byte-compiling build/bdist macosx-10 3-fat/egg/_mysql py to _mysql pyc creating build/bdist macosx-10 3-fat/egg/EGG-INFO copying MySQL_python egg-info/PKG-INFO -> build/bdist macosx-10 3-fat/egg/EGG-INFO copying MySQL_python egg-info/SOURCES txt -> build/bdist macosx-10 3-fat/egg/EGG-INFO copying MySQL_python egg-info/dependency_links txt -> build/bdist macosx-10 3-fat/egg/EGG-INFO copying MySQL_python egg-info/top_level txt -> build/bdist macosx-10 3-fat/egg/EGG-INFO writing build/bdist macosx-10 3-fat/egg/EGG-INFO/native_libs txt zip_safe flag not set; analyzing archive contents creating 'dist/MySQL_python-1 2 3-py2 6-macosx-10 3-fat egg' and adding 'build/bdist macosx-10 3-fat/egg' to it removing 'build/bdist macosx-10 3-fat/egg' (and everything under it) Processing MySQL_python-1 2 3-py2 6-macosx-10 3-fat egg Removing /Library/Frameworks/Python framework/Versions/2 6/lib/python2 6/site-packages/MySQL_python-1 2 3-py2 6-macosx-10 3-fat egg Copying MySQL_python-1 2 3-py2 6-macosx-10 3-fat egg to /Library/Frameworks/Python framework/Versions/2 6/lib/python2 6/site-packages MySQL-python 1 2 3 is already the active version in easy-install pth Installed /Library/Frameworks/Python framework/Versions/2 6/lib/python2 6/site-packages/MySQL_python-1 2 3-py2 6-macosx-10 3-fat egg Processing dependencies for MySQL-python==1 2 3 Finished processing dependencies for MySQL-python==1 2 3 ``` But when I try to use it I get this: ``` caywork:MySQL-python-1 2 3 carl$ python -c "import MySQLdb" /Library/Frameworks/Python framework/Versions/2 6/lib/python2 6/site-packages/MySQL_python-1 2 3-py2 6-macosx-10 3-fat egg/_mysql py:3: UserWarning: Module _mysql was already imported from /Library/Frameworks/Python framework/Versions/2 6/lib/python2 6/site-packages/MySQL_python-1 2 3-py2 6-macosx-10 3-fat egg/_mysql pyc but /Users/carl/Source/MySQL-python-1 2 3 is being added to sys path Traceback (most recent call last): File "" line 1 in File "MySQLdb/__init__ py" line 19 in import _mysql File "build/bdist macosx-10 3-fat/egg/_mysql py" line 7 in File "build/bdist macosx-10 3-fat/egg/_mysql py" line 6 in __bootstrap__ ImportError: dlopen(/Users/carl/ python-eggs/MySQL_python-1 2 3-py2 6-macosx-10 3-fat egg-tmp/_mysql so 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/carl/ python-eggs/MySQL_python-1 2 3-py2 6-macosx-10 3-fat egg-tmp/_mysql so Expected in: dynamic lookup ``` All I can find on the web are older examples of this problem along with numerous rants about how hard it is to get MySQL-python working on OSX If anyone can help with this I would greatly appreciate it!! | The only (admittedly kludgy) solution that I ended up getting to work was to use MySQL-python-1 2 2 after applying <a href="http://gist github com/511466" rel="nofollow">this patch</a> cobbled together from advice found here (http://www mangoorange com/2008/08/01/installing-python-mysqldb-122-on-mac-os-x/) and here (http://flo nigsch com/?p=62) Sorry for the lack of links but I do not have enough rep points to post more than one link |
How to sort lists of tuples from a query according to the lists value? I could not find a clear example on how to sort tuples from a query Here is my whole code: ````import nltk //http://www nltk org/ import pypyodbc text = raw_input() token = nltk word_tokenize(text) print(token) tagged = nltk pos_tag(token) print(tagged) class Database(object): def __init__(self): self connected = False self conn = None self cur = None def connect(self): if not self connected: self conn = pypyodbc connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=Dictionary') self connected = True self cur = self conn cursor() def search(self lists): if not self connected: self connect() for word in lists: self cur execute('SELECT Ybanag FROM Words WHERE English IN (%s)' % (" " join('?'*len(lists))) lists) result = self cur fetchall() return result get = Database() this = get search(token) print(this) ```` and the output of this code is: (for example I enter this sentence: `we all there`)(I have created database using SQL Server Table name: `Words` Columns: `English Ybanag POST`) and display their corresponding value in a column ) ````['we' ' 'there'] //tokenize sentence [('we' 'PRP') (' 'DT') ('there' 'RB')] //tokens and their POST(Part-Of-Speech Tag) [('tore' ) ('ngaming' ) ('sittam' )] //their corresponding value in Ybanag from the dictionary ```` wherein `tore` is `there` `ngaming` is `all` and `sittam` is `we` as you can see the 3rd line was not as `['we' ' 'there']` in sequence What I mean is that from the query how can I sort the output according to the sequence of the lists of the first line `['we' ' 'there']`? I want also to eliminate the symbols `[('' ) ]` in the last line of the ouput This program tends to translate the input sentence into another language like `Ybanag` a mother tongue language in Philippines | You would need to select the English word in the SQL as well so that your 3rd line was a list of (english ybanag) tuples That way you could convert that to a dictionary and iterate over each word in the input list retrieving the Ybanag equivalent in order: ````self cur execute('SELECT English Ybanag FROM Words WHERE English IN (%s)' % (" " join('?'*len(lists))) lists) resultDict=dict(self cur fetchall()) outList=[] for word in lists: outList append(resultDict[word]) ```` This does not solve the problem of words not found in the database nor does it scale well if you are trying to convert a long sentence with many words |
Using Urlllib2 urlopen fails for binary data? I am using python to programatically download a zip file from a web server Using a web browser it is fine I have written this (partial) script; ````response = urllib2 urlopen(url data 10) the_page = response read() f = open(filename 'w') f write(the_page) f close() ```` The request succeeds and I get data The problem is that the file I am downloading -- a zip file -- does not work; the file appears to be corrupt It seems to be the right sort of length and looked at in text editor seems to look like a zip file content Here are the headers from the download; Content-Length: 9891 Content-Disposition: Content-Disposition:attachment; filename="TrunkBackup_20101230 zip" Date: Wed 30 Dec 2009 12:22:08 GMT Accept-Ranges: bytes When I check the length of the response it is correct at 9891 I suspect what is happening is that when I call `response read()` the result is a string with carriage returned 'helpfully' normalized (say `\r` to `\n`) when I write the file the binary data is slightly wrong and the zip file is corrupt My problem is (A) I am not sure if I am right and (B) if I am right how to I save the binary data itself? | Try opening the file in binary mode: ```` f = open(filename 'wb') ```` |
SQLite: no such column error I am getting the `sqlite3 OperationalError: no such colum: bla` error I have a sqlite file which only consists of one table `foo` with column `bar` ````connection = lite connect(db sqlite) def insertEvent(self bar): with connection: cur = connection cursor() cur execute("INSERT INTO foo(bar) VALUES (bar);") insertEvent("bla") ```` Is my syntax wrong or why am I getting the error? I could not find any useful solutions in all the other questions Just in case: I am using the sqlite3 library | Try changing the insert statement to ````cur execute("INSERT INTO foo(bar) VALUES (?);" (bar )) ```` You are not using the `bar` parameter in the insert statement |
How to upload a file to OneDrive using OneDrive REST API? Please allow me to explain <strong>what</strong> I am doing and <strong>How</strong> I am doing <strong>What I am doing?</strong> I am trying to upload a file to Onedrive using its REST API Source: <a href="https://dev onedrive com/items/upload_large_files htm" rel="nofollow">one drive api documentation</a> I am using OneDrive fragments approch to do so as the file can be as huge as 5gb or as small as 1kb (Depends on the user) Currently I am doing it using <a href="https://chrome google com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en" rel="nofollow">POST-MAN</a> Chrome extention to call APIes <strong>How am I doing?</strong> - Generated Access token - Created Session and received Uploading url - Uploading file using PUT request as given below Selected file that I want to upload <them>(File Size: 729676295 bytes)</them> <a href="http://i stack imgur com/Fberp png" rel="nofollow"><img src="http://i stack imgur com/Fberp png" alt="enter image description here"></a> Added headers and sent the request and sent the request <a href="http://i stack imgur com/WkVKn png" rel="nofollow"><img src="http://i stack imgur com/WkVKn png" alt="enter image description here"></a> <strong>Here is the result</strong> <a href="http://i stack imgur com/wDQfj png" rel="nofollow"><img src="http://i stack imgur com/wDQfj png" alt="enter image description here"></a> it is saying that the maximum fragment size is 67108864 bytes so I changed the value of <strong>content-length : 67108864</strong> and <strong>content-range : bytes 0-67108863/729676295</strong> but then I get this error message: <strong>Declared fragment length does not match the provided number of bytes</strong> <a href="http://i stack imgur com/ZnoV5 png" rel="nofollow"><img src="http://i stack imgur com/ZnoV5 png" alt="enter image description here"></a> <strong><them>Please help me to figure out what should I pass in content-length and content-range </them></strong> Many Thanks for you attention | Finally thanks to god after 2 days of struggle I found what was the problem There are some points that you need to keep in mind - You have to divide a file to into equal parts and save it somewhere and upload each of them separately on the same URL that you get after creating a session - <strong>Content-Length</strong> must be the total numbers of bytes of the file that you are uploading in all upload requests of fragments - <strong>Content-Range</strong> will be like: <strong>0-{fragmentLength-1}/{totalNumberOfBytesOfFile}</strong>(same as <them>content-length</them>) and from next fragment the <strong>Content-Range</strong> will be <strong>{uploadedBytes}-{uploadedBytes+nextSetOfBytes-1}/{totalNumberOfBytesOfFile}</strong> <strong>Note:</strong> The Next set of bytes should be as long as the previous was Do not worry because the last fragment can be different P S: Do not use the content-range that you will receive after successfully uploading the fragment |
XCode Target Phase Python Script I am trying to add a Python script to into my project to obtain the build and marketing numbers directly from Git I have created a new target phase and that runs a script as explained in: <a href="http://yeahrightkeller com/2008/10/19/xcode-run-script-build-phase-tip/" rel="nofollow">http://yeahrightkeller com/2008/10/19/xcode-run-script-build-phase-tip/</a> And I have written a Python script that parses the program Info plist using ````from Foundation import NSMutableDictionary ```` However the script fails while being compiled and reports the following error to the build results: ````Running a custom build phase script: gitversion py Traceback (most recent call last): File "/Users/jorge/Documents/Programming iPod/Pruebas/RowOrder/Scripts/gitversion py" line 9 in <module> from Foundation import NSMutableDictionary File "/System/Library/Frameworks/Python framework/Versions/2 6/Extras/lib/python/Foundation/__init__ py" line 8 in <module> File "/System/Library/Frameworks/Python framework/Versions/2 6/Extras/lib/python/PyObjC/objc/__init__ py" line 26 in <module> from _bridgesupport import * File "/System/Library/Frameworks/Python framework/Versions/2 6/Extras/lib/python/PyObjC/objc/_bridgesupport py" line 9 in <module> import pkg_resources File "/System/Library/Frameworks/Python framework/Versions/2 6/Extras/lib/python/pkg_resources py" line 651 in <module> class Environment(object): File "/System/Library/Frameworks/Python framework/Versions/2 6/Extras/lib/python/pkg_resources py" line 654 in Environment def __init__(self search_path=None platform=get_supported_platform() python=PY_MAJOR): File "/System/Library/Frameworks/Python framework/Versions/2 6/Extras/lib/python/pkg_resources py" line 55 in get_supported_platform plat = get_build_platform(); m = macosVersionString match(plat) File "/System/Library/Frameworks/Python framework/Versions/2 6/Extras/lib/python/pkg_resources py" line 181 in get_build_platform plat = get_platform() File "/System/Library/Frameworks/Python framework/Versions/2 6/lib/python2 6/distutils/util py" line 97 in get_platform cfgvars = get_config_vars() File "/System/Library/Frameworks/Python framework/Versions/2 6/lib/python2 6/distutils/sysconfig py" line 525 in get_config_vars func() File "/System/Library/Frameworks/Python framework/Versions/2 6/lib/python2 6/distutils/sysconfig py" line 408 in _init_posix raise DistutilsPlatformError(my_msg) distutils errors DistutilsPlatformError: $MACOSX_DEPLOYMENT_TARGET mismatch: now "10 5" but "10 6" during configure Finished running custom build phase script: gitversion py (exit status = 1) ```` Clearly distutils has somehow hardcoded that it is compiled for version 10 6 (Snow Leopard that is the one I am using) but the project has the MacOSX Deployment target set to 10 5 If i try to set this variable in the project to 10 6 I then get: ````ld: library not found for -lcrt1 10 6 o ```` Any ideas on how to solve this issue? Thanks in advance | Apple distributes Python 2 5 and 2 6 with Snow Leopard (10 6) and both are built with a deployment target of 10 6 If you really do need to target your application for 10 5 you cannot safely use the Apple-supplied Pythons on 10 6 to deploy on 10 5 The easiest solution may be to download and install a <a href="http://www python org/download/releases/2 6 4/" rel="nofollow">Python 2 6 from python org</a> That Python is targeted for 10 3+ so it will work on both 10 5 and 10 6 You will probably also need to ensure that that Python is installed on all machines where your app will be deployed Another option might be to create a separate stand-alone helper app using <a href="http://svn pythonmac org/py2app/py2app/trunk/doc/index html" rel="nofollow">py2app</a> with the python org 2 6 and deploy that along with your main app Or create your whole app under py2app In either case the app would contain its own python framework interpreter and framework independent of the system version EDIT: Based on your comment I am not sure I understand your problem Since you are running on 10 6 it is not clear to me (1) why you have the deployment target set to 10 5 and (2) if you need to have the deployment set to 10 5 I am going to guess that you had an existing Xcode project that was developed on 10 5 and then imported or upgraded from Xcode on 10 5 to Xcode on 10 6 If that is the case then I think the only thing that should have been needed to be done is to change the Active SDK from 10 5 to 10 6 (in the overview) in the top of the project window Doing just that and forcing a Clean All Targets should solve the `crt library not found` error; if not there is something wrong with the project dependencies On the other hand if you really do need to develop on 10 6 for 10 5 then it seems that your gitversion py is introducing an inadvertent dependency on python 2 6 (as can be seen by the traceback) which is not part of 10 5 Unless you really need python 2 6 features you should be able to eliminate that by using python 2 5 which Apple provides on both 10 5 and 10 6 In that case perhaps all you need to do is to ensure that you invoke python in the build phase script with /usr/bin/python2 5 rather than just python |
operations on lists using zip or array I am wondering what is the best to do if I want to sum the elements (elements by elements) of two lists named l1 and l2: ````l3 = [i j for i j in zip(l1 l2)] ```` or converting the lists as arrays and do a simple sum ````from numpy import array l3 = list(array(l1) array(l2)) ```` | It probably depends on how big the lists are `numpy` is designed for efficient operations on large sets of data but introduces some constant overhead because it is not part of native Python Also if you are going for performance <a href="http://docs python org/library/itertools html#itertools izip" rel="nofollow">`itertools izip`</a> may give you better speed <hr> For just random lists I would probably go with `[i+j for i j in izip(l1 l2)]` due to simplicity/readability assuming they are not large enough to bring significant performance into question |
Why is list(xrange) slower than range()? I was doing a couple of tests and found that `xrange()` is MUCH faster than `range()` (as confirmed by various questions/answers as well): ````>>> from timeit import timeit >>> timeit(stmt = 'x = range(1000)' number = 10000) 0 38216601211680734 >>> timeit(stmt = 'x = xrange(1000)' number = 10000) 0 010537726631953959 # xrange is much faster than range ```` I got curious so I tried another test to see if `list(xrange(1000))` would still be faster than simply `range(1000)`: ````>>> timeit(stmt = 'x = range(1000)' number = 10000) 0 3858838963796529 >>> timeit(stmt = 'x = list(xrange(1000))' number = 10000) 0 492734766028903 # now xrange is slower ```` This is also true for more calls: ````>>> timeit(stmt = 'x = range(1000)' number = 100000) 3 6457308233315757 >>> timeit(stmt = 'x = list(xrange(1000))' number = 100000) 5 722031755612818 ```` So my question is why is `list(xrange)` significantly slower than `range` itself? I saw <a href="http://stackoverflow com/questions/4241716/why-are-list-dict-and-tuple-slower-than-and">this question on the slowness of `list()` `dict()` and other constructor methods</a> so is that why `list(xrange)` is so much slower? Using `dis dis()` I found that `list(xrange)` performs more computations than `range`): ````>>> dis dis('x = list(xrange(1000))') 0 SETUP_LOOP 15648 (to 15651) 3 SLICE+2 4 IMPORT_NAME 29545 (29545) 7 LOAD_GLOBAL 30760 (30760) 10 POP_JUMP_IF_FALSE 28257 13 BUILD_LIST 10341 16 <49> 17 <48> 18 <48> 19 <48> 20 STORE_SLICE+1 21 STORE_SLICE+1 >>> dis dis('x = range(1000)') 0 SETUP_LOOP 15648 (to 15651) 3 SLICE+2 4 POP_JUMP_IF_FALSE 28257 7 BUILD_LIST 10341 10 <49> 11 <48> 12 <48> 13 <48> 14 STORE_SLICE+1 ```` | Of course `range()` is going to be faster when the end product you desire is a list of all numbers in a range `range` does all of that in a single function call As opposed to `list(xrange())` which burdens the `list( )` constructor with the overhead of the `rangeiterator` object created to iterate over the `xrange` object which the `list( )` constructor must consume Whereas `range()` constructs the list immediately no intermediate iterator consumption how could that be beaten? The main difference is: 1 function call vs 2 and less importantly 1 global lookup vs 2 |
How to scrap the html data with same kind of tags How would I extract the Agency Fee Bedrooms And Bathroom's info using beautiful soup in python [Here][1] is the webpage I am scrapping ````<ul class="important-fields"> <li class=""> <span> Agency Fees: </span> <strong> AED 5000 </strong> </li> <li class=""> <span> Bedrooms: </span> <strong> Studio </strong> </li> <li class=""> <span> Bathrooms: </span> <strong> 1 </strong> </li> <li> </ul> ```` | You can use Xpath (<a href="http://www w3schools com/xpath/" rel="nofollow">http://www w3schools com/xpath/</a>) to get the data from the HTML using lxml library in python and you can find examples in lxml tutorials (<a href="http://lxml de/tutorial html" rel="nofollow">http://lxml de/tutorial html</a>) |
What is the most efficient way to create a folder with permissions in python (vs running bash/she will commands)? I am converting some bash/she will scripts to Python I would like to only create a directory/folder on a CentOS system if it does not exist already and then set 777 permissions on it I can easily do this with one command in bash: ````mkdir -m 777 "/PATH/TO/DIRECTORY/GOES/HERE"; ```` Right now i am running this command as a subprocess in python but I was wondering if there was a cleaner faster and/or more efficient way of doing it? Any help or even hits will be appreciated! :) | You can set the permissions directly when using <a href="http://docs python org/2/library/os html#os mkdir" rel="nofollow">os mkdir</a>: ````mkdir( ) mkdir(path [ mode=0777]) Create a directory ```` |
Getting a slice of a numpy ndarray (for arbitary dimensions) I have a Numpy array of arbitrary dimensions and an index vector containing one number for each dimension I would like to get the slice of the array corresponding to the set of indices less than the value in the index array for all dimensions e g ````A = np array([[1 2 3 4] [5 6 7 8] [9 10 11 12]]) index = [2 3] result = [[1 2 3] [5 6 7]] ```` The intuitive syntax for this would be something like `A[:index]` but this does not work for obvious reasons If the dimension of the array were fixed I could write `A[:index[0] :index[1] ` `:index[n]]`; is there some kind of list comprehension I could use like `A[:i for i in index]`? | You can slice multiple dimensions in one go: ````result = A[:2 :3] ```` that slices dimension one up to the index 2 and dimension two up to the index 3 If you have arbitary dimensions you can also create a `tuple` of slices: ````slicer = tuple(slice(0 i 1) for i in index) result = A[slicer] ```` A slice defines the `start`(0) `stop`(the index you specified) and `step`(1) - basically like a `range` but useable for indexing And the i-th entry of the tuple slices the i-th dimension of your array If you only specify `stop`-indices you can use the shorthand: ````slicer = tuple(slice(i) for i in index) ```` I would recommend the first option if you know the number of dimensions and the last one if you do not |
decorator __lt__ and others - why use these and how do they work? I stumpled into a problem of understanding the decorators Compared to the code below what is the use of the `__lt__(self number)` method compared to the `less_than(self number)` method? Is there any difference between the two methods and how they handle the arguments? ```` class Sort: def __init__(self number): self number = number def __lt__(self number): return self number < number def less_than(self number): return self number < number ```` | As Martijn Pieters said this has nothing to do with decorators ````s1 = Sort(1) s2 = Sort(2) if s1 < s2: print 'Yes' if s1 less_than(2): print 'Yes' ```` See the difference? In the first if you compare to objects of type Sort In the second if you invoke a method from instance s1 of type Sort |
How to input matrix (2D list) in python 3 4? I am new to python 3 4 and I usually use MATLAB/ GNU Octave for matrix calculation I know we can perform matrix calculation using numpy in python 2 x but numpy does not work for python 3 4 I tried to create this code to input an m by n matrix I intended to input [[1 2 3] [4 5 6]] but the code yields [[4 5 6] [4 5 6] Same things happen when I input other m by n matrix the code yields an m by n matrix whose rows are identical Perhaps you can help me to find what is wrong with my code ````m = int(input('number of rows m = ')) n = int(input('number of columns n = ')) matrix = []; columns = [] # initialize the number of rows for i in range(0 m): matrix = [0] # initialize the number of columns for j in range (0 n): columns = [0] # initialize the matrix for i in range (0 m): matrix[i] = columns for i in range (0 m): for j in range (0 n): print ('entry in row: ' i+1 ' column: ' j+1) matrix[i][j] = int(input()) print (matrix) ```` | The problem is on the initialization step ````for i in range (0 m): matrix[i] = columns ```` This code actually makes every row of your `matrix` refer to the same `columns` object If any item in any column changes - every other column will change: ````>>> for i in range (0 m): matrix[i] = columns >>> matrix [[0 0 0] [0 0 0]] >>> matrix[1][1] = 2 >>> matrix [[0 2 0] [0 2 0]] ```` You can initialize your matrix in a nested loop like this: ````matrix = [] for i in range(0 m): matrix append([]) for j in range(0 n): matrix[i] append(0) ```` or in a one-liner by using list comprehension: ````matrix = [[0 for j in range(n)] for i in range(m)] ```` or: ````matrix = [x[:] for x in [[0]*n]*m] ```` See also: - <a href="http://stackoverflow com/questions/2397141/how-to-initialize-a-two-dimensional-array-in-python">How to initialize a two-dimensional array in Python?</a> Hope that helps |
Python dictionary with base content I am looking for the "good pythonic" way to define a dictionary with base elements Let me explain: I have a serie of key:value that configure my system A group of key:value represent a configuration Each configuration <strong>must</strong> have several common base elements On the other hand each configuration has the possibility to define extra elements I could use python dictionaries but I do not think that could enforce the user to define "Mandatory_Elt_1" & "Mandatory_Elt_2" (or is it?): ````Config_1 = { 'Mandatory_Elt_1':1 'Mandatory_Elt_2':2 'Optional_Elt_3':3 } Config_2 = { 'Mandatory_Elt_1':5 'Mandatory_Elt_2':6 'Optional_Elt_4':7 } ```` A second option would be to subclass dict and define a specific constructor method where I would require the mandatory elements: ````Config = MyDict( { 'Mandatory_Elt_1':5 'Mandatory_Elt_2':6 'Optional_Elt_4':7 } ) ```` A third possibility would be to review the "input interface" such that other coders would not directly touch the base data Instead they would need to pass through a sanitization API Or should I move to a databse based system altogether? Are there any other alternatives? What would be the "lowest friction" way to force some elements to be defined in a dictionary? | If you need some mandatory elements in final dictionary you may use a basic dictionary and then update it with the user's dictionary E g ````base_config = {'m1':1 'm2': 2} user_config = {'m1':3 'new_param':4} base_config update(user_config) final_config = base_config >>> print final_config {'new_param': 4 'm1': 3 'm2': 2} ```` |
What company did Universal-International buy a major stake in during 1946? | null |
Filter a PCAP file from packet ISO/OSI layer I need to split a PCAP file in two different files: the first one should include all (and only) the packets directed to the application layer of the ISO/OSI model while the second one includes all the other ones I am using Scapy to apply the filter: ````pkts = PcapReader(infile) applayerpkts = (pkt for pkt in pkts if pkt haslayer(Raw)) lowlayerspkts = (pkt for pkt in pkts if not pkt haslayer(Raw)) wrpcap(applayerfilename applayerpkts) wrpcap(lowlayersfilename lowlayerspkts) ```` using `pkt haslayer(Raw)` method since that layer should be included only on packets directed to the application layer What is the problem? I have noticed that the sum of `applayerfilename` `lowlayersfilename` (in file size) is different (lower) from the file size of `infile` The reported method is also computationally expensive (and I have got a list of PCAP of ~1 5GB each one) since `infile` is parsed twice I would prefer to apply a different filter parsing one time the input PCAP I could use the `PcapReader` class and manually parsing the PCAP but I do not know how to generate a PCAP to pass to the `wrpcap( )` method Edit: I have also tried with this solution: ````pkts = PcapReader(infile) app_pkts = [] low_pkts = [] for p in pkts: if p haslayer(Raw): app_pkts append(p) else: low_pkts append(p) wrpcap(applayerfilename app_pkts) wrpcap(lowlayersfilename low_pkts) ```` but it does not work since it consumes too much memory because of the size of my input PCAP Does an `append_to_pcap(filename packet)` like function exists (`wrpcap( )` function does not work as an append)? | I have (at least apparently) solved in this way: ````pkts = PcapReader(infile) app_writer = PcapWriter(applayerfilename append=True) low_writer = PcapWriter(lowlayersfilename append=True) for p in pkts: if p haslayer(Raw): app_writer write(p) else: low_writer write(p) app_writer close() low_writer close() ```` |
How do I get the size of an RstDocument in Kivy? This feels like a dumb question but I have crawled the internet for the past few days to no avail over something that seems really simple Anyways what I am trying to do is have a TreeView widget that has RstDocument leaves Now when I do this I get a bunch of leaves that have smaller windows in a similar fashion to this individual: <a href="http://stackoverflow com/questions/36523492/kivy-making-a-custom-treeviewnode">Kivy Making a Custom TreeViewNode</a> Their solution does not work for me because the RstDocument object does not have a texture object associated with it Upon further research it does not seem to have any attribute associated with this size in pixels for that matter and neither does the ScrollView layout that it inherits from Trying to find such numbers gives me stuff that gives sizes that are 100px which is not what is being displayed Ideally I am trying to get it so that the RstDocument displays completely when extended so the end-user scrolls through the tree collapsing what they do not need I do not need the RstDocument to scroll as a ScrollView is already on the TreeView Widget The code as close as legally possible: ````from kivy app import App from kivy uix treeview import TreeView from kivy uix treeview import TreeViewLabel from kivy uix treeview import TreeViewNode from kivy uix scrollview import ScrollView from kivy uix rst import RstDocument class TreeViewRst (RstDocument TreeViewNode): pass class TreeApp (App): def build (self): root = StackLayout() scroll = ScrollView(pos = (0 0) size_hint=(1 0 78)) body = TreeView(hide_root=True indent_level=0 size_hint=(1 None)) body bind(minimum_height=body setter('height')) intro = body add_node(TreeViewLabel(text="Title" font_size=18)) intro_diag = body add_node(TreeViewLabel(text="Article")) body add_node(TreeViewRst(source='lopsem rst' size=(100 100)) parent=intro_diag) scroll add_widget(body) root add_widget(scroll) return root Window size = (360 640) tree = TreeApp() tree run() ```` And a pic of the result: <a href="http://i stack imgur com/dQVil png" rel="nofollow"><img src="http://i stack imgur com/dQVil png" alt="enter image description here"></a> | Nevermind I found the solution to my question I will post it here for reference to someone else having the same or similar issue The problem I had when I was trying to get a size out of the RstDocument Object was the fact that at the time the node was still collapsed and the object's height was 0 as a result When open the viewport attribute inherited from the ScrollView had the size of the document in pixels before the scroll It was not 100% as the height when initially opened was larger than it actually was which is corrected when clicked on or if scrolling was attempted (so I suspect the object does not know until these events occur where a calculation is performed to determine that) Here is what I did: ````from kivy app import App from kivy uix treeview import TreeView from kivy uix treeview import TreeViewLabel from kivy uix treeview import TreeViewNode from kivy uix scrollview import ScrollView from kivy uix rst import RstDocument from kivy core window import Window from kivy uix stacklayout import StackLayout class TreeViewRst (RstDocument TreeViewNode): pass def update_size (event1 event2): event1 size = event1 viewport_size class TreeApp (App): def build (self): root = StackLayout() scroll = ScrollView(pos = (0 0) size_hint=(1 0 78)) body = TreeView(hide_root=True indent_level=0 size_hint=(1 None)) body bind(minimum_height=body setter('height')) intro = body add_node(TreeViewLabel(text="Title" font_size=18)) intro_diag = body add_node(TreeViewLabel(text="Article")) test = body add_node(TreeViewRst(source='lopsem rst' size=(100 400)) parent=intro_diag) test bind(on_scroll_start=update_size) scroll add_widget(body) root add_widget(scroll) return root Window size = (360 640) tree = TreeApp() tree run() ```` The result was all I could hope for: <a href="http://i stack imgur com/WJCFc png" rel="nofollow">Here it is!!!</a> I just want to thank IceMAN for the edit from the other day Also thanks all for this site This is my first time posting a question but it is been instrumental in answering many questions that I have had in the past |
Python equivalent to java io File I am writing script to automate system administration tasks on my Linux system This involves compressing moving deleting renaming and searching a lot of files I learned doing these in Python by looking up examples on Internet and here on Stackoverflow The typical approach is to create a command string and pass it to the OS to have it executed ````print Popen("cat /home/kshitiz/myfile" stdout=PIPE) stdout read() ```` The directory paths are handled as strings Now consider following example: We have a program that asks user for a dir and a file and creates a path If a user enters `/home/kshitiz` and `myfile` the path becomes `/home/kshitizmyfile` In Python I must do jugglery with strings to deal with this In Java I can simply do: `new File(parentDir filename)` Since Python is supposed to be better at OS administration it surprises me that it does not have object oriented abstractions over the file system <strong>What are the other approaches in Python to deal with the file system?</strong> | You are looking for the <a href="http://docs python org/2/library/os path html" rel="nofollow">`os path` module</a>: ````path = os path join(parentDir filename) ```` |
Python - nested for loops and index out of range I am rather new to Python and am running into the following error when using a nested for loop ````IndexError: list index out of range ```` Here is my code ````count = 0 count2 = 1 rlength = range(len(records)) for i in rlength: ex = records[count] id for bla in rlength: if re search(ex records[count2] id) != None: print records[count2] id count2 = 1 count = 1 count2 = count 1 ```` Edit: Fixed with the following code ````rlength = range(len(records)) for i in rlength: ex = records[i] id for bla in rlength: if bla 1 < len(rlength) and re search(ex records[bla 1] id) != None: print records[bla] id ```` | The loop should fail for `i=1` Why ? When `i=1 count2 = 2 (= count 1 and count = 0+1 = 1)` In the inner loop `count2 goes from 2 to 2+len(records)-1-1` (since we increment after looking at the values) = `len(records)` But there is no `records[len(records)]` (and an index out of bound is NOT equivalent to None in python !) |
Interact with other programs using Python I am having the idea of writing a program using Python which shall find a lyric of a song whose name I provided I think the whole process should boil down to couple of things below These are what I want the program to do when I run it: - prompt me to enter a name of a song - copy that name - open a web browser (google chrome for example) - paste that name in the address bar and find information about the song - open a page that contains the lyrics - copy that lyrics - run a text editor (like Microsoft Word for instance) - paste the lyrics - save the new text file with the name of the song I am not asking for code of course I just want to know the concepts or ideas about how to use python to interact with other programs To be more specific I think I want to know fox example just how we point out where is the address bar in Google Chrome and tell python to paste the name there Or how we tell python how to copy the lyrics as well as paste it into the Microsof Word's sheet then save it I have been reading (I am still reading) several books on Python: Byte of python Learn python the hard way Python for dummies Beginning Game Development with Python and Pygame However I found out that it seems like I only (or almost only) learn to creat programs that work on itself (I cannot tell my program to do things I want with other programs that are already installed on my computer) I know that my question somehow sounds rather silly but I really want to know how it works the way we tell Python to regconize that this part of the Google chrome browser is the address bar and that it should paste the name of the song in it The whole idea of making python interact with another program is really really vague to me and I just extremely want to grasp that Thank you everyone whoever spend their time reading my so-long question ttriet204 | You should look into a package called `selenium` for interacting with web browsers |
Pass a variable to extract from JSON String in Python? I have below JSON String Now I want to extract each individual field from that JSON string So I decided to create a method parse_json which will accept a variable that I want to extract from the JSON String Below is my python script - ````#!/usr/bin/python import json jsonData = '{"pp": [0 3 5 7 9] "sp": [1 2 4 6 8]}' def parse_json(data): jj = json loads(jsonData) return jj['+data+'] print parse_json('pp') ```` Now whenever I an passing `pp` to `parse_json` method to extract its value from the JSON String I always get the error as - ````return jj['+data+'] KeyError: '+data+' ```` Any idea how to fix this issue? As I need to pass the variable which I am supposed to extract from the JSON String? | You probably just want this: ```` return jj[data] ```` Your code is trying to look up a key named literally `'+data+'` when instead what you want to do is look up the key with a name of the function's parameter |
What does ETU-R stand for? | null |
Wrong scikit-learn version installed? I encountered the same `ValueError: scoring must return a number got [ ] (<class 'numpy core memmap memmap'>) instead ` error as discussed in <a href="http://stackoverflow com/q/34857870/1257318">Q34857870</a> Based on answers to this question and my own research I believe this issue to be fixed in `scikit-learn` version 0 17 1 though I am still encountering it Then I noticed something strange `conda` lists the right version ` $ conda list scikit-learn packages in environment: scikit-learn 0 17 1 np111py27_0 ` My Jupyter notebook gives the right version: ` %load_ext watermark %watermark scikit-learn scikit-learn 0 17 1 ` But I get a different version when I check the version within my code: ` import sklearn print(sklearn __version__) 0 17 ` I would not think anything of this except I am still seeing a bug in 0 17 that should have been fixed in 0 17 1 so I am wondering whether I am using the wrong version somehow I am wondering if it is somehow connected to <a href="http://stackoverflow com/questions/30666685/scikit-learn-version-ambiguity">Q30666685</a> | You probably have multiple versions of scikit learn installed You can see where it is installed by using ````print(sklearn __file__) ```` and then simply delete that In case if you are still having version troubles work within a virtual environment |
Python double pointer I am trying to get the values from a pointer to a float array but it returns as c_void_p in python The C code ````double v; const void *data; pa_stream_peek(s &data &length); v = ((const float*) data)[length / sizeof(float) -1]; ```` Python so far ````import ctypes null_ptr = ctypes c_void_p() pa_stream_peek(stream null_ptr ctypes c_ulong(length)) ```` The issue being the null_ptr has an int value (memory address?) but there is no way to read the array?! | My ctypes is rusty but I believe you want POINTER(c_float) instead of c_void_p So try this: ````null_ptr = POINTER(c_float)() pa_stream_peek(stream null_ptr ctypes c_ulong(length)) null_ptr[0] null_ptr[5] # etc ```` |
In which year did a Premier League team consider relocating to Ireland? | 1998 |
Why is "if not (a and b)" faster than "if not a or not b"? On a whim I recently tested these two methods with `timeit` to see which evaluation method was faster: ````import timeit """Test method returns True if either argument is falsey else False """ def and_chk((a b)): if not (a and b): return True return False def not_or_chk((a b)): if not a or not b: return True return False ```` and got these results: ```` VALUES FOR a b > 0 0 0 1 1 0 1 1 method and_chk(a b) 0 95559 0 98646 0 95138 0 98788 not_or_chk(a b) 0 96804 1 07323 0 96015 1 05874 seconds per 1 111 111 cycles ```` The difference in efficiency is between one and nine percent always in favour of `if not (a and b)` which is the opposite of what I might expect since I understand that `if not a or not b` will evaluate its terms (`if not a` and then `if not b`) in order running the `if` block once it encounters a true expression (and there are no `and` clauses) In contrast the `and_chk` method needs to evaluate <them>both</them> clauses before it can return any result to the `if not ` that wraps it The timing results however disprove this understanding How then is the `if` condition being evaluated? I am perfectly aware of the fact that this degree of microoptimization is practically if not completely pointless I just want to understand how Python is going about it <hr> For completion's sake this is how I set up `timeit` ````cyc = 1111111 bothFalse_and = iter([(0 0)] * cyc) zeroTrue_and = iter([(1 0)] * cyc) oneTrue_and = iter([(0 1)] * cyc) bothTrue_and = iter([(1 1)] * cyc) bothFalse_notor = iter([(0 0)] * cyc) zeroTrue_notor = iter([(1 0)] * cyc) oneTrue_notor = iter([(0 1)] * cyc) bothTrue_notor = iter([(1 1)] * cyc) time_bothFalse_and = timeit Timer('and_chk(next(tups))' 'from __main__ import bothFalse_and as tups and_chk') time_zeroTrue_and = timeit Timer('and_chk(next(tups))' 'from __main__ import zeroTrue_and as tups and_chk') time_oneTrue_and = timeit Timer('and_chk(next(tups))' 'from __main__ import oneTrue_and as tups and_chk') time_bothTrue_and = timeit Timer('and_chk(next(tups))' 'from __main__ import bothTrue_and as tups and_chk') time_bothFalse_notor = timeit Timer('not_or_chk(next(tups))' 'from __main__ import bothFalse_notor as tups not_or_chk') time_zeroTrue_notor = timeit Timer('not_or_chk(next(tups))' 'from __main__ import zeroTrue_notor as tups not_or_chk') time_oneTrue_notor = timeit Timer('not_or_chk(next(tups))' 'from __main__ import oneTrue_notor as tups not_or_chk') time_bothTrue_notor = timeit Timer('not_or_chk(next(tups))' 'from __main__ import bothTrue_notor as tups not_or_chk') ```` then ran each `timeit Timer( )` function with ` timeit(cyc)` to get the results posted | <h2>TL;DR</h2> The `not_or_chk` function requires two unary operations in <them>addition</them> to two jumps (in the worst case) while the `and_chk` function only has the two jumps (again in the worst case) <h2>Details</h2> The <a href="https://docs python org/2/library/dis html">dis module</a> to the rescue! The `dis` module let us you take a look at the Python bytecode disassembly of your code For example: ````import dis """Test method returns True if either argument is falsey else False """ def and_chk((a b)): if not (a and b): return True return False def not_or_chk((a b)): if not a or not b: return True return False print("And Check:\n") print(dis dis(and_chk)) print("Or Check:\n") print(dis dis(not_or_chk)) ```` Produces this output: <pre class="lang-none prettyprint-override">`And Check: 5 0 LOAD_FAST 0 ( 0) 3 UNPACK_SEQUENCE 2 6 STORE_FAST 1 (a) 9 STORE_FAST 2 (b) 6 12 LOAD_FAST 1 (a) * This block is the * 15 JUMP_IF_FALSE_OR_POP 21 * disassembly of * 18 LOAD_FAST 2 (b) * the "and_chk" * >> 21 POP_JUMP_IF_TRUE 28 * function * 7 24 LOAD_GLOBAL 0 (True) 27 RETURN_VALUE 8 >> 28 LOAD_GLOBAL 1 (False) 31 RETURN_VALUE None Or Check: 10 0 LOAD_FAST 0 ( 0) 3 UNPACK_SEQUENCE 2 6 STORE_FAST 1 (a) 9 STORE_FAST 2 (b) 11 12 LOAD_FAST 1 (a) * This block is the * 15 UNARY_NOT * disassembly of * 16 POP_JUMP_IF_TRUE 26 * the "not_or_chk" * 19 LOAD_FAST 2 (b) * function * 22 UNARY_NOT 23 POP_JUMP_IF_FALSE 30 12 >> 26 LOAD_GLOBAL 0 (True) 29 RETURN_VALUE 13 >> 30 LOAD_GLOBAL 1 (False) 33 RETURN_VALUE None ```` Take a look at the two blocks of Python bytecode that I have marked with the asterisks Those blocks are your two disassembled functions Note that `and_chk` only has two jumps and the calculations in the function are made <them>while deciding whether or not to take the jump</them> On the other hand the `not_or_chk`function requires the `not` operation to be carried out twice in the worst case <them>in addition</them> to the interpreter deciding whether or not to take the jump |
scipy optimize linprog unable to find a feasible starting point despite a feasible answer clearly exists the vector k seems to satisfy all constraints Is there something I am missing here? Thanks ````import numpy as np from scipy optimize import linprog A_ub=[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 1 -1 0 0 1 -1 0 0 1 -1 0 0 1 -1 0 0 1 -1 0 0 1 -1 0 0 1 -1 0 0 1 -1] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 -1 1 0 0 -1 1 0 0 -1 1 0 0 -1 1 0 0 -1 1 0 0 -1 1 0 0 -1 1 0 0 -1 1]] b_ub=[ 10000 100 10000 1840 10000 4000 10000 100 10000 5000 10000 5450 10000 3000 10000 3000 10000 1000 40000 5000 5000 ] A_eq=[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 -5000 0 13390 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 -1840 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 5000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [13290 0 0 0 -13390 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 -1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 1 -1 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 -5450 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 1 -1 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 1 0 -1 0 1 0 -1 0 1 0 1 0 1 0 -1 0 1 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 1 -1 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1 1 -1] [-13290 0 5000 0 0 0 1840 0 5450 0 -1 0 -1 0 -1 0 -1 0 -1 0 -1 0 -1 0 0 0 -1 0 -1 0 0 0 -1 0 -1 0 0 0 0 0 1 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1]] b_eq=[8390 0 0 -1840 0 0 5000 0 0 -100 0 0 0 0 0 -5450 0 0 0 0 0 0 0 0 -1000 0 0] c=[-1351 6146468256165 -99 629272305631787 -542 0389808700279 -0 0 54 302887927385768 -0 043903442258601377 -0 10170162880553937 -0 043903442258601377 -0 043903442258601377 -0 043903442258601377 -0 11764394156352764 -0 043903442258601377 -0 056182133775492554 -0 043903442258601377 -0 043903442258601377 -0 033174575907634424 -0 081074546005202835 -0 043903442258601377 -0 057503980336247616 -0 040480879825992883 -0 046889515046147204 -0 10170162880553937 0 02 0 02 0 0 0 02 0 02 0 0 0 02 0 02 0 0 0 02 0 02 0 0 0 02 0 02 0 0 0 02 0 02 0 0 0 02 0 02 0 0 0 02 0 02 0 0 0 02 0 02 0 0] k=[1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8390 0 0 0 0 0 1840 0 0 0 5000 0 0 0 0 0 100 0 0 0 0 0 0 0 0 0 0 5450 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1000 0] print(all(np dot(A_ub k)<=b_ub)) print(all(np dot(A_eq k)==b_eq)) print(all(map(lambda x :x>=0 k))) linprog(c A_ub b_ub A_eq b_eq) ```` | This answer does not explain <them>why</them> it works I hope someone more familiar with the `linprog` code or with linear programming in general can give a more thorough answer <hr> I get a solution if I use the option `bland=True` (see <a href="http://docs scipy org/doc/scipy/reference/generated/scipy optimize show_options html" rel="nofollow">`show_options`</a> for documentation--scroll to the bottom for the `linprog` options): ````In [130]: linprog(c A_ub b_ub A_eq b_eq options=dict(bland=True)) Out[130]: status: 0 slack: array([ 3610 6490 11840 0 0 14000 10100 0 10000 5000 15450 0 13000 0 10000 3000 11000 0 12220 0 10000 ]) success: True fun: -2683 6935269049131 x: array([ 1 22573363e+00 2 00000000e+00 1 22404780e+00 3 71739130e+00 8 25688073e-02 2 00000000e+03 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 5 00000000e+03 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 2 00000000e+03 6 39000000e+03 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 1 84000000e+03 5 00000000e+03 0 00000000e+00 1 00000000e+04 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 1 00000000e+02 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 -1 11022302e-12 0 00000000e+00 5 45000000e+03 0 00000000e+00 3 00000000e+03 0 00000000e+00 3 00000000e+03 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 1 00000000e+03]) message: 'Optimization terminated successfully ' nit: 50 ```` One component is slightly negative (-1 11e-12) Presumably this is within the default tolerance That can be cleaned up by lowering the tolerance (but note the change in `x[19]`): ````In [131]: linprog(c A_ub b_ub A_eq b_eq options=dict(bland=True tol=1e-15)) Out[131]: status: 0 slack: array([ 3610 6490 11840 0 0 14000 10100 0 10000 5000 15450 0 13000 0 10000 3000 11000 0 12220 0 10000 ]) success: True fun: -2683 693526904935 x: array([ 1 22573363e+00 2 00000000e+00 0 00000000e+00 3 71739130e+00 8 25688073e-02 2 00000000e+03 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 5 00000000e+03 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 1 63900000e+04 0 00000000e+00 0 00000000e+00 0 00000000e+00 2 00000000e+03 6 39000000e+03 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 1 84000000e+03 5 00000000e+03 0 00000000e+00 1 00000000e+04 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 1 00000000e+02 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 5 45000000e+03 0 00000000e+00 3 00000000e+03 0 00000000e+00 3 00000000e+03 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 0 00000000e+00 1 00000000e+03]) message: 'Optimization terminated successfully ' nit: 51 ```` |
Python MySQLdb prevent SQL injection - not working as expected I am trying to query a MySQL database in a secure way avoiding SQL injection I am getting an error when trying to execute the SQL in the DB cursor My code looks like this: ````reseller_list = ('138' ) for reseller in reseller_list: cur1 = db cursor() dbQuery = """ SELECT TRIM(CONCAT(TRIM(c1 first_name) ' ' TRIM(c1 name))) AS 'User name' FORMAT(sum(cost1) 2) AS 'cost1' FORMAT(sum(cost2) 2) AS 'cost2' FROM client as c1 client as c2 WHERE c2 id = %s AND start BETWEEN DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH '%Y-%m-01 00:00:00') AND DATE_FORMAT(LAST_DAY(CURRENT_DATE - INTERVAL 1 MONTH) '%Y-%m-%d 23:59:59') GROUP BY c1 name ORDER BY CONCAT(c1 first_name ' ' c1 name); """ cur1 execute(dbQuery (reseller_id )) ```` And what happens is this: ```` cur1 execute(dbQuery (reseller_id )) File "/usr/lib64/python2 7/site-packages/MySQLdb/cursors py" line 159 in execute query = query % db literal(args) TypeError: not enough arguments for format string ```` I have read a number of pages both on this site and others but cannot see what I am doing wrong I can easily do this using string substitution into the query but want to do it the right way! | You have % signs in your date_format calls so you will need to escape them from the param substitution by doubling them ````WHERE c2 id = %s AND start BETWEEN DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH '%%Y-%%m-01 00:00:00') AND DATE_FORMAT(LAST_DAY(CURRENT_DATE - INTERVAL 1 MONTH) '%%Y-%%m-%%d 23:59:59') ```` |
Division of a list to two sublists based on regex I have a list of the format `l = ["1" "2" "3*" "5" "9*" "10*"]` What is the best way to divide this list to two sublists based on regex ` *\*`? The resulting sublists should look as follows: ````sub1 = ["1" "2" "5"] sub2 = ["3*" "9*" "10*"] ```` | You could just split the string on commas into an array then just separate the array You did not tag a language but in java the string split(" ") would give you an array of strings Then loop over those strings and put the elements into two different lists or reformat the string |
When did the major military operation end? | 25 October 1922 |
Python dataframe sum rows If I have a dataframe with `n` rows is there a way to set the ith row to be sum of `row[i]` and `row[i-1]` and do this so that the assignment to earlier rows is reflected in the latter rows? I would really like to avoid loops if possible Example DF: ```` SPY AAPL GOOG 2011-01-10 0 44 -0 81 1 80 2011-01-11 0 00 0 00 0 00 2011-01-12 -1 11 -2 77 -0 86 2011-01-13 -0 91 -4 02 -0 68 ```` Sample pseudo code of summing two rows: ````DF[2011-01-11] = DF[2011-01-10] DF[2011-01-11] DF[2011-01-12] = DF[2011-01-11] DF[2011-01-12] ```` and so on | based on your question you are looking for a cumulative sum of each columns you could use the `cumsum()` method ````DF cumsum() SPY AAPL GOOG 2011-01-10 0 4400 -0 8100 1 8000 2011-01-11 0 4400 -0 8100 1 8000 2011-01-12 -0 6700 -3 5800 0 9400 2011-01-13 -1 5800 -7 6000 0 2600 ```` |
what is being passed to scrapy DownloaderStats middleware? I am trying to alter Scrapy's stats middleware Here is Scrapy's stats py in full: ````from scrapy exceptions import NotConfigured from scrapy utils request import request_httprepr from scrapy utils response import response_httprepr class DownloaderStats(object): def __init__(self stats): self stats = stats @classmethod def from_crawler(cls crawler): if not crawler settings getbool('DOWNLOADER_STATS'): raise NotConfigured return cls(crawler stats) def process_request(self request spider): self stats inc_value('downloader/request_count' spider=spider) self stats inc_value('downloader/request_method_count/%s' % request method spider=spider) reqlen = len(request_httprepr(request)) self stats inc_value('downloader/request_bytes' reqlen spider=spider) def process_response(self request response spider): self stats inc_value('downloader/response_count' spider=spider) self stats inc_value('downloader/response_status_count/%s' % response status spider=spider) reslen = len(response_httprepr(response)) self stats inc_value('downloader/response_bytes' reslen spider=spider) return response def process_exception(self request exception spider): ex_class = "%s %s" % (exception __class__ __module__ exception __class__ __name__) self stats inc_value('downloader/exception_count' spider=spider) self stats inc_value('downloader/exception_type_count/%s' % ex_class spider=spider) ```` In the `from_crawler` classmethod what is it exactly that is getting passed in? | First of all `DownloaderStats(object)` does not mean that DownloaderStats is being passed an object it means that the DownloaderStats class extends the `object` class In your class method `cls` is the class being called in this case `DownloaderStats` So the code `cls(crawler stats)` could be thought of as `DownloaderStats(crawler stats)` which instantiates an object of the class DownloaderStats Instantiating objects in Python because their <strong>init</strong> method to be called so the value of `crawler stats` gets assigned to the `stats` parameter of the `__init__` method which then gets assigned to `self stats` |
Alternative to exec I am currently trying to code a Python (3 4 4) GUI with tkinter which should allow to fit an arbitrary function to some datapoints To start easy I would like to create some input-function and evaluate it Later I would like to plot and fit it using `curve_fit` from `scipy` In order to do so I would like to create a dynamic (fitting) function from a user-input-string I found and read about `exec` but people say that (1) it is not safe to use and (2) there is always a better alternative (e g <a href="http://stackoverflow com/questions/33409207/how-to-return-value-from-exec-in-functionand">here</a> and in many other places) So I was wondering what would be the alternative in this case? Here is some example code with two nested functions which works but it is not dynamic: ````def buttonfit_press(): def f(x): return x+1 return f print(buttonfit_press()(4)) ```` And here is some code that gives rise to `NameError: name 'f' is not defined` before I can even start to use xval: ````def buttonfit_press2(xval): actfitfunc = "f(x)=x+1" execstr = "def {}:\n return {}\n" format(actfitfunc split("=")[0] actfitfunc split("=")[1]) exec(execstr) return f print(buttonfit_press2(4)) ```` An alternative approach with `types FunctionType` discussed here (<a href="http://stackoverflow com/questions/10303248/true-dynamic-and-anonymous-functions-possible-in-python">10303248</a>) was not successful either So my question is: Is there a good alternative I could use for this scenario? Or if not how can I make the code with `exec` run? I hope it is understandable and not too vague Thanks in advance for your ideas and input <hr> @Gábor ErdÅs: Either I do not understand or I disagree If I code the same segment in the mainloop it recognizes `f` and I can execute the code segment from `execstr`: ````actfitfunc = "f(x)=x+1" execstr = "def {}:\n return {}\n" format(actfitfunc split("=")[0] actfitfunc split("=")[1]) exec(execstr) print(f(4)) >>> 5 ```` <hr> @Åukasz Rogalski: Printing `execstr` seems fine to me: ````def f(x): return x+1 ```` Indentation error is unlikely due to my editor but I double-checked - it is fine Introducing `my_locals` calling it in `exec` and printing in afterwards shows: ````{'f': <function f at 0x000000000348D8C8>} ```` However I still get `NameError: name 'f' is not defined` <hr> @user3691475: Your example is very similar to my first example But this is not "dynamic" in my understanding i e one can not change the output of the function while the code is running <hr> @Dunes: I think this is going in the right direction thanks However I do not understand yet how I can evaluate and use this function in the next step? What I mean is: in order to be able to fit it I have to extract fitting variables (i e `a` in `f(x)=a*x+b`) or evaluate the function at various x-values (i e `print(f(3 14))`) | I am not sure what exactly are you trying to do i e what functions are allowed what operations are permitted etc Here is an example of a function generator with one dynamic parameter: ````>>> def generator(n): def f(x): return x+n return f >>> plus_one=generator(1) >>> print(plus_one(4)) 5 ```` |
wx ProgressDialog py2exe leads to application crash This simple code runs very well : ````import wx app = wx App(0) frame = wx Frame(None) test = wx ProgressDialog('Test' 'Test' maximum = 20 parent = frame style = wx PD_CAN_ABORT) app MainLoop() ```` However when compiling/packing it into an executable with `py2exe` ````from distutils core import setup import py2exe setup(script_args = ['py2exe'] windows=[{'script':'progressdlgprobblem py'}] options = {'py2exe': {'compressed':1 'bundle_files': 1}} zipfile = None) ```` then the ` exe` file crashes <strong>What could be the because of this crash? Does `wx ProgressDialog` require some specific additional elements in order to be used with `py2exe`?</strong> <hr> <them>Addendum 1</them> : when I remove the `style = wx PD_CAN_ABORT` there is no more crash How can the crash come from the `style` ? But then the <them>styling</them> is XP-style when launching from the ` exe` : <img src="http://i stack imgur com/xXEo5 jpg" alt="enter image description here"> and different to the styling I get when launching from the ` py` (without py2exe) : <img src="http://i stack imgur com/Rvpvq jpg" alt="enter image description here"> <hr> <them>Addendum 2</them> : when I remove the `'bundle_files': 1` no more crash But I would like to keep this bundling into one file only ! <strong>How can this bundling into a single exe file be the because of this crash ?</strong> <them>Addendum 3</them> : A big part of the problem is solved by using wx Python 3 0 1 0b instead of 3 0 0 0 (more details soon) | Had issues with the `ProgressDialog` example and added progress and cleanup but is otherwise unchanged ````# -*- coding: utf-8 -*- import wx app = wx App(0) frame = wx Frame(None) max_count = 8 dlg = wx ProgressDialog('Test caption' 'Test text' maximum = max_count parent = frame style = wx PD_CAN_ABORT) keepGoing = True # progress routine from wxPython demo count = 0 while keepGoing and count < max_count: count = 1 wx MilliSleep(125) wx Yield() (keepGoing skip) = dlg Update(count 'progress: {0} %' format(count * 100 0/max_count)) dlg Destroy() # proper cleanup otherwise process has to be killed frame Destroy() app MainLoop() ```` Freezing with `py2exe` is a pain in the ass but delivers IMHO still nice result for the Windows platform Much of the settings is try-and-error In the <a href="http://wiki wxpython org/Py2exe%20with%20Python2 6" rel="nofollow">wxPython wiki</a> there is a good description/explanation how to manage the SxS assembly and the manifest ````# -*- coding: utf-8 -*- """manifest fixes NT-theming and including MSVC runtime issue""" """ # Recipe from http://wiki wxpython org/Py2exe%20with%20Python2 6 """ manifest = """ <?xml version="1 0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm v1" manifestVersion="1 0"> <assemblyIdentity version="5 0 0 0" processorArchitecture="x86" name="%(prog)s" type="win32" /> <description>%(prog)s</description> <trustInfo xmlns="urn:schemas-microsoft-com:asm v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"> </requestedExecutionLevel> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft VC90 CRT" version="9 0 21022 8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"> </assemblyIdentity> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft Windows Common-Controls" version="6 0 0 0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> </assembly> """ from distutils core import setup import py2exe dll_excludes = [ 'w9xpopen exe' 'MSVCP90 dll' # reason see link to wxPython-wiki above ] setup(script_args = ['py2exe'] windows=[{'script':'progressdlg py' # "other_resources": [(24 1 manifest)]}] # manifest added options = {'py2exe': {'compressed':1 'bundle_files': 1 'dll_excludes': dll_excludes }} zipfile = None) ```` At least on my machine (WinXP 7 wxPython 2 9 5 0) this setup (`python setup py py2exe`) produces: - A single ` EXE` - Correct theming also when frozen - No crashes full usability use style flags you like The example will at least work on your machine (where the `MSCV` runtimes are installed already) For a more complete list of excludes see the parallel thread in [wxPython-users]`https://groups google com/forum/#!topic/wxpython-users/vrd-0cpiH1E` The <a href="https://github com/cloudmatrix/esky" rel="nofollow">`esky`</a> library has fixes for this quirks already included and offers live-updating for `wx`-Apps but you may or may not like the different project structure it is setting up Side Note: I was not able to reproduce your crash on wxPython 2 9 5 0 (even without the assembly) I had crashes on XP when freezing with 3 0 0 0 on a Win8 machine but this should be solved in 3 0 1 according to Robin (see `https://groups google com/forum/#!topic/wxpython-users/8OeBfxTC9Xo`) Side note 2: This seems to be a problem with wxPython 3 0 0 0 (classic) At my XP machine this examples crashes even if not frozen If upgrading to <a href="http://wxpython org/Phoenix/snapshot-builds/wxPython_Phoenix-3 0 1 dev75864-py2 7-win32 egg" rel="nofollow">wxPython 3 0 1 (phoenix)</a> then it works again (both unfrozen and py2exe'd) The frozen single-file `EXE` runs without issues on Windows8 64 bit and WinXP with correct theme |
pandas DataFrame to_sql() function if_exists parameter not working When I try to pass the `if_exists='replace'` parameter to `to_sql` I get a programming error telling me the table already exists: ````>>> foobar to_sql('foobar' engine if_exists=you'replace') ProgrammingError: (ProgrammingError) ('42S01' "[42S01] [Microsoft][ODBC SQL Server Driver][SQL Server]There is already an object named 'foobar' in the database (2714) (SQLExecDirectW)") you'\nCREATE TABLE foobar ```` From the docs it sounds like this option should drop the table and recreate it which is not the observed behavior Works fine if the table does not exist already Any ideas if this is a bug or I am doing something wrong? I am using pandas 0 14 and sqlalchemy 0 8 3 and the enthought canopy python distro and I am connecting to SQL Server <strong>EDIT</strong> As per joris' comments: ````>>>pd __version__ Out[4]: '0 14 0' >>>pd io sql has_table('foobar' engine) Out[7]: False >>>foobar to_sql('foobar' engine if_exists=you'replace' index=False) --------------------------------------------------------------------------- ProgrammingError Traceback (most recent call last) <ipython-input-9-2f4ac7ed7f23> in <module>() ---> 1 foobar to_sql('foobar' engine if_exists=you'replace' index=False) C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\generic pyc in to_sql(self name con flavor if_exists index index_label) 948 sql to_sql( 949 self name con flavor=flavor if_exists=if_exists index=index -> 950 index_label=index_label) 951 952 def to_pickle(self path): C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\io\sql pyc in to_sql(frame name con flavor if_exists index index_label) 438 439 pandas_sql to_sql(frame name if_exists=if_exists index=index -> 440 index_label=index_label) 441 442 C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\io\sql pyc in to_sql(self frame name if_exists index index_label) 812 table = PandasSQLTable( 813 name self frame=frame index=index if_exists=if_exists -> 814 index_label=index_label) 815 table insert() 816 C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\io\sql pyc in __init__(self name pandas_sql_engine frame index if_exists prefix index_label) 530 else: 531 self table = self _create_table_statement() -> 532 self create() 533 else: 534 # no data provided read-only mode C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\io\sql pyc in create(self) 546 547 def create(self): -> 548 self table create() 549 550 def insert_statement(self): C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\schema pyc in create(self bind checkfirst) 614 bind _run_visitor(ddl SchemaGenerator 615 self -> 616 checkfirst=checkfirst) 617 618 def drop(self bind=None checkfirst=False): C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\engine\base pyc in _run_visitor(self visitorcallable element connection **kwargs) 1477 connection=None **kwargs): 1478 with self _optional_conn_ctx_manager(connection) as conn: > 1479 conn _run_visitor(visitorcallable element **kwargs) 1480 1481 class _trans_ctx(object): C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\engine\base pyc in _run_visitor(self visitorcallable element **kwargs) 1120 def _run_visitor(self visitorcallable element **kwargs): 1121 visitorcallable(self dialect self > 1122 **kwargs) traverse_single(element) 1123 1124 C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\sql\visitors pyc in traverse_single(self obj **kw) 120 meth = getattr(v "visit_%s" % obj __visit_name__ None) 121 if meth: -> 122 return meth(obj **kw) 123 124 def iterate(self obj): C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\engine\ddl pyc in visit_table(self table create_ok) 87 self traverse_single(column default) 88 --> 89 self connection execute(schema CreateTable(table)) 90 91 if hasattr(table 'indexes'): C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\engine\base pyc in execute(self object *multiparams **params) 660 object 661 multiparams -> 662 params) 663 else: 664 raise exc InvalidRequestError( C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\engine\base pyc in _execute_ddl(self ddl multiparams params) 718 compiled 719 None -> 720 compiled 721 ) 722 if self _has_events: C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\engine\base pyc in _execute_context(self dialect constructor statement parameters *args) 872 parameters 873 cursor -> 874 context) 875 876 if self _has_events: C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\engine\base pyc in _handle_dbapi_exception(self e statement parameters cursor context) 1022 self dialect dbapi Error 1023 connection_invalidated=self _is_disconnect) > 1024 exc_info 1025 ) 1026 C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\util\compat pyc in raise_from_cause(exception exc_info) 194 # the code line where the issue occurred 195 exc_type exc_value exc_tb = exc_info -> 196 reraise(type(exception) exception tb=exc_tb) 197 198 C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\engine\base pyc in _execute_context(self dialect constructor statement parameters *args) 865 statement 866 parameters -> 867 context) 868 except Exception e: 869 self _handle_dbapi_exception( C:\Users\aergener\AppData\Local\Enthought\Canopy\User\lib\site-packages\sqlalchemy\engine\default pyc in do_execute(self cursor statement parameters context) 322 323 def do_execute(self cursor statement parameters context=None): -> 324 cursor execute(statement parameters) 325 326 def do_execute_no_params(self cursor statement context=None): ProgrammingError: (ProgrammingError) ('42S01' "[42S01] [Microsoft][ODBC SQL Server Driver][SQL Server]There is already an object named 'foobar' in the database (2714) (SQLExecDirectW)") you'\nCREATE TABLE foobar (\n\tfactor TEXT NULL \n\tnum_avail INTEGER NULL \n\tpct_avail FLOAT NULL \n\tmin FLOAT NULL \n\tmax FLOAT NULL \n\tptile1 FLOAT NULL \n\tptile99 FLOAT NULL \n\tpct_yday FLOAT NULL \n\tdiff_yday FLOAT NULL \n\tcorr_yday FLOAT NULL\n)\n\n' () ```` | This issue seem to have been fixed in 0 14 1 <a href="https://github com/pydata/pandas/issues/7815" rel="nofollow">reference</a> <h3>Solution</h3> Update your pandas |
How to scroll to a selected item in a ScrolledListBox in python? I am developing an application that displays a large database of items There is also a search bar allowing the user to search that database rather than scrolling through each item to find the one they need When the search returns `True` (a match was made) the information needed shows up in a textbox and more options in another listbox (not scrolled now) but the `ScrolledListBox` does not auto-scroll to the selected item even if I am using `selection_set()` or `list_box active()` I got it! I had to use the `list_box yview_scroll()` command! That takes 2 arguments: 1) The integer/index of where to go 2) Line by line or by pages(UNITS or PAGES) But I do find the see method to be more efficient! | Tkinter does not have a ScrolledListBox class Can you be more specific about which ScrolledListBox implementation you are using? That being said the scrollable widgets in Tkinter typically have a `see` method that will scroll enough to make sure the passed-in index is visible In the comment to this answer you say you are using pmw ScrolledListBox According to <a href="http://pmw sourceforge net/doc/ScrolledListBox html" rel="nofollow">the documentation for the ScrolledListBox widget</a>: <blockquote> In addition methods from the Tkinter Listbox class are forwarded by this megawidget to the listbox component </blockquote> Therefore you can call any method on that widget that you can call on a Listbox widget As I mentioned earlier the Listbox class has a `see` method so you should be able to do something like: ````the_widget see(index) ```` In the above example `index` is the row in the listbox you want to see |
What were kozane made of? | iron or leather |
Is there an easy way for python Unittest to do unit test for only a portion of a function? The to-be-tested python function contains continuous parts which are not well modulized i e : ````def f(): do stuff A do stuff B do stuff C ```` If I just want to test stuff "B" and I do not want to manually mock up each single line in stuff "A/C" it there anyway for python unit test to do that? Thanks! | You need to refactor this function using method extraction That will create a larger number of functions which can be unit tested ````def a(): do stuff A def b(): do stuff B def c(): do stuff C def f(): a() b() c() ```` |
Python write to txt file at specific line I am creating a python stock system in which I need to allow a user to enter a product code and enter their quantity and the software checks a txt file It checks whether the product is found and whether their is enough of them I am stuck trying to make my code subtract the quantity needed from the total quantity in the text file I only want to change the quantity of that one product Any help will be appreciated Thanks Ben Edit: I have to use txt as it is part of the design brief ````x = 10 y = 0 n = 1 data = [line strip() split() for line in open("Untitled txt")] code = input("Please enter Product Code?") quantity = input("How many of these do you need?") for num in range(0 10): if data[x][0] == code: n = 0 y = x x = x - 1 if n == 0: if data[y][3] >= quantity: print("Product in stock") old = int(data [y][3]) quantity = int(quantity) new = old - quantity new = str(new) data[y][3] = new else: print("Product out of stock") else: print("Product not found") ```` This is my txt file ````Code Description Price Quantity 12345670 testitem 1 45 34 12345671 testitem 1 45 34 12345672 testitem 1 45 34 12345673 testitem 1 45 34 12345674 testitem 1 45 34 12345675 testitem 1 45 34 12345676 testitem 1 45 34 12345677 testitem 1 45 34 12345678 testitem 1 45 34 12345679 testitem 1 45 34 12345680 testitem 1 45 34 ```` | All you need to do is do is this in reverse: ````data = [line strip() split() for line in open("Untitled txt")] ```` so each line in data joined by `"\n"` and each element in line joined by a tab? ( split() without arguments could split by a few different characters) ````new_text = "\n" join("\t" join(line) for line in data) ```` I see you are opening the file once for reading into data and one for `r+` but it only needs to be opened for the line of code that it gets written to: ````with open("Untitled txt" "w") as f: f write(new_text) ```` Edit: just noticed you have a typo / mistake: ````if data[y][3] : old = data [y][3] data[1][3] = new ```` it is quite possible you just need to change the last `1` to `y` |
Where to save my custom scripts so that my python scripts can access the module in the default directory? This is going to be a multi-part question but the ultimate aim is such that I can access custom-made modules/libraries/functions like how I do in native python <strong>Where are the non-native but `pip` installed python libraries stored and how to configure my interpreter/IDE to access them?</strong> My users' script all starts with: ````#!/usr/bin/env python -*- coding: utf-8 -*- ```` <strong>What is the difference between accessing from `/usr/bin` and `/usr/bin/env` will the custom-made modules that should import like native python modules/packages work?</strong> <strong>Should my custom scripts become packages? if so how do I make the user-side code checks for `ImportError` and install/setup these packages in the `try-except`?</strong> e g ````try: import module_x except ImportError: # Install package but how to do it within the script? pass ```` <strong>Is there a place to store my custom scripts such that it imports like a native library?</strong> If so where? What are the consequences? | Well you have asked a lot of questions; I will address the one in the subject line You can put Python module files anywhere you want and still `import` them without any problems as long as they are in your <a href="http://docs python org/2/tutorial/modules html#the-module-search-path">module search path</a> You can influence your module search path by altering the environment variable `PYTHONPATH` in your she will before invoking Python or by altering the <a href="http://docs python org/2/library/sys html#sys path">sys path</a> variable inside your code So if you have installed `/home/alvas/python/lib/module_x py` and `/usr/local/python/lib/foo py` you could run: ````PYTHONPATH=/home/alvas/python/lib:/usr/local/python/lib /home/alvas/scripts/bar py ```` and then the statements ````import module_x import foo ```` should simply work Alternatively you could do something like this in your code: ````#!/usr/bin/env python import sys sys path append('/home/alvas/python/lib') import module_x sys path append('/usr/local/python/lib') import foo ```` Either approach will work |
How do I move this method-decorator pattern inside a class? Currently I am using a decorator to dynamically add methods from a class into a list; this way I can iterate over all of them at the same time when I need to and I do not have manually add each of them at once: ````predicates_list = [] def predicate(func): predicates_list append(func) return func class Person(object): @predicate def name_is_bill(self name): return True if name == 'bill' else False def test_everything(self tester): if any(predicate(name) for predicate in predicates_list: return True else: return False ```` However it does not make sense to have the decorating function and the list outside the scope of the Person class â only the Person class or its subclasses will use it I have had no luck trying to make the decorator function a class method or a static method As a class method I get errors about needing two arguments (That error makes sense but do I need to pass `cls` or `self` as the first argument in the decorator? If so how?) As a static method I do not have access to the class's properties I could specify the name of the class in the decorator function but I will run into problems if I need to subclass Person There must be an elegant way to do this but I am out of ideas | The pattern you are using looks correct Most of the examples in the official <a href="https://wiki python org/moin/PythonDecoratorLibrary" rel="nofollow">Python Decorator Library</a> use the same pattern you have adopted - decorator definition outside the class See for instance the <a href="https://wiki python org/moin/PythonDecoratorLibrary#Property_Definition" rel="nofollow">Property Definition</a> example |
What does the organization's literature impose on membership decision making? | null |
Django template How to Convert numbers to Words I am searching for a template tag to convert a value like 522 to five hundred twenty two only Looking in docs i came across <blockquote> django contrib humanize </blockquote> which has a build in tag intword but it works only with number with numbers greater than a million as a alternative solution i have created a tag using function from <a href="http://stackoverflow com/questions/13913165/python-script-to-convert-from-numbers-to-words-for-printing-cheques/13932483#13932483">Python script to convert from numbers to words for printing cheques</a> kindly suggest if any better solution possible | Check out this library: <a href="https://pypi python org/pypi/num2words" rel="nofollow">num2words</a> Straight from the docs: ````>>> from num2words import num2words >>> num2words(42) forty-two >>> num2words(42 ordinal=True) forty-second >>> num2words(42 lang='fr') quarante-deux ```` |
Where does morphine come from? | the opium poppy |
Check if file has a CSV format with Python Could someone provide an effective way to check if a file has CSV format using Python ? | Python has a <a href="http://docs python org/library/csv html" rel="nofollow">csv module</a> so you could try parsing it under a variety of different dialects |
Using google data API I want to learn google contacts API to manipulate my gmail contacts I have two gmail accounts one is for my regular use the other for test purpose However when I run the <a href="http://code google com/p/gdata-python-client/source/browse/samples/contacts/" rel="nofollow">example code</a>(I wrote it based on contacts_example py) I find that I can use the first account but not the second Here is a snippet of the code: ````try: gd_client = gdata contacts client ContactsClient(source='GoogleInc-ContactsPythonSample-1') gd_client ClientLogin(user pw gd_client source) except gdata client BadAuthentication: print 'Invalid user credentials given ' return ```` When I run it I get this and I swear my password is right ````Please enter your username: drizzlexsi@gmail com Password: Invalid user credentials given ```` Any idea what can lead to this error? I think it has something to do with my test account but I am not sure what is it | There is an account setting in Google which makes this work Go to <a href="https://myaccount google com/" rel="nofollow">https://myaccount google com/</a> on your account that does not work and under the "Account settings -> Signing in" section there is a thing called "Less secure apps" Click on "Turn on" It should now work The direct page for this is <a href="https://www google com/settings/security/lesssecureapps" rel="nofollow">https://www google com/settings/security/lesssecureapps</a> I hope that helps |
How to replace keys (key labels) in a dictionary from a list of tokens I have a dictionary `dict = {'a': 'cat' 'b':'dog'}` and I want to replace the keys in the dict with new keys (or key labels) from a list `['c' would']` so that I get (the same) `dict = {'c': 'cat' would':'dog'}` How can I do this? | You can define the relation between the old keys and their replacements in another dictionary like this Here `mapping` is the dictionary which maps the old keys with the new keys ````d mapping = {'a': 'cat' 'b':'dog'} {"a":"c" "b":"d"} print {mapping[k]:v for k v in d items()} ```` <strong>Output</strong> ````{'c': 'cat' would': 'dog'} ```` |
How many sailors died from scurvy between the years 1500 and 1800? | two million |