input_text
stringlengths
1
40.1k
target_text
stringlengths
1
29.4k
What kind of plane was the Red Wing?
biplane
It should be faster cProfile says it is faster but the program actually runs slower Hope you can help because this one is giving me a real headache I am developping a small predator-prey simulation in python(3 3) which uses a simple feedforward neural network Today I changed the function which performed each "tick" of the brain from pure python to numpy arrays in order to optimize it for when I use bigger brains I checked the performance speed (of the whole main program "loop") with cProfile and as I expected the "tick" function (inside the brain class) was faster However when running the program I noticed that actually using numpy was slower (100 loops in ~12 seconds vs 100 loops in ~9) Why could this be? Here is the code: Original implementation: ````class Brain: def __init__(self inputs hidden outputs): self input_num = inputs self hidden_num = hidden self output_num = outputs self h_weight = [] self o_weight = [] for _ in range(self input_num * self hidden_num): self h_weight append(random random()*2-1) for _ in range(self hidden_num * self output_num): self o_weight append(random random()*2-1) def tick(self): input_num = self input_num hidden_num = self hidden_num output_num = self output_num hidden = [0]*hidden_num output = [0]*output_num inputs = self input h_weight = self h_weight o_weight = self o_weight e = math e count = -1 for x in range(hidden_num): temp = 0 for y in range(input_num): count = 1 temp -= inputs[y] * h_weight[count] hidden[x] = 1/(1+e**(temp)) count = -1 for x in range(output_num): temp = 0 for y in range(hidden_num): count = 1 temp -= hidden[y] * o_weight[count] output[x] = 1/(1+e**(temp)) self output = output ```` New implementation (using numpy): ````class Brain: def __init__(self inputs hidden outputs): self input_num = inputs self hidden_num = hidden self output_num = outputs self h_weights = random random((self hidden_num self input_num)) self o_weights = random random((self output_num self hidden_num)) self h_activation = zeros((self hidden_num 1) dtype=float) self o_activation = zeros((self output_num 1) dtype=float) self i_output = zeros((self input_num 1) dtype=float) self h_output = zeros((self hidden_num 1) dtype=float) self o_output = zeros((self output_num 1) dtype=float) def tick(self): i_output = self input h_weights = self h_weights o_weights = self o_weights h_activation = dot(h_weights i_output) h_output = tanh(h_activation) o_activation = dot(o_weights h_output) o_output = tanh(o_activation) self output = o_output ```` And here is the main loop of the program which I have timed (ignore the other functions they have no influence on the "brain tick()" function) It is inside another class which is also irrelevant: ```` def update(self): GUI update() if not self pause: self tick = 1 if self tick % 1000 == 0: if self globalSelection: self newGeneration(self creatures) else: for specie in self species: if not specie isPlant: creatureList = [creature for creature in self creatures if creature specie == specie] self newGeneration(creatureList) for creature in self creatures: if not creature specie isPlant: if self useHunger and creature hunger < 1: creature hunger = 1/240 creature setInputs() creature brain tick() creature move(creature brain output[0]*50-25 creature brain output[1]*8) creature interactions() threading Timer(self tickrate self update) start() ```` Right now the brain is set to 5 inputs 200 hidden and 2 output just for testing speed Here are the results of cProfile: Original: ```` 3312 function calls in 0 094 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0 000 0 000 0 094 0 094 <string&gt;:1(<module&gt;) 200 0 006 0 000 0 007 0 000 __init__ py:263(move) 200 0 024 0 000 0 024 0 000 __init__ py:286(setInputs) 200 0 001 0 000 0 001 0 000 __init__ py:360(interactions) 200 0 033 0 000 0 033 0 000 __init__ py:415(tick) 1 0 005 0 005 0 094 0 094 __init__ py:46(update) 1 0 007 0 007 0 020 0 020 __init__ py:471(update) 1 0 000 0 000 0 000 0 000 _weakrefset py:79(add) 3 0 000 0 000 0 000 0 000 threading py:127(__init__) 1 0 000 0 000 0 000 0 000 threading py:160(_release_save) 1 0 000 0 000 0 000 0 000 threading py:163(_acquire_restore) 1 0 000 0 000 0 000 0 000 threading py:166(_is_owned) 1 0 000 0 000 0 000 0 000 threading py:175(wait) 2 0 000 0 000 0 000 0 000 threading py:297(__init__) 1 0 000 0 000 0 000 0 000 threading py:305(is_set) 1 0 000 0 000 0 000 0 000 threading py:325(wait) 1 0 000 0 000 0 000 0 000 threading py:507(_newname) 1 0 000 0 000 0 000 0 000 threading py:534(__init__) 1 0 000 0 000 0 000 0 000 threading py:577(start) 1 0 000 0 000 0 000 0 000 threading py:775(daemon) 1 0 000 0 000 0 000 0 000 threading py:810(__init__) 1 0 000 0 000 0 000 0 000 threading py:887(current_thread) 225 0 002 0 000 0 002 0 000 {built-in method aacircle} 200 0 001 0 000 0 001 0 000 {built-in method aaline} 200 0 000 0 000 0 000 0 000 {built-in method abs} 4 0 000 0 000 0 000 0 000 {built-in method allocate_lock} 200 0 001 0 000 0 001 0 000 {built-in method atan2} 400 0 001 0 000 0 001 0 000 {built-in method cos} 1 0 000 0 000 0 094 0 094 {built-in method exec} 225 0 001 0 000 0 001 0 000 {built-in method filled_circle} 4 0 000 0 000 0 000 0 000 {built-in method filled_polygon} 1 0 000 0 000 0 000 0 000 {built-in method get_ident} 1 0 000 0 000 0 000 0 000 {built-in method get_pressed} 1 0 000 0 000 0 000 0 000 {built-in method get} 2 0 000 0 000 0 000 0 000 {built-in method len} 200 0 000 0 000 0 000 0 000 {built-in method radians} 1 0 000 0 000 0 000 0 000 {built-in method round} 400 0 001 0 000 0 001 0 000 {built-in method sin} 1 0 000 0 000 0 000 0 000 {built-in method start_new_thread} 1 0 006 0 006 0 006 0 006 {built-in method update} 5 0 000 0 000 0 000 0 000 {method 'acquire' of '_thread lock' objects} 1 0 000 0 000 0 000 0 000 {method 'add' of 'set' objects} 1 0 000 0 000 0 000 0 000 {method 'append' of 'list' objects} 2 0 000 0 000 0 000 0 000 {method 'blit' of 'pygame Surface' objects} 1 0 000 0 000 0 000 0 000 {method 'disable' of '_lsprof Profiler' objects} 1 0 001 0 001 0 001 0 001 {method 'fill' of 'pygame Surface' objects} 8 0 000 0 000 0 000 0 000 {method 'random_sample' of 'mtrand RandomState' objects} 2 0 000 0 000 0 000 0 000 {method 'release' of '_thread lock' objects} 3 0 000 0 000 0 000 0 000 {method 'render' of 'pygame font Font' objects} ```` New: ```` 3322 function calls in 0 068 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0 000 0 000 0 068 0 068 <string&gt;:1(<module&gt;) 200 0 005 0 000 0 006 0 000 __init__ py:265(move) 200 0 022 0 000 0 023 0 000 __init__ py:288(setInputs) 200 0 001 0 000 0 001 0 000 __init__ py:362(interactions) 200 0 005 0 000 0 014 0 000 __init__ py:417(tick) 1 0 005 0 005 0 068 0 068 __init__ py:47(update) 1 0 005 0 005 0 019 0 019 __init__ py:473(update) 1 0 000 0 000 0 000 0 000 _weakrefset py:79(add) 3 0 000 0 000 0 000 0 000 threading py:127(__init__) 1 0 000 0 000 0 000 0 000 threading py:160(_release_save) 1 0 000 0 000 0 000 0 000 threading py:163(_acquire_restore) 1 0 000 0 000 0 000 0 000 threading py:166(_is_owned) 1 0 000 0 000 0 000 0 000 threading py:175(wait) 2 0 000 0 000 0 000 0 000 threading py:297(__init__) 1 0 000 0 000 0 000 0 000 threading py:305(is_set) 1 0 000 0 000 0 000 0 000 threading py:325(wait) 1 0 000 0 000 0 000 0 000 threading py:507(_newname) 1 0 000 0 000 0 000 0 000 threading py:534(__init__) 1 0 000 0 000 0 000 0 000 threading py:577(start) 1 0 000 0 000 0 000 0 000 threading py:775(daemon) 1 0 000 0 000 0 000 0 000 threading py:810(__init__) 1 0 000 0 000 0 000 0 000 threading py:887(current_thread) 225 0 002 0 000 0 002 0 000 {built-in method aacircle} 200 0 001 0 000 0 001 0 000 {built-in method aaline} 200 0 001 0 000 0 001 0 000 {built-in method abs} 4 0 000 0 000 0 000 0 000 {built-in method allocate_lock} 200 0 000 0 000 0 000 0 000 {built-in method atan2} 400 0 001 0 000 0 001 0 000 {built-in method cos} 400 0 008 0 000 0 008 0 000 {built-in method dot} 1 0 000 0 000 0 068 0 068 {built-in method exec} 225 0 001 0 000 0 001 0 000 {built-in method filled_circle} 4 0 000 0 000 0 000 0 000 {built-in method filled_polygon} 1 0 000 0 000 0 000 0 000 {built-in method get_ident} 1 0 000 0 000 0 000 0 000 {built-in method get_pressed} 1 0 000 0 000 0 000 0 000 {built-in method get} 2 0 000 0 000 0 000 0 000 {built-in method len} 200 0 000 0 000 0 000 0 000 {built-in method radians} 1 0 000 0 000 0 000 0 000 {built-in method round} 400 0 001 0 000 0 001 0 000 {built-in method sin} 1 0 000 0 000 0 000 0 000 {built-in method start_new_thread} 1 0 005 0 005 0 005 0 005 {built-in method update} 5 0 000 0 000 0 000 0 000 {method 'acquire' of '_thread lock' objects} 1 0 000 0 000 0 000 0 000 {method 'add' of 'set' objects} 1 0 000 0 000 0 000 0 000 {method 'append' of 'list' objects} 2 0 000 0 000 0 000 0 000 {method 'blit' of 'pygame Surface' objects} 1 0 000 0 000 0 000 0 000 {method 'disable' of '_lsprof Profiler' objects} 1 0 002 0 002 0 002 0 002 {method 'fill' of 'pygame Surface' objects} 18 0 000 0 000 0 000 0 000 {method 'random_sample' of 'mtrand RandomState' objects} 2 0 000 0 000 0 000 0 000 {method 'release' of '_thread lock' objects} 3 0 000 0 000 0 000 0 000 {method 'render' of 'pygame font Font' objects} ```` As you can see the whole update() function (heart of the simulation) and the brain tick() appear to be substantially faster Why then when running the program it is slower? Cheers
In your new implementation you create 5 numpy arrays with each `Brain` object: ````self h_activation = zeros((self hidden_num 1) dtype=float) self o_activation = zeros((self output_num 1) dtype=float) self i_output = zeros((self input_num 1) dtype=float) self h_output = zeros((self hidden_num 1) dtype=float) self o_output = zeros((self output_num 1) dtype=float) ```` These attributes are not referenced in other parts of the code Creating them is a potentially costly operation which does not seem have a direct counterpart in the original implementation I am not sure that it would outweigh the speed advantage of faster numpy computations but if you are creating a lot of `Brain` objects it is something worth looking at
Get the first letter of each 2-letter word in python I have this code: ````hand=["TS" "AD"] test=['--23456789TJQKA' index(a) for a b in hand] print (test) ```` result is : ````[10 14] ```` How does this snippet work? Is it a built-in function for [a for a b in list] to get the first letter of each 2-letter word in list in python?
This is a normal list comprehension that is splitting the two letter strings in hand into tuple of letters for the first element of hand: ````a b in 'TS' # a == 'T' # b == 'S' '--23456789TJQKA' index('T') # 10 ```` for the second element of hand: ````a b in 'AD' # a == 'A' # b == WOULD' '--23456789TJQKA' index('A') # 14 ````
Finding edge from 2d points Python I have several 2d sets of scattered data that I would like to find the edges of Some edges may be open lines others may be polygons For example here is one plot that has an open edge that I would like to be able to keep I would actually like to create a polygon from the open edges so I can use `point_in_poly` to check if another point lies inside The points that would close the polygon are the boundaries of my plot area by the way <a href="http://i stack imgur com/AtedE png" rel="nofollow"><img src="http://i stack imgur com/AtedE png" alt="enter image description here"></a> <a href="http://i stack imgur com/leHVX png" rel="nofollow"><img src="http://i stack imgur com/leHVX png" alt="enter image description here"></a> Any ideas on where to get started? <strong>EDIT:</strong> Here is what I have already tried: - KernelDensity from sklearn The edges point density varies significantly enough to not be entirely distinguishable from the bulk of the points ````kde = KernelDensity() kde fit(my_data) dens = np exp(kde score_samples(ds)) dmax = dens max() dens_mask = (0 4 * dmax < dens) &amp; (dens < 0 8 * dmax) ax scatter(ds[dens_mask 0] ds[dens_mask 1] ds[dens_mask 2] c=dens[dens_mask] depthshade=False marker='of edgecolors='none') ```` <a href="http://i stack imgur com/SXZf7 png" rel="nofollow"><img src="http://i stack imgur com/SXZf7 png" alt="enter image description here"></a> Incidentally the 'gap' in the left side of the color plot is the same one that is in the black and white plot above I also am pretty sure that I could be using KDE better For example I would like to get the density for a much smaller volume more like using radius_neighbors from sklearn's `NearestNeighbors()` <old start="2"> - ConvexHull from scipy I tried removing points from semi-random data (for practice) while still keeping a point of interest (here 0 0) inside the convex set This was not terribly effective I had no sophisticated way of exlcuding points from an iteration and only removed the ones that were used in the last convex hull This code and accompanying image shows the first and last hull made while keeping the point of interest in the set ````hull = ConvexHull(pts) contains = True while contains: temp_pts = np delete(pts hull vertices 0) temp_hull = ConvexHull(temp_pts) tp = path Path(np hstack((temp_pts[temp_hull vertices 0][np newaxis] T temp_pts[temp_hull vertices 1][np newaxis] T))) if not tp contains_point([0 0]): contains = False hull = ConvexHull(pts) plt plot(pts[hull vertices 0] pts[hull vertices 1]) else: pts = temp_pts plt plot(pts[hull vertices 0] pts[hull vertices 1] 'r-') plt show() ```` <a href="http://i stack imgur com/Tqb4Q png" rel="nofollow"><img src="http://i stack imgur com/Tqb4Q png" alt="enter image description here"></a> Ideally the goal for convex hull would be to maximize the area inside the hull while keeping <strong>only</strong> the point of interest inside the set but I have not been able to code this <old start="3"> - KMeans() from sklearn cluster Using n=3 clusters I tried just run the class with default settings and got three horizontal groups of points I have not learned how to train the data to recognize points that form edges Here is a piece of the model where the data points are coming from The solid areas contain points while the voids do not <a href="http://i stack imgur com/jfOOc png" rel="nofollow"><img src="http://i stack imgur com/jfOOc png" alt="enter image description here"></a> <a href="http://stackoverflow com/questions/32511114/strategy-for-isolating-3d-data-points">Here</a> and <a href="http://stackoverflow com/questions/32357699/interpolating-scattered-data-from-a-volume-that-has-empty-space">here</a> are some other questions I have asked that show some more of what I have been looking at
So I was able to do this in a roundabout way I used images of slices of the model in the xy plane generated from SolidWorks to distinguish the areas of interest <a href="http://i stack imgur com/LeooC png" rel="nofollow"><img src="http://i stack imgur com/LeooC png" alt="Slice of model"></a> If you see them there are points in the corners of the picture that I placed in the model for reference at known distances These points allowed me to determine the number of pixels per millimeter From there I mapped the points in my analysis set to pixels and checked the color of the pixel If the pixel is white it is masked ````def mask_z_level(xi yi msk_img x0=-14 3887 y0=5 564): i am = plt imread(msk_img) msk = np zeros(xi shape dtype='bool') pxmm = np zeros((3 2)) p = 0 for row in range(i am shape[0]): for col in range(i am shape[1]): if tuple(i am[row col]) == (1 0 0 ): pxmm[p] = (row col) p = 1 pxx = pxmm[1 1] / 5 5 pxy = pxmm[2 0] / 6 5 print(pxx pxy) for j in range(xi shape[1]): for i in range(xi shape[0]): x y = xi[i j] yi[i j] dx dy = x - x0 y - y0 dpx = np round(dx * pxx) astype('int') dpy = -np round(dy * pxy) astype('int') if tuple(i am[dpy dpx]) == (1 1 1 ): msk[i j] = True return msk ```` Here is a plot showing the effects of the masking: <a href="http://i stack imgur com/TDjJN png" rel="nofollow"><img src="http://i stack imgur com/TDjJN png" alt="Masked and regular images"></a> I am still fine tuning the borders but I have a very manageable task now that the mask is in largely complete The reason being is that some mask points are incorrect resulting in banding <a href="http://i stack imgur com/DrEK4 png" rel="nofollow"><img src="http://i stack imgur com/DrEK4 png" alt="Bands in integrated data"></a>
How do you set up a python wsgi server under IIS? I work in a windows environment and would prefer to deploy code to IIS At the same time I would like to code in python Having read that IIS can run fastCGI application I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else Does anyone have experience getting a <strong>Python</strong> framework <strong>running under IIS</strong> using something other that plain old CGI? If so can you explain to direct me to some instructions on setting this up?
There should not be any need to use FastCGI There exists a <a href="https://github com/hexdump42/isapi-wsgi">ISAPI extension for WSGI</a>
How can I look inside of different chunks of strings in my Python program? Beginner programmer here still learning a lot Right now I am working with a very large text file and I want to look at the frequency of characters for different chunks of the text For example how often does the character "a" and "b" appear in text[0:600] verses [600:1200] versus [1200:1800] etc Right now I only know how to print text[0:600] but I do not know how to write the syntax to tell Python to look for "a" and "b" ONLY in that chunk of the text I am thinking that maybe the best way to write this would be something like "for each of these chunks I have tell me the frequency counts of 'a' and 'b' " Does this seem doable? Thank you so much! Here is what I have so far if you want to see Its very simple: ````f = open('text txt') fa = f read() fa = fa lower() corn = re sub(r'chr' '' fa) #delete chromosome title potato = re sub(r'[^atcg]' '' corn) #delete all other characters print potato[0:50] ````
You can position the file cursor and read from there: ````with open('myfile txt') as myfile: myfile seek(1200) text = myfile read(600) ```` This will read 600 bytes from position 1200 on Please note that the positions might be off when there are Unicode characters in the text
pattern for saving newline-delimited json with python With Python I am saving json documents onto separate lines like this: ````from bson import json_util # pymongo with open('test json' 'ab') as f: for document in documents: f write(json_util dumps(document)+'\n') ```` and then reading like this: ````with open('test json') as f: for line in f: document = json_util loads(line) ```` The ease and simplicity make me think that there must be a gotcha? Is this all there is to linejson aka <a href="http://jsonlines org/" rel="nofollow">jsonlines</a>?
Yes that is all there is to it
How to write an helper class with sqlalchemy I am using google-appengine as my production environment which maintains 12 mysqldb+mysql:// connections with the mysql server more than 12 connection it is showing socket open failure What i want is to write a simple crud wrapper currently ````class CRUDHelper(object): _instance = None _engine = None _session = None def __new__(cls *args **kwargs): if cls _instance: print "Reusing instance" return cls _instance cls _instance = super(CRUDHelper cls) __new__(cls *args **kwargs) return cls _instance def __init__(self): if not CRUDHelper _engine: CRUDHelper _engine = create_engine("mysqldb+mysql://test@/test?unix_socket=/cloudsql/appid:appname") CRUDHelper _engine echo = True self engine = CRUDHelper _engine if not CRUDHelper _session: CRUDHelper _session = scoped_session(sessionmaker(autoflush = True bind=self engine)) self sessionn = CRUDHelper _session Base metadata create_all(bind= self engine) def get(self model id): session = self session() # Developer is an sqlalchemy model dev = session query(model) filter_by(id=id) one() session close() return dev def save(self object merge=False): self session flush() if not merge: self session add(object) else: self session merge(object) self session commit() ```` this is my crud wrapper The above code is scalable as well as will not go beyond the 12 connections which is what i desire but the problem is consider a developer entity with id = 1 has name= "bob" and as age= 23 ````crud = CRUDHelper() dev = curd get(Developer 1) print dev age dev age = 1 crud save(dev merge=True) ```` suppose i run the above snippet of code twice The expected would be 23 and 24 but i am getting only 23 and 23 so can any one suggest me what is doing wrong here or give me a snippet of better wrapper with 12 connections cap
I found the answer it was a problem with my create_engine function
using python decorators with property inside of a class I am trying to use properties and decorators in a class but the problem I keep running into is getting the correct arguments and the number of arguments ````class Xml(object): def __init__(self data_dictionary=None): self data_dictionary = data_dictionary def xml_wrapper(xml_msg): def wrap(): return '<?xml version="1 0" encoding="UTF-8"?&gt;\n'+xml_msg['name'] return wrap @property @xml_wrapper def data_dictionary(self): return self _data_dictionary @data_dictionary setter def data_dictionary(self data): self _data_dictionary = data if __name__ == '__main__': xml = Xml() xml data_dictionary = {'name': 'name 1'} print xml data_dictionary ```` The error I am getting is ```` print xml data_dictionary TypeError: wrap() takes no arguments (1 given) ```` I am not sure why I tried adding self to the xml_wrapper function but I still get an error
In your code the `xml_wrapper` is a decorator which takes a function then wraps it with another function (`wrap`) and returns it The function `wrap` does not take any argument(as in your code) But when you call `xml data_dictionary` python is implicitly passing the instance `xml` (known as `self`) which is causing the problem May be this is what you want: ````&gt;&gt;&gt; class Xml(object): def __init__(self data_dictionary=None): self data_dictionary = data_dictionary def xml_wrapper(f): def wrap(*k **kw): xml_msg = f(*k **kw) return '<?xml version="1 0" encoding="UTF-8"?&gt;\n'+xml_msg['name'] return wrap @property @xml_wrapper def data_dictionary(self): return self _data_dictionary @data_dictionary setter def data_dictionary(self data): self _data_dictionary = data &gt;&gt;&gt; xml = Xml() &gt;&gt;&gt; xml data_dictionary = {"name":"name 1"} &gt;&gt;&gt; print xml data_dictionary <?xml version="1 0" encoding="UTF-8"?&gt; name 1 ```` This time xml_wrapper is taking a function (`data_dictionary`) then calls this function to get the `xml_msg` (inside `wrap`) `wrap` now takes arbitrarily many arguments and just passes those to original function (`data_dictionary`) takes the value formats it and returns
How many people like in the UK?
null
Is there a way to remove too many if else conditions? I am currently making an interactive system using python that is able to understand and reply Hence for this there are lots of conditions for machine to analyze and process For eg take the following code(for reference only): ```` if ('goodbye') in message: rand = ['Goodbye Sir' 'Jarvis powering off in 3 2 1 0'] speekmodule speek(rand n mixer) break if ('hello') in message or ('hi') in message: rand = ['Wellcome to Jarvis virtual intelligence project At your service sir '] speekmodule speek(rand n mixer) if ('thanks') in message or ('tanks') in message or ('thank you') in message: rand = ['You are wellcome' 'no problem'] speekmodule speek(rand n mixer) if message == ('jarvis'): rand = ['Yes Sir?' 'What can I doo for you sir?'] speekmodule speek(rand n mixer) if ('how are you') in message or ('and you') in message or ('are you okay') in message: rand = ['Fine thank you'] speekmodule speek(rand n mixer) if ('*') in message: rand = ['Be polite please'] speekmodule speek(rand n mixer) if ('your name') in message: rand = ['My name is Jarvis at your service sir'] speekmodule speek(rand n mixer) ```` So is there a way in which I can replace all these if else conditions?? Because there are much more conditions going to be and it will make the execution slower
`if/elif/else` is a natural way to structure this kind of code in Python As @imant noted you may use dict-based approach in case of simple branching but I see some mildly complex logic in your `if` predicates so you will have to check all predicates in any case and you will not have any performance gains with another code structure Though it may be a little bit more readable and easier to maintain if you factor out your predicates and actions like this: ````from collections import OrderedDict def goodbye_p(message): return 'goodbye' in message def goodbye_a(): rand = ['Goodbye Sir' 'Jarvis powering off in 3 2 1 0'] # As @Moinuddin Quadri I also assume that your `speek` method # says random message from a list # Otherwise you can use `random choice` method # to get a random message out of a list: `random choice(messages)` speekmodule speek(rand n mixer) def hello_p(message): return 'hello' in message or 'hi' in message def hello_a(): rand = ['Wellcome to Jarvis virtual intelligence project At your service sir '] speekmodule speek(rand n mixer) # Use `OrderedDict` instead of `dict` to control order # of checks and actions branches = OrderedDict([ # (predicate as key action as value) (goodbye_p goodbye_a) (hello_p hello_a) ]) for predicate action in branches items(): if predicate(message): action_result = action() # You can add some logic here based on action results # E g you can return some special object from `goodbye_a` # and then shut down Jarvis here # Or if your actions are exclusive you can add `break` here ```` If all your predicates are the same and contain only substring checks then it may be more performant to have tuples (e g `('hello' 'hi')`) as dict keys Then you can iterate over those keys like this: ````for words action in branches items(): if any(word in message for word in words): action() ````
Linux Mint 17 tkinter not installed I was trying to run a program that I have been making and ran into a problem with tkinter not being installed as when I try to run my script in pycharm I get this error: `ImportError: No module named '_tkinter' please`install the python3-tk package` So I searched on here and found a solution and entered these commands: ````sudo apt-get install python-support sudo update-python-modules -a ```` which did not work so I tried: ````sudo apt-get install python3-tk ```` which was tagged as the answer on this question but it threw this error at me: ````E: dpkg was interrupted you must manually run 'sudo dpkg --configure -a' to correct the problem ```` Being pretty new to linux and the terminal I am completely clueless as to how to do this I am using python 3 5 and just want to install tkinter so I can run this script also before anyone asks yes I have imported `tkinter` and not `Tkinter`
`sudo apt-get install python3-tk` is the correct way to install tkinter for Python 3 on Linux However you interrupted apt while it was installing To fix the errors run the command the error message suggested and then install tkinter ````sudo dpkg --configure -a sudo apt-get install python3-tk ```` Then you can add `from tkinter import *` `import tkinter as tk` or `import tkinter` to the beginning of your program depending on how you want to use it You may also be interested in installing idle-python3 4 Next time you need to install something just open the software manager from Menu search for the program and install it :-)
how to write a function like Mma's NestList in Python For example : NestList(f x 3) ----> [x f(x) f(f(x)) f(f(f(x)))] <a href="http://reference wolfram com/mathematica/ref/NestList html" rel="nofollow">http://reference wolfram com/mathematica/ref/NestList html</a>
You could write it as a generator: ````def nestList(f x c): for i in range(c): yield x x = f(x) yield x import math print list(nestList(math cos 1 0 10)) ```` Or if you want the results as a list you can append in a loop: ````def nestList(f x c): result = [x] for i in range(c): x = f(x) result append(x) return result import math print nestList(math cos 1 0 10) ````
Processing Boolean in a Python List I am using python 2 and I want to compare between item in a list but I got stucked Here is the problem: x = [True False True True False] how do i get the result to process the boolean (True &amp; False &amp; True &amp; True &amp; False)? thanks before
Try this: ````&gt;&gt;&gt; x = [True False True True False] &gt;&gt;&gt; all(x) False ```` I take it that by this: <blockquote> (True &amp; False &amp; True &amp; True &amp; False) </blockquote> you are looking for the intersection of all Boolean values All values in the list must evaluate to `True` for `all(x)` to return `True`
Why does re findall return a list of tuples when my pattern only contains one group? Say I have a string `s` containing letters and two delimiters `1` and `2` I want to split the string in the following way: - if a substring `t` falls between `1` and `2` return `t` - otherwise return each character So if `s = 'ab1cd2efg1hij2k'` the expected output is `['a' 'b' 'cd' 'e' 'f' 'g' 'hij' 'k']` I tried to use regular expressions: ````import re s = 'ab1cd2efg1hij2k' re findall( r'(1([a-z]+)2|[a-z])' s ) [('a' '') ('b' '') ('1cd2' 'cd') ('e' '') ('f' '') ('g' '') ('1hij2' 'hij') ('k' '')] ```` From there i can do `[ x[x[-1]!=''] for x in re findall( r'(1([a-z]+)2|[a-z])' s ) ]` to get my answer but I still do not understand the output The <a href="https://docs python org/2/library/re html" rel="nofollow">documentation</a> says that `findall` returns a list of tuples if the pattern has more than one group However my pattern only contains one group Any explanation is welcome
You pattern has two groups the bigger group: ````(1([a-z]+)2|[a-z]) ```` and the second smaller group which is a <them>subset</them> of your first group: ````([a-z]+) ```` Here is a solution that gives you the expected result although mind you it is really ugly and there is probably a better way I just cannot figure it out: ````import re s = 'ab1cd2efg1hij2k' a = re findall( r'((?:1)([a-z]+)(?:2)|([a-z]))' s ) a = [tuple(j for j in i if j)[-1] for i in a] &gt;&gt;&gt; print a ['a' 'b' 'cd' 'e' 'f' 'g' 'hij' 'k'] ````
Faster way to groupby time of day in pandas I have a time series of several days of 1-minute data and would like to average it across all days by time of day This is very slow: ````from datetime import datetime from pandas import date_range Series time_ind = date_range(datetime(2013 1 1) datetime(2013 1 10) freq='1min') all_data = Series(randn(len(time_ind)) time_ind) time_mean = all_data groupby(lambda x: x time()) mean() ```` Takes almost a minute to run! While something like: ````time_mean = all_data groupby(lambda x: x minute) mean() ```` takes only a fraction of a second Is there a faster way to group by time of day? Any idea why this is so slow?
Both your "lambda-version" and the time property introduced in <a href="http://pandas pydata org/pandas-docs/dev/release html#pandas-0-11-0" rel="nofollow">version 0 11</a> seems to be slow in version 0 11 0: ````In [4]: %timeit all_data groupby(all_data index time) mean() 1 loops best of 3: 11 8 s per loop In [5]: %timeit all_data groupby(lambda x: x time()) mean() Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions RuntimeError'&gt; ignored Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions RuntimeError'&gt; ignored Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions RuntimeError'&gt; ignored 1 loops best of 3: 11 8 s per loop ```` With the current master both methods are considerably faster: ````In [1]: pd version version Out[1]: '0 11 1 dev-06cd915' In [5]: %timeit all_data groupby(lambda x: x time()) mean() 1 loops best of 3: 215 ms per loop In [6]: %timeit all_data groupby(all_data index time) mean() 10 loops best of 3: 113 ms per loop '0 11 1 dev-06cd915' ```` So you can either update to a master or wait for 0 11 1 which should be released this month
Thinkof Python Chaper6,exercise8 ````&gt;&gt;&gt; def gcd(m n): if m%n==r and n !=0 and are !=0: return gcd(m n)==gcd(n r) elif n==0 or r==0: return gcd(m 0)==1 else: print None ```` <blockquote> <blockquote> <blockquote> gcd(5 6) </blockquote> </blockquote> </blockquote> ````Traceback (most recent call last): File "<pyshell#35&gt;" line 1 in <module&gt; gcd(5 6) File "<pyshell#34&gt;" line 5 in gcd return gcd(m 0)==1 File "<pyshell#34&gt;" line 2 in gcd if m%n==r and n !=0 and are !=0: ZeroDivisionError: integer division or modulo by zero ```` Sorry I just modified it to another version but still got similar error message Many thanx to you all!
I suspect you changed your code pasted from `gcd(5 0)` to `gcd(5 6)` when posting this question Your call to `gcd` is passing the values `5` and `0` as indicated by your error message The line `if m%n==r:` is attempting to perform division by 0 - a mathematical impossibility That is the reason for your `ZeroDivisionError` exception Edit: Formatting is off so I missed this on first pass but in the line `r=int()` you are setting `r` to 0 That means this line `return gcd(m n)==gcd(n r)` is passing 0 to `gcd`
Simple Pantheon panel applet on eOS? I would like to make a simple applet for the Pantheon Panel on eOS Luna with Python I cannot find any documentation on any API It is been suggested on some fora I should use the same procedure as Gnome or Unity The applets I have tried however (like the one on <a href="http://stackoverflow com/questions/6094506/simple-gnome-panel-applet-in-python">this answer</a>) simply did not work Could you guide me a little towards what I should be doing to have a simple applet icon menu showing on the Pantheon panel?
It seems one has to use the App Indicator module as per Ubuntu documentation The `appindicator` package of PyGtk did not work out but the PyGi `AppIndicator3` does work fine as far as I can tell A simple example is: ````#!/usr/env/bin/ python from gi repository import Gtk from gi repository import AppIndicator3 as appindicator def menuitem_response(w buf): print buf if __name__ == "__main__": ind = appindicator Indicator new ( "example-simple-client" "indicator-messages" appindicator IndicatorCategory APPLICATION_STATUS) ind set_status (appindicator IndicatorStatus ACTIVE) ind set_attention_icon ("indicator-messages-new") menu = Gtk Menu() for i in range(3): buf = "Test-undermenu - %d" % i menu_items = Gtk MenuItem(buf) menu append(menu_items) menu_items show() ind set_menu(menu) Gtk main() ```` Example drawn from <a href="http://developer ubuntu com/resources/technologies/application-indicators/" rel="nofollow">here</a>
Interruption of a os rename in python I made a script in python that renames all files and folders(does not <them>recurse</them>) in " " directory: the directory in which file is kept It happened that I ran the script in a directory which contained no files and only one directory let us say <strong>imp</strong> with path ` \imp` While program was renaming it the electricity went off and the job was interrupted (sorry did't had UPS) Now as the name suggests assume <them>imp</them> contains important data The renaming process also took quite good time ( compared to others ) before electricity went off even when all it was renaming was one folder After this endeavour is some data corrupted lost or anything? Just make this more useful: what happens os rename is <strong>forced</strong> to stop when it is doing its job? How is the effect different for files and folders? <h2>Details</h2> <strong>Python Version</strong> - 2 7 10 <strong>Operating System</strong> - Windows 10 Pro
You are using Windows which means you are (probably) on NTFS NTFS is a modern <a href="https://en wikipedia org/wiki/Journaling_file_system" rel="nofollow">journaling</a> file system It should not <them>corrupt</them> or <them>lose</them> any data though it is possible that only some of the changes that constitute a rename have been applied (for instance the filename might change without updating the modification time or <them>vice-versa</them>) It is also possible that none of those changes have been applied Note the word "should" is not the same as "will " NTFS <them>should not</them> lose data in this fashion and if it does it is a bug But because all software has bugs it is important to keep backups of files you care about
I cannot execute my Python code on Geany I use Windows 8 1 and installed Geany 1 24 recently It launches without a problem but i cannot execute the code because it gives an error saving file What can be the problem?
Either your disk is full or there is some interrupt which can cause by other programs' execution or something else that violates program execution You can check out <a href="http://wiki geany org/config/all_you_never_wanted_to_know_about_file_saving" rel="nofollow">wiki</a> page of Geany for getting more info <blockquote> If anything goes wrong in writing (disk full network interruption) the file is likely to be truncated On some file systems it is truncated to zero length Geany will give a warning of possible truncation </blockquote>
Getting the Response value of an XMLHttpRequest in Polymer I am using Polymer and core-ajax to send a set of variables to a python/flask backend which then sends back an XMLHttpRequest response with a an array of x and y values (for graphing) What I do not quite understand is how to grab the `response` value that is sent back to me Here is how I send the information: ````Polymer("add-graphItem" { addNewGraph: function () { var HeaderName = this $ graphOptionsLoad $ headerValue selectedItem label; var FunctionName = this $ graphFunctionsLoad $ functionValue selectedItem label; console log("The options are " HeaderName " and " FunctionName); var params = {}; if (this $ graphOptionsLoad $ headerValue selectedItem) { params['DataHeader'] = this $ graphOptionsLoad $ headerValue selectedItem label; } if (this $ graphFunctionsLoad $ functionValue selectedItem) { params['FunctionName'] = this $ graphFunctionsLoad $ functionValue selectedItem label; } this $ sendOptions params = JSON stringify(params); var x = this $ sendOptions go(); console log(x) } }) ```` And what I get back in my console is: ````XMLHttpResquest {statusText: "" status: 0 responseURL: "" response:"" responseType:""} onabort: null onerror: null onload: null onloadend: null onloadstart: null onprogress: null onreadystatechange: function () { ontimeout: null readyState: 4 response: "{↵ "graph": [↵ {↵ "Header": "MakeModeChange"↵ } ↵ {↵ "x values": [↵ 0 0 ↵ 131 35 ↵ 26971 3 ↵ 27044 75 ↵ 27351 4 ↵ 27404 483333333334 ↵ 27419 416666666668 ↵ 33128 96666666667 ↵ 33549 13333333333 ↵ 34049 48333333333 ↵ 77464 26666666666 ↵ 77609 71666666666 ↵ 174171 85 ↵ 259166 98333333334↵ ]↵ } ↵ {↵ "y values": [↵ 1 ↵ 2 ↵ 3 ↵ 4 ↵ 5 ↵ 6 ↵ 7 ↵ 8 ↵ 9 ↵ 10 ↵ 11 ↵ 12 ↵ 13 ↵ 14↵ ]↵ }↵ ]↵}" responseText: "{↵ "graph": [↵ {↵ "Header": "MakeModeChange"↵ } ↵ {↵ "x values": [↵ 0 0 ↵ 131 35 ↵ 26971 3 ↵ 27044 75 ↵ 27351 4 ↵ 27404 483333333334 ↵ 27419 416666666668 ↵ 33128 96666666667 ↵ 33549 13333333333 ↵ 34049 48333333333 ↵ 77464 26666666666 ↵ 77609 71666666666 ↵ 174171 85 ↵ 259166 98333333334↵ ]↵ } ↵ {↵ "y values": [↵ 1 ↵ 2 ↵ 3 ↵ 4 ↵ 5 ↵ 6 ↵ 7 ↵ 8 ↵ 9 ↵ 10 ↵ 11 ↵ 12 ↵ 13 ↵ 14↵ ]↵ }↵ ]↵}" responseType: "" responseURL: "http://127 0 0 1:5000/getGraph" responseXML: null status: 200 statusText: "OK" timeout: 0 timeout: 0 upload: XMLHttpRequestUpload withCredentials: false __proto__: XMLHttpRequest ```` Any help on how to grab and store the `response` or `responseText` would be greatly appreciated
In core-ajax you can access to your response by access to the core-ajax element response for example ````var coreAjax = document querySelector('core-ajax'); console log (coreAjax response); ```` To handle response from core-ajax instead of adding an event listener you could also use 'on-core-response' attribute and pass your callback function ````<polymer-element name="test-coreajax"&gt; <template&gt; <core-ajax auto url="http://gdata youtube com/feeds/api/videos/" handleAs="json" on-core-response="{{handleResponse}}"&gt;</core-ajax&gt; </template&gt; <script&gt; Polymer('test-coreajax' { // your other functions handleResponse: function() { //your code after callback } }); </script&gt; </polymer-element&gt; ````
Filter twitter files by location I am trying to find lat/long information for numerous tweets One path to a tweet lat/long data in a json tweet is {you'location: {you'geo': {you'coordinates : [120 0 -5 0]}}} I want to be able to check each tweet if this location path exists If it does then I want to use that information in a function later on If it does not then I want to check another location path and finally move on to the next tweet Here is the code I have currently to check if this path exists and if there is corresponding data 'data' is a list of twitter files that I opened using the <them>data append(json loads(line))</them> method ````counter = 0 for line in data: if you'coordinates' in data[counter][you'location'][you'geo']: print counter "HAS FIELD" counter = 1 else: counter = 1 print counter 'no location data' ```` I get a KeyError error with this code If I just do the below code it works but is not specific enough to actually get me to the information that I need ````counter = 0 for line in data: if you'location' in data[counter]: print counter "HAS FIELD" counter = 1 else: counter = 1 print counter 'no location data' ```` Does anyone have a way to do this Below is some more background on what I am doing overall but the above sums up where I am stuck Background: I have access to 12 billion tweets purchased through gnip that are divided up into multiple files I am trying to comb through those tweets one-by-one and find which ones have location (lat/long) data and then see if the corresponding coordinates fall in a certain country If that tweet does fall in that country I will add it to a new database which is a subset of the my larger database I have successfully created a function to test if a lat/long falls in the bounding box of my target country but I am having difficulty populating the lat/long for each tweet for 2 reasons 1) There are multiple places that long/lat data are stored in each json file if it exists at all 2) The tweets are organized in a complex dictionary of dictionaries which I have difficulty maneuvering through I need to be able to loop through each tweet and see if a specific lat/long combination exists for the different location paths so that I can pull it and feed it into my function that tests if that tweet originated in my country of interest
<blockquote> I get a KeyError error with this code </blockquote> Assume keys should be in double quotes because they have `'`: ````counter = 0 for line in data: if "you'coordinates" in data[counter]["you'location"]["you'geo"]: print counter "HAS FIELD" counter = 1 else: counter = 1 print counter 'no location data' ````
Python : get master volume windows 7 I am trying to built an App in which user has to just scroll his/her mouse over the windows sound icon to change the sound level Linux users are already familiar with this I have divided my problem in these steps: ```` 1 ) Get current audio device list using a python api 2 ) Control the master voulme using the api 3 ) Attach a mouse event listener to it (Sorry i am from Java background) 4 ) Get mouse event listener method to do my work ```` Plz suggest a `proper python API` to achieve my task And is this the `correct approach` towards my problem statement or there is a better way to approach this
For this purpose you could use PyWin32 <a href="http://sourceforge net/projects/pywin32/" rel="nofollow">http://sourceforge net/projects/pywin32/</a> or ctypes And your approach is pretty fine Here is a simple example for mouse with pywin32: ````import win32api import win32con def click(x y): win32api SetCursorPos((x y)) win32api mouse_event(win32con MOUSEEVENTF_LEFTDOWN x y 0 0) win32api mouse_event(win32con MOUSEEVENTF_LEFTUP x y 0 0) click(10 10) ```` and here is a similar one with ctypes: ````import ctypes ctypes windll user32 SetCursorPos(10 10) ctypes windll user32 mouse_event(2 0 0 0 0) ctypes windll user32 mouse_event(4 0 0 0 0) ```` Ctypes is somewhat harder sometimes to figure out and debug (requieres ALOT of time on MSDN) but it is awesomely fast
cannot import gdal in python? I have `gdal` installed and running on Ubuntu Jaunty but I cannot run `gdal2tiles` because I get the error: ````Traceback (most recent call last): File "/usr/local/bin/gdal2tiles py" line 42 in <module&gt; import gdal ImportError: No module named gdal ```` When I open python and type `import gdal` I get the same error I have `set LD_LIBRARY_PATH` (without spaces!) to `/usr/local/lib` but it does not seem to have made any difference Looks like Python cannot find `gdal` Can anyone help? Thanks!
Ith seems to be a "<strong><them>Python Path</them></strong>" issue &nbsp;Python libraries are looked-up within a defined path Try ````import sys sys path ```` If the directory where the gdal py and related files is not in this list then Python cannot find it That is for the "diagnostics" part To fix the situation you have several options They all hinge on knowing the rules which Python uses to build this path - The PYTHONPATH environement variable can be altered to include the desired path - Python can be started from the directory where the desired library resides - sys path can be dynamically altered with sys path append("/SomePath/To/MyStuff") The only place where I have seen the rules pertaining to the building of sys path formerly described within the "official" Python documentation is in the <a href="http://docs python org/tutorial/modules html">tutorial</a> at section 6 1 2 <strong>Excerpt:</strong> ``` modules are searched in the list of directories given by the variable sys path which is initialized from the directory containing the input script (or the current directory) PYTHONPATH and the installation- dependent default This allows Python programs that know what they’re doing to modify or replace the module search path Note that because the directory containing the script being run is on the search path it is important that the script not have the same name as a standard module or Python will attempt to load the script as a module when that module is imported This will generally be an error See section Standard Modules for more information ```
Python - encoding info in a table I am processing assembly language source with python My main table driven by opcode has information about each opcode including number/usage of register operands size of the operation etc It is currently stored as a dict with the opcode as key and a list of indicators as the value It works but it is pretty easy to screw up and I will not remember how it works when I have to fix it Is there a better way to separate the data from the processing? ````opdefs={ #operator defs #[number of register operands # <for each operand code 1=dest 2=src 3=both 4=overhead&gt; #storage use code:0 for none 1 for dest 2 for source #operation size(-means call opsizer routine)] 'cpy2': [2 1 2 0 4] 'cpy1': [2 1 2 0 2] 'cpy4': [2 11 12 0 8] ```` In this cpy2 has two register operands the first one is a destination the second one a source it has no storage references and it is 4 bytes long The main loop after tokenizing each line of the file looks like ````numoperands=opdefs[tokens[0]][0] #numer of operands for operandnum in range(1 numoperands+1): if opdefs[tokens[0]][operandnum]==1: #dest register destreg(tokens[operandnum]) #count times register is loaded ```` I would not mind if i was only going to run this once but i figure there has to be a better way to organize or encode this Any suggestions?
First use the <a href="http://docs python org/2/library/collections html#collections namedtuple" rel="nofollow">`collections namedtuple` class factory</a> to create a tuple-like object to replace your lists; store your operator codes in a tuple <them>within</them> that object: ````from collections import namedtuple opdef = namedtuple(opdef 'opcount opcodes storage size') opdefs = { 'cpy2': opdef(2 (1 2) 0 4) 'cpy1': opdef(2 (1 2) 0 2) 'cpy4': opdef(2 (11 12) 0 8) } ```` Now you can address these with `opdefs[token[0]] opcount` `opdefs[token[0]] size` etc This would already be far more readable You can use the names to define your entries if you find that easier to read: ````opdefs = { 'cpy2': opdef(opcount=2 opcodes=(1 2) storage=0 size=4) # } ```` You <them>could</them> get away with omitting the `opcount` argument and just use `len(opdefs[token[0]] opcodes)` Next you could use constants to denote the various options you have For `storage` you could use: ````S_NONE S_DEST S_SOURCE = range(3) ```` for example then use those names throughout: ````opdefs = { 'cpy2': opdef(opcount=2 opcodes=(1 2) storage=S_NONE size=4) # } ```` Because we use a separate tuple for the opcodes you just loop over those: ````operands=opdefs[tokens[0]] opcodes for operandnum opcode in enumerate(operands 1): if opcode == 1: #dest register destreg(tokens[operandnum]) #count times register is loaded ````
converting appended images list in Pandas dataframe I have a list which I created after appending the images from a folder ````samples=[] for filename in glob glob(path '/* png'): samples append(misc imread(filename)) ```` And a sample of the list looks like ````[array([[ 4 4 4 5 5 4] [ 5 5 5 6 6 5] [ 5 5 5 6 6 4] [12 12 11 12 12 7] [12 11 11 13 12 7] [11 11 10 12 12 7]] dtype=uint8) array([[ 4 4 4 7 7 6] [ 5 5 5 6 6 4] [ 5 5 5 7 7 5]] dtype=uint8)] ```` How it convert the image's dimensions in a Pandas DataFrame when I tried to do it with ````df=pd DataFrame(samples) ```` It gives me an error ````ValueError: Must pass 2-d input ```` Please Suggest- I will appreciate every help
Try converting it into a pandas <a href="http://pandas pydata org/pandas-docs/stable/generated/pandas Panel html" rel="nofollow">panel</a> ````import cv2 img = cv2 imread('path/Picture_1 png') imgPanel = pd Panel(img) ```` For more info see: <a href="http://pandas-docs github io/pandas-docs-travis/dsintro html#panel" rel="nofollow">Panel- Introduction</a> <a href="http://pandas-docs github io/pandas-docs-travis/whatsnew html#n-dimensional-panels-experimental" rel="nofollow">n-dimensional Panel (Experimental)</a> <a href="http://pandas-docs github io/pandas-docs-travis/cookbook html#panels" rel="nofollow">Cookbook- Panel</a> <a href="http://pandas-docs github io/pandas-docs-travis/cookbook html#panelnd" rel="nofollow">Panel-nd cookbook</a>
What was a term for Arabs who were not Muslim?
null
Django statelessness? I am just wondering if Django was designed to be a fully <strong>stateless</strong> framework? It seems to encourage statelessness and external storage mechanisms (databases and caches) but I am wondering if it is possible to store some things in the server's memory while my app is in develpoment and runs via `manage py runserver`
Sure it is possible But if you are writing a web application you probably will not want to do that because of threading issues
Most efficient way to translate words in Python Hi I wanted to ask if this what you see below is quickest and most efficient way to translate words in python I only need translation to english from other foreign languages Would it be more efficient to divide dictionary into one dictionary for every language or is it good the way it is right now? It would be nice if code would work in python 2 7 and 3 x and above In code below I have to change iteritems to items which is no big deal ````#!/usr/bin/env python # -*- coding: utf-8 -*- dct = {'apple': ['apfel' 'pomme' 'manzana' 'jabłko'] 'pineapple': ['ananas' 'ananas' 'piña' 'ananas']} def translate(q): for eng_word trans_list in dct iteritems(): for trans_word in trans_list: if trans_word == q: q = eng_word print q return q query = 'pomme' query = translate(query) query = 'ananas' query = translate(query) print query ````
Use a dictionary whose keys are foreign words and whose values are English words Then you can translate in O(1) time with one line of code ````d = {'apfel': 'apple' 'jablko': 'apple' 'ananas': 'pineapple' 'manzana': 'apple' 'pomme': 'apple' 'pina': 'pineapple'} print d["pomme"] ````
ipython from emacs on windows XP no prompt and no print output I want to integrate ipython to emacs 23 on windows XP I could find quite some information online but nothing did the trick The following is required in my `~/ emacs d/init el`: - python-mode - pymacs - ipython pyreadline is also installed I launch ipython with a bat file (in my system path) with the flags -i and -you The information text ````c:\Program\emacs-23 2\bin&gt;c:\program\python27\scripts\ipython -i -you Python 2 7 (r27:82525 Jul 4 2010 09:01:59) [MSC v 1500 32 bit (Intel)] Type "copyright" "credits" or "license" for more information IPython 0 10 1 -- An enhanced Interactive Python ? > Introduction and overview of IPython's features %quickref > Quick reference help > Python's own help system object? > Details about 'object' ?object also works ?? prints more ```` does not appear until I write the first command I get no prompt Writing and "executing" numbers do result in the red "`Out[n]:`" and the number `Print` does not give anything `a` gives the a colorful ipython error text ending with `NameError: name 'a' not defined` In other words the error stream seems ok the standard output seems ok but `print` and whatever is responsible for printing the prompt cannot seem to find the correct stream <hr> emacs `*Message*` buffer says: ````comint-send-string: Output file descriptor of Python<1&gt; is closed ```` for every output (not appearing) in the python she will
Make sure you are using <a href="https://launchpad net/pyreadline/1 6/1 6" rel="nofollow">pyreadline 1 6</a> Version 1 5 writes to the stream using the console API even when run via Emacs That causes many problems similar to the ones you are seeing
In what parts of Scotland was Old English spoken?
southern and eastern
What purpose were export carriers developed for?
null
Use np loadtxt to split a column while reading Is there any way to use np loadtxt and the converters argument to split a column into two columns? The lines in my text file looks like this: ````1 2 A=3;B=4 ```` and I want to read this in as: ````[1 2 3 4] ```` The file is quite large so reading line by line will be too slow I tried this: ````parse_col = lambda x: [ float(x split(';')[0] split('=')[1]) int(x split(';')[1] split('=')[1]) ] np loadtxt('demo txt' usecols=[0 1 2] comments='#' converters={2:parse_col} dtype=int) ```` Thanks!
You can create a generator that calls a parser and pass it to `np genfromtxt`: ````import re import numpy as np def parser(s): for i in re findall('[a-zA-Z]+' s): s = s replace(i '') return s replace('=' '') replace(';' ' ') gen = (parser(line) for line in open('demo txt')) np genfromtxt(gen comments='#' usecols=(0 1 2 3)) ```` Note that I used `re findall` to identify and replace a more general pattern as pointed out by @PadraicCunningham
Where did the leading Cubist architects study?
null
Unicode character in Django project path I am using Django 1 7 3 on a Mac I have created a Django project in the following path: /Users/cheng/百度云同步盘/Dev/django/testproject/ (The project is called 'testproject') I am having trouble loading a template file: ````/Users/cheng/百度云同步盘/Dev/django/testproject/ > vis > templates > vis > index html ```` (my app name is called 'vis') When I hit the right URL I got: ````UnicodeEncodeError at /vis/ 'ascii' codec cannot encode characters in position 13-18: ordinal not in range(128) Python Path: ['/Users/cheng/\xe7\x99\xbe\xe5\xba\xa6\xe4\xba\x91\xe5\x90\x8c\xe6\xad\xa5\xe7\x9b\x98/Dev/django/testproject' Unicode error hint The string that could not be encoded/decoded was: heng/百度云同步盘/Dev/ ```` As you can see the unicode portion of the path '百度云同步盘' has been ascii encoded as '\xe7\x99\xbe\xe5\xba\xa6\xe4\xba\x91\xe5\x90\x8c\xe6\xad\xa5\xe7\x9b\x98' Is there anyway to solve this problem besides moving the project to a non-unicode dir? Thank you! <hr> Update: I am using python 2 7 9 Full stack trace: ````Environment: Request Method: GET Request URL: http://127 0 0 1:8000/vis/ Django Version: 1 7 3 Python Version: 2 7 9 Installed Applications: ('django contrib admin' 'django contrib auth' 'django contrib contenttypes' 'django contrib sessions' 'django contrib messages' 'django contrib staticfiles' 'vis') Installed Middleware: ('django contrib sessions middleware SessionMiddleware' 'django middleware common CommonMiddleware' 'django middleware csrf CsrfViewMiddleware' 'django contrib auth middleware AuthenticationMiddleware' 'django contrib auth middleware SessionAuthenticationMiddleware' 'django contrib messages middleware MessageMiddleware' 'django middleware clickjacking XFrameOptionsMiddleware') Traceback: File "/usr/local/lib/python2 7/site-packages/django/core/handlers/base py" in get_response 111 response = wrapped_callback(request *callback_args **callback_kwargs) File "/Users/cheng/百度云同步盘/Dev/django/testproject/vis/views py" in index 7 return render(request 'vis/index html' context) File "/usr/local/lib/python2 7/site-packages/django/shortcuts py" in render 50 return HttpResponse(loader render_to_string(*args **kwargs) File "/usr/local/lib/python2 7/site-packages/django/template/loader py" in render_to_string 170 t = get_template(template_name dirs) File "/usr/local/lib/python2 7/site-packages/django/template/loader py" in get_template 144 template origin = find_template(template_name dirs) File "/usr/local/lib/python2 7/site-packages/django/template/loader py" in find_template 126 loader = find_template_loader(loader_name) File "/usr/local/lib/python2 7/site-packages/django/template/loader py" in find_template_loader 98 TemplateLoader = import_string(loader) File "/usr/local/lib/python2 7/site-packages/django/utils/module_loading py" in import_string 26 module = import_module(module_path) File "/usr/local/Cellar/python/2 7 9/Frameworks/Python framework/Versions/2 7/lib/python2 7/importlib/__init__ py" in import_module 37 __import__(name) File "/usr/local/lib/python2 7/site-packages/django/template/loaders/app_directories py" in <module&gt; 33 app_template_dirs = calculate_app_template_dirs() File "/usr/local/lib/python2 7/site-packages/django/template/loaders/app_directories py" in calculate_app_template_dirs 27 template_dir = template_dir decode(fs_encoding) File "/usr/local/Cellar/python/2 7 9/Frameworks/Python framework/Versions/2 7/lib/python2 7/encodings/utf_8 py" in decode 16 return codecs utf_8_decode(input errors True) Exception Type: UnicodeEncodeError at /vis/ Exception Value: 'ascii' codec cannot encode characters in position 13-18: ordinal not in range(128) ````
````File "/usr/local/lib/python2 7/site-packages/django/template/loaders/app_directories py" in calculate_app_template_dirs 27 template_dir = template_dir decode(fs_encoding) ```` This appears to be a bug in the Django template loader It is trying to ` decode` a string that it already Unicode causing an implicit ` encode` to the default encoding which in your case is ASCII so it cannot encode the Chinese The string in question is a module file path which comes from AppConfig path which is defined to be a Unicode string I suggest filing a bug against Django (eg ‘Template loader fails for path unencodable in default encoding’) In the meantime you could try to work around it by setting the default encoding to `utf-8` in your `sitecustomize py` or just run your app from a directory whose path is all-ASCII
Youtube video duration to Django model Which is easiest way to get info from youtube video and save in to database? For example I want get duration from youtube video my model: ````class Video(models Model): video_id = models CharField(max_length=150) title = models CharField(max_length=150) slug = AutoSlugField(populate_from="title") description = models TextField(blank=True) #duration = models CharField(max_length=10 default=video_duration) views = models PositiveIntegerField(default=0) likes = models PositiveIntegerField(default=0) category = models ForeignKey("VideoCategory") tags = models ManyToManyField("Tag") created = models DateTimeField(auto_now_add=True) modified = models DateTimeField(auto_now=True) """ My idea: def get_video_duration(): xml = "http://gdata youtube com/feeds/api/videos/" video_id open xml parse s = take duration from xml in seconds import datetime video_duration = str(datetime timedelta(seconds=s)) in h:m:s """ def __str__(self): return self title ```` Can someone help me please? Thank you in advance Edit: Thank you for answers so I tried method with json but a I get error video_duration is not defined ````class Video(models Model): video_id = models CharField(max_length=150) title = models CharField(max_length=150) slug = AutoSlugField(populate_from="title") description = models TextField(blank=True) duration = models CharField(max_length=10 default=video_duration) views = models PositiveIntegerField(default=0) likes = models PositiveIntegerField(default=0) category = models ForeignKey("VideoCategory") tags = models ManyToManyField("Tag") created = models DateTimeField(auto_now_add=True) modified = models DateTimeField(auto_now=True) def video_duration(): h = httplib2 Http() url = "http://gdata youtube com/feeds/api/videos/%sv=2&amp;alt=json" % video_id respose = h request(url) res = json loads(respose[1]) video_duration = res['entry']['media$group'][ 'media$content'][0]['duration'] return video_duration ````
getting the duration of a video from youtube is quite simple you just need to analyze the response of the api call i did it with httplib2 its better to work with json instead of xml videoID in the request url is the id of youtube video ```` import httplib2 import json h = httplib2 Http() respose = h request("http://gdata youtube com/feeds/api/videos/videoID?v=2&amp;alt=json") res = json loads(respose[1]) duration = res['entry']['media$group']['media$content'][0]['duration'] ````
Unfamiliar syntax in python code sample While reading through the code samples on Youtube API's in python I encountered that line of code: ````print 'Video category: %s' % entry media category[[]0] text ```` (<a href="https://developers google com/youtube/1 0/developers_guide_python" rel="nofollow">https://developers google com/youtube/1 0/developers_guide_python</a> in `Video entry contents` section) What does `[[]0]` mean? Or is it syntactically incorrect?
It is definitely the mistype The correct piece of their api would be `print 'Video category: %s' % entry media category[0] text`: ````def PrintEntryDetails(entry): print 'Video title: %s' % entry media title text print 'Video published on: %s ' % entry published text print 'Video description: %s' % entry media description text print 'Video category: %s' % entry media category[0] text print 'Video tags: %s' % entry media keywords text print 'Video watch page: %s' % entry media player url print 'Video flash player URL: %s' % entry GetSwfUrl() print 'Video duration: %s' % entry media duration seconds ```` Also - <a href="https://code google com/p/gdata-issues/issues/detail?id=3710" rel="nofollow">https://code google com/p/gdata-issues/issues/detail?id=3710</a> have a look at this issue The answer from the support there - "Thanks for the report! Looks like there are a few instances of this in our older docs We will look into it "
Selenium file upload leaves file selector window open (OS/X and Python) I am able to upload a file to a remote server using Selenium but the file selector dialog sticks around even once the file is uploaded <a href="https://code google com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_Does_WebDriver_support_file_uploads?" rel="nofollow">The Selenium FAQ notes that</a> "You cannot interact with the native OS file browser dialog directly but we do some magic so that " Given the use of "magic" here it is not surprising that the behavior I get is a little rough around the edges But there appear to be workarounds Taking my cues from <a href="http://stackoverflow com/a/16864547/2829764">this answer</a> I have the following code: ````import contextlib time from selenium import webdriver import selenium webdriver common action_chains as action_chains with contextlib closing(webdriver Chrome()) as driver: driver get("http://www bing com/images") driver find_element_by_id("sbi_t") click() driver find_element_by_id("sbi_file") click() driver find_element_by_id("sbi_file_upload") send_keys("//Loch Ness Monster jpg") print driver current_url # Still `http://www bing com/images` :( file_upload = driver find_element_by_id("sbi_file_upload") action_chains ActionChains(driver) click(file_upload) perform() # http://stackoverflow com/a/16864547/2829764 ```` But at the end of this the file upload window is still there I suspect I need a slightly different workaround since I am on a Mac Can anyone help?
Do not click upload button at all Set the filename via `send_keys()` and click "Go" (tested and works for me): ````element = driver find_element_by_id("sbi_file_upload") element send_keys('/Path/to/file jpeg') driver find_element_by_css_selector('div#sbi_sb_ipt span[name=go]') click() ````
When can a Grand Lodge declare another lodge as regular?
null
What was again revised in May of 2010?
Greek government deficit
Google search sniffer global conf is not defined I have made a google search sniffer with the help of the book Violent Python but when i run this code using `python sniffer py -i mon0` it says ```` traceback (most recent call last): File "test py line 30 in <module&gt; main() File "test py" line 23 in main conmf iface = options interface NameError: global name 'conf' is not defined ```` I am using the latest version of scapy on windows with python 2 7 Oh and i also kind of bodge installed it by moving the folders into the right place ````from scapy import * import optparse def findGoogle(pkt): if pkt haslayer(Raw): payload = pkt getLayer(Raw) load if 'GET' in payload: if 'google' in payload: are = re findall(r'(?!)\&amp;q=( *?)\&amp;' payload) if r: search = r[0] split('&amp;')[0] search = search replace('q=' '') replace('+' ' ') replace('%20' ' ') print "Searched for" search def main(): parser = optparse OptionParser('usage %prog -i '+ '<interface&gt;') parser add_option('-i' dest='interface' type='string' help='specify interface to listen on') (options args) = parser parse_args() if options interface == None: print parser usage exit(0) else: conf iface = options interface try: print '[*]Starting Google Sniffer ' sniff(filter='tcp port 80' prn=findGoogle) except KeyboardInterrupt: exit(0) if __name__ == '__main__': main() ````
Looks like you mistyped a line <a href="https://github com/reconSF/python/blob/master/violent_python/sniff/google-searches py" rel="nofollow">while transcribing it</a> ````from scapy import * ```` should read ````from scapy all import * ```` The `scapy` documentation is somewhat sparse but evidently `conf` is defined in there EDIT: Digging into the source it looks like `all py` imports <a href="http://bb secdev org/scapy/src/17cfed75e2249520bb1772be9dfacda930c01f20/scapy/config py?at=default" rel="nofollow">`config py`</a> which includes the line ````conf=Conf() ```` so that is definitely the culprit
Where are many of the Bronx's playwrights from?
Latin America and Africa
Python create a dictionary from a zip of 3 lists ````I have 3 list that i would like to put into a dictionary: list1=['a' 'b' 'c'] list2=[1 2 3] list3=[0 5 0 3 0 1] ```` traditionally i could create a dictionary like this with just list1 list2 ````my_dict = dict(zip(list1 list2)) #sort on list 2 descending sorted_my_dict = sorted(my_dict items() key=operator itemgetter(1) reverse=True) ```` i want to print this: `c:[3 0 1] b:[2 0 3] a:[1 0 5]` This did not work: ````my_dict=dict(list1 zip(list2 list3)) ````
You need to add one more zip since `dict` constructor accepts list of `tuple`s but not two `list`s: ````my_dict_3 = dict(zip(list1 zip(list2 list3))) ```` Also note that `dict`s in Python are not ordered and this code `sorted(my_dict items() key=operator itemgetter(1) reverse=True)` returns list of `tuple`s instead of <them>sorted</them> `dict` To sort `my_dict_3` you can use following code: ````sorted_my_dict_3_items = sorted(my_dict_3 items() key=lambda item: item[1][0] reverse=True) sorted_my_dict_3 = OrderedDict(sorted_items) ````
Python unable to retrieve form with urllib or mechanize I am trying to fill out and submit a form using Python but I am not able to retrieve the resulting page I have tried both mechanize and urllib/urllib2 methods to post the form but both run into problems The form I am trying to retrieve is here: <a href="http://zrs leidenuniv nl/ul/start php">http://zrs leidenuniv nl/ul/start php</a> The page is in Dutch but this is irrelevant to my problem It may be noteworthy that the form action redirects to <a href="http://zrs leidenuniv nl/ul/query php">http://zrs leidenuniv nl/ul/query php</a> First of all this is the urllib/urllib2 method I have tried: ````import urllib urllib2 import socket cookielib url = 'http://zrs leidenuniv nl/ul/start php' params = {'day': 1 'month': 5 'year': 2012 'quickselect' : "unchecked" 'res_instantie': '_ALL_' 'selgebouw': '_ALL_' 'zrssort': "locatie" 'submit' : "Uitvoeren"} http_header = { "User-Agent" : "Mozilla/5 0 (X11; Linux x86_64) AppleWebKit/535 11 (KHTML like Gecko) Chrome/17 0 963 46 Safari/535 11" "Accept" : "text/html application/xhtml+xml application/xml;q=0 9 */*;q=0 8" "Accept-Language" : "nl-NL nl;q=0 8 en-US;q=0 6 en;q=0 4" } timeout = 15 socket setdefaulttimeout(timeout) request = urllib2 Request(url urllib urlencode(params) http_header) response = urllib2 urlopen(request) cookies = cookielib CookieJar() cookies extract_cookies(response request) cookie_handler = urllib2 HTTPCookieProcessor(cookies) redirect_handler = urllib2 HTTPRedirectHandler() opener = urllib2 build_opener(redirect_handler cookie_handler) response = opener open(request) html = response read() ```` However when I try to print the retrieved html I get the original page not the one the form action refers to So any hints as to why this does not submit the form would be greatly appreciated Because the above did not work I also tried to use mechanize to submit the form However this results in a ParseError with the following code: ````import mechanize url = 'http://zrs leidenuniv nl/ul/start php' br = mechanize Browser() response = br open(url) br select_form(nr = 0) ```` where the last line exits with the following: "ParseError: unexpected '-' char in declaration" Now I realize that this error may indicate an error in the DOCTYPE declaration but since I cannot edit the form page I am not able to try different declarations Any help on this error is also greatly appreciated Thanks in advance for your help
It is because the `DOCTYPE` part is malformed Also it contains some strange tags like: ````<!Co Dreef / Eelco de Graaff Faculteit der Rechtsgeleerdheid Universiteit Leiden&gt;<!e-mail j dreef@law leidenuniv nl &gt; ```` Try <a href="http://validator w3 org/" rel="nofollow">validating</a> the page yourself <hr> Nonetheless you can just strip off the junk to make mechanizes html parser happy: ````import mechanize url = 'http://zrs leidenuniv nl/ul/start php' br = mechanize Browser() response = br open(url) response set_data(response get_data()[177:]) br set_response(response) br select_form(nr = 0) ````
What type of agreement is the deal with Emirates ?
sponsorship deal
python's `with` statement target is unexpectedly None seems like I do not understand something with---the python `with` statement Consider this class: ````class test(object): def __enter__(self): pass def __exit__(self *ignored): pass ```` now when using it with `with` like in ````with test() as michael: print repr(michael) ```` I would expect some output like <them><test instance at memore blah&gt;</them> But I get <them>None</them> Something wrong here? Any suggestions would help (I am using Python 2 6 6 ) <strong>EDIT:</strong> Thanks to <a href="http://stackoverflow com/users/20713/ephemient">ephement</a> for pointing me to the documentation The `__enter__` method should read ```` def __enter__(self): return self ````
From the <a href="http://docs python org/reference/compound_stmts html#the-with-statement">`with`</a> documentation: <blockquote> If a target was included in the `with` statement the return value from `__enter__()` is assigned to it </blockquote> If you `def __enter__(self): return self` then your expected output is produced
Make Python Class Methods searchable in Mongodb I have a Mongodb collection and I have created a Python class for documents in the collection The class has some properties and methods which are not stored with the document Should I try and store them to make the properties searchable or should I not store them and search the objects in Python? Here is an example: ````# Child class Child: def __init__(self **kwargs): self __dict__ update(kwargs) @property def parent(self): try: return Parent(**db Parents find_one({'child':self _id})) except: return None # Parent class Parent: def __init__(self **kwargs): self __dict__ update(kwargs) @property def child(self): try: return Child(**db Children find_one({'parent':self _id})) except: return None ```` In this example to search for all the children who is parent's name is "foo" I have to do this: ````results = [Child(**c) for c in db Children find() if c parent name == 'foo'] ```` This means I have to pull all the Children documents from Mongodb and search them Is it smarter to write the Parent data (or a subset of it) to the Child document so I can use Mongodb to do the searching?? So my Child class could look like this: ````# Child class Child: def __init__(self **kwargs): self __dict__ update(kwargs) @property def parent_name(self): try: return db Parents find_one({'child':self _id})['name'] except: return None def _save(self): # something like this to get and save all the properties data = {m[0]:getattr(self m[0]) for m in inspect getmembers(self)} db Children find_and_modify({'_id':self _id} {'$set':data} upsert=True) # search results = [Child(**c) for c in db Children find({'parent_name':'foo'})] ```` So the search is more efficient but I think having to keep the Child objects updated could be painful and dangerous If I change the name of a Parent I have to also rewrite its children Feels wrong Any better ideas???
You don’t have to load <them>all</them> `Children` ````parent_ids = db Parents find({'name': 'foo'}) distinct('_id') children = db Children find({'parent': {'$in': parent_ids}}) ```` (Also why do you have both a `child` field on a parent <them>and</them> a `parent` field on a child?)
Scriptable HTTP benchmark (preferable in Python) I am searching for a good way to stress test a web application Basically I am searching für something like <a href="http://httpd apache org/docs/2 0/programs/ab html" rel="nofollow">ab</a> with a scriptable interface Ideally I want to define some tasks that simulate different action on the webapp (register a account login search etc ) and the tool runs a hole bunch of processes that executes these tasks* As result I would like something like "average request time" "slowest request (per uri)" etc *: To be independed from the client bandwith I will run theses test from some EC2 instances so in a perfect world the tool will already support this - otherwise I will script is using <a href="http://code google com/p/boto/" rel="nofollow">boto</a>
You can maybe look onto these tools: - <a href="https://pypi python org/pypi/palb" rel="nofollow">palb (Python Apache-Like Benchmark Tool)</a> - HTTP benchmark tool with command line interface resembles ab It lacks the advanced features of ab but it supports multiple URLs (from arguments files stdin and Python code) - <a href="http://testutils org/multi-mechanize/" rel="nofollow">Multi-Mechanize</a> - Performance Test Framework in Python Multi-Mechanize is an open source framework for performance and load testing - Runs concurrent Python scripts to generate load (synthetic transactions) against a remote site or service - Can be used to generate workload against any remote API accessible from Python - Test output reports are saved as HTML or JMeter-compatible XML - <a href="http://pylot org/" rel="nofollow">Pylot (Python Load Tester)</a> - Web Performance Tool Pylot is a free open source tool for testing performance and scalability of web services It runs HTTP load tests which are useful for capacity planning benchmarking analysis and system tuning Pylot generates concurrent load (HTTP Requests) verifies server responses and produces reports with metrics Tests suites are executed and monitored from a GUI or she will/console ( <a href="http://code google com/p/pylt/" rel="nofollow">Pylot on GoogleCode</a> ) - <a href="http://grinder sourceforge net/" rel="nofollow">The Grinder</a> Default script language is Jython Pretty compact <a href="http://pierrerebours com/blog/load-testing-using-grinder" rel="nofollow">how-to guide</a> - <a href="http://tsung erlang-projects org/" rel="nofollow">Tsung</a> Maybe a bit unusual for the first use but really good for stress-testing <a href="http://beebole com/blog/erlang/test-performance-and-scalability-of-your-web-applications-with-tsung/" rel="nofollow">Step-by-step guide</a> 1 for locust io in answer above
Install Anaconda on Ubuntu 12 04 via command line I would like to install <a href="https://store continuum io/cshop/anaconda/" rel="nofollow">Anaconda</a> on a remote server The server is running Ubuntu 12 04 I only have access to this server via SSH How can I install Anaconda via the command line?
Something along the lines of: wget <a href="http://09c8d0b2229f813c1b93-c95ac804525aac4b6dba79b00b39d1d3 r79 cf1 rackcdn com/Anaconda-2 1 0-Linux-x86_64 sh">http://09c8d0b2229f813c1b93-c95ac804525aac4b6dba79b00b39d1d3 r79 cf1 rackcdn com/Anaconda-2 1 0-Linux-x86_64 sh</a> to get the installer for 64 bit linux followed by: bash Anaconda-2 x x-Linux-x86[_64] sh
Need Pattern for lookup tables in Google App Engine I am using the Python version of Google App Engine and Datastore What is a good way to load a table that will contain lookup data? By look up data I mean that after the initial load no rows will need to be inserted deleted or updated Blowing away all rows and reloading the table is not acceptable if it destroys referential integrity with other rows referring to it Here is an example of a couple kinds that I am using that I want to load lookup data into ```class Badge(db Model): name = db StringProperty() level = db IntegerProperty() class Achievement(db Model): name = db StringProperty() level = db IntegerProperty() badge = db ReferenceProperty(reference_class=Badge) ``` Here is an example of a kind not holding look up data but referring to it ```class CamperAchievement(db Model): camper = db ReferenceProperty(reference_class=Camper) achievement = db ReferenceProperty(reference_class=Achievement) session = db ReferenceProperty(reference_class=Session) passed = db BooleanProperty(default=True)``` I am looking to find out two things: What should the code to load the data look like? What should trigger the loading code to execute?
I <them>think</them> you are referring to some kind of write-behind cache but it is not really that clear from your question This is a common pattern for reading data slow a slow source (like a database/disk) and caching it in a fast source (like memcache/memory) for quick retrieval later It is then your responsibility to empty out all the cached items when things change See the first example on <a href="http://code google com/appengine/docs/python/memcache/usingmemcache html" rel="nofollow">Using memcache</a>
__file__ and os path module not playing nicely? ````import os print __file__ print os path dirname(__file__) os chdir('/tmp') print __file__ # unchanged of course print os path dirname(__file__) # now broken ```` I have this issue above where `dirname(__file__)` can no longer be relied upon after `os chdir` has been used in the script after module loader has set `__file__` What is the usual mechanism for working around this assuming you may not know where/when/how `os chdir` may have been called previously? <strong>edit:</strong> i hope this second example can better clarify my issue ````import os old_dir = os getcwd() print os path abspath(__file__) os chdir('/tmp') print os path abspath(__file__) os chdir(old_dir) ```` the output is like this : ````wim@wim-acer:~$ python --version Python 2 7 1+ wim@wim-acer:~$ pwd /home/wim wim@wim-acer:~$ python /home/wim/spam py /home/wim/spam py /home/wim/spam py wim@wim-acer:~$ python /spam py /home/wim/spam py /tmp/spam py ````
The `__file__` must exist in `sys path` somewhere ````for dirname in sys path: if os path exists( os path join(dirname __file__) ): # The directory name for `__file__` was dirname ````
How can I use a regex subpattern with a named group in Python? I am translating a regex-heavy script from Perl to Python and I have a problem with regex subpatterns In Perl if I write the following works as expected i e the string "OK" is written I have never given it much thought but it just looks like Perl knows that those are different groups although they have the same name ````my $ident = qr{ (?<guill&gt; ['"`]? ) [a-zA-Z_] \w* \g{guill} }x; my $idents = qr{ (?: $ident \s* \s* )* $ident }x; my $test = q{'test' "test"}; if ($test =~ $idents) { say 'OK'; } ```` I have found no way to interpolate a subpattern inside a pattern in Python besides concetenating strings before they are compiled as regex patterns so I translated my Perl code as: ````ident = r"(?P<guill&gt; ['\"`]? ) [a-zA-Z_] \w* (P=guill)" idents = r"(?: " ident r" \s* \s* )* " ident test = "'test' \"test\"" if re match( idents test re VERBOSE ): print "OK" ```` Unsurprisingly that does not even compile as Python complains about the "redefinition of group name 'guill' as group 3" I tried the Perlish way and `re compile` would `ident` but then it refused to concatenate a string with a pattern object What would be the Pythonish way of achieving this?
This can be done using true regular expressions ````ident0 = r"[a-zA-Z_] \w*" ident1 = r"' [a-zA-Z_] \w* '" ident2 = r"\" [a-zA-Z_] \w* \"" ident3 = r"` [a-zA-Z_] \w* `" ident = "(?:" ident0 "|" ident1 "|" ident2 "|" ident3 ")" ````
TypeError: unbound method instance as first argument Ok one TypeError more Here is my code: ````class musssein: def notwendig(self name): self name = name all = [] # fuer jede Eigenschaft eine extra Liste day = [] time = [] prize = [] what = [] kategorie = [] with open(name) as f: for line in f: data = line replace('\n' '') #Umbruchzeichen ersetzen if data != ' ': # immer nur bis zur neuen Zeile bzw bis zum ' ' lesen all append(data) # in liste einfuegen else: kategorie append(all pop()) what append(all pop()) prize append(all pop()) time append(all pop()) day append(all pop()) def anzeige(): musssein notwendig('schreiben txt') print table Table( table Column('Datum' day) table Column('Kategorie' kategorie) table Column('Was?' what) table Column('Preis' prize align=table ALIGN LEFT)) ```` The description is in german but it explain me just what you probably already know When I run now `anzeige()` the terminal shows me only: `File "test py" line 42 in anzeige musssein notwendig('schreiben txt') TypeError: unbound method notwendig() must be called with musssein instance as first argument (got str instance instead)` I tried many possibilities and read a lot of other threads but I did not find the right one which explained it
You must create (instantiate) an object of the class `mussein` before calling its method ````def anzeige(): my_var = mussein() my_var notwendig('schreiben txt') ```` So the `self` parameter of the `notwendig` method is `my_var` (an instance of mussein) By the way usually the class names must start with a capital letter So in this case it should be `Mussein`
Pseudocode interpretation How would the following pseudocode translate into Python? ````function IntNoise(32-bit integer: x) x = (x<<13) ^ x; return ( 1 0 - ( (x * (x * x * 15731 789221) 1376312589) &amp; 7fffffff) / 1073741824 0); end IntNoise function ```` I am not sure about the following items: the '32-bit integer:x' argument in the IntNoise call ; the '<<' and the '&amp;7fffffff' The function is a random number generator from this webpage <a href="http://freespace virgin net/hugo elias/models/m_perlin htm" rel="nofollow">http://freespace virgin net/hugo elias/models/m_perlin htm</a>
The "32-bit integer" part does not unless you use `numpy int32` Just mask the value to 32 bits when it makes sense The "<<" stands The "&amp; 7fffffff" Needs to be converted The "&amp;" stands but the hexadecimal literal needs a bit: `0x7fffffff`
Order a sentence alphabetically and count the number of times each words appears and print in a table I am struggling with the print in a table part of the question So far I have managed to order the user inputted sentence alphabetically and count the number of times each word occurs Here is the code: ````thestring = (raw_input()) sentence = thestring split(" ") sentence sort() count = {} for word in thestring split(): try: count[word] = 1 except KeyError: count[word] = 1 print sentence print count ```` And when I run the code I get this: ````['apple' 'apple' 'banana' 'mango' 'orange' 'pear' 'pear' 'strawberry'] {'apple': 2 'pear': 2 'strawberry': 1 'mango': 1 'orange': 1 'banana': 1} ```` However ideally I want it printed in a table that looks something like: ````apple | 2 banana | 1 mango | 1 orange | 1 pear | 2 strawberry| 1 ```` Thanks for any help!
`Counter` is the better solution but if you want to stick to your code just replace `print count` by ````for c in sorted(count): print c ' '*(10-len(c))+'|'+' '*(6-len(str(count[c])))+str(count[c]) ````
Is there a comparison key for set objects? Is there a way to give a comparator to `set()` so when adding items it checks an attribute of that item for likeness rather than if the item is the same? For example I want to use objects in a set that can contain the same value for one attribute ````class TestObj(object): def __init__(self value *args **kwargs): self value = value super() __init__(*args **kwargs) values = set() a = TestObj('a') b = TestObj('b') a2 = TestObj('a') values add(a) # Ok values add(b) # Ok values add(a2) # Not ok but still gets added # Hypothetical code values = set(lambda x y: x value != y value) values add(a) # Ok values add(b) # Ok values add(a2) # Not added ```` I have implemented my own sorta thing that does similar functionality but wanted to know if there was a builtin way ````from Queue import Queue class UniqueByAttrQueue(Queue): def __init__(self attr *args **kwargs): Queue __init__(self *args **kwargs) self attr = attr def _init(self maxsize): self queue = set() def _put(self item): # Potential race condition worst case message gets put in twice if hasattr(item self attr) and item not in self: self queue add(item) def __contains__(self item): item_attr = getattr(item self attr) for x in self queue: x_attr = getattr(x self attr) if x_attr == item_attr: return True return False def _get(self): return self queue pop() ````
Just define <a href="https://docs python org/3/reference/datamodel html#object __hash__" rel="nofollow">`__hash__`</a> and <a href="https://docs python org/3/reference/datamodel html#object __hash__" rel="nofollow">`__eq__`</a> on the object in terms of the attribute in question and it will work with `set`s For example: ````class TestObj(object): def __init__(self value *args **kwargs): self value = value super() __init__(*args **kwargs) def __eq__(self other): return self value == other value def __hash__(self): return hash(self value) ```` If you cannot change the object (or do not want to say because other things are important to equality) then use a `dict` instead You can either do: ````mydict[obj value] = obj ```` so new objects replace old or ````mydict setdefault(obj value obj) ```` so old objects are maintained if the `value` in question is already in the keys Just make sure to iterate using ` viewvalues()` (Python 2) or ` values()` (Python 3) instead of iterating directly (which would get the keys not the values) You could actually use this approach to make a custom `set`-like object with a key as you describe (though you would need to implement many more methods than I show to make it efficient the default methods are usually fairly slow): ````from collections abc import MutableSet # On Py2 collections without abc class keyedset(MutableSet): def __init__(self it=() key=lambda x: x): self key = key self contents = {} for x in it: self add(x) def __contains__(self x): # Use anonymous object() as default so all arguments handled properly sentinel = object() getval = self contents get(self key(x) sentinel) return getval is not sentinel and getval == x def __iter__(self): return iter(self contents values()) # itervalues or viewvalues on Py2 def __len__(self): return len(self contents) def add(self x): self contents setdefault(self key(x) x) def discard(self x): self contents pop(self key(x) None) ````
Coroutines in Python: Best Practices I am wondering what the best practices are for writing coroutines in Python 3 I am developing basic methods which should accept some input (using the send() method) perform computations on this input and then yield output The first approach I found is to essentially do the following: ````def coroutine(func): data = yield while 1: data = yield func(data) ```` That seems to work but the line in the loop is bending my mind It appears to first yield a function and <them>then</them> take input and perform the assignment <them>after</them> resuming This is completely non-intuitive to me The other approach I am looking at is: ````def coroutine(): while 1: data = yield [ do stuff with data here ] yield result ```` This code is much easier for me to understand and it also let us me put code right into the generator instead of passing in a function But it is annoying to use Every actual call to the generator (like "gen send(2)") has to be followed by a "gen send(None)" to advance the generator to the next yield It seems to me like the problem here stems from the "yield" keyword being used for two different things: a return statement and an input statement If possible I want an approach that let us me take input do calculations on that input and then yield output without having to pass in functions and use one-liners as in the first approach or having to send extraneous values as in the second approach How can I do this? <hr> Please note: In reality I will be sending in multiple values So the problems of having extraneous "g send(None)" statements get worse
You can do it as you did in your first example You just have to "do stuff with data" inside the loop Here is an example: ````def coroutine(): data = yield while True: print("I am doing stuff with data now") data = data * 2 data = yield data ```` You can use it like this: ````&gt;&gt;&gt; co = coroutine() &gt;&gt;&gt; next(co) &gt;&gt;&gt; co send(1) I am doing stuff with data now 2 &gt;&gt;&gt; co send(88) I am doing stuff with data now 176 ```` You are correct that `yield` plays a dual role both yielding a result out and accepting the value subsequently passed in via `send` (Likewise `send` plays a dual and complementary role in that every `send` call returns the value that the generator yields ) Note the order there: when you have a `yield` expression it <them>first</them> yields the value out and then the value of the `yield` expression becomes whatever is `sent` in <them>afterwards</them> This may seem "backwards" but you can get it to be "forwards" by doing it in a loop as you essentially already did The idea is that you first yield some initial value (maybe a meaningless one) This is necessary because you cannot use `send` before a value has been yielded (since there would be no `yield` expression to evaluate to the sent value) Then every time you use `yield` you are giving out the "current" value while simultaneously accepting input to be used in computing the "next" value As I mentioned in a comment it is not clear from your example why you are using generators at all In many cases you can achieve a similar effect just by writing a class that has its own methods for passing things in and getting things out and if you write the class you can make the API whatever you want If you choose to use generators you have to accept the dual input/output roles of `send` and `yield` If you do not like that do not use generators (or if you need the suspended function-state they provide you can use them but wrap them with a class that separates the sending from the yielding)
Python 3 x What is the best way to do this code? I am writing a code where the user inputs as many numbers as they want until they input Stop Each input gets added to a list I want the input to be integer so the inputs are able to be sorted correctly but then when 'Stop' is inputted an error message will be created But if I make the input string then the numbers will be sorted incorrectly Here is the code: ````Num_List = list() Numbers = input('Enter a number: ') Num_List append(Numbers) Num_B = False while Num_B == False: Numbers = input('Enter a number: ') Num_List append(Numbers) if Numbers == 'Stop': Num_List remove('Stop') Num_List = [i for i in Num_List if i is not ''] Num_List sort(reverse=False) sorted(Num_List) print(Num_List) Num_B = True ````
Here is my approach: In an infinite loop get a user's input If it is <them>'Quit'</them> then break out of the loop Otherwise convert to integer and append to the list of numbers The code: ````numbers = list() while True: token = input('Number: ') if token == 'Quit': break numbers append(int(token)) print('List is:' numbers) ```` <h1>Update</h1> Judging by the original poster's ignoring empty strings I guess some of the imput are empty strings which causes `ValueError` With that guess I modified my code to take in accounts of those tokens that are not converted to numbers successfully ````numbers = list() while True: token = input('Number: ') if token == 'Stop': break try: numbers append(int(token)) except ValueError: print('Invalid token ignore: {!r}' format(token)) print('List is:' numbers) ```` <h1>Update 2:</h1> I have modifying my code yet again This time the code runs fine in both Python 2 and 3 interpreters ````from __future__ import print_function # Level the difference between Python 2 and 3 try: raw_input except NameError: raw_input = input numbers = list() while True: try: token = raw_input('Number: ') numbers append(int(token)) except ValueError: if token == 'Stop': break print('Invalid token ignore: {!r}' format(token)) print('List is:' numbers) ```` <h1>Update 3</h1> Output for update 2 from Python 3 run: ````Number: 7 Number: 87 Number: 120 Number: Invalid token ignore: '' Number: foo Invalid token ignore: 'foo' Number: bar Invalid token ignore: 'bar' Number: Stop List is: [7 87 120] ```` Output from Python 2 run is the same
Why is pymongo not returning index information of the collection? If I run the getIndexes method in the she will : ````xyz:PRIMARY&gt; db my_collection count() 26672 xyz:PRIMARY&gt; db my_collection getIndexes() // Prints indexes and their info ```` However `index_information` method in pymongo is returning a blank dict for all collections in python she will other operations on the collection work fine ````&gt;&gt;&gt; my_collection count() 26672 &gt;&gt;&gt; my_collection index_information() {} ```` Mongodb version : 3 0 2 Pymongo version : 2 5 2
According to <a href="https://docs mongodb com/ecosystem/drivers/driver-compatibility-reference/#python-driver-compatibility" rel="nofollow">Python Driver Compatibility</a> section in MongoDB documentation PyMongo 2 5 does not fully support MongoDB 3 0: <a href="http://i stack imgur com/L8i0E png" rel="nofollow"><img src="http://i stack imgur com/L8i0E png" alt="enter image description here"></a> <sup><them>Python Driver Compatibility (From MongoDB Documentation)</them></sup> So you should upgrade your PyMongo to the latest version or 2 8 at least
How to get exactly models field after I filtered the models object? It is hard to describe what I want to do but I will try After I have filtered the models like this ( I maximum could get only 1 object): ````tweets = Tweet objects filter(user__iexact=username) # username variable I got from URL ```` I want to show which user wrote that tweet So I am trying to do this in my templates like this: ````<h1&gt;{{tweets username}}</h1&gt; ```` However it is not showing anything By the way it is my models: ````class Tweet(models Model): text = models CharField(max_length=140) date = models DateField(default=date today) username = models CharField(max_length=140) ````
You need to filter your Tweets as such: ````tweets = Tweet objects filter(username__iexact=username) ```` If you only want one Tweet back: ````tweet = Tweet objects get(username__iexact=username) ```` Which tweet instance is returned would depend on the default ordering of the model which is `id` unless you specify it in the model's `Meta` options In the template you need to either loop over the tweets returned to display `tweet username` which only exists on an instance or you need to pass in the username and just display: ````<h1&gt;{{ username }}</h1&gt; ````
How do I extract int values from string? Hello I have a `list` like this: ````B= ["('33' '207')" "('33' '408')" "('33' '408')" "('33' '408')" "'NaN'" "('33' '207')"] ```` I would like to return an array of integers like the following: ````B1 = [33 207 33 408 33 408 33 408 NaN Nan 33 408] ```` I am trying to use `regex` as `B1[0]=re findall(r'\d+' B[0])`
Simply use split: ````B1 = [(float(a[1]) float(a[-2])) for a in (b split("'") for b in B)] ````
In which season was online voting introduced?
ten
How to truncate a string's length to the largest multiple of a smaller integer? I have a string `path` of arbitrary length and an integer `x` that is less than or equal to than the length of `path` I want to truncate `path`'s length to the largest multiple of `x` that is less or equal to `path`'s original length Here is the best I have been able to come up with but I feel like Python would have a better way to do this: ````final_length = 0 while final_length x <= len(path): final_length = final_length x final_path = path[:final_length] ````
Integer division will give you want without using a loop ````x = 3 s = 'hello world' s[:(len(s) // x) * x] ```` returns ````hello wor ```` which has length 9
Python smooth curve I have set of very closely spaced coordinates I am connecting those coordinates by drawing line between them by using python's image draw line() But the final curve obtained is not smooth as the lines at the coordinates are not properly intersecting I also tried drawing arc instead of lines but image draw arc() would not take any float input for coordinates Can anyone suggest me other method to connect those points such that final curve will be smooth
Splines are the standard way to produce smooth curves connecting a set of points See the <a href="http://en wikipedia org/wiki/Spline_%28mathematics%29" rel="nofollow">Wikipedia</a> In Python you could use <a href="http://docs scipy org/doc/scipy-0 14 0/reference/tutorial/interpolate html" rel="nofollow">`scipy interpolate`</a> to compute a smoth curve: <img src="http://i stack imgur com/JKBCN png" alt="scipy interplote">
This specific str replace() in Python with BeautifulSoup is not working I am trying to automate a task that occurs roughly monthly which is adding a hyperlink to a page that looks like: ````2013: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2012: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2011: Jan Feb Mar ```` Whenever we get a new document for that month we add the ````<a href="document_001 pdf"&gt;Jul</a&gt; ```` tags around it So I am using BeautifulSoup in Python You can see below that I am picking out the HTML "p" tag that contains this data and doing a replace() on the first month that it finds (finds Month using the reverse dictionary I created and the third parameter of replace() indicates to only do the first one it finds) ````# Modify link in hr php: hrphp = open('\\\\intranet\\websites\\infonet\\hr\\hr php' 'r') read() soup = BeautifulSoup(hrphp) # Parsing with BeautifulSoup Months = {k: v for k v in enumerate(calendar month_abbr)} # Creates a reverse dictionary for month abbreviation lookup by month number ie "print Months[07]" will print "Jul" print hrphp+"\n\n\n\n\n" # DEBUGGING: Compare output before hrphp = hrphp replace( str(soup findAll('p')[4]) str(soup findAll('p')[4]) replace( Months[int(InterlinkDate[1][-5:-3])] "<a href=\""+FilenameNewsletter+"\"&gt;"+Months[int(InterlinkDate[1][-5:-3])]+"</a&gt;" 1) 1 ) print hrphp # DEBUGGING: Compare output after ```` See how it is a nested replace()? The logic seems to work out fine but for some reason it does not actually change the value Earlier in the script I do something similar with the Months[] dictionary and str replace() on a segment of the page and that works out although it does not have a nested replace() like this nor does it search for a block of text using soup findAll() Starting to bang my head around on the desk any help would be greatly appreciated Thanks in advance
What you end up doing with the code `str(soup findAll('p')[4]) replace` is just replacing the values that are found in a string representation of the results in `soup findAll('p')[4]` which will more than likely differ from the string in `hrphp` because <a href="http://www crummy com/software/BeautifulSoup/bs4/doc/#making-the-soup" rel="nofollow">"Beautiful Soup gives you Unicode"</a> after it parses Beautiful Soups documentation holds the answer Have a look at the <a href="http://www crummy com/software/BeautifulSoup/bs4/doc/#modifying-the-tree" rel="nofollow">Changing Attribute Values section</a>
PyAudio compilation on Raspbian When trying to install `pyaudio` with `pip install pyaudio` on Raspbian I get: ````Collecting pyaudio Could not find any downloads that satisfy the requirement pyaudio Some externally hosted files were ignored as access to them may be unreliable (use --allow-external pyaudio to allow) No distributions at all found for pyaudio ```` <strong>How to build `pyaudio` with Raspbian?</strong> Does it need a specific tool?
Try install with the package manager: ````sudo apt-get install python-pyaudio ````
strip away html tags from extracted links I have the following code to extract certain links from a webpage: ````from bs4 import BeautifulSoup import urllib2 sys import re def tonaton(): site = "http://tonaton com/en/job-vacancies-in-ghana" hdr = {'User-Agent' : 'Mozilla/5 0'} req = urllib2 Request(site headers=hdr) jobpass = urllib2 urlopen(req) invalid_tag = ('h2') soup = BeautifulSoup(jobpass) print soup find_all('h2') ```` The links are contained in the 'h2' tags so I get the links as follows: ````<h2&gt;<a href="/en/cashiers-accra"&gt;cashiers </a&gt;</h2&gt; <h2&gt;<a href="/en/cake-baker-accra"&gt;Cake baker</a&gt;</h2&gt; <h2&gt;<a href="/en/automobile-technician-accra"&gt;Automobile Technician</a&gt;</h2&gt; <h2&gt;<a href="/en/marketing-officer-accra-4"&gt;Marketing Officer</a&gt;</h2&gt; ```` But I am interested in getting rid of all the 'h2' tags so that I have links only in this manner: ````<a href="/en/cashiers-accra"&gt;cashiers </a&gt; <a href="/en/cake-baker-accra"&gt;Cake baker</a&gt; <a href="/en/automobile-technician-accra"&gt;Automobile Technician</a&gt; <a href="/en/marketing-officer-accra-4"&gt;Marketing Officer</a&gt; ```` I therefore updated my code to look like this: ````def tonaton(): site = "http://tonaton com/en/job-vacancies-in-ghana" hdr = {'User-Agent' : 'Mozilla/5 0'} req = urllib2 Request(site headers=hdr) jobpass = urllib2 urlopen(req) invalid_tag = ('h2') soup = BeautifulSoup(jobpass) jobs = soup find_all('h2') for tag in invalid_tag: for match in jobs(tag): match replaceWithChildren() print jobs ```` But I could not get it to work even though I thought that was the best logic i could come up with I am a newbie though so I know there is something better that could be done Any help will be gracefully appreciated Thanks
You could navigate for the next element of each `<h2&gt;` tag: ````for h2 in soup find_all('h2'): n = h2 next_element if n name == 'a': print n ```` It yields: ````<a href="/en/financial-administrator-accra-1"&gt;Financial Administrator</a&gt; <a href="/en/house-help-accra-17"&gt;House help</a&gt; <a href="/en/office-manager-accra-1"&gt;Office Manager </a&gt; ````
Set timeout for Python socket when sending data out I would like to set timeout for Python socket client That means socket client connects to server then sends data within 1 second If it takes more than 1 second the method would raise some kind of exception or error Here is my source code: ````def sendDataTelnet(ipTmp strTmp): # try to send data to <ipTmp&gt; try: s = socket socket(socket AF_INET socket SOCK_STREAM) writeLog("connecting to %s" % (ipTmp)) s settimeout(1 0) s connect((ipTmp 4242)) writeLog("connected to %s start to send data" % (ipTmp)) s sendall(strTmp) s close() s = None writeLog("done writing to %s" % (ipTmp)) return True except socket timeout: writeLog("timed out when connecting to %s" % (ipTmp)) s close() s = None return False except socket error: writeLog("error when communicating with %s" % (ipTmp)) s close() s = None return False ```` This does not work for me It works only when "connect" action takes longer than 1 second However if it connects fine but it sends large amount of data that takes more than 1 second no exception raised
You could set an alarm timeout prior to the socket call and clear when done eg ````import os signal class TimeoutError(Exception): pass def handle_timeout(signum frame): import errno raise TimeoutError(os strerror(errno ETIME)) TIMEOUT=1 signal signal(signal SIGALRM handle_timeout) signal alarm(TIMEOUT) try: s = socket socket(socket AF_INET socket SOCK_STREAM) # your code except TimeoutError: print "Timeout reached" finally: signal alarm(0) ````
Unexpected behavior in pandas mad() with groupby() Suppose I create a dataframe: ````In [1]: df = pd DataFrame({'a':[1 1 1 2 2 2] 'b':[1 2 3 4 5 6]}) ```` If I do most statistics on a grouped version of that dataframe they come out as expected: ````In [2]: df groupby('a') median() Out[2]: b a 1 2 2 5 ```` But when I calculate the median absolute deviation (mad) I get an extra column 'a' which is all zeros: ````In [3]: df groupby('a') mad() Out[3]: a b a 1 0 0 666667 2 0 0 666667 ```` The mad() function seems to work fine on a normal dataframe just not on a grouped on Unless this is a feature not a bug and I just do not understand it Thoughts?
This is a bug slated to be fixed for 0 14 (releasing soon) see <a href="https://github com/pydata/pandas/issues/5610" rel="nofollow">here</a> The bug is that non-cythonized routines are calling `apply` rather than ``agg` effectively work-around is to do: ````df groupby('a') agg(lambda x: x mad()) ````
TypeError: Cannot convert 'int' object to str implicitly(python) <strong><them>Resolved and Fixed</them></strong> How do I close this? :D I have been working none stop lately on adding features to my chat bot and occasionally come across an issue that I need assistance in I have looked at other suggested threads already <strong>The Short Explanation:</strong> Trying to get it to select a number between 1 and n The command a user can use would be /roll 20 this returns 1-20 I am trying to be able to get args to replace `random randint(n)` while <strong>n = integer</strong> Sorry if my explanation is bad Been up days working nonstop <strong>The Original Code(python) before attempt:</strong> ```` elif used_prefix and cmd lower() == "roll" and self rank(user) &gt;= 1: args = args lower() if len(args) == 0: post("Select a dice amount(6 8 10 20)") else: if args == "6": post("Rolled %s" % random randint(1 6)) elif args == "8": post("Rolled %s" % random randint(1 8)) elif args == "10": post("Rolled %s" % random randint(1 10)) elif args == "20": post("Rolled %s" % random randint(1 20)) else: post("Select a dice amount(6 8 10 20") ```` <strong>The End Result Code(Python) after attempt:</strong> ````elif used_prefix and cmd lower() == "roll" and self rank(user) &gt;= 1: args = args lower() n = args lower() if len(args) == 0: post("Select a dice amount(6 8 10 20)") else: post("Rolled %s" % str(random randint(1 n))) ```` <strong>The Traceback</strong> ```` [STATUS] Setting status Online [LOAD] Loading Errors [LOAD] Loading Locks [SAVE] Appending default Connected Connected Youcoldyet(4)-[devlcars]:[/roll 20](Monday 11 May 2015 01:07:23 AM) [ERR] Fatal error (C:\Python34\lib\random py:218) Cannot convert 'int' object to str implicitly Traceback (most recent call last): File "C:\Users\Administrator\Downloads\hmm\bot py" line 575 in <module&gt; TestBot easy_start(rooms "Hidden" "Hidden") File "C:\Users\Administrator\Downloads\hmm\ck py" line 1278 in easy_start self main() File "C:\Users\Administrator\Downloads\hmm\ck py" line 1254 in main con _feed(data) File "C:\Users\Administrator\Downloads\hmm\ck py" line 550 in _feed self _process(food decode() rstrip("\r\n")) #numnumz ;3 File "C:\Users\Administrator\Downloads\hmm\ck py" line 560 in _process getattr(self func)(args) File "C:\Users\Administrator\Downloads\hmm\ck py" line 670 in rcmd_u self _callEvent("onMessage" message user message) File "C:\Users\Administrator\Downloads\hmm\ck py" line 957 in _callEvent getattr(self mgr evt)(self *args **kw) File "C:\Users\Administrator\Downloads\hmm\bot py" line 447 in onMessage post("Rolled %s" % str(random randint(1 n))) File "C:\Python34\lib\random py" line 218 in randint return self randrange(a b+1) TypeError: Cannot convert 'int' object to str implicitly [96m[SAV][0m Saving Rooms [STATUS] Setting status Offline Waiting 30 seconds for you to read the error ```` <strong>What I could do and try:</strong> I am trying to be able to get args to replace `random randint(n)` while <strong>n = integer</strong> I could try doing `n = args lower()` However when I did that it returned a value error since I was unable to get the second option selected and that would force users to use the command /roll n n I thought about trying to set the new code to be `random randint(1 n)` Then setting `n = args lower()` that would possibly allow roll selection <strong><them>Update</them></strong> Tried my idea and it simply returned: ````TypeError: Cannot convert 'int' object to str implicitly ```` I even proceeded to change the line to `post("Rolled %s" % str(random randint(1 n)))` which failed Oh and if you were wondering this is a roll command for Role Playing purposes Any and all feedback/suggestions are welcomed I am hoping to get this resolved
You need to convert `n` to an integer before using it inside `random randint(1 n)` You may use `random randint(1 int(n))`
Splitting a list inside a list I have a list of this format: ````["['05-Aug-13 10:17' '05-Aug-13 10:17' '05-Aug-13 15:17']"] ```` I am using: ````for d in date: print d ```` This produces: ````['05-Aug-13 10:17' '05-Aug-13 10:17' '05-Aug-13 15:17'] ```` I then try and add this to a `defaultdict` so underneath the `print d` I write: ````myDict[text] append(date) ```` Later I try and iterate through this by using: ````for text date in myDict iteritems(): for d in date: print d '\n' ```` But this does not work just producing the format show in the first line of code in this question The format suggests a list in a list so I tried using: ````for d in date: for e in d: myDict[text] append(e) ```` But this included every character of the line as opposed to each separate date What am I doing wrong? How can I have a `defaultdict` with this format ````text : ['05-Aug-13 10:17' '06-Aug-13 11:17'] ```` whose values can all be reached?
Your list contains only one element: the string representation of another list You will have to parse it into an actual list before treating it like one: ````import ast actual_list = ast literal_eval(your_list[0]) ````
Who won the 1876 election as a result of voter intimidation?
Wade Hampton
Flask-Script command that passes all remaining args to nose? I use a simple command to run my tests with nose: ````@manager command def test(): """Run unit tests """ import nose nose main(argv=['']) ```` However nose supports many useful arguments that now I could not pass Is there a way to run nose with manager command (similar to the call above) and still be able to pass arguments to nose? For example: ````python manage py test --nose-arg1 --nose-arg2 ```` Right now I would get an error from `Manager` that `--nose-arg1 --nose-arg2` are not recognised as valid arguments I want to pass those args as `nose main(argv= <<< args comming after python manage py test &gt;&gt;&gt;)`
In the sources of `flask_script` you can see that the `"too many arguments"` error is prevented when the executed `Command` has the attribute `capture_all_args` set to `True` which is not documented anywhere You can set that attribute on the class just before you run the manager ````if __name__ == "__main__": from flask ext script import Command Command capture_all_args = True manager run() ```` Like this additional arguments to the manager are always accepted The downside of this quick fix is that you cannot register options or arguments to the commands the normal way anymore If you still need that feature you could subclass the `Manager` and override the `command` decorator like this ````class MyManager(Manager): def command(self capture_all=False): def decorator(func): command = Command(func) command capture_all_args = capture_all self add_command(func __name__ command) return func return decorator ```` Then you can use the `command` decorator like this ````@manager command(True) # capture all arguments def use_all(*args): print("args:" args[0]) @manager command() # normal way of registering arguments def normal(name): print("name" name) ```` Note that for some reason `flask_script` requires `use_all` to accept a varargs but will store the list of arguments in `args[0]` which is a bit strange `def use_all(args):` does not work and fails with `TypeError "got multiple values for argument 'args'"`
Python-Bloomberg Open API: Are there any examples? I searched everywhere including here for an answer regarding the <a href="http://www openbloomberg com/open-api/" rel="nofollow">bloomberg open API</a> for Python I have two questions regarding this: 1 Is the historical data such as historical prices given for free? 2 If So where can I find examples regarding how to retrieve this data? I tried to use <a href="https://github com/bpsmith/pybbg" rel="nofollow">pybbg</a> but did not manage to work with it Also the <a href="http://www openbloomberg com/files/2013/04/blpapi-developers-guide pdf" rel="nofollow">Bloomberg developers guide</a> does not include Python guidelines
If you download the installer and install it from <a href="http://www openbloomberg com/open-api/" rel="nofollow">http://www openbloomberg com/open-api/</a> There is a folder called examples within the Python folder with example * py files NoAdmin_DesktopAPI_SDK\API\APIv3\Python\v3 5 5\examples
Class inheritance in python I am solving this problem : <blockquote> Consider the following hierarchy of classes: ````class Person(object): def __init__(self name): self name = name def say(self stuff): return self name ' says: ' stuff def __str__(self): return self name class Lecturer(Person): def lecture(self stuff): return 'I believe that ' Person say(self stuff) class Professor(Lecturer): def say(self stuff): return self name ' says: ' self lecture(stuff) class ArrogantProfessor(Professor): def say(self stuff): return 'It is obvious that ' self say(stuff) ```` As written this code leads to an infinite loop when using the Arrogant Professor class Change the definition of ArrogantProfessor so that the following behavior is achieved: ````e = Person('eric') le = Lecturer('eric') pe = Professor('eric') ae = ArrogantProfessor('eric') e say('the sky is blue') #returns eric says: the sky is blue le say('the sky is blue') #returns eric says: the sky is blue le lecture('the sky is blue') #returns believe that eric says: the sky is blue pe say('the sky is blue') #returns eric says: I believe that eric says: the sky is blue pe lecture('the sky is blue') #returns believe that eric says: the sky is blue ae say('the sky is blue') #returns eric says: It is obvious that eric says: the sky is blue ae lecture('the sky is blue') #returns It is obvious that eric says: the sky is blue ```` </blockquote> My solution to this is: ````class ArrogantProfessor(Person): def say(self stuff): return Person say(self ' It is obvious that ') Person say(self stuff) def lecture(self stuff): return 'It is obvious that ' Person say(self stuff) ```` But the checker gives only half marks for this solution What is the mistake that I am making and what are the test cases on which this code fails? (I am new to python and learned about classes some time ago )
You probably should use `super()` instead of hard-wiring the class `Person`: ````class ArrogantProfessor(Person): def say(self stuff): return super(ArrogantProfessor self) say(self lecture(stuff)) def lecture(self stuff): return 'It is obvious that ' super(ArrogantProfessor self) say(stuff) ````
jquery not firing on similar instances I have code; ````<script type="text/javascript"&gt; $(function() { $( "#datepicker input" ) datepicker(); }); ```` watching a form field in html I call a form using Django and only one instance of the form shows the jquery datepicker The form fields have the same class name id and are both formatted properly as input fields Any suggestions or hints would be appreciated EDIT: For more clarification The forms were being called from separate pages SOLVED: There was a condition in the html that only loaded the JQuery library depending the form returned that is where the problem was Thank you for your assistance
There should only be a single instance of an ID on a page You cannot have multiple #datepicker on one page
What area is urban and not suburban?
null
django rest return result that combines filters I am new to Django rest and i am trying to return response that have to use two query sets: The first one is for the specific project and the second one is only for specific users inside this project: serializers py ````class ProjectFiltersSerializer(serializers ModelSerializer): class Meta: model= Project fields = ('id' 'title' 'users') ```` views py ````class FiltersDetail(APIView): """ Retrieve filters instance """ def get_project(self project_pk): try: return models Project objects filter(pk=project_pk) except Snippet DoesNotExist: raise Http404 def get_returning_customers(self project_pk): return [(you pk you"%s %s" % (you first_name you last_name)) for you in User objects filter(return=1)] def get(self request project_pk format=None): snippet = self get_project(project_pk) | self get_returning_customers(project_pk) serializer = ProjectFiltersSerializer(snippet many=True) return Response(serializer data) ```` I am getting "Cannot combine queries on two different base models" Is this the right way to do this? Thanks
You can use Nested Serializer For more information: <a href="http://www django-rest-framework org/api-guide/relations/#nested-relationships" rel="nofollow">http://www django-rest-framework org/api-guide/relations/#nested-relationships</a>
You have 3 unapplied migration(s) Your project may not work properly until you apply the migrations for app(s): admin auth I have just created Django project and ran server It works fine but showed me warnings like ````You have 14 unapplied migration(s) ```` Then I ran ````python manage py migrate ```` in the terminal It worked fine but showed me this ````?: (1_7 W001) MIDDLEWARE_CLASSES is not set HINT: Django 1 7 changed the global defaults for the MIDDLEWARE_CLASSES django contrib sessions middleware SessionMiddleware django contrib auth middleware AuthenticationMiddleware and django contrib messages middleware MessageMiddleware were removed from the defaults If your project needs these middleware then you should configure this setting ```` And now I have this warning after starting my server ````You have 3 unapplied migration(s) Your project may not work properly until you apply the migrations for app(s): admin auth ```` So how do I migrate correctly to get rid of this warning? I am using PyCharm and tried to create the project via PyCharm and terminal and have the same issue ````~$ python3 5 --version Python 3 5 2 &gt;&gt;&gt; django VERSION (1 10 1 'final' 1) ````
So my problem was that I used wrong python version for migration ````python3 5 manage py migrate ```` solves problem
Any way to access methods from individual stages in PySpark PipelineModel? I have created a PipelineModel for doing LDA in Spark 2 0 (via PySpark API): ````def create_lda_pipeline(minTokenLength=1 minDF=1 minTF=1 numTopics=10 seed=42 pattern='[\W]+'): """ Create a pipeline for running an LDA model on a corpus This function does not need data and will not actually do any fitting until invoked by the caller Args: minTokenLength: minDF: minimum number of documents word is present in corpus minTF: minimum number of times word is found in a document numTopics: seed: pattern: regular expression to split words Returns: pipeline: class pyspark ml PipelineModel """ reTokenizer = RegexTokenizer(inputCol="text" outputCol="tokens" pattern=pattern minTokenLength=minTokenLength) cntVec = CountVectorizer(inputCol=reTokenizer getOutputCol() outputCol="vectors" minDF=minDF minTF=minTF) lda = LDA(k=numTopics seed=seed optimizer="them" featuresCol=cntVec getOutputCol()) pipeline = Pipeline(stages=[reTokenizer cntVec lda]) return pipeline ```` I want to calculate the perplexity on a dataset using the trained model with the `LDAModel logPerplexity()` method so I tried running the following: ````try: training = get_20_newsgroups_data(test_or_train='test') pipeline = create_lda_pipeline(numTopics=20 minDF=3 minTokenLength=5) model = pipeline fit(training) # train model on training data testing = get_20_newsgroups_data(test_or_train='test') perplexity = model logPerplexity(testing) pprint(perplexity) ```` This just results in the following `AttributeError`: ````'PipelineModel' object has no attribute 'logPerplexity' ```` I understand why this error happens since the `logPerplexity` method belongs to `LDAModel` not `PipelineModel` but I am wondering if there is a way to access the method from that stage
All transformers in the pipeline are stored in `stages` property Extract `stages` take the last one and you are ready to go: ````model stages[-1] logPerplexity(testing) ````
the dominion act was passed in what year
1871
pkg_resources resource_filename: how to return fully qualified shared library name? With Anaconda Python3 5 on Darwin the following function `import pkg_resources pkg_resources resource_filename('icqsol' 'icqLaplaceMatricesCpp') ` will return something like `'//anaconda/lib/python3 5/site-packages/icqsol-0 3 19-py3 5-macosx-10 5-x86_64 egg/icqsol/icqLaplaceMatricesCpp'` whereas what I need is `'/anaconda/lib/python3 5/site-packages/icqsol-0 3 19-py3 5-macosx-10 5-x86_64 egg/icqsol/icqLaplaceMatricesCpp cpython-35m-darwin so' ` Note the suffix <strong>' cpython-35m-darwin so'</strong> in this particular case I believe setuptools automatically adds this suffix when using python 3 5 -- it is absent when using python 2 7 Does anybody know how to return the fully qualified shared library so I can use `import ctypes sharedLibName = lib = ctypes cdll LoadLibrary(sharedLibName)) ` ? Thanks in advance for any help
`SOABI` is the key you are looking for; returns `None` on python2 and the relevant extension bits on python3 5 I added the extension suffix as well but not really sure how that works on python3 5 (on mine `SHLIB_EXT` returns `" so"` for py27 and `None` for py3) ````&gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys version_info) sys version_info(major=3 minor=5 micro=1 releaselevel='final' serial=0) &gt;&gt;&gt; import sysconfig &gt;&gt;&gt; sysconfig get_config_vars('SOABI') ['cpython-35m-darwin'] &gt;&gt;&gt; sysconfig get_config_vars() get('SHLIB_EXT' ' so') ' so' ````
What is an easy and fast way to put returned XML data into a dict? I am trying to take the data returned from: ````http://ipinfodb com/ip_query php?ip=74 125 45 100&amp;timezone=true ```` Into a dict in a fast and easy way What is the best way to do this? Thanks
`xml etree` from standard library starting from python2 5 look also at `lxml` which has the same interface I do not "dived in" to much but i think that <a href="http://www diveintopython3 org/xml html" rel="nofollow">this is also applicable to python >= 2 5 too</a> <strong>Edit:</strong> This is a fast and really easy way to parse xml do not really put data to a dict but the api is pretty intuitive
Play simple beep with python without external library Using only the modules that come with a standard python 2 6 installation would it be possible to play a simple beeping noise?
If you are on a Unix terminal you can print "\a" to get a terminal bell: ````&gt;&gt;&gt; def beep(): print "\a" &gt;&gt;&gt; beep() ```` Of course that will print a newline too… So `sys stdout write("\a")` might be better But you get the idea
How to find top values in a csv column and print the entire row having these top values using Python? I am relatively new to python and I find it to be useful since I do need to routinely find values out of a large csv file thus I tried to use it ````This is my csv file: Name Tag Size Height1 Height2 Name1 B1 244 42798 5900 Name2 BEFORE 200 22798 2234 Name3 B5 240 25798 2745 Name4 B7 220 32798 4590 ```` I tried to use this code but I still get them jumbled up ````import csv input = open('file csv' 'r') number_top_values = raw_input(‘How many top values you need to find?’) #number of top values file = csv reader(input) line1 = file next() height = [(row[3] (row[4])) for row in file] height sort(key = lambda x: x[1]) height reverse() height = height[:number_top_values] print height ```` I need to find in the column the top values for Height1 and Height2 (top 2 or top 3 so on depending on how many top values I need to find) and get the entire row having these top values Any suggestions or possible answers will be a great help Thanks
You are currently using this: ````height = [(row[3] (row[4])) for row in file] height sort(key = lambda x: x[1]) height reverse() ```` In the first line there you remove some of the data you need (since you need the whole row) The third line can be made redundant with a modification to the second line Together: ````height = list(file) height sort(key=lambda x: int(x[3]) reverse=True) ```` This sorts on `Height1` If you want to sort on `Height2` change `3` to `4` If you want to sort on one and then the other you can sort twice or do something a little trickier: ````height sort(key=lambda x: (int(x[3]) int(x[4])) reverse=True) ````
Django: multiple accounts with multiple users under each account but account-specific data Using Django 1 5 here I have an application I have created that currently has one big set of data for one "account" if you will Meaning all the data in all the models in my application are available to all logged-in users Now I want to be able to allow more people to use my application but with their own set of data So I need to separate users into different accounts with different sets of data for each account There could potentially be one or multiple users that has access to each account At this time I do not need different users within one account to have different levels of access though I do intend for one user to be the account "owner" <img src="http://i stack imgur com/semOg png" alt="enter image description here"> I know that to make this conversion I of course need to add a field to every model with a foreign key to a new "account" model But beyond that I am a little foggy This appears to be a square peg in the round hole of Django's auth system So the question is what is the best approach? A few thoughts I had so far: - Simply filter each and every query by account - Wrap each and every view with a decorator but with multiple models do I have to create a different decorator for each model? Can I tell from within the decorator which model is being accessed? - Somehow make use of the Auth system's `user_passes_test` decorator but again different models - Extend the auth system to include a `request account` attribute - Create a new mixin for my views? What if I am not using exclusively CBVs? - Different middleware? I considered using a new group for each account and then filtering by group instead of a new account model but I predict that would be a poor fit in this situation as it is not using groups as they were intended This is less of a code question and more of a big-picture best-practices question How would you approach this?
What you request is not so exotic: This is called <them>authority data</them> - you seperate your users to authorities and each authority will have each own data For instance you may have a number of departments in an organization - the data of each department can be edited only by members of the same department I have already written a blog post with a simple approach to that using django: <a href="http://spapas github io/2013/11/05/django-authoritiy-data/" rel="nofollow">http://spapas github io/2013/11/05/django-authoritiy-data/</a> To recap the post I propose just adding an `Authority` model for which your `User` will have a `ForeignKey` (each `User` will have a `Profile`) Now all your Models whose data will belong to specific `Authorities` will just contain a `ForeignKey` to `Authority` To check for the permissions you could use CBVs - the django admin will only be available to the central Administrators that have access to all the data I recommend against using the django permissions for authorization of `Authority` data If you want read the post which is much more detailed and ask here any questions
The football Association of Canada was formed on June 12 of what year?
null
How to create a HTTP proxy handler with Python 3 HTTP lib I am trying define a proxy handler to use http client behind a proxy company I know just how to use or define a proxy handler to urllib : ````http_proxy_full_auth_string = "http://"+"%s:%s@%s:%s" % (http_proxy_user http_proxy_passwd http_proxy_server http_proxy_port) proxy_handler = urllib request ProxyHandler({"http": http_proxy_full_auth_string}) opener = urllib request build_opener(proxy_handler) urllib request install_opener(opener) resp = urllib request urlopen(uri) read() ```` And using http client ? P S: sorry for the low english skills
See the <a href="https://docs python org/3/library/http client html#http client HTTPConnection set_tunnel" rel="nofollow">`httplib`</a> python 3 documentation ````import http client conn = http client HTTPSConnection("proxy_domain" 8080) conn set_tunnel("www python org") conn request("HEAD" "/index html") ````
Single double or triple double quotes for Python’s raw string notation for regex? I wonder when to use which for Python’s raw string notation for regular expressions: single quotes double quotes or triple double quotes? From <a href="https://docs python org/2/howto/regex html" rel="nofollow">https://docs python org/2/howto/regex html</a> <blockquote> When used with triple-quoted strings this enables REs to be formatted more neatly: ````pat = re compile(r""" \s* # Skip leading whitespace (?P<header&gt;[^:]+) # Header name \s* : # Whitespace and a colon (?P<value&gt; *?) # The header's value -- *? used to # lose the following trailing whitespace \s*$ # Trailing whitespace to end-of-line """ re VERBOSE) ```` </blockquote> I replaced the triple double quotes with double quotes and with single quotes but neither works The article however also uses single quotes and double quotes in other examples: ````r"\w+\s+\1" r'(\b\w+)\s+\1' ```` I wonder why? Thanks!
<strong>The benefit of raw strings</strong> With raw strings you do not have to worry about backslashes inside the string as in: ````r"\d" ```` Without the `r` the string would not reach the engine in the state you expect You would have to escape the backslash <strong>The benefit of triple quotes</strong> With triple quotes (as others have said) is that your strings can span multiple lines as in: ````r"""(?x) # let us write this complex regex in free-space mode! \d # match a digit $ # at the end of a line """ ````
how to associate a newly created EC2 security group with an instance How do I add an EC2 instance to a newly created security group? The security group was created with ````client = session client("ec2") group_id = client create_security_group( DryRun=False GroupName=group_name VpcId=vpc_id Description=description ) ````
You will want to modify the attributes of the instance: ````modify_attribute(attribute value dry_run=False) ```` `modify_attribute` changes an attribute of this instance Use the attribute <strong>groupSet</strong> - <them>Set of Security Groups or IDs</them> ````i modify_attribute('groupSet' 'sg-xxxx5678') ```` See <a href="http://boto readthedocs io/en/latest/ref/ec2 html#boto ec2 instance Instance modify_attribute" rel="nofollow">boto ec2 instance</a>
How to receive python's array in function How do I receive an array (like numpy ones) into a function? Let us say the array `a = [[2] [3]]` and the function `f` Tuples works like this: ````def f((a b)): print a * b f((2 3)) ```` But how is it with arrays? ````def f(#here): print a*b f([[2] [3]]) ````
Tuple unpacking in function arguments has been removed from Python 3 so I suggest you stop using it Lists can be unpacked just like tuples: ````def f(arg): [[a] [b]] = arg return a * b ```` Or as a tuple: ````((x ) (y )) = a ```` But I would just use indexes: ````return arg[0][0] * arg[1][0] ````
How to use the Django admin template for a form? I want to use the existing Django Admin template for a form of my own The situation is like there are two models say A and B and I want a form that displays the details about both the models in a songle form of my own So I am using a `ModelForm` But I want to use the templates from the `django admin` How can I do that?
I think its better to override the admin interface <a href="https://docs djangoproject com/en/dev/ref/contrib/admin/#overriding-admin-templates" rel="nofollow">https://docs djangoproject com/en/dev/ref/contrib/admin/#overriding-admin-templates</a>
Django admin page is missing images/css/js I have found a few questhons re my problem you the solutions did not help me so I started a new question Basically that is how I see the admin page <img src="http://i stack imgur com/hhuOv jpg" alt="no css/no js/ no images"> Apache's config: ````<VirtualHost * * * *:80&gt; ServerName ******** org ServerAdmin ****@****** org WSGIScriptAlias / /var/www/webproxy/webproxy/wsgi py DocumentRoot /var/www/cgi-bin/ ScriptAlias /cgi-bin/ /var/www/cgi-bin/ ErrorLog /var/www/webproxy/apache/error log LogLevel warn CustomLog /var/www/webproxy/apache/access log combined Alias /media/ "/var/www/webproxy/media/" <Directory "/var/www/webproxy/media/"&gt; Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny allow Allow from all </Directory&gt; <Directory "/var/www/webproxy/static/"&gt; Order deny allow Allow from all </Directory&gt; ```` This is what I have in urls py: ````from django conf urls defaults import * from django contrib import admin admin autodiscover() from core import urls as core_urls from settings import MEDIA_ROOT WEBPROXY_MEDIA_ROOT urlpatterns = patterns('' (r'^admin/' include(admin site urls)) (r'^media/(?P<path&gt; *)$' 'django views static serve' {'document_root': MEDIA_ROOT}) (r'^ui/(?P<path&gt; *)$' 'django views static serve' {'document_root': WEBPROXY_MEDIA_ROOT}) ) ```` settings py: ````MEDIA_ROOT = '/var/www/webproxy/media/' STATIC_ROOT = '/var/www/webproxy/static/' WEBPROXY_MEDIA_ROOT = '/var/www/webproxy/static/media/' ```` I am not sure what is wrong here Any help would be really appreciated
First you should not be serving the static files via `django views static serve` in production as that is meant to be used <them>only</them> for local development (read docs <a href="https://docs djangoproject com/en/dev/howto/static-files/#django views static serve" rel="nofollow">here</a>): <blockquote> There may be files other than your project's static assets that for convenience you would like to have Django serve for you in local development </blockquote> Second your Django Admin static files reside under the location Django was installed at I find using directly these files a better solution than copying (or symlink'ing) the Django admin static files under my own static files directories Example Django static files location on my server: ````/usr/local/lib/python2 7/dist-packages/django/contrib/admin/static/admin/; ```` Therefore in your web server config you have to point the url `/media/admin` to ````[my_django_location]/contrib/admin/static/admin/ ```` If you are doing things locally then you might need another entry in your `urls py`: ````(r'^admin/static/(?P<path&gt; *)$' 'django views static serve' '/path/to/your/admin/files/') ````
recv() method in python recieving a sentence instead of character This is my code which recvieves the messages from the client: ````def RecieveFromClient(clientSocket address): print "Connection from " str(clientSocket) message = None while True: message = clientSocket recv(1024) print message if message == 'c': break clientSocket close() print "client gone" ```` Now when I telnet to the server that is listening to the client and press a single character it immediately prints out the character on the server side What I want is receive a line or complete sentence from the user Is it possible?
recv() will return whenever it gets new data recv(size) will return only once it has size worth of data You are going to have to make the length of the message an explicit part of your protocol Here is the best way: prefix every message with a length either as a fixed-size integer (converted to network byte order using socket ntohs() or socket ntohl() please!) or as a string followed by some delimiter (like '123:') Source :<a href="http://stackoverflow com/a/1716173/1802922">http://stackoverflow com/a/1716173/1802922</a>
give openid users additional information So I am writing an app in python for google appengine on the jinja2 templating platform I have gotten OpenID to work just fine on my site and it allows the user to login and I can display their email/ID up in the top right corner Now I want users to have their own usernames and be able to store some additional data about them such as site visits and certain posts to areas of the site I know I need to create a table in the database with users and everything but what is the correct way to do this with OpenID I want to automatically create the user when someone logs in for the first time but I am not quite sure how to do this efficiently I think I can manage it by redirecting them to a page after login that checks their federated_identity in a database and if it exists there already it just redirects them on to the home page but if not it creates a new user Is there a more efficient way so that I am not querying the database everytime someone logs in or is that a pretty decent way to do it?
You are right you have to create your own User model and store the extra information and whatever business logic you have in your application All you have to do is to store something unique (`federated_id` for example) along with the extra `username` `name` etc After logging in with the OpenID you will check if that particular `federated_id` is in your datastore and you will return that particular `user_db` or create a new one with default values and return the newly created `user_db` The important thing is that in your requests you will always deal with your own `user_db` entity and not the `users get_current_user()` because this is basically read only and limited Here is a full example that also demonstrates a <a href="http://stackoverflow com/a/11181467/8418">base handler class</a> with the `get_user()` function that will return your own `user_db` entity if the user is logged in and `None` otherwise If the user is going to login for the first time a new user_db entity is created with some default values (`name` `username` `email` `admin` `federated_id`): ````from google appengine api import users from google appengine ext import ndb import webapp2 class User(ndb Model): name = ndb StringProperty(required=True) username = ndb StringProperty(required=True) email = ndb StringProperty() federated_id = ndb StringProperty() admin = ndb BooleanProperty() class BaseHandler(webapp2 RequestHandler): def get_user_db(self): federated_user = users get_current_user() if not federated_user: return None user_db_qry = User query(User federated_id == federated_user user_id()) user_db_list = user_db_qry fetch(1) #If that returns non empty list then return the first element which is the user_db if user_db_list: return user_db_list[0] #Otherwise create a new user_db entity with default values and return user_db = User( name=federated_user nickname() title() username=federated_user nickname() email=federated_user email() federated_id=federated_user user_id() admin=users is_current_user_admin() ) user_db put() return user_db class MainHandler(BaseHandler): def get(self): self response headers['Content-Type'] = 'text/html' if self get_user_db(): self response out write('Hello %s!</br&gt;' % self get_user_db() name) self response out write('<a href="%s"&gt;Logout</a&gt;' % (users create_logout_url(self request uri))) else: self response out write('Hello stranger!<br&gt;') self response out write('<a href="%s"&gt;Login</a&gt;' % (users create_login_url(self request uri))) app = webapp2 WSGIApplication([('/' MainHandler)] debug=True) ```` There are many different approaches to this problem but I think this is a good start to get the idea
Python - Cannot add more than 1 score to a list Sorry if I get this wrong this is my first post I wrote a program to keep a LIST of cricketers and their scores and adds new scores to their tally which works fine but when I add a new batsman I cannot add more than one score Can anyone see what I am doing wrong please I have been at this for two days now Here is the code: - ````import pickle scores = [["Moe" 100] ["Curly" 50] ["Larry" 0]] #setup the save function same as usual def save_scores(): file = open("pickle dat" "wb") pickle dump(scores file) file close() print('Scores Saved') print() #setup the load same as yours def load_scores(): file = open("pickle dat" "rb") scores = pickle load(file) file close() print(scores) print() #print the scores to the screen def print_scores(): for i in range(0 len(scores)): print(scores[i]) print() #add a score to the list def add_score(): #first setup a flag like in a bubble sort This will show if we find a name flag = False a = '' #ask for the name and the new score name = input("Enter your name: ") score = int(input("Enter your score: ")) #now count through the list of names for i in range (0 len(scores)): #take out each name and store it in var a a = (scores[i][0]) #strip the space off the end Unfortunately when Python stores names #in a list it adds spaces to the end of them The only way to strip them #off is to put them in a variable first hence a a replace(' ' '') #now we set the flag if we find the name we just typed in if a == name: #and add the score to the name in the list scores[i] append(score) flag = True #if we get to here and the flag is still false then the name does not exist #in the list so we add the name and the score to the list if flag == False: arr = (name score) scores append(arr) def print_menu(): print('1 Print Scores') print('2 Add a Score') print('3 Load Scores') print('4 Save Scores') print('5 Quit') print() menu_choice = 0 print_menu() while True: menu_choice = int(input("Type in a number (1-5): ")) if menu_choice == 1: print_scores() if menu_choice == 2: add_score() if menu_choice == 3: print_scores() if menu_choice == 4: save_scores() if menu_choice == 5: print ("Goodbye") break ````
Replace: ````arr = (name score) ```` with: ````arr = [name score] ```` The thing is you are using a `tuple` when a new player is added But `tuples` are <strong>immutable</strong> in python you cannot modify them That is the reason you are unable to append further scores to a new player Replacing `tuple` with a `list` will fix the issue as `lists` are <strong>mutable</strong>
How do I change the figure size for a seaborn violin_plot? How do I change the size of my image so it is suitable for printing? For example I would like to use to A4 paper whose dimensions are 11 7 inches by 8 27 inches in landscape orientation
You can set the context to be `poster` or manually set `fig_size` ````import numpy as np import seaborn as sns import matplotlib pyplot as plt np random seed(0) n p = 40 8 d = np random normal(0 2 (n p)) d = np log(np arange(1 p 1)) * -5 10 # plot sns set_style('ticks') fig ax = plt subplots() # the size of A4 paper fig set_size_inches(11 7 8 27) sns violinplot(data=d inner="points" ax=ax) sns despine() fig savefig('example png') ```` <a href="http://i stack imgur com/uUFRv png"><img src="http://i stack imgur com/uUFRv png" alt="enter image description here"></a>
Python smtplib security I was experimenting with an email python script and was wondering if when writing a python-based email script is it is less secure as opposed to when credentials are send over the internet when logging into a web page? In the following script are the user and pass in the clear? ````import smtplib from email mime text import MIMEText GMAIL_LOGIN = 'xxxxxx@gmail com' GMAIL_PASSWORD = 'amiexposed?' def send_email(subject message from_addr=GMAIL_LOGIN to_addr=GMAIL_LOGIN): message = MIMEText(message) message['Subject'] = 'Test message' message['From'] = from_addr message['To'] = to_addr server = smtplib SMTP('smtp gmail com' 587) server ehlo() server starttls() server ehlo() server login(GMAIL_LOGIN GMAIL_PASSWORD) server sendmail(from_addr to_addr message as_string()) server close() if __name__ == '__main__': send_email('testing email script' 'This is a test message') ````
That would entirely depend how the TLS connection is set up If you are requiring valid certificates (I believe if a certificate which is not trusted is encountered your startTLS method will throw an exception (I am not sure <strong>you should verify this</strong>)) But considering you are setting up TLS and sending everything over the TLS connection everything should be encrypted This means neither your password username or even your message and addressees will be sent in plain text So <strong>no your username and password are not send clear</strong>
PySpark Streaming example does not seem to terminate I am trying to understand the Python API of Spark Streaming by a simple example ````from pyspark streaming import StreamingContext dvc = [[-0 1 -0 1] [0 1 0 1] [1 1 1 1] [0 9 0 9]] dvc = [sc parallelize(i 1) for i in dvc] ssc = StreamingContext(sc 2 0) input_stream = ssc queueStream(dvc) def get_output(rdd): print(rdd collect()) input_stream foreachRDD(get_output) ssc start() ```` This prints the the required output but then prints a lot of empty lists at the end and does not terminate Can someone tell me where I might be going wrong
Streaming in most cases(unless terminated by conditions in your code) is supposed to be infinite The purpose of a streaming application is to consume data coming in at regular intervals And hence after processing the first 4 RDDs `(i e [[-0 1 -0 1] [0 1 0 1] [1 1 1 1] [0 9 0 9]])` you have nothing in the queue whereas spark streaming builds on the notion that something new might come into `queueStream` If you are doing a one-time ETL you might consider dropping streaming
Django Group Permission Check in Template I want to check group have permission in template for loop My Context Processors ````from django contrib auth models import User Group Permission from django db models import Q def users(request): users = User objects filter(is_active=1) exclude(id=request user id) groups = Group objects exclude(Q(name='customer') | Q(name='vendor') | Q(name='labour')) permissions = Permission objects all() return { 'all_users': users 'all_groups' : groups 'permissions' : permissions } ```` My template ````<table&gt; <tr&gt; <th&gt;Permission</th&gt; <th&gt;Content Type</th&gt; <th&gt;Access Group</th&gt; </tr&gt; {% for permission in permissions %} <tr class="item-row"&gt; <td&gt; {{permission name}} <input type="hidden" name="permission_{{permission id}}" /&gt; </td&gt; <td&gt; {{permission content_type app_label}} </td&gt; <td&gt; {% for group in all_groups %} <span class="checkboxes fln"&gt; <span class="checkbox"&gt; <small class="single checkNo"&gt; <input type="checkbox" name="group_{{group id}}_permission_{{permission id}}"/&gt; </small&gt; <b&gt;{{group name}}</b&gt; </span&gt; </span&gt; {% endfor %} </td&gt; </tr&gt; {% endfor %} </table&gt; ```` If group have permission I want to change this line ````<input type="checkbox" name="group_{{group id}}_permission_{{permission id}}" {%if 'condition' %} checked="checked" {% endif %}/&gt; ```` How can I check group have that permission
Group permissions are in well permissions: From <a href="https://docs djangoproject com/en/dev/ref/contrib/auth/#django contrib auth permissions" rel="nofollow">the docs</a> <blockquote> <strong>permissions</strong> Many-to-many field to Permission: </blockquote> So you could just do: ````{% if permission in group permissions all %} checked="checked" {% endif %} ````