input_text
stringlengths
1
40.1k
target_text
stringlengths
1
29.4k
Python - Win32Com - How to extract hyperlink from Excel spreadsheet cell? I am trying to get hyperlinks from individual cells in an excel spreadsheet with the following code: ````import win32com client import win32ui app = win32com client Dispatch("Excel Application") app visible = True workbook = app Workbooks Open("test xlsx") sheet = workbook Sheets[0] test_cell = sheet Range("A8") value ```` This prints the following: ````test_cell you'Link title' ```` But when I try to extract the hyperlink it did not return the link/url in string format but a 'COMObject unknown': ````test_cell = sheet Range("A8") Hyperlinks test_cell <COMObject <unknown&gt;&gt; ````
````sheet Range("A8") Hyperlinks Item(1) Address ````
Converting Algorithm from Python to C: Suggestions for Using bin() in C? So essentially I have a <a href="/questions/tagged/homework" class="post-tag" title="show questions tagged &#39;homework&#39;" rel="tag">homework</a> problem to write in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a> and instead of taking the easy route I thought that I would implement a little algorithm and some coding practice to impress my Professor The question is to help us to pick up C (or review it the former is for me) and the question tells us to return all of the integers that divide a given integer (such that there is no remainder) What I did in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> was to create a <strong>is_prime()</strong> method a <strong>pool_of_primes()</strong> method and a <strong>combinations()</strong> method So far I have everything done in C up to the <strong>combinations()</strong> method The problem that I am running into now is some syntax errors (i e not being able to alter a string by declaration) and mainly the <a href="/questions/tagged/binary" class="post-tag" title="show questions tagged &#39;binary&#39;" rel="tag">binary</a> that I was using for the purpose of what would be included in my list of combinations But without being able to alter my string by declaration the Python code is kind of broken Here is the <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> code: ````def combinations(aList): ''' The idea is to provide a list of ints and combinations will provide all of the combinations of that list using binary To track the combinations we use a string representation of binary and count down from there Each spot in the binary represents an on/off (included/excluded) indicator for the numbers ''' length = len(aList) #Have this figured out s = "" canidates = 0 nList = [] if (length &gt;=21): print("\nTo many possible canidates for integers that divide our number \n") return False for i in range(0 length): s = "1" canidates = pow(2 i) #We now have a string for on/off switch of the elements in our #new list Canidates is the size of the new list nList append(1) while (canidates != 0): x = 1 for i in range(0 length): if(int(s[i]) == 1): x = x*aList[i] nList append(x) canidates -= 1 s = '' temp = bin(canidates) for i in range(2 len(temp)): s = s+temp[i] if (len(s) != length): #This part is needed in cases of [1 000-1 = 0 111] while( len(s) != length): s = '0'+s return nList ```` Sorry if the entire code is to lengthy or not optimized to a specific suiting But it works and it works well :) Again I currently have everything that <strong>aList</strong> would have stored as a singly-linked list in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a> (which I am able to print/use) I also have a little macro I included in C to convert binary to an integer: ````#define B(x) S_to_binary_(#x) static inline unsigned long long S_to_binary_(const char *s) { unsigned long long i = 0; while (*s) { i <<= 1; i = *s++ - '0'; } return i; } ```` This may be Coder's Block setting in but I am not seeing how I can change the binary in the same way that I did in Python Any help would be greatly appreciated! Also as a note what is typically the best way to return a finalized code in C? <strong>EDIT:</strong> Accidentally took credit for the macro above <h1><strong>UPDATE</strong></h1> I just finished the code and I <a href="https://github com/Twoody/integers_that_divide_me/blob/master/main c" rel="nofollow">uploaded it onto Github</a> I would like to thank @nneonneo for providing the step that I needed to finish it with exemplary code If anyone has any further suggestions about the code I would be happy to see there ideas on [Github]!
Why use a string at all? Keep it simple: use an integer and use bitwise math to work with the number Then you do not have to do any conversions back and forth It will also be loads faster You can use a `uint32_t` to store the "bits" which is enough to hold 32 bits (since you max out at 21 this should work great) For example you can loop over the bits that are set by using a loop like this: ````uint32_t my_number = ; for(int i=0; i<32; i++) { if(my_number &amp; (1<<i)) { /* bit i is set */ } } ````
In what city did Japan set up a provisional capital?
Chungking
tell() of Python behaving differently on Mac OS X 10 8 and Ubuntu 10 04 I was working on a binary file ( gz file) trying to open it in append mode (ab+) As is guaranteed by the file open() opening it in append mode because tell() to point to the end of file (EOF) But this is not what I see on Ubuntu 10 04 as opening a file in append mode the file pointer still points to the beginning of the file rather than the end But this is not the case on My Mac OS X 10 8 as the functions behave correctly as expected Behavior as seen on Ubuntu 10 04 ````Python 2 6 5 (r265:79063 Oct 1 2012 22:04:36) [GCC 4 4 3] on linux2 Type "help" "copyright" "credits" or "license" for more information &gt;&gt;&gt; fp = open("file_name gz" "ab+") &gt;&gt;&gt; fp tell() 0 ```` Doing a seek gives me the correct number though ````&gt;&gt;&gt; fp seek(0 2) &gt;&gt;&gt; fp tell() 753236 ```` Behavior as seen on Mac OS X 10 8 ````Python 2 6 7 (r267:88850 Oct 11 2012 20:15:00) [GCC 4 2 1 Compatible Apple Clang 4 0 (tags/Apple/clang-418 0 60)] on darwin Type "help" "copyright" "credits" or "license" for more information &gt;&gt;&gt; fp = open("file_name gz" "ab+") &gt;&gt;&gt; fp tell() 753236 ```` The same behavior was observed with the other modes 'a' and 'a+b' Has any one encountered such a situation before?
As <a href="http://docs python org/2/library/functions html#open" rel="nofollow">the documentation</a> says: <blockquote> `'a'` for appending (which on <them>some</them> Unix systems means that all writes append to the end of the file regardless of the current seek position) </blockquote> Nothing about where the file pointer starts out and even the parenthesized part is only true on "some Unix systems" But you are expecting it to work the same way on all platforms Do not do that The right answer is to explicitly seek to the end if you want to be at the end: ````fp = open("file_name gz" "ab+") fp seek(0 2) fsize = fp tell() ```` (Of course if you just want to know the file size you do not even need this; you can just `fstat` the file or `stat` it without even opening it…) <hr> In fact both OS X and Linux will append all writes to the end of the file regardless of the seek position And I believe they will both seek to the end in "a" mode but will do different things in "a+" mode If you are using Python 2 x `open` on all POSIX systems ultimately just depends on `fopen` So let us look at the manpages Linux <a href="http://linux die net/man/3/fopen" rel="nofollow">`fopen(3)`</a>: <blockquote> a+ Open for reading and appending (writing at end of file) The file is created if it does not exist The initial file position for reading is at the beginning of the file but output is always appended to the end of the file </blockquote> Mac <a href="https://developer apple com/library/mac/documentation/Darwin/Reference/Manpages/man3/fopen 3 html" rel="nofollow">`fopen(3)`</a> <blockquote> ``a+'' Open for reading and writing The file is created if it does not exist The stream is positioned at the end of the file Subsequent writes to the file will always end up at the then current end of file irrespective of any intervening fseek(3) or similar </blockquote> <hr> But the details do not matter; if you are writing portable code you cannot use `a` this way
Only about what percentage of the people raised in the religion continue to identify themselves as Jehovah's Witnesses?
37%
Python 3 utf8 value decode to string Hi i am using python3 and i want to change utf8 value to string (decode) Here is my code now ````s1 = '\u54c7' print(chr(ord(s1))) # print 哇 ```` It is fine if input is one char but how to change a string? ````s2 = '\u300c\u54c7\u54c8\u54c8!!\u300d' print(chr(ord(s2))) # Error! I want print "「哇哈哈!!」" ```` Thanks Edit: ================================================================ Hi all i update the question If i got the string is "s3" like below and i use replace to change format but print "s3" not show "哇哈哈!!" If i initiated s4 with \u54c7\u54c8\u54c8!!' and print s4 it is look like correct so how can i fix s3 ? ````s3 = '&amp;#x54c7;&amp;#x54c8;&amp;#x54c8;!!' s3 = s3 replace("&amp;#x" "\\you") replace(";" "") # s3 = \u54c7\u54c8\u54c8!! s4 = '\u54c7\u54c8\u54c8!!' print(s3) # \u54c7\u54c8\u54c8!! print(s4) # 哇哈哈!! ````
If you are in fact using python3 you do not need to do anything You can just print the string Also you can just copy and paste the literals into a python string and it will work ````'「哇哈哈!!」' == '\u300c\u54c7\u54c8\u54c8!!\u300d' ```` In regards to the updated question the difference is escaping If you type a string literal some sequences of characters are changed to characters that cannot be easily typed or be displayed The string is not stored as the series of characters you see but as a list of values created from characters like 'a' ';' and '\300' Note that all of those have a len of 1 because they are all one character To actually convert those values you could use `eval` the answer provided by Iron Fist or find a library that converts the string you have I would suggest the last since the rules surrounding such things can be complex and rarely are covered by simple replacements I do not recognize the particular pattern of escaping so I cannot recommend anything sorry
NumPy Broadcasting: Calculating sum of squared differences between two arrays I have the following code It is taking forever in Python There must be a way to translate this calculation into a broadcast ````def euclidean_square(a b): squares = np zeros((a shape[0] b shape[0])) for i in range(squares shape[0]): for j in range(squares shape[1]): different = a[i :] - b[j :] sqr = different**2 0 squares[i j] = np sum(sqr) return squares ````
You can use <a href="http://docs scipy org/doc/numpy-1 10 0/reference/generated/numpy einsum html" rel="nofollow">`np einsum`</a> after calculating the differences in a <a href="http://docs scipy org/doc/numpy-1 10 1/user/basics broadcasting html" rel="nofollow">`broadcasted way`</a> like so - ````ab = a[: None :] - b out = np einsum('ijk ijk>ij' ab ab) ```` Or use <a href="http://docs scipy org/doc/scipy-0 15 1/reference/generated/scipy spatial distance cdist html" rel="nofollow">`scipy's cdist`</a> with its optional metric argument set as `'sqeuclidean'` to give us the squared euclidean distances as needed for our problem like so - ````from scipy spatial distance import cdist out = cdist(a b 'sqeuclidean') ````
Extract features for tag prediction project I am thinking of doing a project for keyword extraction of stack exchange questions in python I have an input data from kaggle com which has id title body and tags for training I am thinking of implementing some machine learning algorithms like SVM neural networks etc to train classifiers The problem is for input to these algorithms we need features And i do not have idea how to extract features from this input for these algorithms as i have never extracted features from a paragraph before Any help will be appreciated
Feature selection is of crucial importance it gives information of the relevance of features for your problem Good theoretical explanation is given in Pattern Recognition by Sergios Theodoridis and Konstantinos Koutroumbas book I found this simple code example ````# Feature Importance from sklearn import datasets from sklearn import metrics from sklearn ensemble import ExtraTreesClassifier # load the iris datasets dataset = datasets load_iris() # fit an Extra Trees model to the data model = ExtraTreesClassifier() model fit(dataset data dataset target) # display the relative importance of each attribute print(model feature_importances_) ```` Result ````0 1087327 0 06409384 0 32304493 0 50412853 ```` You can read more [<a href="http://machinelearningmastery com/feature-selection-in-python-with-scikit-learn/] with" rel="nofollow">http://machinelearningmastery com/feature-selection-in-python-with-scikit-learn/] with</a> examples
Python - Task Scheduler 0x1 Having a frustrating time with scheduling a Python script (C:\Python27\test py) which has the following code: ````import xlrd import csv with xlrd open_workbook('Z:/somefile xls') as wb: sh = wb sheet_by_index(3) with open('Z:/somefile csv' 'wb') as f: c = csv writer(f) for r in range(sh nrows): c writerow(sh row_values(r)) ```` This script is supposed to take worksheet 3 in "somefile xls" and save it into it is own csv file When I run it manually from the Python She Will it works as intended Z:\ is a mapped drive located on an entirely different server When I try to run from the Task Scheduler I keep getting the 0x1 result code I have the Task set up as the following: - Run whether user is logged on or not - Do Not Store Password - Run with highest privileges - Program/script: python exe - Add arguments (optional): "test py" - Start in (optional): C:\Python27 I have read quite a few posts all with different suggestions none of which worked Anyone else run into this situation before? Jeff
I ran into this a few weeks ago Task Scheduler can be a real pain! For whatever reason I have never been able to get a script to run when the "Run whether user is logged on or not" option is selected I spent something like 10 hours on the phone with my IT department trying to figure it out It cannot be done Un-checking that option should then allow your script to run
According to recent research who is enrolled in the Universities in France in higher number men or women?
null
PyQt Designer: How to make a button's edges rounder? In PyQt's designer tool when you create a QPushButton at first it will look like this: <a href="http://i stack imgur com/EKQzf png" rel="nofollow"><img src="http://i stack imgur com/EKQzf png" alt="pic 1"></a> If you right-click on it pick 'Change stylesheet' and change the button background color to orange for example you will get this: <a href="http://i stack imgur com/y87dz png" rel="nofollow"><img src="http://i stack imgur com/y87dz png" alt="pic 2"></a> If you notice the button's shape changed slightly it is edges became more sharp and even the 'click' makes it look more 'squared' and I do not want that I want it to look like before but just with the background set to orange Is this possible? As an alternative is there a way so make the edges rounder? Thank you
You can get the effect you want by setting the radius of the border in the stylesheet like so: ````border-radius: 15px ```` Edit: I guess I spoke to soon I tried it out myself and it does not have the desired effect when you have set a background color There is some other weird stuff that happens when you change the color; it removes some other default styling that you will need to add back in manually if you want it to look similar to how it did before Try adding the following into the QPushButton's stylesheet and play around with the numbers to see how they affect the button: ````background-color: orange; border-style: outset; border-width: 2px; border-radius: 15px; border-color: black; padding: 4px; ```` You may also need to set up some style changes for when the button is pushed (e g change the border-style to inset on pressed)
Who wrote The Crucifixion of Jesus?
Frederick Zugibe
Looking for an Amazon SES example sending a raw mail including attachment The Amazon SES documentation is not clear for me So if you can help me with an example tot send raw text e-mails including a PDF attachment this will help me a lot I use Python 2 5 and Google App engine I have to use "raw" because that is the only SES option if I include attachments My problems at the moment : - What is the content of the post request - Which message fields should I put in the header - How to handle the "returnPath" - How to handle the text body It should be : Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes Content-Transfer-Encoding: base64 - How do I construct the HMAC signature for this post I know how to make the signature but how does the raw string looks for the signature function
The procedure I am using is outlined in <a href="https://gist github com/2883593" rel="nofollow">this gist</a> It mostly comes from following the example given <a href="http://codeadict wordpress com/2010/02/11/send-e-mails-with-attachment-in-python/" rel="nofollow">here</a>
Python - Setting a limit on a variable I have just started to learn python can anyone help me For example if I had a variable called 'speed' and I only wanted it to go to 100 and not above and not to go below 0 But I also want the code to still run so I could set it lower or higher my code so far: ````import tkinter as tk speed = 80 def onKeyPress(event value): global speed text delete("%s-1c" % 'insert' 'insert') text insert('end' 'Current Speed: %s\n\n' % (speed )) speed = value print(speed) if speed &gt;= 100: text insert('end' 'You have reached the speed limit') speed = 80 root = tk Tk() root geometry('300x200') text = tk Text(root background='black' foreground='white' font=('Comic Sans MS' 12)) text pack() # Individual key bindings root bind('<KeyPress-w&gt;' lambda e: onKeyPress(e 1)) root bind('<KeyPress-s&gt;' lambda e: onKeyPress(e -1)) # root mainloop() ```` How would I get the 'speed' variable to stop at 100 without stopping the whole of the code?
````if speed &gt;= 100: speed=100 text insert('end' 'You have reached the speed limit') ````
Adding numpy matrices together I have several matrices each one stored in a NumPy array and I would like to add them all ````a1=np load("20130101T054446") a2=np load("20130102T205729") a3=np load("20130104T153006") a4=np load("20130113T130758") a5=np load("20130113T212154") ```` I know its possible to add them in this away: ````z=a1+a2+a3+a4+a5 ```` But since I have hundreds of matrices I would like to do it in a easy away Is there any way to import all at the same time and ascribe it to different variables?
Instead of loading each dataset into a different variable you could create a list of all datasets you want to load load them into a list and then sum them up ````import numpy as np datasets = ["20130101T054446" "20130102T205729" "20130104T153006" "20130113T130758" "20130113T212154"] # easy to extend if you have more of them a = [np load(d) for d in datasets] z = np sum(a axis=0) ````
Sort list of strings and place numbers after letters in python I have a list of strings that I want to sort By default letters have a larger value than numbers (or string numbers) which places them last in a sorted list ````&gt;&gt;&gt; 'a' &gt; '1' True &gt;&gt;&gt; 'a' &gt; 1 True ```` I want to be able to place all the strings that begins with a number at the bottom of the list Example: Unsorted list: ````['big' 'apple' '42nd street' '25th of May' 'subway'] ```` Python's default sorting: ````['25th of May' '42nd street' 'apple' 'big' 'subway'] ```` Requested sorting: ````['apple' 'big' 'subway' '25th of May' '42nd street'] ````
````&gt;&gt;&gt; a = ['big' 'apple' '42nd street' '25th of May' 'subway'] &gt;&gt;&gt; sorted(a key=lambda x: (x[0] isdigit() x)) ['apple' 'big' 'subway' '25th of May' '42nd street'] ```` Python's sort functions take an optional `key` parameter allowing you to specify a function that gets applied before sorting Tuples are sorted by their first element and then their second and so on You can read more about sorting <a href="https://wiki python org/moin/HowTo/Sorting" rel="nofollow">here</a>
What is a safety hazard to track workers?
voltages on contact wires
OpenCV Lip Segmentation How do people usually extract the shape of the lips once the mouth region is found (in my case using haar cascade)? I tried color segmentation and edge/corner detection but they are very inaccurate for me I need to find the two corners and the very upper and lower lip at the center I have heard things about active appearance models but I am having trouble understanding how to use this with python and I do not have enough context to figure out if this is even the conventional method for detecting different parts of the lips Is that my best choice or do I have other options? If I should use it how would I get started with it using python and simplecv?
Here are two papers for lip segmentation using edge detection and color segmentation Try them out <a href="https://docs google com/viewer?a=v&amp;q=cache%3amS_FaM4f0O8J%3awww eurecom fr/util/publidownload en htm?id=3142%20simplest%20lip%20segmentation&amp;hl=en&amp;gl=in&amp;pid=bl&amp;srcid=ADGEESip7HISlmxem1v8PVeaf2U8IcO1bFKByP_3GpN-kl0jJokuVqNF_yp5NCLPJOjXumS5Mr-eMPEHUa6bEEASmN8mwVtkj6TxeRQ0HLDeclgvh9PceYigAAKPs-OSC7QbL623WRJM&amp;sig=AHIEtbQb362J2H_xjmNfb0v286SNdIc7BA" rel="nofollow">paper1</a> <a href="http://www-clips imag fr/geod/User/nicolas eveno/Doc/Eveno_ICME2002 PDF" rel="nofollow">paper2</a>
Is there an easy way in Python to wait until certain condition is true? I need to wait in a script until a certain number of conditions become true? I know I can roll my own eventing using condition variables and friends but I do not want to go through all the trouble of implementing it since some object property changes come from external thread in a wrapped C++ library (Boost Python) so I cannot just hijack `__setattr__` in a class and put a condition variable there which leaves me with either trying to create and signal a Python condition variable from C++ or wrap a native one and wait on it in Python both of which sound fiddly needlessly complicated and boring Is there an easier way to do it barring continuous polling of the condition? Ideally it would be along the lines of ````res = wait_until(lambda: some_predicate timeout) if (not res): print 'timed out' ````
You have basically answered your own question: no Since you are dealing with external libraries in boost python which may change objects at their leisure you need to either have those routines call an event handler refresh or work with a condition
How do I add plain text info to forms in a formset in Django? I want to show a title and description from a db query in each form but I do not want it to be in a charfield I want it to be html-formatted text sample template code: ````{% for form data in zipped_data %} <div class="row"&gt; <div class="first_col"&gt; <span class="title"&gt;{{ data 0 }}</span&gt; <div class="desc"&gt; {{ data 1|default:"None" }} </div&gt; </div&gt; {% for field in form %} <div class="fieldWrapper" style="float: left; "&gt; {{ field errors }} {{ field }} </div&gt; {% endfor %} {% endfor %} ```` Is this the most idiomatic way of doing this? Or is there a way to add text that will not be displayed inside of a textarea or text input to my model: ````class ReportForm(forms Form): comment = forms CharField() ```` ?
Instead of zipping your forms with the additional data you can override the constructor on your form and hold your title/description as <them>instance-level</them> member variables This is a bit more object-oriented and learning how to do this will help you solve other problems down the road such as dynamic choice fields ````class MyForm (forms Form): def __init__ (self title desc *args **kwargs): self title = title self desc = desc super (MyForm self) __init__ (*args **kwargs) # call base class ```` Then in your view code: ````form = MyForm ('Title A' 'Description A') ```` Adjust accordingly if you need these values to come from the database Then in your template you access the instance variables just like you do anything else e g : ```` <h1&gt;{{ form title }}</h1&gt; <p&gt;{{ form desc }}</p&gt; ```` From the way you phrased your question I think you probably have some confusion around the way Django uses Python <them>class attributes</them> to provide a declarative form API versus <them>instance-level</them> attributes that you apply to individual instances of a class in this case your form objects - <a href="http://stackoverflow com/questions/207000/python-difference-between-class-and-instance-attributes">Check out this link for a good discussion on the distinction</a> - <a href="http://stackoverflow com/questions/206734/why-do-attribute-references-act-like-this-with-python-inheritance">And this one</a>
how to create a command-line-argument in python How to create an argument in Python ? Assume I have a script install py that executes packages on a host I have another config script named config py where i store the host name &amp; package names but I want to create my host name as an "argument" that i can run in terminal using this command install And it should catch the host name as an argument [i e 'install linuxServer1' and it should install directly to that host ] ````#codes from config py hostName = "linuxServer1" package=['test1' 'test2' ] #codes from install py Install = [] for i in config package: Install append("deploy:"+i+" host=") for f in Install: subprocess call(["fabric" f+config hostName]) ````
I think you should have a look on "<strong>argparse</strong>" module of python it will solve your current problem :) Let Us take 1 example - The following code is a Python program that takes a list of integers and produces either the sum or the max: ````import argparse parser = argparse ArgumentParser(description='Process some integers ') parser add_argument('integers' metavar='N' type=int nargs='+' help='an integer for the accumulator') parser add_argument('--sum' dest='accumulate' action='store_const' const=sum default=max help='sum the integers (default: find the max)') args = parser parse_args() print(args accumulate(args integers)) ```` If asked for help(Assuming the Python code above is saved into a file called prog py)- ````$ python prog py -h usage: prog py [-h] [--sum] N [N ] Process some integers positional arguments: N an integer for the accumulator optional arguments: -h --help show this help message and exit --sum sum the integers (default: find the max) ```` When run with the appropriate arguments it prints either the sum or the max of the command-line integers: ````$ python prog py 1 2 3 4 4 $ python prog py 1 2 3 4 --sum 10 ```` If invalid arguments are passed in it will issue an error: ````$ python prog py a b c usage: prog py [-h] [--sum] N [N ] prog py: error: argument N: invalid int value: 'a' ````
self restarting daemon in python in *nix system I need to created a daemon in python I did search and found a good piece of <a href="http://www jejik com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">code</a> The daemon should be started automatically after system boots and it should be started if it was unexpectedly closed I went through chapter about daemons in <a href="http://rads stackoverflow com/amzn/click/0201563177" rel="nofollow">Advanced programming in the Unix environment</a> and have two questions To run script automatically after the boot I need put my daemon script to /etc/init d Is that correct? What should I do to respawn the daemon? According to the book I need add a respawn entry into /etc/inittab but I do not have /etc/inittab on my system Should I create it by myself?
I suggest you look into <a href="http://upstart ubuntu com/" rel="nofollow">upstart</a> if you are on Ubuntu It is way better than `inittab` but does involve some learning curve to be honest <strong>Edit</strong> (by Blair): here is an adapted example of an upstart script I wrote for one of my own programs recently A basic upstart script like this is fairly readable/understandable though (like many such things) they can get complicated when you start doing fancy stuff ````description "mydaemon - my cool daemon" # Start and stop conditions Runlevels 2-5 are the # multi-user (i e networked) levels This means # start the daemon when the system is booted into # one of these runlevels and stop when it is moved # out of them (e g when shut down) start on runlevel [2345] stop on runlevel [!2345] # Allow the service to respawn automatically but if # crashes happen too often (10 times in 5 seconds) # there is a real problem and we should stop trying respawn respawn limit 10 5 # The program is going to daemonise (double-fork) and # upstart needs to know this so it can track the change # in PID expect daemon # Set the mode the process should create files in umask 022 # Make sure the log folder exists pre-start script mkdir -p -m0755 /var/log/mydaemon end script # Command to run it exec /usr/bin/python /path/to/mydaemon py --logfile /var/log/mydaemon/mydaemon log ````
Python match all substrings and reversed strings I have to match all occurrences of substring in a string and return all match starting positions: example of input data: ````2 4 AC TGGT 4 25 CATA TCATATGCAAATAGCTGCATACCGA 0 0 ## to end the file ```` I would like to do this without using numbers in such lines as it seems not really necessary;(but they will still be in the input files) And I do not know exactly what is wrong with this code but it keeps printing (infinity loop) of printing 0s on the output file ````#!/usr/bin/env python import sys from operator import itemgetter def find_all(a_str sub): start = 0 while True: start = a_str find(sub start) if start == -1: return yield start start = len(sub) if __name__ == '__main__': testnum=0 input_file = open(sys argv[1]) #input_lines=input_file split("\n") output_file = open(sys argv[2] "w") while True: testnum+=1 values_raw = input_file readline() #values_raw=raw_input() ##rubish values=values_raw split() flag=0 for element in values: if element == "0": break string1=str(input_file readline()) string2=str(input_file readline()) lista = find_all(string2 string1) output_file write("\nTeste "+str(testnum)+"\nocorrencia direta: ") for item in lista: output_file write(str(item)+" ") #reversed search string1=string1[::-1] lista = find_all(string2 string1) output_file write("\nTeste "+str(testnum)+"\nocorrencia inversa complementar: ") for item in lista: output_file write(str(item)+" ") if ((len(string1)==0)): break ```` I accidentally removed the string1 and string2 lines when pasting the code //I match for the original and for the reversed match but as the code is almost the same I thought I should not post it too
You can use `regex`: ````&gt;&gt;&gt; import re &gt;&gt;&gt; pat = 'CATA' &gt;&gt;&gt; strs = 'TCATATGCAAATAGCTGCATACCGA' &gt;&gt;&gt; [m start() for m in re finditer(pat strs)] [1 17] ````
Who prevents Nine Eyes from going online?
Q
Sampling from MultiIndex DataFrame I am working with the following panel data in a `MultiIndex` pandas `DataFrame` called `df_data`: ```` y x n time 0 0 0 423607 -0 307983 1 0 565563 -0 333430 2 0 735979 -0 453137 3 0 962857 1 671106 1 0 0 772304 1 221366 1 0 455327 -1 024852 2 0 864768 0 609867 3 0 334429 -2 567936 2 0 0 435553 -0 259228 1 0 221501 0 484677 2 0 773628 0 650288 3 0 293902 0 566452 ```` `n` indexes an individual (there are 500 of them) `t` indexes time It is a balanced panel I would like to create a random sample of `nn=100` individuals with replacement Also if an individual makes it into the random sample then all 4 time observations (t=0 1 2 3) for this individual should be assigned to the sample The following line is doing almost what I want: ````df_sample = df_data loc[np random randint(3 size=100) tolist()] ```` However it does not sample an individual repeatedly So if the created list of random variables is say [2 3 2 4 1 ] then the third individual (index =2 is the third individual) is only selected once and not twice into the random sample This means that as soon as the random vector above contains the same individual more than once I end up with fewer than 100 individuals (with 4 time observations each) in the random sample I also tried the `df_data sample`function but I does not seem to be able to handle the specific multilevel index I have here in the panel I could write all kinds of loops to get this done but I thought there should be a simpler (and faster) way of doing this I am on Python 3 5 and I am using pandas version 0 17 1 Thanks
You can use `itertools product` to quickly produce the format needed to select with duplicates from a `MultiIndex`: Sample data: ````from itertools import product individuals = list(range(500)) time = (0 1 2 3 ) index = pd MultiIndex from_tuples(list(product(individuals time))) df = pd DataFrame(data={'A': np random random(size=2000) 'B': np random random(size=2000)} index=index) A B 0 0 0 208461 0 842118 1 0 481681 0 096121 2 0 420538 0 922363 3 0 859182 0 078940 1 0 0 171162 0 255883 1 0 338864 0 975492 2 0 270533 0 504605 3 0 691041 0 709189 2 0 0 220405 0 925001 1 0 811951 0 479795 2 0 010527 0 534866 3 0 561204 0 915972 3 0 0 813726 0 083478 1 0 745100 0 462120 2 0 189111 0 552039 3 0 006141 0 622969 ```` Combine the result of `np random randint` with the `time` values using `product`: ````sample_ix = np random randint(low=0 high=500 size=100) len(np unique(sample_ix)) 91 sample_multi_ix = list(product(sample_ix time)) [(55 0) (55 1) (55 2) (55 3) (254 0) (254 1) (254 2) (254 3) ] ```` and select accordingly: ````sample = df loc[sample_multi_ix :] sample info() MultiIndex: 400 entries (55 0) to (135 3) Data columns (total 2 columns): A 400 non-null float64 B 400 non-null float64 dtypes: float64(2) memory usage: 9 4+ KB ```` If you want a unique `sample` `index` you can add: ````sample index = pd MultiIndex from_tuples(list(product(list(range(100)) time))) MultiIndex: 400 entries (0 0) to (99 3) Data columns (total 2 columns): A 400 non-null float64 B 400 non-null float64 dtypes: float64(2) ````
nosetests/unittest still shows error when test passes? I have a unit test that tests if an api point is unaccessible if not authenticated like this: ````def test_endpoint_get_unauth(self): are = self get('/api/endpoint/1') self assertStatusCode(are 401) ```` The test passes but nosetests/unittest still shows me an error that an exception was raised saying "not authorized " Is there anyway to stop this? Full log: ````ERROR in views [/myenv/lib/python2 7/site-packages/flask_restless/views py:115]: Not Authorized -------------------------------------------------------------------------------- Traceback (most recent call last): File "/myapp/myenv/lib/python2 7/site-packages/flask_restless/views py" line 113 in decorator return func(*args **kw) File "/myapp/myenv/lib/python2 7/site-packages/flask/views py" line 84 in view return self dispatch_request(*args **kwargs) File "/myapp/myenv/lib/python2 7/site-packages/flask/views py" line 149 in dispatch_request return meth(*args **kwargs) File "/myapp/myenv/lib/python2 7/site-packages/flask_restless/views py" line 989 in get preprocessor(instance_id=instid) File "/myapp/app/api/api py" line 16 in check_auth raise ProcessingException(message='Not Authorized' status_code=401) ProcessingException ---------------------------------------------------------------------- Ran 16 tests in 15 788s OK ````
The error does not come from failed test case but from tested application which is complaining about unauthorized access This is natural as your test case is just trying to make the unauthorized access As both tested application and test suite are using stdout for output it confuses you You could play a bit with configuring logging of the app and test suite to get it to different files and you would see who is telling what
Distinguishing between article pages and list/disambiguation pages in Wiki I am generating random pages from Wikipedia using '<a href="https://en wikipedia org/wiki/Special%3aRandom" rel="nofollow">https://en wikipedia org/wiki/Special:Random</a>' and reading them using BeautifulSoup The problem is that I only want article pages like : <a href="http://en wikipedia org/wiki/Ada_County _Idaho" rel="nofollow">http://en wikipedia org/wiki/Ada_County _Idaho</a> But sometimes it a list page or disambiguation page (which I do not want) e g : <a href="http://en wikipedia org/wiki/List_of_U S _counties_named_after_personal_first_names" rel="nofollow">http://en wikipedia org/wiki/List_of_U S _counties_named_after_personal_first_names</a> Is there an easy way to distinguish these cases?
Use <a href="https://www mediawiki org/wiki/API" rel="nofollow">the API</a> to tell if a page is disambiguation E g <a href="https://en wikipedia org/w/api php?action=query&amp;prop=pageprops&amp;format=json&amp;ppprop=disambiguation&amp;generator=random&amp;grnnamespace=0&amp;grnlimit=10" rel="nofollow">this</a> will retrieve 10 random titles in article namespace (<a href="https://en wikipedia org/wiki/Special%3aApiSandbox#action=query&amp;prop=pageprops&amp;format=json&amp;ppprop=disambiguation&amp;generator=random&amp;grnnamespace=0&amp;grnlimit=10" rel="nofollow">try interactively in sandbox</a>) Disambiguation pages will have `"pageprops":{"disambiguation":""}` in their properties Unfortunately there is no such easy way for lists you will have to guess from their titles (`/^List of */`) or categories
python one2many/many2one key error this is my code verbindingen py ````from openerp osv import fields osv import logging class verbindingen(osv osv): _name = "verbindingen verbindingen" _description = "De verbindingen" _columns = { #'customer_id' : fields one2many('res partner' 'x_customer_id' 'Customer ID') 'kanaal_id' : fields one2many('verbindingen kanalen' 'verbinding_id') 'aansluitadres_straat' : fields char('Aansluitadres straat' size = 40) 'aansluitadres_huisnummer' : fields char('Aansluitadres huisnummer' size = 6) 'aansluitadres_postcode' : fields char('Aansluitadres postcode' size = 6) 'aansluitadres_toevoeging' : fields char('Aansluitadres toevoeging' size = 6) 'aansluitadres_plaats' : fields char('Aansluitadres plaats' size = 40) 'verbinding_type_id' : fields one2many('verbindingen types' 'verbinding_id' 'Verbinding type') 'leveranciers_id' : fields integer('Leveranciers ID' size = 20) 'service_id' : fields integer('Service ID' size = 20) 'dikader' : fields integer('Dikader') 'management_ip' : fields char('Management ip' size = 15) 'management_username' : fields char('Management username' size = 20) 'management_psswd' : fields char('Management password' size = 20) } ```` kanalen py ````from openerp osv import fields osv class kanalen(osv osv): _name = "verbindingen kanalen" _description = "Kanalen van de verbindingen" _columns = { 'type_kanaal' : fields selection([] 'Type kanaal') 'verbinding_id' : fields many2one('verbindingen verbindingen') 'VLAN_ID' : fields integer('Vlan ID') 'MAC' : fields char('MAC Adress' size = 17) 'IP' : fields char('IP-adres') 'VCI/VPI' : fields char('VCI/VPI') 'status' : fields selection([('active' 'Active') ('inactive' 'Inactive')] 'Status') ```` } When I try to install this module I get a KeyError: 'verbinding_id' error I have no clue what is wrong with my code
You have created two models as I see from your code i e `verbindingen verbindingen` and `verbindingen kanalen` then where is the `verbindingen types` ? if is it not there then create model `verbindingen types` and new m2o field there or remove the from relation field ````'verbinding_type_id' : fields one2many('verbindingen types' 'verbinding_id' 'Verbinding type') ````
Unescape _xHHHH_ XML escape sequences using Python I am using Python 2 x [not negotiable] to read XML documents [created by others] that allow the content of many elements to contain characters that are not valid XML characters by escaping them using the `_xHHHH_` convention e g ASCII BEL aka YOU+0007 is represented by the 7-character sequence `you"_x0007_"` Neither the functionality that allows representation of any old character in the document nor the manner of escaping is negotiable I am parsing the documents using cElementTree or lxml [semi-negotiable] Here is my best attempt at unescapeing the parser output as efficiently as possible: ````import re def unescape(s subber=re compile(r'_x[0-9A-Fa-f]{4 4}_') sub repl=lambda mobj: unichr(int(mobj group(0)[2:6] 16)) ): if "_" in s: return subber(repl s) return s ```` The above is biassed by observing a very low frequency of "_" in typical text and a better-than-doubling of speed by avoiding the regex apparatus where possible The question: Any better ideas out there?
You might as well check for `'_x'` rather than just `_` that will not matter much but surely the two-character sequence's even rarer than the single underscore Apart from such details you do seem to be making the best of a bad situation!
Get coordinates from a lambda function point I am fitting data to certain curves I have a model lambda function and I would like to obtain the exact coordinates (x y) of the maximum point of it I am able to know the maximum value however I also need to know its position in x-axis Is that possible? Thanks for your help in advance ```` from pylab import * from scipy import optimize fitf = lambda f x: f[0]*(1/(1+((x-f[1])/f[2])**2)) errf = lambda f x y: fitf(f x) - y f0 = [0 1 2] f1 success = optimize leastsq(errf f0[:] args=(x y)) pos = linspace(100 100 1000) max = fitf_voigt(f1 pos) max() print 'Peak max = %f' %max ```` args(x y) come from my experimental data
You can get the position of the maximal value using the `argmax` function: ````In [1]: import numpy as np In [2]: x = np random randn(100) In [3]: x max() Out[3]: 2 6054091710887723 In [4]: x argmax() Out[4]: 27 In [5]: x[27] Out[5]: 2 6054091710887723 In [6]: x[27] == x max() Out[6]: True ````
blocking read(1) with timeout in pyserial I use the following piece of code to read the serial port until i get a terminating character ````"""Read until you see a terminating character with a timeout""" response=[] byte_read='' break_yes=0 time_now = time clock() while ((not (byte_read=='\r') ) and (break_yes==0)): byte_read = self ser read(1) if (not(len(byte_read)== 0) and (not (byte_read =='\r'))): response append(byte_read) if ( time clock() - time_now &gt; 1 ): if self DEBUG_FLAG: print "[animatics Motor class] time out occured check code" break_yes=1 if break_yes==0: return '' join(response) else: return 'FAIL' ```` This works well but because of the while loop the cpu resources are taken up I think that having a blocking read(1) with a timeout will save some of the cpu The flag i am looking for C is "MIN == 0 TIME > 0 (read with timeout)" in termios i am looking for a similar flag in Python I could also use the io readline to read till i get '\r' but i want to stick to pyserial as much as possible without any other dependency Would greatly appreciate advice Do let me know if i should do it in a completely different way either too Thanks
You should read the documentation of Pyserial: it clearly states that a timeout of 0 as you pass it to the constructor will turn on non-blocking behaviour: <a href="http://pyserial sourceforge net/pyserial_api html#classes" rel="nofollow">http://pyserial sourceforge net/pyserial_api html#classes</a> Just get rid of the timeout parameter and you should be set
Detect gray things with OpenCV I would like to detect an object using OpenCV that is distinctly different from other elements in the scene as it is gray This is good because I can just run a test with ARE == G == B and it allows to be independent of luminosity but doing it pixel by pixel is slow Is there a faster way to detect gray things? Maybe there is an OpenCV method that does the ARE == G == B test `cv2 inRange` does color thresholding it is not quite what I am looking for
I am surprised that such a simple check is slow probably you are not coding it efficiently Here is a short piece of code that should do that for you It optimal neither in speed nor in memory but quite in number of lines of code :) ````std::vector<cv::Mat&gt; planes; cv::split(image planes); cv::Mat mask = planes[0] == planes[1]; mask &amp;= planes[1] == planes[2]; ```` For the sake of it here is a comparison with something that would be the fastest way to do it in my opinion (without parallelization) ````#include <opencv2/core/core hpp&gt; #include <opencv2/highgui/highgui hpp&gt; #include <iostream&gt; #include <vector&gt; #include <sys/time h&gt; //gettimeofday static double P_ellapsedTime(struct timeval t0 struct timeval t1) { //return ellapsed time in seconds return (t1 tv_sec-t0 tv_sec)*1 0 (t1 tv_usec-t0 tv_usec)/1000000 0; } int main(int argc char* argv[]) { struct timeval t0 t1; cv::Mat image = cv::imread(argv[1]); assert(image type() == CV_8UC3); std::vector<cv::Mat&gt; planes; std::cout << "Image resolution=" << image rows << "x" << image cols << std::endl; gettimeofday(&amp;t0 NULL); cv::split(image planes); cv::Mat mask = planes[0] == planes[1]; mask &amp;= planes[1] == planes[2]; gettimeofday(&amp;t1 NULL); std::cout << "Time using split: " << P_ellapsedTime(t0 t1) << "s" << std::endl; cv::Mat mask2 = cv::Mat::zeros(image size() CV_8U); unsigned char *imgBuf = image data; unsigned char *maskBuf = mask2 data; gettimeofday(&amp;t0 NULL); for (; imgBuf != image dataend; imgBuf = 3 maskBuf++) *maskBuf = (imgBuf[0] == imgBuf[1] &amp;&amp; imgBuf[1] == imgBuf[2]) ? 255 : 0; gettimeofday(&amp;t1 NULL); std::cout << "Time using loop: " << P_ellapsedTime(t0 t1) << "s" << std::endl; cv::namedWindow("orig" 0); cv::imshow("orig" image); cv::namedWindow("mask" 0); cv::imshow("mask" mask); cv::namedWindow("mask2" 0); cv::imshow("mask2" mask2); cv::waitKey(0); } ```` Bench on an image: ````Image resolution=3171x2179 Time using split: 0 06353s Time using loop: 0 029044s ````
When did the study of stateless societies begin?
null
Pandas dataframe row reduction/compression (for rows having the same value) I have a df such as: ````seed value 1 2 1 3 1 4 2 20 2 60 ```` would like to get a shorter dataframe (df_short) with the average value for same seeds such as ````seed value 1 3 2 40 ```` tried df groupby("seed") seems working though I am getting a DataFrameGroupBy object which I cannot use as a dataframe Then from the question <a href="http://stackoverflow com/questions/13582449/convert-dataframegroupby-object-to-dataframe-pandas">Convert DataFrameGroupBy object to DataFrame pandas</a> I tried the following: ````from pandas import * df = DataFrame({'seed' : [1 1 1 2 2] 'value' : [2 3 4 20 60]}) df_short=df groupby('seed') aggregate(np mean) print df_short #works as expected print df_short['seed'] #error ```` `print list(df_short columns values)` should give me `['seed' 'value']`
If you run the first three commands (through `df = df groupby('seed') mean()`) you will notice that the values 1 and 2 are the index of df and cannot be accessed using `df[seed]` We can use <a href="http://pandas pydata org/pandas-docs/dev/generated/pandas DataFrame reset_index html" rel="nofollow">reset_index</a> to convert seed to a column Notice the new index values are 0 and 1 ````In [48]: from pandas import * df = DataFrame({'seed' : [1 1 1 2 2] 'value' : [2 3 4 20 60]}) df = df groupby('seed') mean() df reset_index(inplace=True) print df['seed'] print df['value'] print list(df columns values) 0 1 1 2 Name: seed dtype: int64 0 3 1 40 Name: value dtype: int64 ['seed' 'value'] ````
Formatting List Output I have a list with entries similar to the following: ````[('sw1' 'sw2') ('sw1' 'sw3') ('sw1' 'sw4') ('sw2' 'sw3') ('sw2' 'sw4') ('sw3' 'sw4')] ```` I would like to convert the tuples to strings and print them on individual lines like so in order to pass them as arguments to another program: ````(sw1 sw2)\n (sw1 sw3)\n (sw1 sw4)\n (sw2 sw3)\n (sw2 sw4)\n (sw3 sw4)\n ```` I tried `strip()` and `split()` but those do not appear to be supported for tuples I am assuming I would need some regex expression to accomplish what I am trying to do but even then I am not sure hot to handle the fact that a potential field separator of ` ` is both within and between the tuples Any pointers are greatly appreciated I am old and just trying to learn to program
You can use string formatting as follows: ````a = [('sw1' 'sw2') ('sw1' 'sw3') ('sw1' 'sw4') ('sw2' 'sw3') ('sw2' 'sw4') ('sw3' 'sw4')] for i in a: print('({:} {:})' format(*i)) # (sw1 sw2) # (sw1 sw3) # (sw1 sw4) # (sw2 sw3) # (sw2 sw4) # (sw3 sw4) ```` This does not change your tuples per se but does format the printing of them as you wished The code simply iterates over your list and prints the tuples with a given format The string `format` method is covered <a href="http://docs python org/3/library/functions html#format" rel="nofollow">here</a>
pygame:How to make the rect of an image transparent or the same color with backgroud? I just started using pygame today and got a little trouble I rotated the car image but it seemed that the rect area not suited to the image perfectly(as showed in the picture the white area is larger than the image I rotated) Can you make the rect area's color transparent or the same as background so that the image looks better? Thanks <img src="http://i stack imgur com/BLCbw png" alt="car image"> Hello This is my concerning code(from 'Rapid Game Development in Python' by Richard Jones): ````class CarSprite(pygame sprite Sprite): MAX_FORWARD_SPEED = 10 MAX_REVERSE_SPEED = 10 ACCELERATION = 2 TURN_SPEED = 5 def __init__(self image position): pygame sprite Sprite __init__(self) self src_image = pygame image load(image) self src_image = self src_image convert() self position = position self speed = self direction = 0 self k_left = self k_right = self k_down = self k_up = 0 self rect = self src_image get_rect() self rect center = position def update(self deltat): # SIMULATION self speed = (self k_up self k_down) if self speed &gt; self MAX_FORWARD_SPEED: self speed = self MAX_FORWARD_SPEED if self speed <-self MAX_REVERSE_SPEED: self speed = -self MAX_REVERSE_SPEED self direction = (self k_right self k_left) x y = self position rad = self direction * math pi / 180 x = -self speed*math sin(rad) y = -self speed*math cos(rad) self position = (x y) self image = pygame transform rotate(self src_image self direction) self rect = self image get_rect() self rect center = self position def draw(self screen): self image set_alpha(150) screen blit(self image self rect) ````
I cannot see the image for some reason but I think what you want is `Surface set_colorkey(Color flags=0)` If you enter in the color of the background it (the background) will become transparent Another cool thing is that if you set the colorkey before you rotate the car the background will automatically become the color you set the colorkey to Just be careful If you are importing the image from an external source make sure you do `image=image convert()` before setting colorkey
Django queryset filtering not working I want the admin users to see only the model instances they created I followed these instructions <a href="http://stackoverflow com/questions/9574788/filter-django-admin-by-logged-in-user">Filter django admin by logged in user</a> ````class FilterUserAdmin(admin ModelAdmin): def save_model(self request obj form change): if getattr(obj 'user' None) is None: #Assign user only the first time superusers can edit without changing user obj user = request user obj save() def queryset(self request): qs = super(FilterUserAdmin self) queryset(request) if request user is_superuser: return qs return qs filter(user=request user) def has_change_permission(self request obj=None): if not obj: # the changelist itself print('query change') return True # So they can see the change list page return obj user == request user or request user is_superuser class CampaignAdmin(FilterUserAdmin): ```` This is how my code looks like Saving is fine However other users are seeing the model campaign in their campaign list though they were not able to edit it When a user who is not the owner clicks the campaign to edit 403 Forbidden page is seen <strong>I do not want the model instance to be shown in the other users' campaign list </strong>
You should override <a href="https://docs djangoproject com/en/1 9/ref/contrib/admin/#django contrib admin ModelAdmin get_queryset" rel="nofollow">`get_queryset`</a> not `queryset` The method was renamed from `queryset` to `get_queryset` in Django 1 6 ````def get_queryset(self request): qs = super(FilterUserAdmin self) get_queryset(request) if request user is_superuser: return qs return qs filter(user=request user) ```` Note that you do not need to use `getattr` when checking `if getattr(obj 'user' None) is None:` you can simplify it to `if obj user is None`
wxPython and MDI like app I want to build an application in wxPython which have multiple windows like MDI I do not want use MDIParentFrame which is old I have seen wx aui too but I do not like it What I want is a main frame that hase a menu and toolbar and more child windows Child windows must minimize when main frame minimize and got focus when main frame clicked How do this ? Thanks all
You either use one of the MDI implementations that wxPython already has built-in or you reinvent the wheel and create your own widgets
numpy array delete row if one string element is repeated in another row I have an array like this: ````vals = numpy array([['user1' 'number1' 'grades1'] ['user1' 'number2' 'grade2'] ['user3' 'number3' 'grade3'] ['user4' 'number4' 'grade4']]) ```` And I would like to delete one whole row containing `user1` because is repeated (it does not matter which row may be) in another row at the first column Also if there are more rows displaying `user1` just keep the first one found so the output can be something like: ````array([['user1' 'number1' 'grade1'] ['user3' 'number3' 'grade3'] ['user4' 'number4' 'grade4']]) ```` So far I tried: ````a = (vals[0:1 0:1] == vals[1:2 0:1]) vals = numpy delete(vals numpy where(a) axis=0) ```` However how can I use this making a loop?
You can use `numpy unique` which can also return indices ````unique_user unique_indices = numpy unique(vals[: 0] return_index = True) unique_vals = vals[unique_indices] ````
Python: CSV write by column rather than row I have a python script that generates a bunch of data in a while loop I need to write this data to a CSV file so it writes by column rather than row For example in loop 1 of my script I generate: ````(1 2 3 4) ```` I need this to reflect in my csv script like so: ````Result_1 1 Result_2 2 Result_3 3 Result_4 4 ```` On my second loop i generate: ````(5 6 7 8) ```` I need this to look in my csv file like so: ````Result_1 1 5 Result_2 2 6 Result_3 3 7 Result_4 4 8 ```` and so forth until the while loop finishes Can anybody help me? <h2> </h2> <hr> EDIT The while loop can last over 100 000 loops
The reason `csv` does not support that is because variable-length lines are not really supported on most filesystems What you should do instead is collect all the data in lists then call `zip()` on them to transpose them after ````&gt;&gt;&gt; l = [('Result_1' 'Result_2' 'Result_3' 'Result_4') (1 2 3 4) (5 6 7 8)] &gt;&gt;&gt; zip(*l) [('Result_1' 1 5) ('Result_2' 2 6) ('Result_3' 3 7) ('Result_4' 4 8)] ````
Is there a more pythonic way to build this dictionary? What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I am currently using the following but I feel like I am just missing a cleaner way NOTE: `values` is a list that is not related to any dictionary ````for value in values: new_dict[key_from_value(value)] = value ````
At least it is shorter: ````dict((key_from_value(value) value) for value in values) ````
Python: Taking parameter input and returning output equation I am working on a project that requires a function (I will call it target) that will take an input named parameter_vector and will output an equation for other functions to take as an input The output equation I am using as a test case is the standard quadratic equation: ````Ax^2 Bx C ```` My target function will take a parameter_vector in that looks like: ````parameter_vector = [A B C] ```` and will use these indices as coefficients in writing out my equation as an output Here is my code so far: ````def target(parameter_vector): pv = parameter_vector x = pv[0]*x**2 pv[1]*x pv[2] return x ```` As I am sure you can guess the following error pops up in my she will: ````UnboundLocalError: local variable 'x' referenced before assignment ```` So I did a little research and came across the lambda variable that is used for place-holding a variable I tried to input: ````x = pv[0]*lambda**2 pv[1]*x pv[2] ```` But this popped up: ````File "source_parameters py" line 7 x = pv[0]*lambda**2 pv[1]*lambda pv[2] ^ SyntaxError: invalid syntax ```` Am I approaching this completely wrong? I am sure even sure whether the output should be a string or not Any help would be greatly appreciated!
You misunderstood how lambdas work; they create a function from an expression Given `x` as input that would look like this: ````lambda x: pv[0]*x**2 pv[1]*x pv[2] ```` The expression produces a function object which you can return directly from your `target()` function: ````def target(pv): return lambda x: pv[0]*x**2 pv[1]*x pv[2] ```` You could unpack the `parameter_vector` into the three components first to make it clearer you need to have 3 values in it: ````def target(parameter_vector): a b c = parameter_vector return lambda x: a * x ** 2 b * x c ```` or you can generalise this to any length of `parameter_vector`: ````def target(parameter_vector): return lambda x: sum(p * x ** (len(parameter_vector) - i - 1) for i p in enumerate(parameter_vector)) ```` Quick demo: ````&gt;&gt;&gt; lambda x: pv[0]*x**2 pv[1]*x pv[2] <function <lambda&gt; at 0x102a0c6e0&gt; &gt;&gt;&gt; def target(parameter_vector): a b c = parameter_vector return lambda x: a * x ** 2 b * x c &gt;&gt;&gt; new_function = target([3 2 5]) # 3x^2 2x 5 &gt;&gt;&gt; new_function <function <lambda&gt; at 0x102a0c7d0&gt; &gt;&gt;&gt; new_function(2) 21 &gt;&gt;&gt; new_function(3) 38 &gt;&gt;&gt; new_function(4) 61 &gt;&gt;&gt; def target(parameter_vector): return lambda x: sum(p * x ** (len(parameter_vector) - i - 1) for i p in enumerate(parameter_vector)) &gt;&gt;&gt; new_function = target([3 2 5]) &gt;&gt;&gt; new_function(2) 21 &gt;&gt;&gt; new_function = target([3 2 5 -2]) # 3x^3 2x^2 5x - 2 &gt;&gt;&gt; new_function(2) 40 ````
Pass multiple arguments to a function in tkinter When I trying to pass the `employeeNum` and `employeePass` to a function called displayButton it told me that I miss these two arguments ````from tkinter import * def displayButton(root employNum employPass): Label(root text = employNum ) grid(row = 3 column = 1 sticky = N+S+W+E) Label(root text = employPass) grid(row = 4 column = 1 sticky = N+S+W+E) def main(): root = Tk() Label(root text = 'Employee Number: ') grid(row = 0 column = 0 sticky = W) Label(root text = 'Login Password: ') grid(row = 1 column = 0 sticky = W) employeeNum = StringVar() employeePass = StringVar() Entry(root textvariable = employeeNum) grid(row = 0 column = 1 columnspan = 2 sticky = W) Entry(root textvariable = employeePass) grid(row = 1 column = 1 columnspan = 2 sticky = W) checkButton = BooleanVar() Checkbutton(root text = 'Remember Me' variable = checkButton) grid(row = 2 column = 1 sticky = W) Button(root text = 'Save' relief = RAISED) grid(row = 2 column = 2 sticky = E) display = Button(root text = 'Display' relief = RAISED command = lambda: displayButton(root employeeNum employeePass)) display grid(row = 3 column = 2 sticky = E) display bind('<Button-1&gt;' displayButton) Label(root text = "Employee's number is ") grid(row = 3 column = 0 sticky = W) Label(root text = "Employee's Passowrd is ") grid(row =4 column = 0 sticky = W) root mainloop() main() ```` The error it gives me is : ````TypeError: displayButton() missing 2 required positional arguments: 'employNum' and 'employPass' ````
You do not need to bind the button so you can remove this line ````display bind('<Button-1&gt;' displayButton) ```` If you are working with `StringVar()` and if you want to read it is content you have to use ` get()` `employNum get()` and `employPass get()` This code should work: ````from Tkinter import * def displayButton(root employNum employPass): Label(root text = employNum get() ) grid(row = 3 column = 1 sticky = N+S+W+E) Label(root text = employPass get()) grid(row = 4 column = 1 sticky = N+S+W+E) def main(): root = Tk() Label(root text = 'Employee Number: ') grid(row = 0 column = 0 sticky = W) Label(root text = 'Login Password: ') grid(row = 1 column = 0 sticky = W) employeeNum = StringVar() employeePass = StringVar() Entry(root textvariable = employeeNum) grid(row = 0 column = 1 columnspan = 2 sticky = W) Entry(root textvariable = employeePass) grid(row = 1 column = 1 columnspan = 2 sticky = W) checkButton = BooleanVar() Checkbutton(root text = 'Remember Me' variable = checkButton) grid(row = 2 column = 1 sticky = W) Button(root text = 'Save' relief = RAISED) grid(row = 2 column = 2 sticky = E) display = Button(root text = 'Display' relief = RAISED command = lambda: displayButton(root employeeNum employeePass)) display grid(row = 3 column = 2 sticky = E) #display bind('<Button-1&gt;' displayButton) Label(root text = "Employee's number is ") grid(row = 3 column = 0 sticky = W) Label(root text = "Employee's Passowrd is ") grid(row =4 column = 0 sticky = W) root mainloop() main() ````
What is unique about Tbilisi?
"carrying a heavy cruisers complement of defensive weapons and large P-700 Granit offensive missiles"
How to include a file that stay in STATIC directory into a Django template inheritance I have the following directory in django app ```` |-- migrations |-- static | |-- help_content html | |-- images | `-- vendors `-- templates `-- coolapp |-- other_content html `-- parent html ```` Now in `parent html` I would like to able to do this: ````{% include " /static/help_content html" %} ```` But it fails What is the right way to do it? This is ok though: ````{% include "coolap/other_content html" %} ````
The include tag will look for your specified file on "TEMPLATES_DIR" setting For sure the static folder is not included and should not (is possible but not too coherent) I think you should move "help_content html" inside of "templates" folder you can put it in another folder inside "templates" if you want to keep some order there The Static folder is meant to store css js and that kind of files which you can include using "static" template tag for example Hope this help you
Google App Engine Shared Memcache is having short life span I realize the shared memcache in Google App Engine can only hold the key-value for a very short period I have perform the following call for 20 times at different timestamp ````_MEMCACHE_DURATION = 14*24*60*60 memcache add(email user_timestamp _MEMCACHE_DURATION) ```` My expectation is the key-value will last for 14 days However I find out the oldest item age is "1 hr 42 min" When I look at documentation I thought that valid time is up to 1 month : <a href="https://cloud google com/appengine/docs/python/memcache/functions#Client_add" rel="nofollow">https://cloud google com/appengine/docs/python/memcache/functions#Client_add</a> I was wondering is such behavior correct?
read about the difference between shared and paid memcache in the official docs shared comes with no guarantees about how long the data will remain there Official documentation: <a href="https://cloud google com/appengine/docs/developers-console/#memcache" rel="nofollow">https://cloud google com/appengine/docs/developers-console/#memcache</a> Best practices for memcache: <a href="https://cloud google com/appengine/articles/best-practices-for-app-engine-memcache" rel="nofollow">https://cloud google com/appengine/articles/best-practices-for-app-engine-memcache</a>
Python error: "LookupError: no codec search functions registered: cannot find encoding" I am running Enthough Canope python distribution in Windows 7 and cannot run working python in a command line 'python' brings up: ````Python 2 7 3 |CUSTOM| (default Aug 8 2013 05:30:12) [MSC v 1500 64 bit (AMD64)] on win32 Type "help" "copyright" "credits" or "license" for more information ```` but any python command yields: ````&gt;&gt;&gt; x = 5 LookupError: no codec search functions registered: cannot find encoding ```` Any idea why this is happening? I can run ipython perfectly well but I am concerned that inability to run basic python is preventing other functionality such as installing new packages Grateful for assistance
Did you make Canopy User Python your default python? My guess is you did not Doing so will invoke Canopy's User python executable from the command line and `x=5` should work Another way to achieve the same is to open a "Canopy Command Prompt" window from the Windows Start menu: that will only make Canopy your default python for that session To access it `Start &gt; All programs &gt; Enthought Canopy &gt; Canopy Command Prompt` One way or another when you start Canopy's `python` from the terminal you should see: ````C:\Users\jrocher\&gt; python Enthought Canopy Python 2 7 3 | 32-bit | (default Dec 2 2013 16:14:17) [MSC v 1500 32 bit (Intel)] on win32 Type "help" "copyright" "credits" or "license" for more information &gt;&gt;&gt; ````
pytest: If a crash/segfault/etc occurs during testing is there a way to make pytest log the crash as a test failure and continue testing? I have a few unit tests written using pytest that have successfully caused segfaults to occur However if a segfault occurs (on my Mac) during these execution pytest seems to quit altogether and provide no information on what caused the python interpreter to crash Now I could infer from the logs the specific test that was crashing and determine the values used within but I was wondering if there was any way to be able to somehow log the crash as a regular test failure and keep iterating through my tests without stopping? If helpful I can try to conceive an example but I think the question should be pretty self-explanatory
Using the pytest-xdist plugin it will restart the nodes automatically when they crash so installing the plugin and running the tests with `-n1` should make py test survive the crashing tests
What do some people believe should be the basis for affirmative action instead of religion based legislation?
null
Extract json objects within a list using a list comprehesion I am trying to save specific items from one list in an other list using list comprehesion I downloaded several tweets and I saved them in a text file I called txt files and saved all items in a list This is my code so far: ````import json random allTweets = [] i = range(1 50) for n in i: tweetFile = [line rstrip() for line in open('twitfull' str(n) ' txt')] allTweets extend(tweetFile) tweets = [json loads(item) for item in allTweets] ```` Data example in list: ````json object {'id': 746029083335680003 'in_reply_to_user_id': None 'in_reply_to_status_id': None 'source': '<a href=" " rel="nofollow"&gt;TweetDeck</a&gt;' 'favorited': False 'contributors': None 'favorite_count': 0 'retweeted': False 'is_quote_status': False 'lang': 'es' 'created_at': 'Thu Jun 23 17:16:08 0000 2016' 'in_reply_to_screen_name': None 'coordinates': None 'geo': None 'id_str': '746029083335680003' 'filter_level': 'low' 'timestamp_ms': '1466702168674' 'in_reply_to_user_id_str': None 'retweet_count': 0 'place': None 'truncated': False 'in_reply_to_status_id_str': None 'text': 'Se da lectura a los acuerdos entre Gobierno y FARC-EP #FinDelConflicto #AdiósALaGuerra #PazenColombia #ElUltimoDiaDeLaGuerra #Cuba' 'user': {'friends_count': 356 'id': 814202096 'notifications': None 'profile_sidebar_border_color': '5ED4DC' 'profile_image_url': 'http://pbs twimg com/profile_images/2594545116/r7de57w8q920u7p0hft6_normal jpeg' 'favourites_count': 3 'utc_offset': -25200 'url': 'http://yamimontoya blogspot com' 'profile_background_image_url': 'http://abs twimg com/images/themes/theme4/bg gif' 'verified': False 'profile_sidebar_fill_color': '95E8EC' 'followers_count': 348 'created_at': 'Mon Sep 10 01:05:29 0000 2012' 'location': 'Cuba' 'profile_background_color': '0099B9' 'name': 'Yami Montoya' 'lang': 'es' 'time_zone': 'Pacific Time (US &amp; Canada)' 'following': None 'id_str': '814202096' 'is_translator': False 'contributors_enabled': False 'profile_background_tile': False 'listed_count': 13 'default_profile': False 'follow_request_sent': None 'default_profile_image': False 'profile_link_color': '0099B9' 'screen_name': 'yami679' 'description': 'Periodista cubana editora de Tiempo21 cu orgullosa de vivir en mi Isla ' 'profile_use_background_image': True 'profile_text_color': '3C3940' 'profile_image_url_https': ' ' 'protected': False 'profile_background_image_url_https': ' ' 'statuses_count': 115828 'geo_enabled': False} 'entities': {'hashtags': [{'text': 'FinDelConflicto' 'indices': [55 71]} {'text': 'AdiósALaGuerra' 'indices': [72 87]} {'text': 'PazenColombia' 'indices': [88 102]} {'text': 'ElUltimoDiaDeLaGuerra' 'indices': [103 125]} {'text': 'Cuba' 'indices': [126 131]}] 'user_mentions': [] 'urls': [] 'symbols': []}} ```` A sample of `tweets` list: ````[{'id': 746029040851521536 'in_reply_to_user_id': None 'in_reply_to_status_id': None 'source': '<a href="http://twitter com" rel="nofollow"&gt;Twitter Web Client</a&gt;' 'favorited': False 'contributors': None 'favorite_count': 0 'possibly_sensitive': False 'retweeted': False 'is_quote_status': False 'lang': 'es' 'created_at': 'Thu Jun 23 17:15:58 0000 2016' 'in_reply_to_screen_name': None 'coordinates': None 'geo': None 'id_str': '746029040851521536' 'filter_level': 'low' 'timestamp_ms': '1466702158545' 'in_reply_to_user_id_str': None 'retweeted_status': {'id': 745637507493093377 'in_reply_to_user_id': None 'in_reply_to_status_id': None 'source': '<a href="http://twitterfeed com" rel="nofollow"&gt;twitterfeed</a&gt;' 'favorited': False 'contributors': None 'favorite_count': 0 'possibly_sensitive': False 'retweeted': False 'is_quote_status': False 'lang': 'es' 'created_at': 'Wed Jun 22 15:20:09 0000 2016' 'in_reply_to_screen_name': None 'coordinates': None 'geo': None 'id_str': '745637507493093377' 'filter_level': 'low' 'in_reply_to_user_id_str': None 'retweet_count': 1 'place': None 'truncated': False 'in_reply_to_status_id_str': None 'text': 'Denuncian por traición a la patria a Juan Manuel Santos: COLOMBIAN NEWS\n21de junio de 2016\n\xa0\n1 \xa0\xa0\xa0\xa0Denuncian ' 'user': {'friends_count': 834 'id': 1090274636 'notifications': None 'profile_sidebar_border_color': 'FFFFFF' 'profile_image_url': 'http://pbs twimg com/profile_images/3459756751/f7d00d504bdc55a4e30f214c46a73188_normal jpeg' 'favourites_count': 14 'utc_offset': -18000 'url': 'http://www periodicodebate com' 'profile_background_image_url': 'http://pbs twimg com/profile_background_images/772390136/0a690154c8cb12a6b4b918b66222bbd9 jpeg' 'verified': False 'profile_sidebar_fill_color': 'EFEFEF' 'followers_count': 6272 'created_at': 'Mon Jan 14 21:55:47 0000 2013' 'location': 'Colombia' 'profile_background_color': 'F5F8FA' 'name': 'Periódico Debate' 'lang': 'es' 'time_zone': 'Bogota' 'profile_banner_url': ' ' 'following': None 'id_str': '1090274636' 'is_translator': False 'contributors_enabled': False 'profile_background_tile': False 'listed_count': 47 'default_profile': False 'follow_request_sent': None 'default_profile_image': False 'profile_link_color': '009999' 'screen_name': 'DebateCol' 'description': None 'profile_use_background_image': True 'profile_text_color': '333333' 'profile_image_url_https': ' ' 'protected': False 'profile_background_image_url_https': ' ' 'statuses_count': 11887 'geo_enabled': False} 'entities': {'hashtags': [] 'user_mentions': [] 'urls': [{'display_url': 'bit ly/28WKaS0' 'indices': [113 136] 'expanded_url': ' ' 'url': ' '}] 'symbols': []}} 'retweet_count': 0 'place': None 'truncated': False 'in_reply_to_status_id_str': None 'text': 'RT @DebateCol: Denuncian por traición a la patria a Juan Manuel Santos: COLOMBIAN NEWS\n21de junio de 2016\n\xa0\n1 \xa0\xa0\xa0\xa0Denuncian ' 'user': {'friends_count': 563 'id': 274595199 'notifications': None 'profile_sidebar_border_color': 'C0DEED' 'profile_image_url': 'http://pbs twimg com/profile_images/378800000541161030/4eebcd7336d7aa698bdcb13601869f87_normal jpeg' 'favourites_count': 152080 'utc_offset': -14400 'url': None 'profile_background_image_url': 'http://abs twimg com/images/themes/theme1/bg png' 'verified': False 'profile_sidebar_fill_color': 'DDEEF6' 'followers_count': 1515 'created_at': 'Wed Mar 30 16:06:52 0000 2011' 'location': 'usa' 'profile_background_color': 'C0DEED' 'name': 'Raul Escobar' 'lang': 'es' 'time_zone': 'Eastern Time (US &amp; Canada)' 'following': None 'id_str': '274595199' 'is_translator': False 'contributors_enabled': False 'profile_background_tile': False 'listed_count': 17 'default_profile': True 'follow_request_sent': None 'default_profile_image': False 'profile_link_color': '0084B4' 'screen_name': 'RaulEscobar1154' 'description': None 'profile_use_background_image': True 'profile_text_color': '333333' 'profile_image_url_https': ' ' 'protected': False 'profile_background_image_url_https': ' ' 'statuses_count': 166211 'geo_enabled': False} 'entities': {'hashtags': [] 'user_mentions': [{'id_str': '1090274636' 'id': 1090274636 'screen_name': 'DebateCol' 'indices': [3 13] 'name': 'Periódico Debate'}] 'urls': [{'display_url': 'bit ly/28WKaS0' 'indices': [139 140] 'expanded_url': ' ' 'url': ' '}] 'symbols': []}} {'id': 746029040658710528 'in_reply_to_user_id': None 'in_reply_to_status_id': None 'source': '<a href="http://twitter com" rel="nofollow"&gt;Twitter Web Client</a&gt;' 'favorited': False 'contributors': None 'favorite_count': 0 'retweeted': False 'is_quote_status': False 'lang': 'es' 'created_at': 'Thu Jun 23 17:15:58 0000 2016' 'in_reply_to_screen_name': None 'coordinates': None 'geo': None 'id_str': '746029040658710528' 'filter_level': 'low' 'timestamp_ms': '1466702158499' 'in_reply_to_user_id_str': None 'retweet_count': 0 'place': None 'truncated': False 'in_reply_to_status_id_str': None 'text': '#AdiosALaGuerra y será que todos los integrantes de la guerrilla estan de acuerdo? estos señores tienen total control de este grupo? Ojala!' 'user': {'friends_count': 2 'id': 704447284524744704 'notifications': None 'profile_sidebar_border_color': 'C0DEED' 'profile_image_url': 'http://pbs twimg com/profile_images/704448554119647232/OCMVOVr4_normal jpg' 'favourites_count': 6 'utc_offset': None 'url': None 'profile_background_image_url': '' 'verified': False 'profile_sidebar_fill_color': 'DDEEF6' 'followers_count': 6 'created_at': 'Mon Feb 29 23:24:55 0000 2016' 'location': None 'profile_background_color': 'F5F8FA' 'name': 'Desafinado' 'lang': 'pt' 'time_zone': None 'following': None 'id_str': '704447284524744704' 'is_translator': False 'contributors_enabled': False 'profile_background_tile': False 'listed_count': 0 'default_profile': True 'follow_request_sent': None 'default_profile_image': False 'profile_link_color': '2B7BB9' 'screen_name': 'eg0max' 'description': None 'profile_use_background_image': True 'profile_text_color': '333333' 'profile_image_url_https': ' ' 'protected': False 'profile_background_image_url_https': '' 'statuses_count': 18 'geo_enabled': False} 'entities': {'hashtags': [{'text': 'AdiosALaGuerra' 'indices': [0 15]}] 'user_mentions': [] 'urls': [] 'symbols': []}}] ```` When I call items from `tweets` to print <them>text</them> or <them>ids</them> it works well: ````itemtest = random randint(0 len(tweets) - 1) print (tweets[itemtest]['id']) print (tweets[itemtest]['created_at']) print (tweets[itemtest]['text']) print (tweets[itemtest]['user']['screen_name']) ```` However if I want to save text in one list using list comprehesion it displays an error: This is the code I used: ````tweetText = [tw['text'] for tw in tweets] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-2-5ea2c15220c6&gt; in <module&gt;() ---> 1 tweetText = [tw['text'] for tw in tweets] <ipython-input-2-5ea2c15220c6&gt; in <listcomp&gt;( 0) ---> 1 tweetText = [tw['text'] for tw in tweets] KeyError: 'text' ```` <h1>This is the solution I found</h1> <h2>Edited 2016 May 25</h2> ````items = range(0 len(tweetsdata)) tweet_ids = [] tweet_source = [] tweet_text = [] tweet_users = [] trash = [] for n in items: try: ids = tweets[int(n)]['id'] links = 'https://twitter com/statuses/' str(ids) text = tweets[int(n)]['text'] users = tweets[int(n)]['user']['screen_name'] tweet_ids append(ids) tweet_source append(links) tweet_text append(text) tweet_users append(users) except KeyError: unknown = tweets[int(n)]['limit'] trash append(unknown) ```` However this solution could be improved by a better code Any suggestions are appreciated! Thanks
This works for me (manually made JSON string from your json object): ````import json random j = """ { "id": 746029083335680003 "created_at": "Thu Jun 23 17:16:08 0000 2016" "text": "The text" "user": { "screen_name": "usr123" "description": "description" "statuses_count": 123 "geo_enabled": null } "entities": { "hashtags": [{ "text": "a hash tag" "indices": [55 71] }] "user_mentions": [] "urls": [] "symbols": [] } } """ tweets = [json loads(j)] itemtest = 0 print (tweets[itemtest]['id']) print (tweets[itemtest]['created_at']) print (tweets[itemtest]['text']) print (tweets[itemtest]['user']['screen_name']) tweetText = [tw['text'] for tw in tweets] print(tweetText) ```` Output: ````746029083335680003 Thu Jun 23 17:16:08 0000 2016 The text usr123 ['The text'] ```` <hr> Works as well with two elements: ````import json random j = [""" { "id": 746029083335680003 "created_at": "Thu Jun 23 17:16:08 0000 2016" "text": "The text" "user": { "screen_name": "usr123" "description": "description" "statuses_count": 123 "geo_enabled": null } "entities": { "hashtags": [{ "text": "a hash tag" "indices": [55 71] }] "user_mentions": [] "urls": [] "symbols": [] } }""" """ { "id": 746029083335680003 "created_at": "Thu Jun 23 17:16:08 0000 2016" "text": "The text" "user": { "screen_name": "usr123" "description": "description" "statuses_count": 123 "geo_enabled": null } "entities": { "hashtags": [{ "text": "a hash tag" "indices": [55 71] }] "user_mentions": [] "urls": [] "symbols": [] } } """] tweets = [json loads(i) for i in j] print(len(tweets) tweets) itemtest = 0 print (tweets[itemtest]['id']) print (tweets[itemtest]['created_at']) print (tweets[itemtest]['text']) print (tweets[itemtest]['user']['screen_name']) tweetText = [tw['text'] for tw in tweets] print(tweetText) ````
How to redirect to another page in Python in CGIAr <strong>If I want to redirect the user from a cgi script to a HTML page using core libraries from the following:</strong> ````import cgi ```` Please could someone point me in the right direction Nothing more Simply redirect from cgi script to html page How ever you would do this Python If you have to physically write out the HTTP Response Headers to achieve this then I would appreciate any info on how to do this TIA Andrew
You need to output one more header ("Status") in addition to the `Location` one e g : ````print "Status: 301 Moved" print "Location:/wherever com/" ````
Can scraping be applied to this page which is actively recalculating? I would like to grab satellite positions from the page(s) below but I am not sure if scraping is appropriate because the page appears to be updating itself every second using some internal code (it keeps updating after I disconnect from the internet) Background information can be found in my question at Space Stackexchange: <a href="http://space stackexchange com/q/13217/12102">A nicer way to download the positions of the Orbcomm-2 satellites</a> I need a "snapshot" of four items <strong>simultaneously</strong>: - UTC time - latitude - longitude - altitude Right now I use screen shots and manual typing Since these values are being updated by the page - is conventional web-scraping going to work here? I found a "screen-scraping" tag should I try to learn about that instead? I am looking for the simplest solution to get those four values I wonder if I can just use `urllib` or `urllib2` and avoid installing something new? example page: <a href="http://www satview org/?sat_id=41186U" rel="nofollow">http://www satview org/?sat_id=41186U</a> I need to do 41179U through 41189U (the eleven Orbcomm-2 satellites that SpaceX just put in orbit) <a href="http://i stack imgur com/VJIOl png" rel="nofollow"><img src="http://i stack imgur com/VJIOl png" alt="highlighted screen shot of satview org"></a>
One option would be to fire up a <them>real browser</them> and continuously poll the position in an endless loop: ````import time from selenium import webdriver driver = webdriver Firefox() driver get("http://www satview org/?sat_id=41186U") while True: location = driver find_element_by_css_selector("#sat_latlon texto_track2") text latitude longitude = location split("\n")[:2] print(latitude longitude) time sleep(1) ```` Sample output: ````(you'-16 57' you'66 63') (you'-16 61' you'66 67') ```` Here we are using <a href="https://selenium-python readthedocs org/" rel="nofollow">`selenium`</a> and Firefox - there are multiple drivers for different browsers including headless like <a href="http://phantomjs org/" rel="nofollow">`PhantomJS`</a>
Python email payload decoding I know this question has been asked thousand of time but I am near to a nervous break so I cannot help but to ask for help I have an email with french accents caractères The sentence is : "céline : Berlin Annette : 0633' The email package of python changes ':' on '=3A' "é" on "=E9" How to get back to the accent ?? and to the "=" sign ? I tried several things looking through the net : getting the payload : ````&gt;&gt;&gt; z = message get_payload() &gt;&gt;&gt; z 'C=E9line =3A Berlin Annette =3A 0633' &gt;&gt;&gt; infos(z) (<type 'str'&gt; ' 'C=E9line =3A Berlin Annette =3A 0633') ```` decoding it by its charset: ````&gt;&gt;&gt; z = message get_payload() decode(message get_content_charset()) &gt;&gt;&gt; z you' C=E9line =3A Berlin Annette =3A 0633' &gt;&gt;&gt; infos(z) (<type 'unicode'&gt; you' 'C=E9line =3A Berlin Annette =3A 0633') ```` or encoding it in utf_8 after decoding: ````&gt;&gt;&gt; z = message get_payload() decode(message get_content_charset()) encode('utf-8') &gt;&gt;&gt; z 'C=E9line =3A Berlin Annette =3A 0633' &gt;&gt;&gt; infos(z) (<type 'str'&gt; 'C=E9line =3A Berlin Annette =3A 0633') ```` I also tried urllib: ````urllib unquote(z) 'C=E9line =3A 00493039746784 Berlin Annette =3A 0633' ```` nothing seems to work :(
You can use <a href="https://docs python org/2/library/quopri html#quopri decodestring">`quopri decodestring`</a> to decode the string ````&gt;&gt;&gt; quopri decodestring('C=E9line =3A 00493039746784 Berlin Annette =3A 0633') 'C\xe9line : 00493039746784 Berlin Annette : 0633' ```` If you pass `decode=True` to <a href="https://docs python org/2/library/email message html#email message Message get_payload">`Message get_payload`</a> it will do above for you: ````message get_payload(decode=True) ````
What were the Conservatives a founding member of?
null
Unlucky number 13 I came accorss this problem <a href="http://qa geeksforgeeks org/4344/the-unlucky-13" rel="nofollow">Unlucky number 13! </a> recently but could not think of efficient solution this <h3>Problem statement :</h3> N is taken as input <blockquote> N can be very large 0<= N <= 1000000009 </blockquote> Find total number of such strings that are made of exactly N characters which do not include "13" The strings may contain any integer from 0-9 repeated any number of times ````# Example: # N = 2 : # output : 99 (0-99 without 13 number) # N =1 : # output : 10 (0-9 without 13 number) ```` My solution: ````N = int(raw_input()) if N < 2: print 10 else: without_13 = 10 for i in range(10 int('9' * N)+1): string = str(i) if string count("13") &gt;= 1: continue without_13 = 1 print without_13 ```` <h2>Output</h2> The output file should contain answer to each query in a new line modulo 1000000009 Any other efficient way to solve this ? My solution gives time limit exceeded on coding site
I get the feeling that this question is designed with the expectation that you would initially instinctively do it the way you have However I believe there is a slightly different approach that would be faster You can produce all the numbers that contain the number 13 yourself without having to loop through all the numbers in between For example: 2 digits: 13 3 digits position 1: 113 213 313 etc 3 digits position 2: 131 132 133 etc Therefore you do not have to check all the number from 0 to n*9 You simply count all the numbers with 13 in them until the length is larger than N This may not be the fastest solution (in fact I would be surprised if this could not be solved efficiently by using some mathematics trickery) but I believe it will be more efficient than the approach you have currently taken
how to print lines in a file by seeking a position from another text file in python? This is my code for getting lines from a file by seeking a position using f seek() method but I am getting a wrong output it is printing from middle of the first line can you help me to solve this please? ````f=open(r"sample_text_file" "r") last_pos=int(f read()) f1=open(r"C:\Users\ddadi\Documents\project2\check\log_file3 log" "r") f1 seek(last_pos) for i in f1: print i last_position=f1 tell() with open('sample_text txt' 'a') as handle: handle write(str(last_position)) ```` sample_text file contains the file pointer offset which is returned by f1 tell()
If it is printing from the middle of a line that is almost certainly because your offset is wrong You do not explain how you came by the magic number you use as an argument to `seek` and without that information it is difficult to help more precisely One thing is however rather important It is not a very good idea to use `seek` on a file that is open in text mode (the default in Python) Try using `open( 'rb')` and see if the process becomes a little more predictable It sounds as though you may have got the offset by counting characters after reading in text mode but good old Windows includes carriage return characters in text files which are removed by the Python I/O routines before your program sees the text
Save log to a file when the default logging output is console I use ````logging basicConfig(level=logging DEBUG format = '%(asctime)s %(levelname)s %(message)s') ```` for logging By default it goes to console Is it possible to add an option to save this existing log to a file in case of a positive answer? Like it goes to console but in case of an exception there is an option in exception handling function to save log to a file Also I wonder is it safe for hdd to write multiple log lines every second?
you can have quite complex logging structure You can log onto console and in the file directly You can have multiple logging handlers that have different formatting and logging levels (e g you log everything on console but only errors to a file) just read the docs: <a href="https://docs python org/2/howto/logging html" rel="nofollow">https://docs python org/2/howto/logging html</a>
The Hellinistic age marked the rise in what type of religion?
traditional
Python pandas dataframe max in a group based on conditions on other columns I am not sure if this question has been asked before In a pandas dataframe I have data like ```` A B C 1 z 0 0 2 z 1 1 3 z 2 2 4 y 0 0 5 y 1 1 6 z 2 2 5 7 z 0 0 8 z 1 0 2 9 z 2 0 8 ```` I would like to get ```` A B C 1 z 2 2 5 2 y 1 1 3 z 2 0 8 ```` In the above example(from first table) z went from 0 for B and C to 2 for B and 2 5 for C respectively before going to 0 for B and C One important property is B and C can be different however they will go to 0 at the same time Think of it as a counter when device is off all your counters will go back to 0 The devices in above example being y and z Also from the first table you can also see y went from 0 to 1 for both B and C respectively however they never went back to 0 but I still need the maximum which is 1 and 1 for B and C I can write some python code to loop through and do the necessary transformations but I was wondering if this is possible with some pandas magic
Here is an approach that uses vectorized methods all the way through and should be pretty quick Add a column with value `1` when there is a 'reset' of the counter by checking where both B &amp; C are 0 ````df['new_sample'] = (df[['B' 'C']] == 0) any(1) astype(int) ```` Then groupby the device type and using the cumulative sum of the `new_sample` column create a counter for which trial of each device each row represents ````df['sample'] = df groupby('A')['new_sample'] cumsum() ```` Finally you can group by the device and sample number and take the maximum ````In [85]: df groupby(['A' 'sample'] as_index=False)[['B' 'C']] max() Out[85]: A sample B C 0 y 1 1 1 0 1 z 1 2 2 5 2 z 2 2 0 8 ````
Python File I/O issue: Bypassing For Loop? ````def findWord(word): f = open("words txt" "r") given_line = f readlines() for line in f: if str(word) in line: part = line[0] ## print(line+"\n"+str(word)+" is a "+part) return True else: return False print("fail") f close() def partSpeech(inX): f = open("words txt" "a") inX = inX split() for i in inX: i = i lower() if(findWord(i) == False): if "ify" in i[-3:] or "ate" in i[-3:] or "ize" in i[-3:] or "ing" in i[-3:] or "en" in i[-2:] or "ed" in i[-2:]: f write("\nV"+i) elif "ment" in i[-4:] or "ion" in i[-3:] or "acy" in i[-3:] or "ism" in i[-3:] or "ist" in i[-3:] or "ness" in i[-3:] or "ity" in i[-3:] or "or" in i[-2:] or "y" in i[-1:]: f write("\nN"+i) elif "ly" in i[-2:]: f write("\nD"+i) else: print(i+" was already in the database ") ```` Essentially my issue with the above happens at "for line in f:" The problem is that after putting numerous markers (prints to determine where it is getting) throughout the code the for loop is not even ran! I do not understand really whether or not it is just that line or f are not being counted or what but The goal is to in this snippet take a bunch of words loop them through a system that checks whether or not they are already in the given text file (the part I am having issues with) and then if they are not append them with a part of speech tag EDIT: I am not getting an error at all it is just that it is not running the For Loop like it should Every function is called at some point or another partSpeech is called toward the end with a small list of words EDIT 2: PROGRESS! Sort of The text file was empty so it was not reading any line whatsoever Now however it is not taking into account whether or not the words are already there It just skips over them
First off delete this line: ````given_line = f readlines() ```` This is reading the contents of the file into an unused `given_line` variable and leaving `f` positioned at the end of the file Your `for` loop therefore has nothing to loop over <hr> Your `findWord()` function is doing a number of odd/problematic things any of which might be causing the behavior you are assuming means the for loop is not even running Here is a possible re-implementation: ````def findWord(word): # it seems odd to pass a "word" parameter that is not a str but if you must handle that # case you only need to do the cast once word = str(word) # always use the with statement to handle resources like files # see https://www python org/dev/peps/pep-0343/ with open("words txt" "r") as f: for line in f: if word in line: return True return False # only return False after the loop; once we have looked at every line # no need to call f close() the with statement does it for us ````
Comparing 2 lists consisting of dictionaries with unique keys in python I have 2 lists both of which contain same number of dictionaries Each dictionary has a unique key There is a match for each dictionary of the first list in the second list that is a dictionary with a unique key exists in the other list But the other elements of such 2 dictionaries may vary For example: ````list_1 = [ { 'unique_id': '001' 'key1': 'AAA' 'key2': 'BBB' 'key3': 'EEE' } { 'unique_id': '002' 'key1': 'AAA' 'key2': 'CCC' 'key3': 'FFF' } ] list_2 = [ { 'unique_id': '001' 'key1': 'AAA' 'key2': 'DDD' 'key3': 'EEE' } { 'unique_id': '002' 'key1': 'AAA' 'key2': 'CCC' 'key3': 'FFF' } ] ```` I want to compare all elements of 2 matching dictionaries If any of the elements are not equal I want to print the none-equal elements Would you please help Thanks Best Regards
Assuming that the dicts line up like in your example input you can use the `zip()` function to get a list of associated pairs of dicts then you can use `any()` to check if there is a difference: ````&gt;&gt;&gt; list_1 = [{'unique_id':'001' 'key1':'AAA' 'key2':'BBB' 'key3':'EEE'} {'unique_id':'002' 'key1':'AAA' 'key2':'CCC' 'key3':'FFF'}] &gt;&gt;&gt; list_2 = [{'unique_id':'001' 'key1':'AAA' 'key2':'DDD' 'key3':'EEE'} {'unique_id':'002' 'key1':'AAA' 'key2':'CCC' 'key3':'FFF'}] &gt;&gt;&gt; pairs = zip(list_1 list_2) &gt;&gt;&gt; any(x != y for x y in pairs) True ```` Or to get the differing pairs: ````&gt;&gt;&gt; [(x y) for x y in pairs if x != y] [({'key3': 'EEE' 'key2': 'BBB' 'key1': 'AAA' 'unique_id': '001'} {'key3': 'EEE' 'key2': 'DDD' 'key1': 'AAA' 'unique_id': '001'})] ```` You can even get the keys which do not match for each pair: ````&gt;&gt;&gt; [[k for k in x if x[k] != y[k]] for x y in pairs if x != y] [['key2']] ```` Possibly together with the associated values: ````&gt;&gt;&gt; [[(k x[k] y[k]) for k in x if x[k] != y[k]] for x y in pairs if x != y] [[('key2' 'BBB' 'DDD')]] ```` <strong>NOTE:</strong> In case you are input lists are not sorted yet you can do that easily as well: ````&gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; list_1 list_2 = [sorted(l key=itemgetter('unique_id')) for l in (list_1 list_2)] ````
reference file-like object in memory I am using python to run a terminal program call bedtools Bedtools takes file names as arguments However because I can only have 256 files open at once I am limited in my multithreading ability I was hoping to be able to send a file in memory to the terminal but it does not have a name like a SpooledTemporaryFile() Is there a way to get around this? example: ````f=tempfile NamedTemporaryFile(delete=True) region=tempfile SpooledTemporaryFile() region write(b'chr1\t1090917\t1136917\n') region seek(0) subprocess call(['/usr/local/bin/shuffleBed' '-incl' str(region) '-i' 'temp'+chromosome+'ShuffleMutations bed' '-g' 'hg19 genome'] stdout=f) ```` is there a away to give region a name so the terminal can find it?
Use NamedTemporaryFile to create the input file If you close it there should be no drain on file descriptors ````f=tempfile NamedTemporaryFile(delete=True) region=tempfile NamedTemporaryFile(delete=False) region write(b'chr1\t1090917\t1136917\n') region close() subprocess call(['/usr/local/bin/shuffleBed' '-incl' region name '-i' 'temp'+chromosome+'ShuffleMutations bed' '-g' 'hg19 genome'] stdout=f) ````
Synchronize a Linux system command and a while-loop in Python With the RaspberryPi system I have to synchronize a Raspbian system command (`raspivid -t 20000`) with a while loop that reads continuously from a sensor adn stores samples in an array The Raspbian command start a video recording by the RaspberryPi camera CSI module and I have to be sure that it starts at the same instant of the acquisition by the sensor I have seen many solution that have confused me among modules like `multiprocessing` `threading` `subprocess` ecc So far the only thing that I have understood is that the `os system()` function blocks execution of following python's commands placed in the script as long as it runs So if I try with: ````import os import numpy as np os system("raspivid -t 20000 /home/pi/test h264") data = np zeros(20000 dtype="float") #memory pre-allocation supposing I have to save 20000 samples from the sensor (1 for each millisecond of the video) indx=0 while True: sens = readbysensor() #where the readbysensor() function is defined before in the script and reads a sample from the sensor data[indx]=sens if indx==19999: break else: indx+=1 ```` that while-loop will run only when the `os system()` function will finish But as I wrote above I need that the two processes are synchronized and work in parallel Any suggestion?
Just add an `&amp;` at the end to make the process detach to the background: ````os system("raspivid -t 20000 /home/pi/test h264 &amp;") ```` According to `bash` man pages: <blockquote> If a command is terminated by the control operator &amp; the she will executes the command in the background in a subshell The she will does not wait for the command to finish and the return status is 0 </blockquote> Also if you want to minimize the time it takes for the loop to start after executing `raspivid` you should allocate your `data` and `indx` prior to the call: ````data = np zeros(20000 dtype="float") indx=0 os system("raspivid -t 20000 /home/pi/test h264 &amp;") while True: # ```` <strong>Update:</strong> Since we discussed further in the comments it is clear that there is no really a need to start the loop "at the same time" as `raspivid` (whatever that might mean) because if you are trying to read data from the I2C and make sure you do not miss any data you will be best of starting the reading operation prior to running `raspivid` This way you are certain that in the meantime (however big of delay there is between those two executions) you are not missing any data Taking this into consideration your code could look something like this: ````data = np zeros(20000 dtype="float") indx=0 os system("(sleep 1; raspivid -t 20000 /home/pi/test h264) &amp;") while True: # ```` This is the simplest version in which we add a delay of 1 second before running `raspivid` so we have time to enter our `while` loop and start waiting for I2C data This works but it is hardly a production quality code For a better solution run the data acquisition function in one thread and the `raspivid` in a second thread preserving the launch order (the reading thread is started first) Something like this: ````import Queue import threading import os # we will store all data in a Queue so we can process # it at a custom speed without blocking the reading q = Queue Queue() # thread for getting the data from the sensor # it puts the data in a Queue for processing def get_data(q): for cnt in xrange(20000): # assuming readbysensor() is a # blocking function sens = readbysensor() q put(sens) # thread for processing the results def process_data(q): for cnt in xrange(20000): data = q get() # do something with data here q task_done() t_get = threading Thread(target=get_data args=(q )) t_process = threading Thread(target=process_data args=(q )) t_get start() t_process start() # when everything is set and ready run the raspivid os system("raspivid -t 20000 /home/pi/test h264 &amp;") # wait for the threads to finish t_get join() t_process join() # at this point all processing is completed print "We are all done!" ````
Python and sharepoint integration I am working on integrating python and sharepoint I am facing major problems with the GetItems and CopyIntoItems web service calls present in the Copy web service The library i am using to consume the service is Python-suds I want to know if 1 Are these are the right methods to be used for downloading/uploading files from/to sharepoint ? - If yes - the way i am using them is like this - i) client service GetItems('Shared Documents/filename doc') * I get a dictionray like structure that is something like this (reply){ GetItemResult = 0 } Obviously it is not returning any byte array stream - I am not sure what i am missing ii) I am not able to understand how to represent FieldInformationCollection and FieldInformation in Python and I am confused about how the method works in general with the different data types - If the answer is no - Wow i have to start from scratch what is the best way of doing it with python - suds ( a working example shud be gr8 ! )
Look at <a href="http://pypi python org/pypi/haufe sharepoint" rel="nofollow">http://pypi python org/pypi/haufe sharepoint</a> It provides a solid base for adding file operations
Can I use Dataflow for Python SDK from a Jupyter notebook? I want to play with <a href="https://github com/GoogleCloudPlatform/DataflowPythonSDK" rel="nofollow">Dataflow for Python SDK</a> from a Jupyter notebook I am not sure what are the dependencies needed and if I can spread the code over multiple notebook cells or not What are the steps involved?
Yes! There are no special steps involved For example using a Conda environment (recommended for using IPython/Jupyter notebooks) the commands to start a Jupyter notebook are: - conda create -n TESTENV jupyter - source activate TESTENV - pip install <a href="https://github com/GoogleCloudPlatform/DataflowPythonSDK/archive/v0 2 3 tar gz" rel="nofollow">https://github com/GoogleCloudPlatform/DataflowPythonSDK/archive/v0 2 3 tar gz</a> - jupyter notebook The commands above install version v0 2 3 of Python Dataflow Please change it to the version desired In the first notebook cell execute the following import statement: import google cloud dataflow as df Now you are all set You can spread the workflow code over multiple cells Check out the following notebook describing a very simple workflow: <a href="https://github com/silviulica/WorkflowExamples/blob/master/notebooks/HelloWorld ipynb" rel="nofollow">https://github com/silviulica/WorkflowExamples/blob/master/notebooks/HelloWorld ipynb</a>
What important political issues relate to infliction of pain?
null
Python: How do I split a text file and place into VB equivalent of an array? I have a text file 1 8Mb in size It is a data file 1974-present of daily values A typical line of data looks like this ```` 1979 12 5 1 345678 0 1234985 5 0 56342145 Final_value 1979 12 6 0 0 0 0 Missing_value 1979 12 7 1 928345 0 4784356 8 1 76942542 Preliminary_value ```` Each day has this same kind of setup to with everything situated into columns I want to be able to process the data taking average values over a period time graphing the data etc There are two header lines in the text file that would have to be taken off first otherwise all the data looks the same What is best way to go about splitting off the data into ??? and then being able to read the separate bits of individual data and work them I am kind of really lost in this situation In VB it would be easy but I am not use enough to Python yet to be able to even figure out what the proper term is to use instead of array I want each element to a an 'array' of its own and each of them is going to have something like 12 000+ elements as of the current date
Install `pandas` then simply read the file use `pandas read_table`: ````import pandas as pd data_frame = pd read_table('test_data txt' sep='\s+' header=None) data_frame columns = ['year' 'month' 'day' 'n1' 'n2' 'n3' 'n4' 'type'] data_frame ```` <img src="http://i stack imgur com/boHwh png" alt="enter image description here"> As a starting point you might want to try `data_frame describe()` There are many functions to aggregate or summarize the data For more information <a href="http://pandas pydata org/pandas-docs/stable/" rel="nofollow">check out the documentation</a>
When did the Romantic era end?
the early 20th century
Test if collections Mapping is equal to other mapping or dict I have written a custom mapping class that inherits from `collections Mapping` Is there an easy way to test if an instance's data is equal to another mapping object e g `dict`?
Sure Write `__eq__` and `__ne__` methods that perform this comparison
mysql-python install with Percona I have Percona Server installed on CentOS I want to install mysql-python but I am getting this error EnvironmentError: mysql_config not found There is no such file for Percona Server How can I install mysql-python to connect to Percona mysql ?
You can get mysql_config by running: ````yum install Percona-XtraDB-Cluster-devel ```` Once you have this go ahead and install mysql-python: ````yum install mysql-python ```` I searched a lot of google before I found this here at: <a href="http://www percona com/forums/questions-discussions/percona-xtradb-cluster/11038-mysql-config-sysbench-percona-xtradb-cluster" rel="nofollow">http://www percona com/forums/questions-discussions/percona-xtradb-cluster/11038-mysql-config-sysbench-percona-xtradb-cluster</a>
Iterating through dictionary for tuples This is more for clarification: If I said: ````for key value in dictionary iteritems(): ```` This would actually give me keys and values rather than just each key being assigned to both "key" and "value" It is just something that has always confused me about Python?
For purposes of example the following two are equivalent: <h1>Example 1</h1> ````for item in dictionary: print(item dictionary[item]) ```` <h1>Example 2</h1> ````for k v in dictionary items(): print(k v) ```` However in Example 1 you do not have direct access to the `value` of the item itself only the key whereas in Example 2 you do have access to it in the form of `v` <h1>Terminal</h1> ````&gt;&gt;&gt; dictionary = {'a': 1 'b': 2 'c': 3} &gt;&gt;&gt; for item in dictionary: print(item dictionary[item]) b 2 c 3 a 1 &gt;&gt;&gt; for k v in dictionary items(): print(k v) b 2 c 3 a 1 ```` And of course `k v` are arbitrary as `k` and `v` can be anything e g : ````&gt;&gt;&gt; for abc xyz in dictionary items(): print(abc xyz) b 2 c 3 a 1 ````
What do homomorphic flowers have to make it harder to be pollinated by animals?
null
Python Regex Help Needed (Basic) I need a python regex which can help me eliminate illegal characters inside a word The conditions are as such: - The first character must be a-z only - All characters in the word should only be a-z (lower case) plus apostrophe ' and hyphen - - The last character must be a-z or apostrophe ' only - You can assume that the word is always lower-case Test data: ```` s = "there is' -potato ' around- 'the 'farm-" ```` Expected output: ````&gt;&gt;&gt;print(s) there is' potato all' around the farm ```` My code is currently as such but it does not work correctly: ````newLine = re findall(r'[a-z][-\'a-z]*[\'a-z]?' s) ```` Any assistance would be greatly appreciated! Thanks!
Just match only the chars you do not want and remove ith through `re sub` ````&gt;&gt;&gt; import re &gt;&gt;&gt; s = """potato -potato 'human' potatoes-""" &gt;&gt;&gt; m = re sub(r"(?m)^['-]|-$" r'' s) &gt;&gt;&gt; print(m) potato potato human' potatoes ```` <strong>OR</strong> ````&gt;&gt;&gt; m = re sub(r"(?m)^(['-])?([a-z'-]*?)-?$" r'\2' s) &gt;&gt;&gt; print(m) potato potato human' potatoes ```` <a href="http://regex101 com/r/zK8jF5/3" rel="nofollow">DEMO</a>
When did Haas give birth to Tito's son?
1941
AttributeError: class Tk has no attribute 'tk' hey guys i stuck on simple python GUI program ````import Tkinter as tk window = tk Tk text_box = tk Entry(window) def save_text(): str1 = text_box get() fx = open("file1 txt" "w") fx write(str1) fx close() btn1 = tk Button(window text="Save" command="save_text") text_box pack() btn1 pack() window mainloop() ```` i this error: ````Traceback (most recent call last): File "C:/Users/Saket/PycharmProjects/guiform1/firstform py" line 5 in <module&gt; text_box = tk Entry(window) File "C:\Python27\lib\lib-tk\Tkinter py" line 2385 in __init__ Widget __init__(self master 'entry' cnf kw) File "C:\Python27\lib\lib-tk\Tkinter py" line 1965 in __init__ BaseWidget _setup(self master cnf) File "C:\Python27\lib\lib-tk\Tkinter py" line 1943 in _setup self tk = master tk AttributeError: class Tk has no attribute 'tk' ```` Anybody having idea what am i doing wrong please help me??
You have to call `tk Tk` to create an instance: ````window = tk Tk() ^^ ```` You will then have a `tk Tk`-type object to interact with
Partially unpacking of tuple in Numpy array indexing In order to solve a problem which is only possible element by element I need to combine NumPy's tuple indexing with an explicit slice ````def f(shape n): """ :param shape: any shape of an array :type shape: tuple :type n: int """ x = numpy zeros( (n ) shape ) for i in numpy ndindex(shape): # i = (k l ) x[: k l ] = numpy random random(n) ```` `x[: *i]` results in a `SyntaxError` and `x[: i]` is interpreted as `numpy array([ x[: k] for k in i ])` Unfortunally it is not possible to have the n-dimension as last (`x = numpy zeros(shape+(n ))` for `x[i] = numpy random random(n)`) because of the further usage of `x` EDIT: Here some example wished in comment ````&gt;&gt;&gt; n shape = 2 (3 4) &gt;&gt;&gt; x = np arange(24) reshape((n )+(3 4)) &gt;&gt;&gt; print(x) array([[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]]) &gt;&gt;&gt; i = (1 2) &gt;&gt;&gt; print(x[ ??? ]) # '???' expressed by i with any length is the question array([ 6 18]) ````
If I understand the question correctly you have a multi-dimensional numpy array and want to index it by combining a `:` slice with some number of other indices from a tuple `i` The index to the numpy array is a tuple so you can basically just combine those 'partial' indices to one tuple and use that as the index A naive approach might look like this ````x[ (: ) i ] = numpy random random(n) # does not work ```` but this will give a syntax error Instead of `:` you have to use the <a href="https://docs python org/2/library/functions html#slice" rel="nofollow">`slice`</a> builtin ````x[ (slice(None) ) i ] = numpy random random(n) ````
Import statement: Config file Python I am maintaining a dictionary and that is loaded inside the config file The dictionary is loaded from a JSON file <strong>In config py</strong> ````name_dict = json load(open(dict_file)) ```` I am importing this config file in several other scripts(file1 py file2 py filen py) using ````import config ```` statement My question is when will the config py script be executed ? I am sure it will not be executed for every import call that is made inside my multiple scripts But what exactly happens when an import statement is called
The top-level code in a module is executed once the first time you `import` it After that the module object will be found in `sys modules` and the code will not be re-executed to re-generate it There are a few exceptions to this: - `reload` obviously - Accidentally importing the same module under two different names (e g if the module is in a package and you have got some directory in the middle of the package in `sys path` you could end up with `mypackage mymodule` and `mymodule` being two copies of the same thing in which case the code gets run twice) - Installing import hooks/custom imported that replace the standard behavior - Explicitly monkeying with `sys modules` - Directly calling functions out of `imp`/`importlib` or the like - Certain cases with `multiprocessing` (and modules that use it indirectly like `concurrent futures`) <hr> For Python 3 1 and later this is all described in detail under <a href="http://docs python org/3/reference/import html" rel="nofollow">The import system</a> In particular look at the Searching section (The `multiprocessing`-specific cases are described for that module ) For earlier versions of Python you pretty much have to infer the behavior from a variety of different sources and either reading the code or experimenting However the well-documented new behavior is intended to work like the old behavior except in specifically described ways so you can usually get away with reading the 3 x docs even for 2 x <hr> Note that <them>in general</them> you do not want to rely on whether top-level code in the module is run once or multiple times For example given a top-level function definition as long as you never compare function objects or rebind any globals that it (meaning the definition itself not just the body) depends on it does not make any difference However there are some exceptions to that and loading start-time config files is a perfect example of an exception
How to get next form content in python This is my first script(also post) in python In script i filled form content and submit it So After submitting form it will generate result on next form Now the issue is next form link not static it will changed according data entered in previous form See below some code of my script ````import mechanize browser = mechanize Browser() browser open('https://example com') browser select_form(nr=1) browser form["MyIDNO"] = '000D6F0004C46834' browser form["RuleID"] = '0109108301234567890A' browser submit() ```` Above code just fill data and submit it Now i want next opened form content I am getting dynamic link as below <a href="https://example com/index php?option=com_gencert&amp;task=results&amp;tmpl=gencert&amp;cfId=189537&amp;MyIDNO=000D6F0004C46834&amp;RuleID=0109108301234567890A&amp;esKey=" rel="nofollow">https://example com/index php?option=com_gencert&amp;task=results&amp;tmpl=gencert&amp;cfId=189537&amp;MyIDNO=000D6F0004C46834&amp;RuleID=0109108301234567890A&amp;esKey=</a> As seen in above link it will generated based on `MyIDNO` and `RuleID` I tried one solution as below ````html = browser response() read() print html ```` It will print all content in html form Now i need to parse specific data See below some output ````<tr&gt; <td&gt;<strong&gt;User key: </strong&gt;</td&gt; <td&gt;0200fde8a7f3d1084224962a4e7c54e69ac3f04da6b8</td&gt; </tr&gt; <tr&gt; <td&gt;<strong&gt;Institute id: </strong&gt;</td&gt; <td&gt; 030780ffa3641183273ad548ae09872f9dcf4b0c4267<br/&gt;000d6f0004c468345445535453454341010910830123<br/&gt;4567890a<br/&gt; </td&gt; </tr&gt; <tr&gt; <td&gt;<strong&gt;part id:</strong&gt;</td&gt; <td&gt;00ecd01536ff66296f9d572219d7acac02d59b24c6</td&gt; </tr&gt; <tr&gt; ```` From above content i need below output ````User key: 0200fde8a7f3d1084224962a4e7c54e69ac3f04da6b8 Institute id: 030780ffa3641183273ad548ae09872f9dcf4b0c4267000d6f0004c4683454455354534543410109108301234567890a part id: 00ecd01536ff66296f9d572219d7acac02d59b24c6 ````
Once you have the html document you can use <a href="http://www crummy com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup</a> for getting the data you need ````from bs4 import BeautifulSoup # submit form as per your snippet html = browser response() read() soup = BeautifulSoup(html 'html parser') # Process the content with BeautifulSoup ````
Pipe output of python script I am running ` /sample py --url http://blah com` without error though if I run ` /sample py --url http://blah com | wc -l` or similar I receive an error: `UnicodeEncodeError: 'ascii' codec cannot encode character you'\u200f' in position 0: ordinal not in range(128)` How do I make a python script compatible with my terminal commands? I keep seeing reference to `sys stdin isatty` though its use case appears to be opposite
Try: ````( /sample py --url http://blah com) | wc -l ```` This spawns a subshell to run your python script then pipes the output from `stdout` to `wc`
Google application engine Datastore - any alternatives to aggregate functions and group by? As is mentioned in the doc for google app engine it does not support group by and other aggregation functions Is there any alternatives to implement the same functionality? I am working on a project where I need it on urgent basis being a large database its not efficient to iterate the result set and then perform the logic Please suggest Thanks in advance
The best way is to populate the summaries (aggregates) at the time of write This way your reads will be faster since they just read - at the cost of writes which will have to update the summaries if its likely to be effected by the write Hopefully you will be reading more often than writing/updating summaries
Shortest (and Least Dangerous) Path on a Graph I am working on an assignment that has me traversing a simple square graph with the goal of accumulating the least amount of danger The end points are simple: from the top left vertex to the bottom right I am restricted to moving horizontally and vertically between vertexes Each room in the dungeon (each vertex on the graph) has a specified danger level Example: ````0 7 2 5 4 0 > 1 > 1 > 2 > 2 > 1 > 3 > 1 > 0 1 5 1 2 1 1 2 2 1 1 1 9 5 3 5 1 1 9 1 0 ```` I have been throwing around the idea of using a Priority Queue but I still do not know how exactly I would use that P Q in the first place I could try Dijkstra's Algorithm but I am not calculating distance between nodes; rather I am calculating minimized danger That being said am I right to assume that the danger in one room is the weight on the edge between two nodes? I was hoping someone could give me an idea as to how I could approach this problem I will be writing the program in Python if that is any help
It is been a while since I do these problems but I am pretty sure the algorithm to use here is Dijkstra's From Wikipedia: <blockquote> For a given source node in the graph the algorithm finds the shortest path between that node and every other It can also be used for finding the shortest paths from a single node to a single destination node by stopping the algorithm once the shortest path to the destination node has been determined [The implementation based on a min-priority queue] is asymptotically the fastest known single-source shortest-path algorithm for arbitrary directed graphs with unbounded non-negative weights </blockquote> <a href="http://en wikipedia org/wiki/Dijkstra%27s_algorithm" rel="nofollow">http://en wikipedia org/wiki/Dijkstra%27s_algorithm</a> Your intuition is correct but you were tripped up by the definition of "distance" in this case Instead of thinking of the problem in terms of danger simply convert "danger" to "distance" in your mind The problem of finding the least dangerous path between the top-left and bottom-right nodes of the graphs then becomes finding the shortest path between those nodes which is precisely what Dijkstra's is supposed to solve
How show interactive charts in a GTK window? I need to do some charts and it will be so much better if they are interactive I want something like <a href="http://www highcharts com/demo/line-basic" rel="nofollow">that</a> So I look for packages and <a href="http://bokeh pydata org/en/latest/" rel="nofollow">Bokeh</a> seems interesting But once I will have my beautiful chart How to insert it in a Gtk window?
You can use <a href="http://webkitgtk org/" rel="nofollow">WebKitGtk</a> to embed web pages
How to mock MongoClient for python unit test? I have following piece of code to UT which makes me in trouble: ```` def initialize(): try : self client = MongoClient("127 0 0 1" 27017) self conn = self client["DB_NAME"] except Exception: print "Except in initialize!" return False return True ```` I write following test case to cover the above function hope to get return value "True": ````def mock_mongodb_mongoclient_init(self para1 para2): pass def mock_mongodb_mongoclient_getitem(self name): return {"DB_NAME":"Something"} def test_mongodb_initialize_true(self): self patcher1 = patch('pymongo MongoClient __init__' new=self mock_mongodb_mongoclient_init) self patcher2 = patch('pymongo MongoClient __getitem__' new=self mock_mongodb_mongoclient_getitem) self patcher1 start() self patcher2 start() self assertEqual(initialize() True) self patcher1 stop() self patcher2 stop() ```` But this never works! It always report "Exception in initialize!"! and return "False" How could I UT this MongoClient and makes the function return "True"?
For simply pass the initialize() we can mock the pymongo MongoClient as following: ````import unittest import pymongo from mock import patch class MyMongo(object): def initialize(self): try : self client = pymongo MongoClient("127 0 0 1" 27017) self conn = self client["DB_NAME"] except Exception: print "Except in initialize!" return False return True class TestMyMongo(unittest TestCase): def test_mongodb_initialize_true(self): with patch('pymongo MongoClient') as mock_mongo: self mymongo = MyMongo() self assertEqual(self mymongo initialize() True) ```` However I am not sure if you are trying to mock the MongoClient or just the MongoClient <strong>init</strong> part?
checkin python if a list of dictonaries does NOT contain a specific value This is some what of a supplementary question to my recent query about searching dictionary items in a list: <a href="http://stackoverflow com/questions/8695177/check-if-python-dictionary-contains-value-and-if-so-return-related-value">Check if python dictionary contains value and if so return related value</a> I have an array containing dictionaries in the format: ````fileList = [ {"fileName": "file1 txt" "fileMod": "0000048723"} {"fileName": "file2 txt" "fileMod": "0000098573"} ] ```` I was able to return a list of fileMod values for existing items in the fileList using a rather neat list comprehension as suggested: ````fileMod = [item['fileMod'] for item in fileList if item['fileName'] == filename] ```` This returns a value if there is a matching filename but I forgot to include that I also need to know when there is a filename that does not match any of the entries in filelist I am sure this should be simple but I think I have just been looking at it too long to see the woods for the trees
<strong>"checkin python if a list of dictonaries does NOT contain a specific value"</strong> ````if not any(item for item in fileList if item['fileName'] == filename): ```` returns true if no dictionary in your list fulfills the condition This is possibly faster than checking the whole `fileMod` because it stops as soon as a match is found <hr> <strong>"This returns a value if there is a matching filename but I forgot to include that I also need to know when there is a filename that does not match any of the entries in filelist "</strong> (a different question?) ````fileMod = [] fileBad = [] for item in fileList: if item['fileName'] == filename: fileMod append(item['fileMod']) else: fileBad append(item['fileMod']) ```` or ````fileMod = {True: [] False: []} # a dictionary of lists for item in fileList: fileMod[item['fileMod'] == filename] append(item['fileMod']) ```` This last code returns a dict of lists: `fileMod[True]` is a list of positive founds `fileMod[False]` is a list of negative founds
How much was spent on health per capita after 2004?
null
Balanced brackets using Python I want to implement an algorithm that can find errors in the usage of brackets in string I read several examples and came to idea of creating special class for brackets with function of matching opening and closing brackets ````class Bracket: def __init__(self bracket_type position): self bracket_type = bracket_type self position = position def Match(self c): if self bracket_type == '[' and c == ']': return True if self bracket_type == '{' and c == '}': return True if self bracket_type == '(' and c == ')': return True return False ```` Next I am using stack whether sting is balanced or not I created a loop going through every symbol and if symbol is a bracket I want to assign it to my special class in order to match for closing one further ````if __name__ == "__main__": text = sys stdin read() opening_brackets_stack = [] Balanced = True bracket = Bracket for i symbol in enumerate(text): if symbol in ['(' '[' '{']: bracket bracket_type = symbol opening_brackets_stack append(symbol) elif bracket Match(bracket bracket_type symbol) == True: opening_brackets_stack pop(symbol) elif len(opening_brackets_stack) == 0: True ```` But unfortunately that does not work ````AttributeError: 'str' object has no attribute 'bracket_type' ```` Why that is happening? And what can you say about structure of algorithm - is it right?
If you want `bracket` to be an instance of the class `Bracket` you will need to instantiate it: ````bracket = Bracket() # note these ^^ ```` You are also going to get an error on `bracket Match()` regarding passing too many arguments You should call that method like so: ````bracket Match(symbol) ```` since the instance of `Bracket()` (`bracket`) is implicitly passed as `self`
fabric python install problem Just installed fabric trying to use to same fabfile that works on a different server getting this error here: ````Traceback (most recent call last): File "/var/lib/python-support/python2 6/fabric py" line 1211 in main load(fabfile fail='warn') File "/var/lib/python-support/python2 6/fabric py" line 467 in load execfile(filename) File "fabfile py" line 2 in <module&gt; from fabric api import * ImportError: No module named api ````
Looks like you have different versions of Fabric on those servers they changed the module structure recently
WxPython differences between Windows and Linux The tutorials I have found on WxPython all use examples from Linux but there seem to be differences in some details For example in Windows a Panel behind the widgets is mandatory to show the background properly Additionally some examples that look fine in the tutorials do not work in my computer So do you know what important differences are there or maybe a good tutorial that is focused on Windows? **EDIT: ** I just remembered this: Does anybody know why when subclassing wx App an OnInit() method is required rather than the more logical `__init__`()?
<blockquote> <strong>EDIT:</strong> I just remembered this: Does anybody know why when subclassing wx App an OnInit() method is required rather than the more logical `__init__()`? </blockquote> I use `OnInit()` for symmetry: there is also an `OnExit()` method Edit: I may be wrong but I do not think using `OnInit()` is required
Create function in Python depending of x which returns a composition of functions depending of x I want to apply a function `f` to a data `X` beign `X` a numpy array The problem is that `f` is a sort of "linear combination" of functions let us say `f_i` and each of this functions depends also of another parameter let us say: ````param = 1 0 #same param for every f_i call def f(x): for xi in range(len(x)): cummulate sum of f_i(x xi param) return the result of the loop which depends of (x) ```` Any help with this? I tried sympy but the `f_i` are not trivial math function but a combination of them
You have got a few approaches here First and easiest is to pass in `params` as an argument which could be an array of extra arguments for each function: ````def f(x params): for i in len(x): # Pass in params[i] to f_i ```` In the case that you need `f` to only accept one argument you can do the second approach using a <a href="http://ynniv com/blog/2007/08/closures-in-python html" rel="nofollow">closure</a>: ````def f_creator(params): def closure(x): for i in len(x): # Pass in params[i] to f_i return closure f = f_creator( params for f_is go in here ) # Use f for any special calculations that you need ```` Finally if these parameters are constant and do not change over the course of your program you can set them to global constants This approach is not recommended because it makes it difficult to test things and makes the code less robust to change ````params = def f(x): for i in len(x): # Calculate f_i using global params ````
Matplotlib: Is it possible to create an new axis with a given y-offset without creating subplot? With the help of <strong>sankey-toolbox</strong> in <strong>Matplotlib</strong> we can plot sankey-diagrams automaticly: The position of a sankey-object is automaticly calculated based on the position of its prior-object and cannot be given manually; and when a sankey-diagram is initialized the position of the first sankey-object will be assigned with the input of an axis (the (0 0)-point will be the center-point of this object) And Here is the situation: i want to draw two sankey diagrams with a given y-offset and several ports of the two diagrams should be connected Therefore are two coordinate systems with y-offset in the same subplot required I have tried the '<strong>add_axes</strong>' method but with this method a new subplot is created and there will be a graphic scaling problem Now this is the question: Is it possible to create a new coordinate system with a given y-offset without creating subplot?
Not really a complete answer but it might help you to find the solution: `sankey add()` supports a `transform` keyword argument Depending on your figure create a new `transform` instance and use it for the shifted part of your figure: ````offset = transforms ScaledTranslation(0 0 0 5 fig dpi_scale_trans) new_transform = ax transData offset sankey add(flows=[-0 25 0 15 0 1] fc='#37c959' label='two' orientations=[-1 -1 -1] prior=0 connect=(0 0) transform = new_transform) ```` In order to create the new transform the helper function `matplotlib transforms offset_copy()` may also be useful: ````new_transform = offset_copy(ax transData fig=fig x = 0 05 y=0 10 units='inches') ````
Python count Null and not Null values in Dataframe I have a dataframe ````Date Name 1995 Harry 1995 John 1997 NaN 1995 NaN 1998 Nina 1998 NaN 1997 Carrie ```` I need to count a NaN/(not NaN) values for each Date So the output should be ````Date Nan/NaN+notNaN 1995 1/3 1997 1/2 1998 1/2 ```` I was trying with `df groupby(['Date']) agg({'Name' : 'count'})` but can i do the same with `df groupby(['Date']) agg({'df Name isnull()' : 'count'})` or smth like that?
What about something like that: ````In [52]: df groupby('Date') agg({'Name': lambda x: x isnull() sum() 'Date': 'count'}) Out[52]: Name Date Date 1995 1 3 1997 1 2 1998 1 2 ```` Or you could do following: ````In [60]: df groupby('Date') agg({'Name': lambda x: x isnull() sum() astype(str) '/' str(x size)}) Out[60]: Name Date 1995 1/3 1997 1/2 1998 1/2 ```` Or with `format`: ````In [62]: df groupby('Date') agg({'Name': lambda x: '{}/{}' format(x isnull() sum() len(x))}) Out[62]: Name Date 1995 1/3 1997 1/2 1998 1/2 ````
When was the Cyber Security Cooperation Program shut down?
null
On what day did Darlan die?
December 24
How many members does the contemporary Communist Part of China have?
eighty million members
Tkinter Multiprocessing and audio input from pyaudio I am writing a program that is continuously taking input from a microphone using pyaudio and every 5 seconds does some calculations after which it updates some matplotlib plot in a tkinter widget I got so far: ````import threading from array import array from Queue import Queue Full import pyaudio from matplotlib import pyplot as plt import numpy as np CHUNK_SIZE = 1000 MIN_VOLUME = 500 PLOT_CHUNK_SIZE = CHUNK_SIZE * 5 BUF_MAX_SIZE = CHUNK_SIZE * 10 PLOT_MAX_SIZE = PLOT_CHUNK_SIZE * 10 big_chunk = np array( []) def main(): stopped = threading Event() q = Queue(maxsize=int(round(BUF_MAX_SIZE / CHUNK_SIZE))) plot_queue = Queue(maxsize=int(round(PLOT_MAX_SIZE / PLOT_CHUNK_SIZE))) listen_t = threading Thread(target=listen args=(stopped q)) listen_t start() record_t = threading Thread(target=record args=(stopped q plot_queue)) record_t start() plot_t = threading Thread(target=plot_chunk args=(stopped plot_queue)) plot_t start() try: while True: listen_t join(0 1) record_t join(0 1) plot_t join(0 1) except KeyboardInterrupt: stopped set() listen_t join() record_t join() plot_t join() def record(stopped q plot_queue): global big_chunk p ready while True: if stopped wait(timeout=0): break vol = max(q get()) if vol &gt;= MIN_VOLUME: big_chunk = np append(big_chunk q get()) print 'new chunk' if len(big_chunk) &gt; PLOT_CHUNK_SIZE-1: plot_queue put(big_chunk) big_chunk = np array( []) else: print "-" def plot_chunk(stopped plot_queue): while True: if stopped wait(timeout=0): break features = plot_queue get() my_features = do_calculations(features) plt imshow(my_features) def listen(stopped q): stream = pyaudio PyAudio() open( format=pyaudio paInt16 channels=1 rate=44100 input=True frames_per_buffer=1024 ) while True: if stopped wait(timeout=0): break try: q put(array('h' stream read(CHUNK_SIZE))) except Full: pass # discard if __name__ == '__main__': main() ```` I tried to do it with threads and it works fine except for the plotting It seems matplotlib and tkinter do not work with threads and multiprocessing would be the way to go So I tried this: ````import Tkinter as Tk import multiprocessing from Queue import Empty Full import time import pyaudio import array class GuiApp(object): def __init__(self q): self root = Tk Tk() self root geometry('300x100') self text_wid = Tk Text(self root height=100 width=100) self text_wid pack(expand=1 fill=Tk BOTH) self root after(100 self CheckQueuePoll q) def CheckQueuePoll(self c_queue): try: str = c_queue get(0) self text_wid insert('end' str) except Empty: pass finally: self root after(100 self CheckQueuePoll c_queue) # Data Generator which will generate Data def GenerateData(q): for i in range(10): print "Generating Some Data Iteration %s" %(i) time sleep(0 1) q put("Some Data from iteration %s \n" %(i)) def listen( q): CHUNK_SIZE = 100 stream = pyaudio PyAudio() open( format=pyaudio paInt16 channels=1 rate=44100 input=True frames_per_buffer=1024 ) while True: try: q put(array('h' stream read(CHUNK_SIZE))) except Full: pass # discard if __name__ == '__main__': # Queue which will be used for storing Data q = multiprocessing Queue() q2 = multiprocessing Queue() q cancel_join_thread() # or else thread that puts data will not term q2 cancel_join_thread() # or else thread that puts data will not term gui = GuiApp(q) t1 = multiprocessing Process(target=GenerateData args=(q )) t2 = multiprocessing Process(target=listen args=(q2 )) t1 start() t2 start() gui root mainloop() t1 join() t2 join() ```` Where I get the following error: ````q put(array('h' stream read(CHUNK_SIZE))) TypeError: 'module' object is not callable ```` Any Ideas?
The problem is that `array` in your code is a module which is not callable (as the error message says) <strong>Either</strong> change your import to ````from array import array ```` <strong>or</strong> change your code to ````array array( ) ````
Python change Accept-Language using requests I am new to python and trying to get some infos from IMDb using requests library My code is capturing all data (e g movie titles) in my native language but i would like to get them in english How can i change the accept-language in requests to do that?
All you need to do is define your own headers: ````import requests url = "http://www imdb com/title/tt0089218/" headers = {"Accept-Language": "en-US en;q=0 5"} are = requests get(url headers=headers) ```` You can add whatever other headers you would like to modify as well
Adding a text to an image in Python Is there the most popular way of adding a text on an image in Python? I found a few completely different approaches this seems to be best but it does not work: ````from PIL import Image from PIL import ImageFont from PIL import ImageDraw img = Image open("/full_path/1 jpg") draw = ImageDraw Draw(img) font = ImageFont truetype("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C ttf" 16) draw text((0 0) "Sample Text" (255 255 255) font=font) img save('/full_path/sample-out jpg') ```` After its running the picture still does not have a text on it
try this: ````import PIL from PIL import ImageFont from PIL import Image from PIL import ImageDraw img=Image open("pathToImage") font = ImageFont truetype("pathToFont" 10) draw = ImageDraw Draw(img) draw text((0 0) "This is a test" (255 255 0) font=font) draw = ImageDraw Draw(img) draw = ImageDraw Draw(img) img save("a_test png") ````
framework for creating local environment for native libraries I write code that often depends on native libraries on linux or mac os Usually I do not have permissions to install the respective native lib in the system so I resort to creating a local folder ~/env where I install my libs I than add this to my PATH LD_LIBRARY_PATH C_INCLUDE_DIRS etc I really like <strong>homebrew</strong> and I was wondering if there is a framework (or a tool) like that (hopefully in python :) ) that will ease the process of adding native dependencies to my local environemt on both linux and mac Thanks! Cheers
GNU autoconf automake libtool will do the job nicely and in a very clean and portable manner but you will need a good amount of time and work to make it working correctly You may also be interested in using WAF: <a href="http://code google com/p/waf/" rel="nofollow">http://code google com/p/waf/</a>
The OSHA claimed that the Tajik government censored what?
null
Community, or Nation are direct translations of what word in reference to Islam?
Ummah