input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
Python (Pandas): count of records between values at a given time (Packets in Flight) I have a DataFrame based on packet logs from a wireless channel that has indexes `"transmitted"` and `"received"` being respective floats of time since start I want to get the distribution of how many packets are in the air at any time I do this at the moment by ````t_packets = pd Series([df[(df transmitted < t) & (t < df received)] count() max() for t in range(tmax)]) ```` This is a computationally nasty (~40s for each iteration) but I have not been able to work out a better way with my limited pandas experience Anyone got any ideas for a 'better' way to accomplish this? | basically i think you want to flatten the data and create a timeseries out of it ````tx = pd DataFrame(index=df transmitted) rx = pd DataFrame(index=df received) tx['p'] = 1 #adding a packet rx['p'] = -1 #receiving a packet #create the time series here t = pd concat([tx rx]) t sort() cumsum() ```` it is easy from here figuring out the actual times you can also resample to make it clearer but this should do it <hr> edit: adding how to resample by seconds: ````#assuming that indexed times are in seconds t sort(inplace=True) t index = pd to_datetime(t index * 10e9) #to convert from nanoseconds to seconds t resample('s' how='sum') cumsum() ```` |
How to show a pandas dataframe as a flask-boostrap table? I would like to show a pandas dataframe as a boostrap-html table with flask thus I tried the following: The data ( csv table): ````Name Birth Month Origin Age Gender Carly Jan Uk 10 F Rachel Sep UK 20 F Nicky Sep MEX 30 F Wendy Oct UK 40 F Judith Nov MEX 39 F ```` The python code (`python_script py`): ````from flask import * import pandas as pd app = Flask(__name__) @app route("/tables") def show_tables(): data = pd read_csv('table csv') data set_index(['Name'] inplace=True) data index name=None females = data loc[data Gender=='f'] return render_template('view html' tables=[females to_html(classes='female')] titles = ['na' 'Female surfers']) if __name__ == "__main__": app run(debug=True) ```` The `templates` directory (`view html`): ````<!doctype html> <title>Simple tables</title> <link rel=stylesheet type=text/css href="{{ url_for('static' filename='style css') }}"> <div class=page> <h1>Surfer groups</h1> {% for table in tables %} <h2>{{titles[loop index]}}</h2> {{ table|safe }} {% endfor %} </div> ```` The boostrap `style css`: ````body { font-family: "Lucida Sans Unicode" "Lucida Grande" sans-serif;} a h1 h2 { color: #377ba8; } h1 h2 { margin: 0; } h1 { border-bottom: 2px solid #eee; } h2 { font-size: 1 2em; } table dataframe dataframe th dataframe td { border: none; border-bottom: 1px solid #C8C8C8; border-collapse: collapse; text-align:left; padding: 10px; margin-bottom: 40px; font-size: 0 9em; } male th { background-color: #add8e6; color: white; } female th { background-color: #77dd77; color: white; } tr:nth-child(odd) { background-color:#eee; } tr:nth-child(even) { background-color:#fff; } tr:hover { background-color: #ffff99;} ```` So far when I run my `python_script py`: ```` * Running on http://127 0 0 1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger pin code: 123-221-151 ```` I got two issues: a Not Found error and when I go to `http://127 0 0 1:5000/tables` I got an `builtins KeyError KeyError: 'Name'` Any idea of how to show a pandas dataframe as a table with pandas and flask? | The problem here is with the `data csv` file When you do `read_csv()` on it: ````In [45]: pd read_csv("/tmp/a csv") Out[45]: Name Birth Month Origin Age Gender 0 Carly Jan Uk 10 F 1 Rachel Sep UK 20 F 2 Nicky Sep MEX 30 F 3 Wendy Oct UK 40 F 4 Judith Nov MEX 39 F In [46]: df = pd read_csv("/tmp/a csv") In [47]: df columns Out[47]: Index([you'Name Birth Month Origin Age Gender'] dtype='object') ```` As you can see there is only one column instead of four because it cannot understand that 'Birth Month' is supposed to be one column To fix this you can open the file and change the first line to: ````"Name" "Birth Month" "Origin" "Age" "Gender" ```` And then while reading the csv: ````In [62]: pd read_csv("/tmp/a csv" sep='\s+' quotechar='"') Out[62]: Name Birth Month Origin Age Gender 0 Carly Jan Uk 10 F 1 Rachel Sep UK 20 F 2 Nicky Sep MEX 30 F 3 Wendy Oct UK 40 F 4 Judith Nov MEX 39 F ```` Or you could have also just changed `Birth Month` to `Birth_Month` For the '404 Not Found' error the problem is that you have not defined any route for '/' So (after editing the header of the csv) I would do something like: ````from flask import * import pandas as pd app = Flask(__name__) @app route("/tables") def show_tables(): data = pd read_csv("/tmp/a csv" sep='\s+' quotechar='"') data set_index(['Name'] inplace=True) data index name=None females = data loc[data Gender=='F'] return render_template('view html' tables=[females to_html(classes='female')] titles = ['na' 'Female surfers']) @app route("/") def show_home(): return "Hello Guys! Visit: <a href='/tables'> this link </a>" if __name__ == "__main__": app run(debug=True) ```` |
Can I make pprint in python3 not split strings like in python2? Is there a way to tell `pprint` in `python3` not to `split` strings on `\s`? If you send a long string into python3's `pprint` it will look for `\s` and split python2's `pprint` did not do this Can this behavior be disabled? I looked through the source for `pprint` and it does not look like there is an option I saw for this Can I trick it somehow? Here is an example of what I am getting: ````>>> PP pprint("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZ" width=-1 compact=True) ('ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ' 'ZZZZZ') ```` And here is what I want: ````>>> PP pprint("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZ" width=-1 compact=True) ('ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZ') ```` To clarify I do want it to obey widths just not for strings So when I see eg: ````PP pprint(["ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZZZZZZZZZ" "CATS"]) ```` I want: ````['ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZZZZZZZZZ' 'CATS'] ```` Not: ````['ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ' 'ZZZZZZZZZZZZZ' 'CATS'] ```` | You could just set the `width` option to a really large value such as `sys maxsize`: ````>>> import sys >>> import pprint as PP >>> PP pprint("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZ" width=sys maxsize compact=True) 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZ' ```` Setting `width` to `-1` has no special meaning The only other option is to subclass the `PrettyPrinter()` class and wrapping the `_format()` method: ````import sys from pprint import PrettyPrinter class NoStringWrappingPrettyPrinter(PrettyPrinter): def _format(self object *args): if isinstance(object str): width = self _width self _width = sys maxsize try: super() _format(object *args) finally: self _width = width else: super() _format(object *args) NoStringWrappingPrettyPrinter() pprint(yourobject) ```` This sets the width to `sys maxsize` only for strings: ````>>> NoStringWrappingPrettyPrinter() pprint(["ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZ" "CATS"]) ['ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZ' 'CATS'] ```` |
Coming from a Visual C# Express IDE/C# programming background is there a tutorial for creating python applications? It is very overwhelming coming from something that helps you create applications straight forward to something with somewhat convoluted documentation Can someone <strong>please</strong> share a tutorial on how to create a simple Hello World application using Python No I do not mean command line I mean a physical window I am trying to learn how to program in Python and so far all I find is command line applications and I do not really find use for them unless I can visually show off my skills So where can I learn some Python GUI development People have suggested wxWidgets PyQT etc but once again that means nothing to me because I know diddly squat about them I need an up to date tutorial :S | Here is a great tutorial for wxPython (my GUI API of choice: extremely powerful good community/mailing list and cross-platform (it wraps the native platform's widgets)) <a href="http://wiki wxpython org/Getting%20Started" rel="nofollow">http://wiki wxpython org/Getting%20Started</a> Installing wxpython can be done through a simple setup exe : <a href="http://downloads sourceforge net/wxpython/wxPython2 8-win32-unicode-2 8 10 1-py26 exe" rel="nofollow">http://downloads sourceforge net/wxpython/wxPython2 8-win32-unicode-2 8 10 1-py26 exe</a> or <a href="http://downloads sourceforge net/wxpython/wxPython2 8-win32-unicode-2 8 10 1-py25 exe" rel="nofollow">http://downloads sourceforge net/wxpython/wxPython2 8-win32-unicode-2 8 10 1-py25 exe</a> (depending on python version) Here is a simple hello world with a simple event bound to the button ````import wx class MyFrame(wx Frame): def __init__(self): wx Frame __init__(self None) text = wx StaticText(self label="hello world!") button = wx Button(self label="press me") sizer = wx BoxSizer(wx VERTICAL) sizer Add(text flag=wx ALL border=20) sizer Add(button flag=wx ALL border=20) self SetSizer(sizer) self Layout() self Show(True) self Bind(wx EVT_BUTTON self on_button button) def on_button(self event): wx MessageBox("Hey!") if __name__ == "__main__": app = wx App(False) f = MyFrame() ```` or an even simpler example: ````import wx app = wx PySimpleApp() frame = wx Frame(None wx ID_ANY "Hello World") frame Show(True) app MainLoop() app MainLoop() ```` |
Where can oxonium ions be found? | in acidic solution with other solvents |
Python 3 4 Tkinter Understanding code/setting window size I am trying to make a tkinter GUI using classes which I am pretty new to (I have watched all of TNB's tutorials on it) and I am having some issues with implementing features into my code and understanding it I am trying to adapt code I found on this site to get the basic structure and I cannot figure out how/why some of it works and how to add some things in This is my code so far: ````import tkinter as tk class Application(tk Tk): # Inheriting tkinter classes etc def __init__(self): tk Tk __init__(self) # Creates window? container = tk Frame(self) # Creates frame object container pack(side="top" fill="both" expand=True) # Places container/frame inside window container grid_rowconfigure(0 weight=1) # ? container grid_columnconfigure(0 weight=1) # ? self frames = {} # What does this do? for F in (MenuPage StartPage InfoPage SettingsPage): page_name = F __name__ # What is __name__ for? frame = F(container self) self frames[page_name] = frame # Creating dictionary entries? frame grid(row=0 column=0 sticky="NSEW") self show_frame("MenuPage") # Pushes menu page to top when initialised def show_frame(self page_name): frame = self frames[page_name] frame tkraise() # Raises frame to top of stack class MenuPage(tk Frame): def __init__(self parent controller): tk Frame __init__(self parent) self controller = controller label = tk Label(self text="This is the menu page") label pack(side="top" fill="x" pady=10) # Begins quiz start_btn = tk Button(self text="Start" command=lambda : controller show_frame("StartPage")) start_btn pack() # Takes user to information page info_btn = tk Button(self text="Information" command=lambda: controller show_frame("InfoPage")) info_btn pack() # Takes user to settings page settings_btn = tk Button(self text="Settings" command=lambda: controller show_frame("SettingsPage")) settings_btn pack() # Quits program/closes all GUIs quit_btn = tk Button(self text="Quit" command=self controller destroy) quit_btn pack() # First page of quiz will need to inherit from settings? class StartPage(tk Frame): def __init__(self parent controller): tk Frame __init__(self parent) self controller = controller label = tk Label(self text="This is the start") label pack(side="top" fill="x" pady=10) class InfoPage(tk Frame): def __init__(self parent controller): tk Frame __init__(self parent) self controller = controller label = tk Label(self text="This is the info page") label pack(side="top" fill="x" pady=10) # Takes user back to main menu menu_btn = tk Button(self text="Go to the menu page" command=lambda: controller show_frame("MenuPage")) menu_btn pack() class SettingsPage(tk Frame): def __init__(self parent controller): tk Frame __init__(self parent) self controller = controller label = tk Label(self text="This is the settings page") label pack(side="top" fill="x" pady=10) # Takes user back to main menu menu_btn = tk Button(self text="Go to the menu page" command=lambda: controller show_frame("MenuPage")) menu_btn pack() if __name__ == "__main__": # What does this do? app = Application() app mainloop() ```` (I want to add in functionality for the quit button where it actually closes the whole GUI program So far I have tried various methods of using destroy() as the button command and just the quit command but I am having no luck I also tried having the destroy function inside the Application() class and calling it from the command but that did not work either I am not sure whether I am using it right or not ) - Fixed thanks to Bryan Oakley and furas Another thing I have no clue how to do is changing the size parameters of the windows so that every window is say (500x200) This is easy when not using classes but I do not even know where to begin when using them and having multiple frames I have also marked/labelled some lines of code that it would be great if someone could explain to me There has been a post before going through some parts of the original code explaining but they only addressed specific parts requested by that user Thanks in advance :) (Hoping all the indentation has copied over right now) | This code was designed so that the main program (the "controller") is the central point for controlling the GUI That is why `self` (the application itself) is passed in as the `controller` parameter to the other frames Thus to call any function on the controller from one of the other pages you would call `self controller destroy()` To associate that with the quit button you would do it like this: ````quit_btn = tk Button(self text="Quit" command=self controller destroy) quit_btn pack() ```` Note: it is a very bad habit to create widgets and lay them out -- calling `pack` or `grid` or `place` -- in a single statement You should always separate the creation of widgets from arranging them on the screen When you do it in a single statement your variable will always be set to `None` which is useless |
Flask-SQLAlchemy Abstract Base Model In my Flask-SQLAlchemy App I want to add a few fields (created(by|on) changed(by|on)) to every Model/Table my code right now ````from import db class Brand(db Model): __tablename__ = 'md_brands' id = db Column(db Integer primary_key=True) name = db Column(db String(64) unique=True nullable=False) def __repr__(self): return you'<Brand {}>' format(self name) ```` I am not sure if it is better to use Mixins or somehow extend the base db Model (or if even there is a better way to do this) What (and why) is the best way to add such fields (created(by|on) changed(by|on)) to all my models? | Both are pretty much the same Here is a Mixin that I use ```` class ModelMixin(object): def __repr__(self): return unicode(self __dict__) @property def public_view(self): """return dict without private fields like password""" return model_to_dict(self self __class__) ```` and then ````class User(db Model ModelMixin): """ attributes with _ are not exposed with public_view """ __tablename__ = "users" id = db Column(db Integer primary_key=True) ```` |
What did demonstrators wear during the media rally? | wore shirts demanding that the government "Stop Killing the Press. |
Bind event to wx button directy using wx EVT_BUTTON? I read several wxPython books and am now quite familiar with binding a button with an event Such as in a wx Frame's __init__ method I wrote: ````self btn = wx Button(self 2 "click me") self btn bind(wx EVT_BUTTON self onclick) ```` where `onclick` is something need to do when the button is clicked Recently I am reading someone is wxPython code and come across the following code: ````wx Button(self 2 "click me") wx EVT_BUTTON(self 2 self onclick) ```` The writer use the above way to bind method for every button Thus I have two questions: - The wx Button is instantiated by not bound to any variable Does that means it will be garbage-collected? - I cannot find any document about calling wx EVT_BUTTON directly What actually it creates? What is the difference between it and using the `bind()` function? | Paul's comment is correct but here is some more information: To answer #1 no it will not be garbage collected The parent window owns the C++ part of the button object which in turn has a reference to the Python part of the button object So the Python object will continue to exist as long as the C++ object does For #2: There is very little difference Many years ago the `wx EVT_*` items in wx used to be ordinary functions Now they are instances of the `wx PyEventBinder` class which have a `__call__` method to provide compatibility with the old functions But as Paul mentioned using the binder instances with the `Bind` method from the `wx Window` class is preferred as it is more pythonic and makes the code a bit more self-explanitory |
What resolution didn't Microsoft come to in their certificiation guidelines? | null |
How does the Python's range function work? all I am not really understand for loop in the following can anyone give some tips?thanks in advance ````for i in range(5): print i ```` then it gives 0 1 2 3 4 is that python assign 0 1 2 3 4 to i at the same time? however if i wrote: ````for i in range(5): a=i+1 ```` then I call a it gives 5 only but if i add ''print a'' it gives 1 2 3 4 5 So my question is what is the difference here? i is a string or a list or something else? or maybe can anyone help me to sort out: ````for l in range(5): #vs fs rs are all m*n matrixs got initial values in i e vs[0] fs[0] rs[0] are known #want use this foor loop to update them vs[l+1]=vs[l]+fs[l] fs[l+1]=((rs[l]-re[l]) rs[l+1]=rs[l]+vs[l] #then this code gives vs fs rs ```` if i run this kind of code then I will get the answer only when l=5 how can I make them start looping?i e l=0 got values for vs[1] fs[1] rs[1] then l=1 got values for vs[2] rs[2] fs[2] and so on but python gives different arrays of fs vs rs correspond to different value of l how can I make them one piece? just update rows thanks | A "for loop" in most if not all programming languages is a mechanism to run a piece of code more than once This code: ````for i in range(5): print i ```` can be thought of working like this: ````i = 0 print i i = 1 print i i = 2 print i i = 3 print i i = 4 print i ```` So you see what happens is not that `i` gets the value 0 1 2 3 4 <them>at the same time</them> but rather sequentially I assume that when you say "call a it gives only 5" you mean like this: ````for i in range(5): a=i+1 print a ```` this will print the <them>last</them> value that a was given Every time the loop iterates the statement `a=i+1` will overwrite the last value `a` had with the new value Code basically runs sequentially from top to bottom and a for loop is a way to make the code go back and something again with a different value for one of the variables I hope this answered your question |
Python Tkinter Notebook with Checkbuttons I am having difficulties resolving checkbutton issue in tkinter I am trying to modify code found here on stackoverflow from another question My issue is that my check buttons start off as "square checked" when I want them to have a value of 0 thus being unchecked My second issue is that they uncheck and check together you cannot check 1 and have the other unchecked ````import sys import math from tkinter import ttk import tkinter root = tkinter Tk() note = ttk Notebook(root) OnOrOff1 = 0 OnOrOff2 = 0 tab1 = ttk Frame(note) tab2 = ttk Frame(note) tab3 = ttk Frame(note) Check1 = ttk Checkbutton(tab1 variable=OnOrOff1 onvalue=1 offvalue=0 text="Check me") Check1 grid(row=1 column=1 sticky="W") Check2 = ttk Checkbutton(tab1 variable=OnOrOff2 onvalue=1 offvalue=0 text="Check me") Check2 grid(row=2 column=1 sticky="W") note add(tab1 text = "Tab One") note add(tab2 text = "Tab Two") note add(tab3 text = "Tab Three") note grid() root mainloop() exit() ```` Thanks | The `variable` parameter to a `CheckButton` should be an IntVar not an integer ````OnOrOff1 = tkinter IntVar() OnOrOff2 = tkinter IntVar() ```` |
How to create/save files within a loop in a function? How can I save/create a file within a loop in a function? In the following example I want to run a function which prints a message and saves a file with the message in every iteration However it prints the messages but only saves the very last file (10) I guess it doesnât look so advisable The point is that my real function is a comprehensive water flow model that produces several data sets In the case that somebody wants to see or use all the data of every time step I want to avoid a clogging of the memory by writing everything to the disk I prefer losing CPU performance to a clogged memory ```` def worldloop(message='hello world' no=10): import numpy as np fname_template='/home/blubb/Desktop/blaa{cap}' for i in range(no): cap=no np save(fname_template format(cap=cap) message ) print message ```` | You set `cap = no` every iteration then use `cap` as file name so you are overwriting the same file every time Delete `cap = no` and change `np save(fname_template format(cap=cap) message )` to `np save(fname_template format(cap=i) message )` |
Davidson's argument that God cannot exist apart from the world matched whose argument? | null |
NameError: global name is not defined' creating error when it has been defined i am trying to create a program that will load a file (called lines txt) add lines to it and will remove them i am using tkinter as a gui i cannot however finish the add_line section as it always returns "NameError: global name is not defined' creating error when it has been defined " it is defined on line 29 as `listbox = Listbox(root)` the section it is failing at is in `def Add_Barcode(self):` in `def Add(self):` on line 95 `listbox insert(END term)` ````from tkinter import Tk Frame Menu import sys time math from tkinter import * try: root = Tk() root wm_title("barcode manager") root geometry("250x150+300+300") class Example(Frame): def __init__(self parent): Frame __init__(self parent) self parent = parent self initUI() def initUI(self): self parent title("Registered Barcodes ") menubar = Menu(self parent) self parent config(menu=menubar) fileMenu = Menu(menubar) fileMenu add_command(label="Add Barcode" command=self Add_Barcode) fileMenu add_command(label="Save" command=self Save) fileMenu add_command(label="Exit" command=self onExit) menubar add_cascade(label="File" menu=fileMenu) listbox = Listbox(root) listbox pack(fill=BOTH expand=1) def Popup_Menu(): menu = Menu(root tearoff=0) menu add_command(label="Edit" command=lambda:print("hello")) menu add_command(label="Delete" command=lambda:print(DeleteSelection(self))) def popup(event): menu post(event x_root event y_root) listbox bind("<Button-3>" popup) Popup_Menu() def get_lines(): lines = open('lines txt' 'r') for line in lines: barcode text = line split(' ') text strip('\n') line = ': ' join(str(x) for x in ("GTIN #" barcode text)) listbox insert(END line) get_lines() def DeleteSelection(self) : items = listbox curselection() pos = 0 for i in items : idx = int(i) - pos listbox delete( idx idx ) pos = pos 1 def Add_Barcode(self): import tkinter as tk nroot = Toplevel() nroot wm_title("Add a barcode") textbox_lbl = Label(nroot text="text") textbox_lbl pack(side=LEFT fill=Y) textbox = Entry(nroot bd=2) textbox pack(side=LEFT fill=Y) textbox pack(anchor=CENTER) barcode_lbl = Label(nroot text="barcode") barcode_lbl pack(side=LEFT fill=Y) barcode = Entry(nroot bd=2) barcode pack(side=LEFT fill=Y) barcode pack(anchor=CENTER) def Add(self): nonlocal textbox nonlocal barcode text = textbox get() barcode = barcode get() nroot destroy() a = 0 for item in barcode: a = 1 if a == 7: try: barcode = Get_Check_Digit() barcode = int(barcode) print(barcode) term = ': ' join(str(x) for x in ("GTIN #" barcode text)) print(term) listbox insert(END term) except (): error = Toplevel() error wm_title("Error") error_label = Label(error text="please enter only numbers ") error_label pack(side=TOP fill=X) else: error = Toplevel() error wm_title("Error") error_label = Label(error text="Error") error_label pack(side=TOP fill=X) error_label1 = Label(error text="please enter 7 digits") error_label1 pack(side=TOP fill=X) time sleep(5) error destroy() def Get_Check_Digit(): checklist = [] number = 1 nonlocal barcode for item in barcode: checkitem = int(item) * int(number) checklist append(checkitem) if number == 3: number = 1 elif number == 1: number = 3 checklist = sum(checklist) def roundup(x): return int(math ceil(x / 10 0)) * 10 check_digit = roundup(checklist) check_digit -= checklist num = "" join(str(x) for x in (barcode check_digit)) return num btn = Button(nroot text="Add" command=lambda:Add(self)) btn pack(side=BOTTOM fill=Y) def Save(self): global listbox for item in listbox: print(item) def onExit(self): root destroy() sys exit() app = Example(root) root mainloop() except (): pass ```` | If you want to use the listbox variable later in the Example class you need to declare it with <strong>self</strong> for example: ````self listbox = Listbox(root) ```` and then use it later like: ````self listbox insert(END term) ```` |
Before which year were the Sana'a manuscripts produced? | 671 AD |
Most efficient way to reverse a numpy array Believe it or not after profiling my current code the repetitive operation of numpy array reversion ate a giant chunk of the running time What I have right now is the common view-based method: ````reversed_arr = arr[::-1] ```` Is there any other way to do it more efficiently or is it just an illusion from my obsession with unrealistic numpy performance? | When you create `reversed_arr` you are creating a view into the original array You can then change the original array and the view will update to reflect the changes Are you re-creating the view more often than you need to? You should be able to do something like this: ````arr = np array(some_sequence) reversed_arr = arr[::-1] do_something(arr) look_at(reversed_arr) do_something_else(arr) look_at(reversed_arr) ```` I am not a numpy expert but this seems like it would be the fastest way to do things in numpy If this is what you are already doing I do not think you can improve on it P S Great discussion of numpy views here: <a href="http://stackoverflow com/questions/4370745/view-onto-a-numpy-array">View onto a numpy array?</a> |
What are two main groups of prokaryotic organisms are divided into? | Eubacteria and Archaebacteria |
How to force a directory listing using SimpleHTTPServer? I have an `index html` on the folder where SimpleHTTPServer is running but depending on the value of a URL GET parameter I want to show a directory listing instead Is that possible? I was trying to query the root directory using ajax but it returns `index html`by default I guess one possible option is to rename `index html` to something like `main html` and never use index html | You can override do_GET() and catch the path and parameter you are interested in and do the right thing from there |
clumsy comprehension cleanup I have a nested loop that blends traditional for loops with list comprehensions: ````dct = {} for row in pat_mat: l = [float(x) for x in row[1:]] dct[row[0]] = l ```` How can I aggregate this into a nested list and dictionary comprehension? Do you even think that will change the performance or readability of the code? Should I just leave it alone? Here is the input: ````pat_mat = [['A1BG' '3 59934160035066' '9 01032836656166' '7 49267439718532' '6 41276289887381'] ['A1CF' '0' '0' '0' '0'] ['A2BP1' '3 06579631517157' '5 18615584800032' '3 18689667390982' '2 61953039353937']] ```` And the desired output: ````dict = {'A1CF': [0 0 0 0 0 0 0 0] 'A2BP1': [3 06579631517157 5 18615584800032 3 18689667390982 2 61953039353937] 'A1BG': [3 59934160035066 9 01032836656166 7 49267439718532 6 41276289887381]} ```` | Maybe something like - ````dct = {row[0]:[float(x) for x in row[1:]] for row in pat_mat} ```` Also if the usage of dict in your code is not example you should not name the variable dict as it would override the built in function dict I think comprehensions are a little faster than their for-loop counterparts |
Recursion and Binary Trees ````#Get length of the longest path through recursion def max_height(node): if not node: return 0 left = max_height(node left) #Base Case based on my understanding right = max_height(node right) #Base Case based on my understanding return max_height(left right) 1 ```` I keep calling the max_height to get the length but I am getting an error I have thought of three possibilities: 1) I misunderstand the concept of the base case and I do not actually have a base case 2) I am not properly spacing Python code 3) I am not recursively getting the height of the BST at all but rather the width of the tree which is affecting later calculations I know it is similar to this question but the main difference is that I am really trying to use recursion where the other question used iteration and merely called it recursion <a href="http://stackoverflow com/questions/13322616/how-to-find-the-height-of-a-node-in-binary-tree-recursively">how to find the height of a node in binary tree recursively</a> | - The base case is where the recursion stops and you have one: `not node` (`node == None`) - I do not see an issue with the spacing Make sure you use only tabs or only spaces - This does produce the height: the number of nodes from root to leaf along the longest root-leaf path At every node level you add `1` and follow the higher subtree ````def max_height(node): if not node: # this is the base case: return 0 # where all recursive calls eventually stop left = max_height(node left) # <- these are the recursive calls: right = max_height(node right) # <- function x is called inside function x return max(left right) 1 # max here not max_height ```` Note that this is merely a more verbose version of <a href="http://stackoverflow com/questions/13322616/how-to-find-the-height-of-a-node-in-binary-tree-recursively#answer-13322724">this answer</a> to the question you linked |
When did MGM give Warner Home Video the rights to Turner Broadcasting's films on home video? | null |
What conditions are more likely to cause Exercise-induced bronchoconstriction? | when it is dry and cold |
Python/Tkinter does not update label I am developing a password program that uses Tkinter to make it nicer and I am having some issues The Tkinter label does not update yet it displays the new password in the IDLE I am still learning so please dumb it down a little bit If you need my source code here it is: ````"""Importations""" import os import pygame as pygame from pygame import mixer import random import string import sys from sys import platform as _platform import tkinter as tk from tkinter import ttk """Program Definitions""" #Color Definitions backgroundColor = ("#001F33") #Random password = ("") #Font Sizes LARGE_FONT = ("Times" 16) LARGE_FONT = ("Times" 14) NORMAL_FONT = ("Times" 12) SMALL_FONT = ("Times" 10) XXS_FONT = ("Times" 8) """Various Functions""" #Quit def quitprog(): sys exit() """Class Setup""" #Window Setup class passwordGeneratorApp(tk Tk): #Initialize def __init__(self *args **kwargs): #Container Setup tk Tk __init__(self *args **kwargs) tk Tk iconbitmap(self default = "C:/Program Files/passGenerator/assets/images/programIcon ico") tk Tk wm_title(self "Random Password Generator") container = tk Frame(self) container pack(side = "top" fill = "both" expand = True) container grid_rowconfigure(0 weight = 1) container grid_columnconfigure(0 weight = 1) #MenuBar menubar = tk Menu(container) #FileMenuBar filemenu = tk Menu(menubar tearoff = 1) filemenu add_command(label = "Help" command = lambda: forhelp("For Help Contact the Following!")) filemenu add_separator() filemenu add_command(label = "Exit" command = quitprog) menubar add_cascade(label = "File" state = "disabled" menu = filemenu) tk Tk config(self menu = menubar) self frames = {} #Pages to be Displayed for F in (welcomeScreen generator): frame = F(container self) self frames[F] = frame frame grid(row = 0 column = 0 sticky = "nsew") self show_frame(welcomeScreen) #Show Frame def show_frame(self cont): frame = self frames[cont] frame tkraise() """Pages""" #Welcome Screen class welcomeScreen(tk Frame): #Initialize def __init__(self parent controller): tk Frame __init__(self parent) welcomeScreen configure(self background = backgroundColor) #Generator def generatePass(): char_set = string ascii_uppercase string digits password = ('' join(random sample(char_set*6 6))) print(password) #Openning text_file = open("C:/Program Files/passGenerator/assets/descriptions/welcomemsg txt" "r") file = text_file read() text_file close() #Setups titleLabel = ttk Label(self text = "Random Password Generator" font = LARGE_FONT) msgWelcome = ttk Label(self text = file font = NORMAL_FONT) generateButton = ttk Button(self text = "Generate" command = generatePass) viewButton = ttk Button(self text = "View Passcode" command = lambda: controller show_frame(generator)) #Placement titleLabel pack(pady = 10) msgWelcome pack() generateButton pack(pady = 5) viewButton pack() #Generator class generator(tk Frame): #Initialize def __init__(self parent controller): tk Frame __init__(self parent) generator configure(self background = backgroundColor) char_set = string ascii_uppercase string digits password = ('' join(random sample(char_set*6 6))) print(password) passwordcode = ("You are password is: %s" % password) #Setup titleLabel = ttk Label(self text = "Password Generator" font = LARGE_FONT) displayButton = ttk Button(self text = "Display Password" command = lambda: controller show_frame(welcomeScreen)) passwordLabel = ttk Label(self text = passwordcode font = NORMAL_FONT) #Placement titleLabel pack(pady = 5) displayButton pack() passwordLabel pack(pady = 5) pygame mixer init() app = passwordGeneratorApp() app geometry("1280x720") app mainloop() ```` NOTE: I am running Python 3 4 on Windows | The problem is that the new `generator` frame (you should write class names in capital by the way) is only constructed once in this line: ````frame = F(container self) ```` where `F` is the `generator` class This line is called once in the entire run of your script meaning the value not gettin updated after the first password generation You have two options: - You can destroy the two frames instead of hiding them and just construct them again when they need to be displayed - You can use your current system with raising windows and update the values of the `passwordLabel` widget |
Iteratively insert rows into a postgreSQL database using SQLAlchemy in python I am writing a script that reads data from excel files and writes into a postgresql database I have read data from the excel file and stored each row data as an array of strings I tried a couple of things like <br/><br/> ```` for x in range(len(sh columns)): i = users insert() i execute({sh columns[x] : sh values[0][x]}) ```` Here sh is the reference to my excel sheet and the table I am editing in the postgreSQL database i referred to by users <br/> I also tried an `'INSERT INTO users VALUES %s'%(tuple(sh values[0])` and a few more variations of that <br/> This is really urgent and I have spent over three days on this one task unable to figure out how to go about it | To make sure you can write to the table try in more raw way: ````i execute( "INSERT INTO table (field1 field2 field3) VALUES (%s %s %s) " % (data1 data2 data3) ) ```` Modify the above to have appropriate table name field names and data values Once this works you can refine writing from sh |
ModelForm data not saving django I have read the other posts on here about form data not saving but cannot seem to pinpoint my own problem Have a feeling its something really basic I am missing Really appreciate the help thanks ````#model class AboutMe(models Model): title = models CharField(max_length=30) user = models ForeignKey(User) post = models TextField() created = models DateTimeField(auto_now_add=True) def __unicode__(self): return self title #form class AboutMeForm(forms ModelForm): class Meta: model = AboutMe fields = ['title' 'post'] #view def post_line(request): if request method == 'POST': form = AboutMeForm(request POST) if form is_valid(): new_about = form save(commit=False) new_about user = request user new_about save() return HttpResponseRedirect('index html') else: form = AboutMeForm() return render_to_response('post_line html' locals() context_instance=RequestContext(request)) #template: <div class="post_line"> <form enctype="multipart/form-data" action=' ' method="post">{% csrf_token %} {{ form as_table }} <input type="submit" name="submit" value="post" /> </form> </div> ```` | I am not able to comment here so i am writing here 1) `HttpResponseRedirect('index html')` this is wrong here you have to pass some url like /login/ or /profile/ 2) please print your form like print form and check what you are getting is all fields are valid or anything missing and then tell the form error |
mod_wsgi on archlinux with python 3 2 I actually had mod_wsgi working with python3 1 but after updating some software it no longer works I followed these instructions for python3 1 modified slightly for 3 2: <a href="https://wiki archlinux org/index php/Mod_wsgi" rel="nofollow">https://wiki archlinux org/index php/Mod_wsgi</a> and while it seems to build/install ok trying to start apache give me the error : Cannot load /etc/httpd/modules/mod_wsgi so into server: /etc/httpd/modules/mod_wsgi so: undefined symbol: PyCObject_FromVoidPtr just as this guy got: <a href="http://stackoverflow com/questions/1547310/python-3-1-1-with-enable-shared-will-not-build-any-extensions">Python 3 1 1 with --enable-shared : will not build any extensions</a> Any help would be appreciated I am a linux noob | The released versions of mod_wsgi cannot be used with Python 3 2 You must currently use source code directly from subversion repository for mod_wsgi See: <a href="http://code google com/p/modwsgi/source/checkout" rel="nofollow">http://code google com/p/modwsgi/source/checkout</a> |
Returning a PDF response in Django I am asking a very similar question to <a href="http://stackoverflow com/questions/5008466/return-pdf-response-from-stdout-with-django">this one</a> I am creating a pdf using wkhtmltopdf on an Ubuntu server in Django ````from tempfile import * from subprocess import Popen PIPE tempfile = gettempdir()+"/results pdf" papersize = 'Tabloid' orientation = 'Landscape' command_args = "wkhtmltopdf -O %s -s %s -T 0 -R 0 -B 0 -L 0 http://pdfurl %s" %(orientation papersize tempfile) popen = Popen(command_args stdout=PIPE stderr=PIPE) pdf_contents = popen stdout() read() popen terminate() popen wait() response = HttpResponse(pdf_contents mimetype='application/pdf') return response ```` This gives me a "no such file or directory" error on the popen = Popen line So I changed that line to ````popen = Popen(["sh" "-c" command_args] stdout=PIPE stderr=PIPE) ```` and now I get a "'file' object is not callable" error on the pdf_contents = line I have also tried adding communicate() to the popen = line but I cannot seem to locate the pdf output that way I should add that typing the command_args line into the command line creates a pdf just fine Can anyone point me in the right direction? | You might want to consider changing ````popen = Popen(command_args stdout=PIPE stderr=PIPE) pdf_contents = popen stdout() read() # response = ```` to ````pdf_contents = subprocess check_output(command_args split()) response = ```` or in older versions: ````process = Popen(command_args split() stdout=PIPE stderr=PIPE) pdf_contents = process stdout read() response = ```` I suggest you take a look at the <a href="http://docs python org/library/subprocess html#subprocess check_output" rel="nofollow">check_output</a> function EDIT: Also do not call terminate() as it will kill the process without waiting it to complete possibly resulting in a corrupted PDF You will pretty much only need to use wait() as it will wait for the process to complete (and thus output all it has to output) When using the check_output() function you need not to worry about it as it waits for the process to complete by "default" Other than that naming a variable with the same name as a module (I am talking about tempfile) is a <them>bad</them> idea I suggest you to change it to tmpfile and to check out <a href="http://docs python org/library/tempfile html#tempfile NamedTemporaryFile" rel="nofollow">NamedTemporaryFile</a>s as it is safer to use than what you are doing right now |
Parsing <TR> </TR> tags and printing the elements using BeautifulSoup in Python I am new to Python and I am currently working on solving problems to improve my coding skills I had submitted a form using python and from the next page that is displayed after submitting the form I want to collect some data and display it in my output The required data I want to collect is between `<TR> </TR>` tags and there are lot of `<TR> </TR>` like that in that page for your reference: ````<TR class="even"><TD class="id">6422275</TD><TD class="date"><NOBR>09:06:49</NOBR><BR><NOBR>27 Feb 2016</NOBR></TD><TD class="coder"><A HREF="author aspx?id=201837">THE_ROCK</A></TD><TD class="problem"><A HREF="problem aspx?space=1&amp;num=1000">1000<SPAN CLASS="problemname"> A+B Problem</SPAN></A></TD><TD class="language">Python 2 7</TD><TD class="verdict_ac">Accepted</TD><TD class="test"><BR></TD><TD class="runtime">0 015</TD><TD class="memory">160 KB</TD></TR> ```` So from the whole HTML page I want to read the name `THE_ROCK` (it is present in the above give tag) and if that exists in that page I want to print the complete elements (like problem problemname verdict_ac runtime and memory) in that particular `<TR> </TR>` tags I understood that I can use `BeautifulSoup` but I do not know how to compare stuff and print the elements / tags that are needed specifically Code: ````res = br submit() final_url = res geturl() html_doc = br open(final_url) html_read = (html_doc read()) soup = BeautifulSoup(data convertEntities=BeautifulSoup HTML_ENTITIES) for row in soup find_all('TR'): print '\n' join(row stripped_strings) ```` I am trying to find the `TR` tag but it was not helpful and no output is being printed Can someone tell me where am I doing wrong Is my approach wrong or flow is wrong? Could you please tell me why I am not able to get the output as expected Thanks in advance Any help would be much appreciated | Maybe this will help: ````soup = BeautifulSoup(devs_html 'html parser') row = soup find_all('tr' class_='even') In [195]: row Out[195]: [<tr class="even"><td class="id">6422275</td><td class="date"><nobr>09:06:49</nobr><br><nobr>27 Feb 2016</nobr></br></td><td class="coder"><a href="author aspx?id=201837">THE_ROCK</a></td><td class="problem"><a href="problem aspx?space=1&amp;num=1000">1000<span class="problemname"> A+B Problem</span></a></td><td class="language">Python 2 7</td><td class="verdict_ac">Accepted</td><td class="test"><br/></td><td class="runtime">0 015</td><td class="memory">160 KB</td></tr>] In [196]: row[0] contents Out[196]: [<td class="id">6422275</td> <td class="date"><nobr>09:06:49</nobr><br><nobr>27 Feb 2016</nobr></br></td> <td class="coder"><a href="author aspx?id=201837">THE_ROCK</a></td> <td class="problem"><a href="problem aspx?space=1&amp;num=1000">1000<span class="problemname"> A+B Problem</span></a></td> <td class="language">Python 2 7</td> <td class="verdict_ac">Accepted</td> <td class="test"><br/></td> <td class="runtime">0 015</td> <td class="memory">160 KB</td>] ```` Ok so basically we just searched for rows via the row class (: table row) That should give you a list of rows that you can iterate over Just taking a single row row[0] as an example you can see that you have all the data () contained in the row To get the info out of them you can do: ````In [197]: row[0] find(class_='id') text Out[197]: you'6422275' In [198]: row[0] find(class_='coder') text Out[198]: you'THE_ROCK' ```` And so on until you have all the info you want EDIT: Ok if you just want to find THE_ROCK and print the row: ````for r in row: if 'THE_ROCK' in r find(class_='coder') text: print(r) ```` That should give you the entire row and you can do what whatever you would like with it |
Creating a console in Kivy I am trying to write a very basic Kivy program that will use 3 different layouts to split the screen into : - a header (at the top of the screen) - a text zone (in the middle of the screen) - a console (at the bottom of the screen) So far I was thinking to use a main gridLayout in which I use 3 different floatLayout Here is what the code looks like: ````class Logo(App): def build(self): layout = GridLayout(rows=3) layoutTop = FloatLayout(size=(100 300)) layoutMid = FloatLayout(size=(100 300)) layoutDown = FloatLayout(size=(100 300)) logo = Image(source='imagine png' size_hint=( 25 25) pos=(30 380)) blank = Label(text='' font_size = '25sp' pos=(-200 100)) titre = Label(text='#LeCubeMedia' font_size='40sp' pos=(0 280)) ip = Label(text='192 168 42 1' font_size='25sp' pos=(250 280)) layoutTop add_widget(titre) layoutTop add_widget(logo) layoutTop add_widget(ip) layoutMid add_widget(blank) layout add_widget(layoutTop) layout add_widget(layoutMid) return layout if __name__ == '__main__': Logo() run() ```` Actually my problem is regarding the creation of the console I have read a lot of the <a href="http://kivy org/docs/api-kivy html" rel="nofollow">Kivy docs</a> but I am still looking for a good way to do this type of widget How do you think it would be if I send something with a Python `print` into my Kivy app and then refresh as soon as I need to send something else (to erase the previous print) This way it would be a console-like But so far I have not much ideas Any ideas ? | I have seen 2 types of consoles in Kivy The first is a multiline textinput in a scrollview where you append the new text to the old in the textinput The second is a BoxLayout or GridLayout in a Scrollview where each console output is a separate label in the layout |
How to take multiple sets of inputs separated by space and carriage return in Python 3? So we are allowing a user to enter the number sets they want to enter Each set of input will contain two integers separated by space Then the carriage return denotes the next set of inputs For example ````Enter number of sets: 3 1 3 2 4 5 6 ```` Next we input these in variables a b perform same operations display 3 results: ````4 3 1 ```` It should first take all inputs <them>and then</them> show all respective outputs We have the logic of processing 1 set of input but how do we loop it so that we can accept input in this format? ````sets = int(input("Enter number of sets: ")) inputs = [] for n in range(sets): inputs[n] = int(input() strip()) ```` This crashes with list out of range error We were thinking of creating a list of lists to hold the pair of values Any easier solutions? EDIT: What I am looking for is a way to solve this problem It does not have to be done via lists specifically It is not a generic list out of range problem I do understand what is going wrong I just need another way to do it | The `input()` is returning a string like `"1 3"` Parse that string with something like `a b = map(int input() split())` Save the output by using <them>list append()</them> ````from pprint import pprint inputs = [] results = [] sets = int(input("Enter number of sets: ")) for n in range(sets): s = input() a b = map(int s split()) result = a b inputs append([a b]) results append(result) pprint(inputs) pprint(results) ```` A sample session looks like this: ````Enter number of sets: 3 1 3 2 4 5 6 [[1 3] [2 4] [5 6]] [4 6 11] ```` The learning points are: - Use <a href="https://docs python org/3 5/library/stdtypes html#str split" rel="nofollow">str split()</a> to convert a string like `"1 3"` into a list like `['1' '3']` - Use <a href="https://docs python org/3 5/library/functions html#map" rel="nofollow"><them>map()</them></a> with <a href="https://docs python org/3 5/library/functions html#int" rel="nofollow"><them>int()</them></a> to convert `['1' '3']` to `[1 3]` - Use <a href="https://docs python org/3 5/tutorial/controlflow html#unpacking-argument-lists" rel="nofollow">variable unpacking</a> to extract the two values - Use <a href="https://docs python org/3 5/library/stdtypes html#mutable-sequence-types" rel="nofollow"><them>append()</them></a> to grow the <them>inputs</them> and <them>results</them> lists |
Python comparison of previous data I have a program that asks the user for raw input and then displays it What I want to do is this: If the user enters data that was different from the previous data entered then update the data else do nothing So all I am doing is checking whether the data the user enters is the same as the one they entered before but I would like to know how I go about doing this in Python | Here is a simple way to do it: ````user_input = raw_input('enter an input\n') user_input2 = raw_input('confirm your input\n') if user_input != user_input2: print 'updating ' user_input = user_input2 print 'Input is: {}' format(user_input) ```` If you need to split up a string of input see the documentation for str split and other handy built in functions: <a href="https://docs python org/2/library/stdtypes html#str split" rel="nofollow">https://docs python org/2/library/stdtypes html#str split</a> |
scipy signal spectrogram output not as expected I am using `scipy signal spectrogram()` for analysing a dataset containing values for a current My input to the function is as follows: ````f t Sxx = signal spectrogram(y fs) ```` (for plotting in subplot 3 (from the top) I use `plt pcolormesh(t f Sxx)`) Where `y` is a list of 10002 values containing the y values for the green graph in the first plot (from the top) `fs = 1/T` where `T = x[1]-x[0]` where `x` is the list of x values (time) belonging to the y-values (current) My problem is that ````t[-1]-t[0] != x[-1]-x[0] ```` Meaning: I want to compare plot 3 with the green graph in plot 1 and when these two do not range over the same time-span the spectrogram becomes useless You can see from the picture that `total_length_x > total_length_t` <a href="http://i stack imgur com/HCI6k png" rel="nofollow"><img src="http://i stack imgur com/HCI6k png" alt="enter image description here"></a> Why is this so? And what can I do to make the spectrum range over the same time-span as my original data? | I wrote some code to explain my comments above about the sizes of the data: ````#!/usr/bin/env python import numpy as np import scipy signal from scipy signal import spectrogram WINDOW_LEN = 256 OVERLAP_LEN = WINDOW_LEN / 8 DATA_LEN = 10002 DURATION = 2 0001997 fs = (DATA_LEN - 1) / DURATION eps = 1/(fs * 1000 0) y = np random rand(DATA_LEN) x = np arange(0 DURATION 1/fs 1/fs) f t Sxx = spectrogram(y fs=fs nperseg=WINDOW_LEN) T = np zeros( int(1 np floor((len(y) - WINDOW_LEN) / (WINDOW_LEN - OVERLAP_LEN))) ) T[0] = x[WINDOW_LEN / 2] T[1:] = [x[WINDOW_LEN / 2 (n 1) * (WINDOW_LEN - OVERLAP_LEN)] for n in np arange(0 len(T) - 1)] if all(t - T < eps): print (t - T) print "All are fine" print x[-1] - x[0] print t[-1] - t[0] print T[-1] - T[0] else: print t print T print "Wrong estimates" ```` |
Parsing multiple instance within a sentence in XML - Python I have an xml file that has the following structure where I have several `instances` within a `sentence`: ````<corpus> <text> <sentence> <instance\> <instance\> <instance\> <\sentence> <\text> <\corpus> ```` <strong>How do I extract the whole sentence with all the instances in the sentence?</strong> When i tried `sentence text` it only gives me the words before the first instance `sentence find('instance') text` only gives me the string from the first instance `sentence find('instance') tail` only gives me the words after the first instance before the next instance I have tried this as i prefer the simplicity of `elementtree`: ````import xml etree ElementTree as et input = '''<corpus lang="en"> <text id="d001"> <sentence id="d001 s001"> Your Oct 6 <instance id="d001 s001 t001" lemma="editorial" pos="n">editorial</instance> `` The <instance id="d001 s001 t002" lemma="Ill" pos="a">Ill</instance> <instance id="d001 s001 t003" lemma="Homeless" pos="n">Homeless</instance> '' <instance id="d001 s001 t004" lemma="refer" pos="v">referred</instance> to <instance id="d001 s001 t005" lemma="research" pos="n">research</instance> by us and <instance id="d001 s001 t006" lemma="six" pos="a">six</instance> of our <instance id="d001 s001 t007" lemma="colleague" pos="n">colleagues</instance> that was <instance id="d001 s001 t008" lemma="report" pos="v">reported</instance> in the Sept 8 <instance id="d001 s001 t009" lemma="issue" pos="n">issue</instance> of the Journal of the American Medical Association </sentence> </text> </corpus>''' print>>open('tempfile' 'a+) input corpus = et parse('tempfile') getroot() for text in corpus: for sentence in text: before1st = sentence text instance1st = sentence find('instance') text after1st = sentence find('instance') tail print str(before1st instance1st after1st) replace("\n" " ") strip() ```` The above code only outputs: ````Your Oct 6 editorial `` The ```` The desired output should be the full sentence: ````Your Oct 6 editorial `` The Ill Homeless '' to research by us and six of our colleagues that was reported in the Sept 8 issue of the Journal of the American Medical Association ```` | To get all match use `findall` ````out = [] sentences = corpus findall(' //sentence') for sentence in sentences: out append(sentence text) instances = sentence findall('instance') for instance in instances: out append(instance text) out append(instance tail) out append(sentence tail) filterout = [] for i in out: txt = i replace('\n' ' ') strip() if len(txt): filterout append(txt) print ' ' join(filterout) ```` |
Best way to check multiple equalities? Preferably in Python What is the best way to create a function that checks for multiple equalities? I want the function to return 1 if the input is equal to "f" "fall" "F" "Fall" "fa" etc and if "fall" is in a dictionary | You can do a pythonic version using `filter` combined with 'len > 1' ````input = "fall" the_list = ["f" "fall" "F" "Fall" "fa"] your_test = len(filter(lambda x: x == input the_list)) > 1 \ and "fall" in your_dictionary ```` |
Django: DatabaseError: near "í¤í±í¤í±ï¿½ï¿½ ��1": syntax error The code: ````>>> from django core import serializers >>> objects = serializers deserialize('xml' fixturestr encode('utf8')) >>> o = next(objects) >>> o <DeserializedObject: countries Country(pk=AF)> >>> type(o) <class 'django core serializers base DeserializedObject'> >>> dir(o) ['__class__' '__delattr__' '__dict__' '__doc__' '__format__' '__getattribute__' '__hash__' '__init__' '__module__' '__new__' '__reduce__' '__reduce_ex__' '__repr__' '__setattr__' '__sizeof__' '__str__' '__subclasshook__' '__weakref__' 'm2m_data' 'object' 'save'] >>> o save() Traceback (most recent call last): File "<console>" line 1 in <module> File "/home/marcintustin/oneclickrep/oneclickcosvirt/lib/python2 7/site-packages/django/core/serializers/base py" line 165 in save models Model save_base(self object using=using raw=True) File "/home/marcintustin/oneclickrep/oneclickcosvirt/lib/python2 7/site-packages/django/db/models/base py" line 524 in save_base manager using(using) filter(pk=pk_val) exists())): File "/home/marcintustin/oneclickrep/oneclickcosvirt/lib/python2 7/site-packages/django/db/models/query py" line 562 in exists return self query has_results(using=self db) File "/home/marcintustin/oneclickrep/oneclickcosvirt/lib/python2 7/site-packages/django/db/models/sql/query py" line 441 in has_results return bool(compiler execute_sql(SINGLE)) File "/home/marcintustin/oneclickrep/oneclickcosvirt/lib/python2 7/site-packages/django/db/models/sql/compiler py" line 818 in execute_sql cursor execute(sql params) File "/home/marcintustin/oneclickrep/oneclickcosvirt/lib/python2 7/site-packages/django/db/backends/util py" line 40 in execute return self cursor execute(sql params) File "/home/marcintustin/oneclickrep/oneclickcosvirt/lib/python2 7/site-packages/django/db/backends/sqlite3/base py" line 337 in execute return Database Cursor execute(self query params) DatabaseError: near "í¤í±í¤í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í í° ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¬í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¤í±í¤í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¨í±í¨í±ï¿½ï¿½ï¿½ï¿½1": syntax error ```` The query and params: ````(Pdb) query you'SELECT (1) AS "a" FROM "country" WHERE "country" "iso" = ? LIMIT 1' (Pdb) params (you'AF' ) ```` To be honest I am stumped - I do not even know where to go with this one The query should not even be as long as the horror presented The error message does not decode as utf-8 either The underlying task is to read in an xml fixture and push it to the database Unfortunately the standard `loaddata` command cannot cope with non-ascii characters in utf-8 xml (see my other recent questions if you are interested) For that reason I am trying to do what `loaddata` does but manually so that I can pass the deserializer utf-8 encoded bytes Running python 2 7 5 with django 1 4 on linux I will be grateful for a way to avoid this problem entirely or any hints on how to solve or even further diagnose it Update: This is the result of trying the query manually: ````>>> import sqlite3 >>> conn = sqlite3 connect('database sqlite3 db') >>> c = conn cursor() >>> c execute(you'SELECT (1) AS "a" FROM "country" WHERE "country" "iso" = ? LIMIT 1' (you'AF' )) Traceback (most recent call last): File "<console>" line 1 in <module> OperationalError: near "í¤í±í¤í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í í° ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¬í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¤í±í¤í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¨í±í¨í±ï¿½ï¿½ï¿½ï¿½1": syntax error >>> c execute(you'SELECT (1) AS "a" FROM "country" WHERE "country" "iso" = AF LIMIT 1') Traceback (most recent call last): File "<console>" line 1 in <module> OperationalError: near "í¤í±í¤í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í í° ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¬í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¤í±í¤í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í í° ï¿½ï¿½ï¿½ï¿½í«í° í¬í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½": syntax error >>> c execute(you'SELECT * from "country" WHERE "country" "iso" = AF LIMIT 1') Traceback (most recent call last): File "<console>" line 1 in <module> OperationalError: near "í¤í±í¤í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í§í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¥í±ï¿½ï¿½ï¿½ï¿½í¨í±í¨í±ï¿½ï¿½ï¿½ï¿½1����": syntax error >>> c execute(you'SELECT * from "country"') Traceback (most recent call last): File "<console>" line 1 in <module> OperationalError: near "í¤í±í¤í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½": syntax error >>> c execute('SELECT * from "country"') <sqlite3 Cursor object at 0x4123f10> >>> ```` My terminal is set to use utf-8 It is not clear why passing a unicode object is going so horribly wrong Update 2: This is the version info for sqlite: ````>>> sqlite3 version_info (2 6 0) >>> sqlite3 sqlite_version_info (3 7 11) >>> sqlite3 sqlite_version '3 7 11' >>> sqlite3 x '11' >>> ```` update 3: The same error occurs for every table in the database if attempting to use unicode strings update 4: The same error affects fresh databases Here is the result of running <a href="http://docs python org/2/library/sqlite3 html" rel="nofollow">the example code from the python docs</a> then trying to do a unicode query: ````>>> conn close() >>> conn = sqlite3 connect('example db') >>> c = conn cursor() >>> >>> # Create table >>> c execute('''CREATE TABLE stocks (date text trans text symbol text qty real price real)''') <sqlite3 Cursor object at 0x43e9180> >>> >>> # Insert a row of data >>> c execute("INSERT INTO stocks VALUES ('2006-01-05' 'BUY' 'RHAT' 100 35 14)") <sqlite3 Cursor object at 0x43e9180> >>> >>> # Save (commit) the changes >>> conn commit() >>> c execute(you'SELECT * FROM "stocks"') Traceback (most recent call last): File "<console>" line 1 in <module> OperationalError: near "í¤í±í¤í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½í¥í° í®í±ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½": syntax error >>> ```` Update 5: The package which provides the sqlite libraries is `sqlite-3 7 11-3 fc17 x86_64` | This was almost certainly caused by my having two different versions of python After I cleared out the existing python and reinstalled from source everything works as it should For those who want to recompile from source: - Redhat compiles with UCS-4 enabled as opposed to the default UCS-2 You probably want to configure with something like ` /configure --prefix=/usr --enable-shared --enable-unicode=ucs4` - Python has a lot of dependencies The package manager commands here are probably the easiest way to figure out what you are missing: <a href="http://docs python org/devguide/setup html" rel="nofollow">http://docs python org/devguide/setup html</a>â - Remember if you are using a virtualenv that your environment is likely not picking up changes in your global python |
How do I do a basic REST Post with Requests in Python? I am having trouble using <a href="http://docs python-requests org/en/latest/" rel="nofollow">Requests</a> The API I am testing indicates the parameter device_info to be POSTED in the message body It also says that the device_info as a form field In all the documentation for <a href="http://docs python-requests org/en/latest/" rel="nofollow">Requests</a> I cannot find how to add a "name" to the parameter other than slap the name with it is value in json Here is what I have tried ````import requests import json loginPayload = {'device_info':{'app-id':'fc' 'os-type':'ios'}} loginHeaders = {'content-type': 'application/json' 'Authorization':'Basic base64here'} loginUrl = "http://subdomain test com/endpoint/method" loginPost = requests post(loginUrl params=json dumps(loginPayload) headers=loginHeaders) print loginPost text ```` I have tried changing `params=` to `data=` but I have had no luck The response back I am getting is: ````{ "response": { "message": "Parameter 'device_info' has invalid value ()" "code": 400 "id": "8c4c51e4-9db6-4128-ad1c-31f870654374" } } ```` EDITED: Getting somewhere new! I have no modified my code to look as follows: ````import requests login = 'test' password = 'testtest' url = "http://subdomain domain com/endpoint/method" authentication = (login password) payload = {'device_info': {'device_id': 'id01'}} request = requests post(url data=payload auth=authentication) print request text ```` Which produces: ````{ "response": { "message": "Parameter 'device_info' has invalid value (device_id)" "code": 400 "id": "e2f3c679-5fca-4126-8584-0a0eb64f0db7" } } ```` What seems to be the the issue? Am I not submitting it in the required format? EDITED: The solution was changing my parameters to: ````{ "device_info": "{\"app-id\":\"fc\" \"os-type\":\"ios\" \"device_id\":\"myDeviceID1\"}" } ```` | So there are a few issues here: - You do not say that the website you are posting to requires JSON data in fact in your comment you say that "the encoding that is required is 'application/x-www-form-urlencoded' - `params` refers to the parameters of the query string What you need is the `data` parameter So if your application is looking for 'application/x-www-form-urlencoded' data you should NOT be: - Setting the `Content-Type` header - Using `json dumps` on your payload data What you should do is the following: ````import requests login_payload = {'device_info': {'app-id': 'fc' 'os-type': 'os'}} authentication = (login password) # Anyone who sees your authorization will be able to get this anyway url = 'http://example com/login' response = requests post(url data=login_payload auth=authentication) ```` I do not know of a RESTful API that takes x-www-form-urlencoded data but you could also be describing your issue incorrectly You have not given us much to go on and you have not given me more than the ability to guess As such this is my absolute best guess based on everything else you said |
Most frequent word in one file which is not found in another file using Python I am trying to write a program where I count the most frequently used words from one file but those words should not be available in another file So basically I am reading data from test txt file and counting the most frequently used word from that file but that word should not be found in test2 txt file Below are sample data files test txt and test2 txt test txt: ````The Project is for testing doing some testing to find what is going on the the the ```` test2 txt: ````a about above across after afterwards again against the ```` Below is my script which parses files test txt and test2 txt It finds the most frequently used words from test txt excluding words found in test2 txt I thought I was doing everything right but when I execute my script it gives "the" as the most frequent word But actually the result should be "testing" as "the" is found in test2 txt but "testing" is not found in test2 txt ````from collections import Counter import re dgWords = re findall(r'\w+' open('test txt') read() lower()) f = open('test2 txt' 'rb') sWords = [line strip() for line in f] print(len(dgWords)); for sWord in sWords: print (sWord) print (dgWords) while sWord in dgWords: dgWords remove(sWord) print(len(dgWords)); mostFrequentWord = Counter(dgWords) most_common(1) print (mostFrequentWord) ```` | ````import re from collections import Counter with open('test txt') as testfile open('test2 txt') as stopfile: stopwords = set(line strip() for line in stopfile) words = Counter(re findall(r'\w+' open('test txt') read() lower())) for word in stopwords: if word in words: words pop(word) print("the most frequent word is" words most_common(1)) ```` |
keeping form values after POST as a paramter of python file I have a form which one submitted goes to a php file and inserts values into DB(MySql) After successfully inserting values into DB I want to use the values of this parameter form as a python file in another php file when i submitted file register php -> file description php (button start) -> file exucuter php( execute pythonfile) | Instead of redirecting to <them>exucuter php</them> after doing your DB insert if you ````include 'exucuter php'; // (assuming they are in the same directory) ```` in <them>description php</them> after the DB does its work you should be able to use the values directly from `$_POST` in <them>exucuter php</them> This way you will not have to worry about storing them somewhere or transferring them between the two scripts <hr> If your second script (<them>description php</them>) requires some additional user interaction before your third script (<them>exucuter php</them>) runs then you cannot just include <them>exucuter php</them> and you do need a way to retain the values from your first script There are different ways to do this: storing them in the session or in a file or database putting them in the query string for the form action in <them>description php</them> or including them as hidden inputs Here is an example using hidden inputs: <strong>register php</strong> ````<form action="description php" method="POST"> <label for="x">X: </label><input type="text" name="x" id="x"> <input type="submit" value="Register"> </form> ```` <strong>description php</strong> ````<?php if (isset($_POST['x'])) { /* Do your DB insert */; } ?> <form action="exucuter php" method="POST"> <!--Use a hidden input to pass the value given in register php-> <input type="hidden" name="x" value="<?php isset($_POST['x']) ? $_POST['x'] : ''; ?>"> <label for="y">Y: </label><input type="text" name="y" id="y"> <input type="submit" value="Execute"> </form> ```` <strong>exucuter php</strong> ````<?php if (isset($_POST['x']) && isset($_POST['y'])) { // execute your python program } ```` |
Python ClearCase Download Vobs Popen Password BASH Program Sketchy I coded this program yesterday and it was actually working except for when run by CRON Today I ran the same script and it does not work The script will run without any Tracebacks Errors and it will copy the top folder (vob) from the ClearCase view but none of the actual important data in the folders and files below the target folder Here is my Python script ````def obtainCode(view="My_VIEW" folder="/my_folder"): """Download code from ClearCase's File System and put it on the hard-drive""" dest = '/etc/foo' password = 'passwords' v1 = subprocess Popen(['cleartool' 'setview' view] she will=True stdout=subprocess PIPE) print "v1 = " v1 print "view maybe set :/" c1 = subprocess Popen(['sudo' '-p' '' '-S' 'cp' '-r' folder dest] stdin=subprocess PIPE) c1 stdin write(password '\n') c1 stdin close() c1 wait() #### Close View and Stop Processes #### v2 = subprocess Popen(['cleartool' 'endview' view] she will=True stdin=v1 stdout stdout=subprocess PIPE) v2 kill() v1 kill() ```` Does anyone know: 1) what is going wrong 2) why it would work yesterday but not today 3) a better way to do this? Thank-you for your time and attention | Try and not use `setview` You do not need it and you can use the full path of the view instead ````cleartool startview yourDynamicView cd /view/yourDynamicView/vobs/yourVob ```` I have mentioned before the danger of using setview ("<a href="http://stackoverflow com/a/10252612/6309">Python and ClearCase setview</a>") It creates a subprocess within your subprocess which is not needed here |
Save multiple objects in same model using tastypie in a Django project I have a Django project with following model: ````from django contrib auth models import User class InstalledApps(models Model): user = models ForeignKey(User) app_package_name = models CharField(max_length=50) ```` I am using tastypie to create a POST API endpoint so that user can post multiple objects to InstalledApps model in single a API call: ``` class InstalledAppsResource(ModelResource): class Meta: queryset = InstalledApps objects all() resource_name = 'apps' authorization= Authorization() authentication = Authentication() #validation = InstalledAppsValidation() list_allowed_methods = ['post' 'get'] always_return_data = True def hydrate(self bundle): usrname = bundle request META['HTTP_AUTHORIZATION'][7:] split(':')[0] usr = User objects get(username__exact=usrname) if not bundle obj pk: bundle obj user = usr return bundle ``` When I try to POST to this endpoint: ````curl -X POST -H "Content-Type: application/json" -H "Authorization: ApiKey username:abcde" -d '{"app_package_name": ["pqr" "abc" "xyz"]}' http://127 0 0 1:8000/api/v1/apps ```` I get response: ````{"app_package_name": "['pqr' 'abc' 'xyz']" "id": 16 "resource_uri": "/api/v1/apps/16"} ```` i e rather than having three rows in InstalledApps table it creates a single row with `InstalledApps app_package_name` set to `['pqr' 'abc' 'xyz']` What should I do to save three rows in the InstalledApps table? Thanks! | Try this <strong>URI:</strong> <a href="http://127 0 0 1:8000/api/v1/apps" rel="nofollow">http://127 0 0 1:8000/api/v1/apps</a> <strong>Method:</strong> PATCH <strong>Data to send:</strong> ````{ "objects": [ {"app_package_name": "pqr"} {"app_package_name": "abc"} {"app_package_name": "xyz"} ] } ```` Curl Command: ````curl -X PATCH -H "Content-Type: application/json" -H "Authorization: ApiKey username:abcde" -d '{"objects": [{"app_package_name":"pqr"} {"app_package_name":"pqr"}]}' http://127 0 0 1:8000/api/v1/apps ```` |
Is there a way to install cx_oracle without root access in linux environment? I Am trying to install cx_oracle with python2 7 11 all the tutorials i found for installing cx_oracle needs root access however on the vm i do not have root access on the /usr or /etc folders Is there any way to install cx_oracle in my user directory? | Yes you can simply follow these steps: - Download the source archive and unpack it somewhere - Run the command "python setup py build" - Copy the library to a location of your choice where you do have access (or you can simply leave it in the build location too if you prefer) - Set the environment variable PYTHONPATH to point to the location of cx_Oracle so |
wxPython ScrolledWindow too small I have a panel to control editing of a matplotlib graph in a wxPython frame The wxPython install was recently updated to 2 8 12 1 from 2 6 4 0 and it broke a few things namely the scroll panel no longer fills a block but instead stays at a minimum size I am just now picking this up from a year ago so I am a bit rusty Any help would be much appreciated! Below is a stripped-down version of the code that can be run on its own and displays the problem The ScrolledWindow should expand up to 400px When I run it `self scroll GetSize()` returns `(292 257)` but it clearly is not displaying at that size ````# testing scroll panel for PlotEditFrame import wx # spoof the necessary matplotlib objects class FakePlot: def __init__(self): self figure = FakeFigure() def get_figure(self): return self figure class FakeFigure: def __init__(self): self axes = [FakeAxis() for i in range(0 2)] class FakeAxis: def __init__(self): self lines = [FakeLine(i) for i in range(0 4)] class FakeLine: def __init__(self i): self label = "line #%s"%i def get_label(self): return self label class PlotEditFrame(wx Frame): """ This class holds the frame for plot editing tools """ def __init__(self parent plot): """Constructor for PlotEditFrame""" wx Frame __init__(self parent -1 "Edit Plot") self parent = parent self plot = plot self figure = plot get_figure() self advanced_options = None self scroll = wx ScrolledWindow(self -1) self InitControls() def InitControls(self): """Create labels and controls based on the figure's attributes""" # Get current axes labels self lineCtrls = [( wx StaticText(self scroll -1 "Column:") wx StaticText(self scroll -1 "Color:") wx StaticText(self scroll -1 ""))] for axis in self figure axes: for line in axis lines: color = wx Colour(255 0 0 0) lineTxt = wx TextCtrl(self scroll -1 line get_label() size=(175 -1)) lineColor = wx TextCtrl(self scroll -1 "#%02x%02x%02x"%color Get()) lineBtn = wx Button(self scroll -1 size=(25 25)) lineBtn SetBackgroundColour(color) self lineCtrls append((lineTxt lineColor lineBtn)) # Place controls boxSizer = wx BoxSizer(wx VERTICAL) lineBox = wx StaticBox(self -1 "Lines") lineBoxSizer = wx StaticBoxSizer(lineBox wx VERTICAL) lineSizer = wx FlexGridSizer(rows=len(self lineCtrls)+1 cols=4 vgap=3 hgap=3) for ctrls in self lineCtrls: lineSizer AddMany([(ctrls[0] 0 wx ALIGN_LEFT | wx EXPAND) (ctrls[1] 0 wx ALIGN_LEFT) (ctrls[2] 0 wx ALIGN_CENTER| wx FIXED_MINSIZE) ((3 3) 0 wx ALIGN_CENTER)]) lineSizer AddGrowableCol(0) # Set size self scroll SetSizer(lineSizer) width = self scroll GetBestSize() width height = self scroll GetBestSize() height if height > 400: height = 400 width = width 25 # button size self scroll SetSize((width height)) self scroll SetScrollbars(0 1 1 1) print "set scrollbars at %s x %s"%(width height) lineBoxSizer Add(self scroll 0 wx EXPAND) boxSizer AddMany([ (lineBoxSizer 0 wx EXPAND) ]) self SetSizer(boxSizer) self SetAutoLayout(1) self Fit() height = self GetSize() GetHeight() self SetSizeHints(minH=height maxH=height minW=width maxW=width*5) if __name__ == '__main__': app = wx PySimpleApp(0) parent = wx Frame(None wx ID_ANY 'test' size=(300 300)) plot = FakePlot() panel = PlotEditFrame(parent plot) panel Show() app MainLoop() ```` I cannot figure out what panel needs resized Some things I have tried to no avail: ````# These have no visible effect boxSizer SetMinSize((width height)) self scroll SetVirtualSize((width height)) lineBoxSizer Fit(self scroll) lineBoxSizer SetVirtualSizeHints(self scroll) # This makes the window the right size but not the scroll panel lineBoxSizer SetMinSize((width height)) ```` | I edited your code a bit to get it to work: ````import wx # spoof the necessary matplotlib objects class FakePlot: def __init__(self): self figure = FakeFigure() def get_figure(self): return self figure class FakeFigure: def __init__(self): self axes = [FakeAxis() for i in range(0 2)] class FakeAxis: def __init__(self): self lines = [FakeLine(i) for i in range(0 4)] class FakeLine: def __init__(self i): self label = "line #%s"%i def get_label(self): return self label class PlotEditFrame(wx Frame): """ This class holds the frame for plot editing tools """ def __init__(self parent plot size): """Constructor for PlotEditFrame""" wx Frame __init__(self parent -1 "Edit Plot" size=size) self parent = parent self plot = plot self figure = plot get_figure() self advanced_options = None self scroll = wx ScrolledWindow(self -1) self InitControls() def InitControls(self): """Create labels and controls based on the figure's attributes""" # Get current axes labels self lineCtrls = [( wx StaticText(self scroll -1 "Column:") wx StaticText(self scroll -1 "Color:") wx StaticText(self scroll -1 ""))] for axis in self figure axes: for line in axis lines: color = wx Colour(255 0 0 0) lineTxt = wx TextCtrl(self scroll -1 line get_label() size=(175 -1)) lineColor = wx TextCtrl(self scroll -1 "#%02x%02x%02x"%color Get()) lineBtn = wx Button(self scroll -1 size=(25 25)) lineBtn SetBackgroundColour(color) self lineCtrls append((lineTxt lineColor lineBtn)) # Place controls boxSizer = wx BoxSizer(wx VERTICAL) lineBox = wx StaticBox(self -1 "Lines") lineBoxSizer = wx StaticBoxSizer(lineBox wx VERTICAL) lineSizer = wx FlexGridSizer(rows=len(self lineCtrls)+1 cols=4 vgap=3 hgap=3) for ctrls in self lineCtrls: lineSizer AddMany([(ctrls[0] 0 wx ALIGN_LEFT | wx EXPAND) (ctrls[1] 0 wx ALIGN_LEFT) (ctrls[2] 0 wx ALIGN_CENTER| wx FIXED_MINSIZE) ((3 3) 0 wx ALIGN_CENTER)]) lineSizer AddGrowableCol(0) # Set size self scroll SetSizer(lineSizer) width = self scroll GetBestSize() width height = self scroll GetBestSize() height if height > 400: height = 400 width = width 25 # button size self scroll SetSize((width height)) self scroll SetScrollbars(0 1 1 1) print "set scrollbars at %s x %s"%(width height) lineBoxSizer Add(self scroll 1 wx EXPAND) boxSizer Add(lineBoxSizer 1 wx EXPAND) self SetSizer(boxSizer) self SetAutoLayout(1) #self Fit() height = self GetSize() GetHeight() self SetSizeHints(minH=height maxH=height minW=width maxW=width*5) if __name__ == '__main__': app = wx App(False) plot = FakePlot() frame = PlotEditFrame(None plot size=(300 300)) frame Show() app MainLoop() ```` The main thing was to set the proportion to "1" on the following two lines: ````lineBoxSizer Add(self scroll 1 wx EXPAND) boxSizer Add(lineBoxSizer 1 wx EXPAND) ```` I changed the way you start the program as it is a little silly to put a frame inside another frame for this case Also PySimpleApp is deprecated so I changed that too I have almost never found a good use for the "Fit()" method so I took that out as it was squashing the initial GUI too much Hope that helps! |
The Irish monarch is the head of state for all parts of the isles except? | null |
Python simple data working I am presenting my problem I have a molecule of Benzene I have a Cartesian coordinates for each atom What I want is to rotate the molecule around its center of mass in z and x direction For doing this I need to calculate the center of mass M Within the file the coordinates of the molecule geometry is given below (txt file) ```` X Y Z atom 4 5 7 C atom 3 7 9 C ```` I have many more rows like this The test file comprise of not just numbers and include data The question I have is how can I go over/summarize over rows and strings in Python? Because for center of mass I will need to summarize X coordinate for all atoms and then divide the X coordinate by 6 And I have no idea how to do this I know how to choose certain row and line but I do not need certain elements I need my program to to read lines split them and choose particular sata and summarize them Please guide me through the next steps Thanks in advance | I have written two methods of implementing the code based on the assumptions that I have made and understand what is required to be done here <strong>Method 1: Program 1</strong> ````xcoordinatedata=[] fileopen=open("atomdata txt" "r+") i=0 for rows in fileopen readlines(): if i==0: i=1 pass else: xcoordinatedata append(float(rows split("\t")[1])/6) fileopen close() print "The X coordinate data is" xcoordinatedata ```` <strong>Method 2 :Second method to implement the same program</strong> ````xcoordinatedata=[] fileopen=open("atomdata txt" "r+") i=0 for row in fileopen readlines(): if i!=0: xcoordinatedata append(float(row split("\t")[1])/6) i+=1 i=1 fileopen close() print "out of the program" xcoordinatedata ```` Please let me know if this helps Please provide your code so that I can help you further |
What is Uruguay's oldest theater? | The Solís Theatre |
What was Darwin's process on writing his books? | Darwin always finished one book before starting another |
Django calling function in re sub I have this line in my custom templatetag: ````value = re sub(r'( *)\(bkz: ( *)\b\)' r'\1(bkz: <a href="/baslik/\2">\2</a>)' value) ```` I want to use the slugify function in my link to slugify the \2 How can I do this? | `re sub()` takes either a string or a function as second in parameter you could define a function to do the things you want below is a very trivial example ````value = "aaa1aaa" def slugifier(match_object): return 'X' value = re sub('\d+' slugifier value) >> 'aaaXaaa' ```` Just as a side note `slugify` will escape the `\2` and produce an empty string |
Can I update pycharm intellisense for python? I want to know if it is possible to update Pycharm intellisense for python which does not care about capital or normal letters? It is a pain in the neck to try both each time Currently I am using pycharm 3 0 and python 2 7 4 An example of what I want: For example I have a model named: 'MyModel' I use to type first two letters and then ctrl+space to choose from the list so if I type 'my' instead of 'My' the pycharm says: 'No suggestion' | Did you see this page? <a href="http://www jetbrains com/pycharm/webhelp/editor-code-completion html" rel="nofollow">http://www jetbrains com/pycharm/webhelp/editor-code-completion html</a> It looks like you want to set the <strong>Case sensitive completion</strong> to <strong>None</strong> |
Mininet Script Error: type object 'OVSSwitch' has no attribute 'OVSVersion' I am receiving the following error: ````File "build/bdist linux-x86_64/egg/mininet/node py" line 1162 in start File "build/bdist linux-x86_64/egg/mininet/node py" line 1163 in <genexpr> File "build/bdist linux-x86_64/egg/mininet/node py" line 1129 in intfOpts File "build/bdist linux-x86_64/egg/mininet/node py" line 1072 in isOldOVS AttributeError: type object 'OVSSwitch' has no attribute 'OVSVersion' ```` while I ran the following Mininet script: ````#!/usr/bin/python from mininet net import Mininet from mininet node import Controller RemoteController OVSController from mininet node import CPULimitedHost Host Node from mininet node import OVSKernelSwitch UserSwitch from mininet node import IVSSwitch from mininet cli import CLI from mininet log import setLogLevel info from mininet link import TCLink Intf from subprocess import call def myNetwork(): net = Mininet( topo=None build=False ipBase='10 0 0 0/8') info( '*** Adding controller\n' ) c0=net addController(name='c0' controller=Controller protocol='tcp' port=6633) info( '*** Add switches\n') r1 = net addHost('r1' cls=Node ip='0 0 0 0') r1 cmd('sysctl -w net ipv4 ip_forward=1') s3 = net addSwitch('s3' cls=OVSKernelSwitch) r2 = net addHost('r2' cls=Node ip='0 0 0 0') r2 cmd('sysctl -w net ipv4 ip_forward=1') s5 = net addSwitch('s5' cls=OVSKernelSwitch) info( '*** Add hosts\n') h3 = net addHost('h3' cls=Host ip='10 0 0 3' defaultRoute=None) h4 = net addHost('h4' cls=Host ip='10 0 0 4' defaultRoute=None) h1 = net addHost('h1' cls=Host ip='10 0 0 1' defaultRoute=None) h2 = net addHost('h2' cls=Host ip='10 0 0 2' defaultRoute=None) info( '*** Add links\n') net addLink(h1 s3) net addLink(h2 s3) net addLink(r1 s3) net addLink(s3 r2) net addLink(h3 s5) net addLink(h4 s5) net addLink(s5 r1) net addLink(s5 r2) info( '*** Starting network\n') net build() info( '*** Starting controllers\n') for controller in net controllers: controller start() info( '*** Starting switches\n') net get('s3') start([c0]) net get('s5') start([c0]) info( '*** Post configure switches and hosts\n') CLI(net) net stop() if __name__ == '__main__': setLogLevel( 'info' ) myNetwork() ```` generated by miniedit py The code at line number 1070 at <a href="https://github com/mininet/mininet/blob/master/mininet/node py" rel="nofollow" title="node py">node py</a> seems fine | This works I do not know why: ````#!/usr/bin/python from mininet net import Mininet from mininet node import Controller RemoteController OVSController from mininet node import CPULimitedHost Host Node from mininet node import OVSKernelSwitch UserSwitch from mininet node import IVSSwitch from mininet cli import CLI from mininet log import setLogLevel info from mininet link import TCLink Intf from subprocess import call def myNetwork(): net = Mininet( topo=None build=False ipBase='10 0 0 0/8') info( '*** Adding controller\n' ) c0=net addController(name='c0' controller=RemoteController ip='127 0 0 1' protocol='tcp' port=6633) info( '*** Add switches\n') s1 = net addSwitch('s1' cls=OVSKernelSwitch) s2 = net addSwitch('s2' cls=OVSKernelSwitch) r3 = net addHost('r3' cls=Node ip='0 0 0 0') r3 cmd('sysctl -w net ipv4 ip_forward=1') r4 = net addHost('r4' cls=Node ip='0 0 0 0') r4 cmd('sysctl -w net ipv4 ip_forward=1') info( '*** Add hosts\n') h1 = net addHost('h1' cls=Host ip='10 0 0 1' defaultRoute=None) h2 = net addHost('h2' cls=Host ip='10 0 0 2' defaultRoute=None) h3 = net addHost('h3' cls=Host ip='10 0 0 3' defaultRoute=None) h4 = net addHost('h4' cls=Host ip='10 0 0 4' defaultRoute=None) info( '*** Add links\n') net addLink(h1 s1) net addLink(h2 s1) net addLink(h3 s2) net addLink(h4 s2) net addLink(s1 r3) net addLink(s1 r4) net addLink(s2 r3) net addLink(s2 r4) info( '*** Starting network\n') net build() info( '*** Starting controllers\n') for controller in net controllers: controller start() info( '*** Starting switches\n') net get('s1') start([c0]) net get('s2') start([c0]) info( '*** Post configure switches and hosts\n') CLI(net) net stop() if __name__ == '__main__': setLogLevel( 'info' ) myNetwork() ```` |
how to apply patch in mercurial and show different tool if failed apply I want apply patch in Mercurial: ````hg import patch_name patch ```` But if I get the error `abort: patch failed to apply` Mercurial creates `* rej` files Is there a way show kdiff or vim-diif to correcting conflict | There is not a way to do this The recommended approach is to open the file and the rej file and manually merge in the rejected hunks |
How to define instance methods from wrap I am working on a django site and want to define some instance methods like below ````Class Auth(models Model): def wrap_has_perm(self perm): def wrap(): if self is_staff and self has_perm(perm): return True else: return False can_add_order = wrap_has_perm('finance normal') can_review_order = wrap_has_perm('finance review') is_leader = wrap_has_perm('finance leader') is_finance = wrap_has_perm('finance finance') ```` I want to use `can_add_order` `can_review_order` `is_leader` `is_finance` as django admin site's list_display element But now these instance methods is illegal (TypeError: wrap_has_perm() takes exactly 2 arguments (1 given)) How can I achieve these methods? If I use partial: ````def staff_has_perm(self perm): return self is_staff and self has_perm(perm) can_add_order = partial(staff_has_perm perm='finance normal') can_review_order = partial(staff_has_perm perm='finance review') is_leader = partial(staff_has_perm perm='finance leader') is_finance = partial(staff_has_perm perm='finance finance') ```` It raises (<them>*</them> TypeError: staff_has_perm() takes exactly 2 arguments (1 given)); Should I pass `self` to and how to ? | Move the `self` to `wrap()`'s definition: ````def wrap_has_perm(perm): def wrap(self): ```` However a more Pythonic way to do this might be to use `functools partial`: ````from functools import partial class Auth(models Model): def has_perm(self perm): # can_add_order = partial(has_perm perm='finance normal') can_review_order = partial(has_perm perm='finance review') is_leader = partial(has_perm perm='finance leader') is_finance = partial(has_perm perm='finance finance') ```` |
How to access request body of QNetworkRequest with QHttpMultiPart? I need to calculate a <strong>digest</strong> (checksum) from the <strong>request body</strong> (e g raw POST data) that is being sent via `QNetworkRequest` and include a digest signature in the <strong>request header</strong> How could I do this <them>before</them> sending the request (so the signature can be included in the header) ? This is trivial when I am using a byte array as the request body but what if I have a `QHttpMultiPart` object ? Basically something like `QHttpMultiPart toString()` | As of now the only way seems to be to assemble the MIME multi-part body oneself produce a digest of it and pass that byte data to `QNetworkAccessManager` sending method |
PIL - The submitted file is empty Test Case I have a file upload which works perfectly however I want to write a test for it so I did the following ```` def test_post_ok(self): image = Image new('RGB' (100 100) tmp_file = tempfile NamedTemporaryFile(suffix=' jpg') image save(tmp_file) payload = { "name": "Test" "thumbnail_image": tmp_file } api = APIClient() api credentials(Authorization='Bearer ' self token) response = api post(url payload format='multipart') ```` However the test gives the error ````<PIL JpegImagePlugin JpegImageFile image mode=RGB size=1024x768 at 0x108A5DCF8> {'thumbnail_image': [you'The submitted file is empty ']} ```` I assume I am not doing this correctly if not why? | My earlier guess is wrong You are using the Rest Framework with the multipart functionality (awesome!) so you can send the file as-is and the file will be encoded multipart The error here is the following: - You open the file `tmp_file` - You write the image contents to this file - The filepointer is now at the end of the document - You pass on the document to APIClient() which is a simple test wrapper which passes the argument up through the rest_framework where eventually your call is encoded - The encoding will call `tmp_file read()` Since the pointer is still at the end of the file `read()` will return 0 bytes leaving you with an empty document Solutions: `tmp_file seek(0)` or reopen the file before calling `post()` |
clone url of a pull request I am trying to get the clone URL of a pull request For example in Ruby using the Octokit library I can fetch it from the head and base like so where `pr` is a PullRequest object: `pr head repo clone_url` or `pr base repo clone_url` How can I achieve the same thing using github3 py? | `github3 pull_request(owner repo number) as_dict()['head']['repo']['clone_url']` |
Pandas 'DataFrame' object has no attribute 'unique' I am working in pandas doing pivot tables and when doing the groupby (to count distinct observations) `aggfunc={"person":{lambda x: len(x unique())}}` gives me the following error: `'DataFrame' object has no attribute 'unique'` any ideas how to fix it? | DataFrames do not have that method; columns in DataFrames do: ````df['A'] unique() ```` Or to get the names with the number of observations (using the DataFrame given by closedloop): ````>>> df groupby('person') person count() Out[80]: person 0 2 1 3 Name: person dtype: int64 ```` |
How should I optimize these if/elseif branches for speed? Suppose I have the following python code: ````a = b = 0 if f(a) and (g(b) == 1): # Do Something #1 pass elif f(a) and (g(b) == 2): # Do Something #1 pass ```` You can assume that the functions `f()` and `g()` take up some non-negligible amount of CPU resource I want to optimize this code for computational efficiency Should I change it to the following? ````a = b = 0 if f(a): x = g(b) if x == 1: # Do Something #1 pass elif x == 2: # Do Something #2 pass ```` Is there any way to automate this optimization? I hate doing it by hand throughout my entire codebase <strong>EDIT:</strong> The functions `f()` and `g()` are completely deterministic IE: they always return the same results if given the same input parameters And they have no side effects outside their own stack context | Using a single if for the `f(a)` is definitely more efficient For optimal efficiency you should store the result of expensive common sub-expressions in a variable: ````if f(a): gb = g(b) if gb == 1: if gb == 2: ```` This will execute these functions as seldom as possible <hr> If `g(b)` can also return a value that does not match any `if` then you should profile - it could be beneficial to calculate `g(b)` first and see if it returned any valid value and only then calculate `f(a)` (if these are not dependent of course): ````gb = g(b) if gb in (1 2) and f(a): if gb == 1: if gb == 2: ```` <hr> There is no way that any standard Python compiler could statically optimize these unlike in C/C++ where the function contents can be inlined |
pyramid_mailer subject header issue When I send email using pyramid_mailer in gmail web client all looks fine but in any desktop clients `subject` contains question marks for example: <img src="http://i stack imgur com/JiF1b jpg" alt="enter image description here"> If open source code of email `subject` header looks like: ````Subject: =?utf-8?b?W9CS0LXQsS3Qk9CY0KEt0LrQvtC70YzRhtC10LLQsNC90LjQtV0g0JDQvdC+0L3Q?= =?utf-8?b?uNC8IDIwMTItMTAtMTggMTc6NTg6MzIg0YHQvtC30LTQsNC7INC30LDQv9C40YHR?= =?utf-8?b?jCAjMTM1OSAo0LrQvtC70YzRhtC10LLQsNC90LjQtSk=?= ```` As you can see it is splitted into three parts Try to perform the python code: ````import email header print email header decode_header('=?utf-8?b?W9CS0LXQsS3Qk9CY0KEt0LrQvtC70YzRhtC10LLQsNC90LjQtV0g0JDQvdC+0L3Q?=')[0][0] print email header decode_header('=?utf-8?b?uNC8IDIwMTItMTAtMTggMTc6NTg6MzIg0YHQvtC30LTQsNC7INC30LDQv9C40YHR?=')[0][0] print email header decode_header('=?utf-8?b?jCAjMTM1OSAo0LrQvtC70YzRhtC10LLQsNC90LjQtSk=?=')[0][0] ```` We are getting the following result: ````[Ðеб-ÐÐС-колÑÑевание] Ðнон �м 2012-10-18 17:58:32 Ñоздал Ð·Ð°Ð¿Ð¸Ñ ï¿½ #1359 (колÑÑевание) ```` How I can get rid of this issue? | yep sounds like a bug to me too python base64 encodestring() splits long strings be default into multiple lines which i guess is causing the problem solution would be to replace the newlines in the used subjects or use binascii b2a_base64 for encoding |
Python - determine if user is server or client I am writing a program that needs communication between two pc's I know how to connect and send messages to each other When the user opens the program it should listen to connections But if the user clicks 'connect' the program should stop listening for connections and connect to a user instead How should I achieve that? I have got this right now: <strong>MAIN</strong> ````@threaded def getOnline(self): # fires when the user opens the program client connect(PORT) @threaded def connect(self): # when the user clicks connect global IS_MASTER IS_MASTER = True print('Master:' IS_MASTER) if IS_MASTER: client closeConnection() server connect(CLIENT_IP PORT) ```` <strong>CLIENT</strong> ````class Client(): def __init__(self): self s = socket socket(socket AF_INET socket SOCK_STREAM) def connect(self port): print('Listening to connections') self s bind(('' port)) self s listen(1) conn addr = self s accept() print('Connected by:' addr) def closeConnection(self): print('Not listening any longer') self s close() sys exit() ```` <strong>SERVER</strong> ````class Server(): def __init__(self): self s = socket socket(socket AF_INET socket SOCK_STREAM) def connect(self host port): self s connect((host port)) print('Connected to:' host) ```` Now when I click 'connect' I get: 'ConnectionAbortedError: [Errno 53] Software caused connection abort' Any help would be greatly appreciated! <strong>EDIT</strong> Full Traceback ````Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python framework/Versions/3 3/lib/python3 3/threading py" line 639 in _bootstrap_inner self run() File "/Library/Frameworks/Python framework/Versions/3 3/lib/python3 3/threading py" line 596 in run self _target(*self _args **self _kwargs) File "/Users/cedricgeerinckx/Dropbox/Redux/OSX/Redux py" line 28 in wrapped_f ret = f(*args **kwargs) File "/Users/cedricgeerinckx/Dropbox/Redux/OSX/Redux py" line 204 in getOnline client connect(PORT) File "/Users/cedricgeerinckx/Dropbox/Redux/OSX/Client py" line 14 in connect conn addr = self s accept() File "/Library/Frameworks/Python framework/Versions/3 3/lib/python3 3/socket py" line 135 in accept fd addr = self _accept() ```` | That exception is being thrown inside your `getOnline` method which is run on startup That means the exception is occurring when the connection made in that method is shut down by the `connect` method You should just handle the exception inside `getOnline`: ````@threaded def getOnline(self): # fires when the user opens the program try: client connect(PORT) except ConnectionAbortedError as e: print("Connection shut down!") ```` |
correct me for using generators or tell me other way I have A menu dict item as key and price as value There may exist a combination of item that will be bit cheaper than single item For exa: ````menu = { ('burger' ) : 5 00 ('pizza' ) : 12 00 ('coke' ) : 4 00 ('macpuff' ) : 4 00 ('pasta' ) : 3 00 ('french_fries' ) : 2 00 ('burger' 'coke' 'french_fries') : 10 00 ('pizza' 'coke') : 15 00 } ```` Now suppose i ordered few items then output will be min-amount of given order: ````I/P > burger coke O/P > 9 (5 00 4 00) I/P > burger coke french_fries O/P > 10 00 I/P > pizza coke french_fries O/P > 17 00 (15 00 2 00) ```` here is the code i tried so for all prices which i will use as generators: ````def isSubset(a b): """ compare two iterable and return true if first is subset of second """ b = list(b) if not hasattr(a '__iter__'): a = [a] for each in a: try: b remove(each) except ValueError: return False return True def rest_min_price(order): if order: for item price in menu iteritems(): if isSubset(order[0] item): new_order = order[1:] for itm in item: try: new_order remove(itm) except ValueError: pass yield price rest_min_price(new_order) ```` but when i run this it is saying type error: ````for each in rest_min_price(order_item): print each TypeError: unsupported operand type(s) for : 'int' and 'generator' ```` | Your problem comes in your attempt to combine a generator with recursion: ````yield price rest_min_price(new_order) ```` here `price` is an `int` but `rest_min_price()` is a `generator` (because you `yield` rather than `return` its result) hence you cannot add them together and get a `TypeError` You need to loop through the items in your generator: ````for item in rest_min_price(order_item): # process the item # yield result with price ```` |
Passing parameter (directory) to %cd command in ipython notebook I am trying to pass a parameter (directory) to a %cd command in ipython notebook as below: ```` rootdir = "D:\mydoc" %cd rootdir ```` but i get the following error: ```` [Error 2] The system cannot find the file specified: you'rootdir' D:\mydoc ```` when i am doing ```` %cd D:\mydoc ```` This obviously works but i want to be able to specify my working directories using parameters Many thanks who can help me Best Wishes | You can use `$` to use the value in a variable ````%cd $rootdir ```` |
How to configure environment to build python-embedded c code with LLVM Clang I am trying to compile a program written in c that has python embedded in it I ran `python3 3-config -cflags` to get the cflags I have used in this command ````% >> clang -v einformer c -o einformer - I/usr/local/Cellar/python3/3 3 0/Frameworks/Python framework/Versions/3 3/include/python3 3m -I/usr/local/Cellar/python3/3 3 0/Frameworks/Python framework/Versions/3 3/include/python3 3m -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/usr/local/opt/sqlite/include Apple LLVM version 4 2 (clang-425 0 24) (based on LLVM 3 2svn) Target: x86_64-apple-darwin12 2 0 Thread model: posix "/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10 8 0 -emit-obj -disable-free -disable-llvm-verifier -main-file-name einformer c -pic-level 2 -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 136 -v -g -resource-dir /usr/bin/ /lib/clang/4 2 -D NDEBUG -I /usr/local/Cellar/python3/3 3 0/Frameworks/Python framework/Versions/3 3/include/python3 3m -I /usr/local/Cellar/python3/3 3 0/Frameworks/Python framework/Versions/3 3/include/python3 3m -I /usr/local/include -I /usr/local/opt/sqlite/include -fmodule-cache-path /var/folders/lz/5nhsdlnn3x9g8ry_mkgtgh500000gp/T/clang-module-cache -c-isystem /usr/include/python2 6 -c-isystem -O3 -Wno-unused-result -Wall -Wstrict-prototypes -fdebug-compilation-dir /Users/ardentapprentice/dev/osx/test -ferror-limit 19 -fmessage-length 140 -fwrapv -stack-protector 1 -mstackrealign -fblocks -fobjc-runtime=macosx-10 8 0 -fobjc-dispatch-method=mixed -fobjc-default-synthesize-properties -fno-common -fdiagnostics-show-option -fcolor-diagnostics -o /var/folders/lz/5nhsdlnn3x9g8ry_mkgtgh500000gp/T/einformer-T6nymD o -x c einformer c clang -cc1 version 4 2 based upon LLVM 3 2svn default target x86_64-apple-darwin12 2 0 ignoring duplicate directory "/usr/local/Cellar/python3/3 3 0/Frameworks/Python framework/Versions/3 3/include/python3 3m" ignoring duplicate directory "/usr/local/include" as it is a non-system directory that duplicates a system directory #include " " search starts here: #include < > search starts here: /usr/local/Cellar/python3/3 3 0/Frameworks/Python framework/Versions/3 3/include/python3 3m /usr/local/opt/sqlite/include /usr/include/python2 6 /usr/local/include /usr/bin/ /lib/clang/4 2/include /usr/include /System/Library/Frameworks (framework directory) /Library/Frameworks (framework directory) End of search list einformer c:92:25: warning: implicit declaration of function 'PyString_AsString' is invalid in C99 [-Wimplicit-function-declaration] path_array[i] = PyString_AsString(pypath); ^ 1 warning generated "/usr/bin/ld" -demangle -dynamic -arch x86_64 -dynamic -macosx_version_min 10 8 0 -o einformer /var/folders/lz/5nhsdlnn3x9g8ry_mkgtgh500000gp/T/einformer-T6nymD o -lSystem /usr/bin/ /lib/clang/4 2/lib/darwin/libclang_rt osx a Undefined symbols for architecture x86_64: "_PyList_GetItem" referenced from: _main in einformer-T6nymD o "_PyList_Size" referenced from: _main in einformer-T6nymD o "_PyRun_SimpleStringFlags" referenced from: _main in einformer-T6nymD o "_PyString_AsString" referenced from: _main in einformer-T6nymD o "_Py_Finalize" referenced from: _main in einformer-T6nymD o "_Py_Initialize" referenced from: _main in einformer-T6nymD o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) ```` It seems as though clang is having trouble locating headers maybe? `<Python h>` is included in the source I am not sure what I am doing wrong :/ I Have spent about 3 hours looking through the python documentation <a href="http://docs python org/3 3/c-api/index html" rel="nofollow">http://docs python org/3 3/c-api/index html</a> and googling around but I cannot seem to find any information that helps me | `python3 3-config --cflags` only gives the arguments needed to find the headers `python3 3-config --ldflags` will give you the linker flags This means that you should be able to compile your program with a compiler invocation something like: ````clang -v einformer c -o einformer $(python3 3-config --cflags) $(python3 3-config --ldflags) ```` |
Django unit test on custom model manager method I am pretty new in python and django I have model with custom model manager with a method where i am raising `ValidationError` on some exceptions now i want to test this custom manager method but do not know how to catch `ValidationError` or anyother error in terms of testing django model's customs manager method My scenario is depicted below ````class CustomModelManager(model Manager): def custom_method(self): #for some exception raise ValidationError('a sample validation error') class SampleModel(models Model): ###fields objects = CustomModelManager() ```` i have tried the following unit test but its not working ````def test_samle_model(self): issues = Issues objects custom_method(field1='wrong field')###this will raise that validationError self assertEqualValidationError 'a sample validation error') ```` is it possible to catch 'any error' to test? or am i missing something? | use <a href="https://docs python org/2 7/library/unittest html#unittest TestCase assertRaises" rel="nofollow">assertRaises</a> ````with self assertRaises(ValidationError): issues = Issues objects custom_method(field1='wrong field') ```` |
How to iterate over Django dict Basically I need to iterate a certain dict from a queryset to be rendered on a template: I used this: ````top_donors = Donation objects values('donator') annotate(Sum('amount')) ```` which basically gets a sum of each donator's total amount donated i believe this returns a dict i e ````[{'donator' : 3 'amount_sum' : 5200} {'donator' : 2 'amount_sum' : 1200} { }] ```` is there a better way to get that query? if not i need to iterate over those and display it in a table i e ````name total amount 3 5200 2 1200 ```` what are my options thank you very much! | Do as given below it will work sure ``` {% for i in top_donors %} {{ i donator }} {{ i amount__sum }} {% endfor %} ``` |
Deploy Blender to Azure App I have copied `Blender exe` and all associated files into `Azure API App` then try to run it with my custom Python script like this (using `System Dianostics Process`()): <blockquote> blender exe --background --python myscript py </blockquote> But can not get it run properly Note that it works fine in my local IIS So the question is does Azure App support to run Blender? (as Blender may need to have GPU support machine to run and Azure does not support GPU yet) And if yes so how to see what error return from the `blender exe` command? (I am unable to remote desktop to `Azure Api App` to run the command manually unfortunately) UPDATED: I can run blender script above successfully using `Azure Console` command line by hand But when run the script using code `System Diagnostics Process`() it got this error from StandardError stream: <blockquote> Fatal Python error: Py_Initialize: cannot initialize sys standard streams OSError: [WinError 6] The handle is invalid </blockquote> | @MinhNguyen According to the wiki <a href="https://github com/projectkudu/kudu/wiki/Azure-Web-App-sandbox#win32ksys-user32gdi32-restrictions" rel="nofollow">page</a> of Kudu Azure App Services which include Api App are not support scenarios using GDI+ because of Win32k sys (User32/GDI32) Restrictions but blender works with `gdi32` So unfortunately blender can not work on Azure Api App please consideration for Azure Cloud Service or Virtual Machine for blender <hr> <strong>Update</strong>: As @MinhNguyen comments said blender can be run manually in Kudu console although it seems blender works with GDI because of compiling blender need gdi32 lib So the solution for the issue is that package blender exe and related python script as a webjob to run on Azure |
What effect did Company rule in India produce in 1857? | Indian Rebellion |
save data from form with custom foreign key field in django I have the following Model classes: ````class ContactPerson(models Model): name = models CharField(max_length=30) def __unicode__(self): return self name class Appartment(models Model): contact_person = models ForeignKey(ContactPerson) ```` <strong>Problem:</strong> In template file I want a user to fill contact person's name so I overwrite contact_person field as follows: ````class AppartmentSellForm(ModelForm): contact_person = forms CharField(max_length=30) class Meta: model = Appartment ```` In my view function I am doing the following to save data from a form submitted: ````def appartment_submit(request): if request method == "POST": form = AppartmentSellForm(request POST) if form is_valid(): appartment = form save(commit=False) # ERROR HERE cp = models ContactPerson(name=form cleaned_data['contact_person']) appartment contact_person = cp appartment save() form save(); return HttpResponseRedirect('/sell/') else: form = AppartmentSellForm() return render_to_response('sell_appartment_form html' {'form' : form}) ```` <strong>Error message</strong>: ````#ValueError at /sell/sell_appartment/appartment_submit/ Cannot assign "you'blabla'": "Appartment contact_person" must be a "ContactPerson" instance ** ```` I am using SQLite and django version 1 1 1 <strong>Question:</strong> How to solve this problem? | You can do one of the following: - Try to `exclude` the `contact_person` field as mentioned <a href="https://docs djangoproject com/en/dev/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form" rel="nofollow">in point 3 over here</a> - or you could just not override the field in your `ModelForm` and Django will render it as a `ModelChoiceField` unless you actually want people to type out a name instead of having a dropdown list to choose from |
Pros and cons to using sparse matrices in python/R? I am working with large sparse matrices (document-feature matrices generated from text) in python It is taking quite a bit of processing time and memory to chew through these and I imagine that sparse matrices could offer some improvements But I am worried that using a sparse matrix library is going to make it harder to plug into other python (and ARE through rpy2) modules Can people who have crossed this bridge already offer some advice? What are the pros and cons of using sparse matrices in python/ARE in terms of performance scalability and compatibility? | Using sparse matrices in Python might not be a great idea in itself Have you checked out <a href="http://docs scipy org/doc/scipy/reference/sparse html" rel="nofollow">sparse matrices in numpy / scipy</a>? Numpy brings the immense benefit of using mainly C code to provide performance gains in Python From my limited experience of doing text processing in ARE the performance makes it pretty much unusable for anything beyond exploratory data analysis Regardless you should not be using vanilla lists for sparse matrices it will (understandably) take a while to chew through them |
How to split entries of a file into a list of strings in Python? I have a file such that each line consists of two strings separated by variable space like below: ````"Doe Mary" "W 135" ```` How can this be parsed into pairs of strings `["Doe Mary" "W 135"]`? | ````with open('file txt') as f: pairs = csv reader(f delimiter=' ' skipinitialspace=True) ```` Now you can make a list of `pairs` iterate over it in a for loop whatever |
How can I control the color and opacity of each point in a python scatter plot? I am looking to graph a 4D data set (X Y Z intensity) using opacity to represent intensity I also want the color to be dependent on the Z variable as well to better show depth Here is the relevant code so far I am a novice when it comes to Python: ```` x_list #list of x values as floats y_list #list of y values as floats z_list #list of z values as floats i_list #list of intensity values as floats import matplotlib pyplot as plt from mpl_toolkits mplot3d import Axes3D fig = plt figure() ax = fig add_subplot(111 projection='3d') Axes3D scatter(ax x_list y_list z_list) ```` So how can I do this? I am thinking the color could be a linear relationship between z_list and a color map (hsv for example) and opacity could be linear as well i_list/max(i_list) or something along those lines | I would do something like the following: ````import numpy as np import matplotlib pyplot as plt from mpl_toolkits mplot3d import Axes3D # choose your colormap cmap = plt cm jet # get a Nx4 array of RGBA corresponding to zs # cmap expects values between 0 and 1 z_list = np array(z_list) # if z_list is type `list` colors = cmap(z_list / z_list max()) # set the alpha values according to i_list # must satisfy 0 <= i <= 1 i_list = np array(i_list) colors[: -1] = i_list / i_list max() # then plot fig = plt figure() ax = fig add_subplot(111 projection='3d') ax scatter(x_list y_list z_list c=colors) plt show() ```` Here is an example with `x_list = y_list = z_list = i_list` You can choose any of the <a href="http://matplotlib org/examples/color/colormaps_reference html" rel="nofollow">colormaps here</a> or <a href="http://matplotlib org/examples/pylab_examples/custom_cmap html" rel="nofollow">make your own</a>: <img src="http://i stack imgur com/oNhTO png" alt="enter image description here"> |
How much does the Olympic Torch weigh? | 985 grams |
Is there a way to use the python -m mymod syntax from within the python interpreter? Many packages like unittest have an easy to use command line interface e g the test discovery feature in unittest: <a href="https://docs python org/2/library/unittest html#test-discovery" rel="nofollow">https://docs python org/2/library/unittest html#test-discovery</a> However to achieve the same from within python it is sometimes necessary to dig in much deeper in the documentation In the example above the python code required to achieve the same is much harder to figure out compared to the command line command Therefore I want to know: Is there a consistent way to translate `python -m mymod args` to something that can be used within the python interpreter? Edit: I am asking for a reasonable strategy what to do in a situation where I know the python -m command but nothing more Is this knowledge completely useless when I am forced to use the python interpreter? | You can use the <a href="https://docs python org/2/library/runpy html#runpy run_module" rel="nofollow">`runpy run_module` function</a>: ````import runpy import sys sys argv[1:] = ['arg1' 'arg2' 'arg3'] runpy run_module('module name' run_name='__main__' alter_sys=True) ```` This executes `module name` as if you typed: ````python -m module name arg1 arg2 arg3 ```` |
Group rows based on range python I have a large text file where I am trying to group the first column based on intervals of 200 In the example code below the first four rows would be in a group the next three rows in a different group and the last row in a separate group My thought is to group them based on a for loop with a condition that adds 200 but have not been able to get it to work ````000008 34 576 -87 234 000025 34 825 -87 935 000123 35 935 -86 344 000154 34 395 -86 903 000234 35 219 -86 945 000322 34 240 -86 527 000359 34 893 -87 573 000412 35 291 -87 392 ```` Once I have them grouped I would like to check to see if the last two columns are within a specified range If so then write those rows to a new output file Any help would be appreciated! | You could divide the value by 200 to get a key for `groupby`: ````>>> rows = '''000008 34 576 -87 234 000025 34 825 -87 935 000123 35 935 -86 344 000154 34 395 -86 903 000234 35 219 -86 945 000322 34 240 -86 527 000359 34 893 -87 573 000412 35 291 -87 392''' splitlines() >>> from itertools import groupby >>> for _ group in groupby(rows key=lambda row: int(row split()[0]) // 200): print(list(group)) ['000008 34 576 -87 234' '000025 34 825 -87 935' '000123 35 935 -86 344' '000154 34 395 -86 903'] ['000234 35 219 -86 945' '000322 34 240 -86 527' '000359 34 893 -87 573'] ['000412 35 291 -87 392'] ```` If the number always has six digits you can use `int(row[:6]) // 200` instead |
Converting Dictionary to List in BeautifulSoup How do I save the list of items if `'boa'` is in `href` to a list? I do not want to print them using get() but instead convert them to a list in their own variable (it seems these are in a dictionary?) preferably to `boat_links` Thanks! ````import urllib2 from bs4 import BeautifulSoup #Open Craigslist with BeautifulSoup and save to file url = 'http://losangeles craigslist org/boo/' response = urllib2 urlopen(url) webContent = response read() f = open('C:\Users\dell\Desktop\python\\boat_crawler\craigslist html' 'w') f write(webContent) f close html_doc = open('C:\Users\dell\Desktop\python\\boat_crawler\craigslist html') soup = BeautifulSoup(html_doc) boat_links = [] for a in soup find_all('a'): if 'boa' in a['href']: print a get('href') ```` | I am not sure if you want a list or dictionary or a dictionary of lists so here are all of them ````if a get('href') find('boa')>-1: boat_links append(a get('href')) ```` Here is a dictionary with the a tags text as the key and the href as the value ````boat_links = {} for a in soup find_all('a'): if a get('href') find('boa')>-1: boat_links[a text] = a get('href') ```` Here is a dictionary of lists based on the a tags (what if you have multiple links with the same text) ````boat_links = {} for a in soup find_all('a'): if a get('href') find('boa')>-1 if boat_links has_key(a text): boat_links[a text] append(a get('href')) else: boat_links[a text] = [a get('href')] ```` |
python 2 6 vs 2 7 for pylons/pyramid projects What problems can I have if I will use python 2 7 instead python 2 6 for my pylons/pyramid projects? Before I use python 2 6 on my ubuntu 10 04 but now I have ubuntu 11 04 on my laptop with python 2 7 | Take a look at `http://docs python org/dev/whatsnew/2 7 html` You will find what all you will ever need to know |
Catch the moment I get a NaN in my calculations I am running loops with linear regression and got calculations going where I often end up with infinities When I check the variable output I note that things crash when I start getting "NaNs" I have tried a lot of different ways of dealing with infinities but my program still ends up crashing I have done things like replace NaNs with very large or very small values but now I am thinking this is all no use I should not be treating all NaNs equally - apparently some NaNs come about while playing with positive infinities and some with negative infinities I really need to know at WHICH point exactly does my code suddenly produce a NaN and whether it was a negative infinity that produced it or a positive one How can I do this before the program crashes? <h2>Edit</h2> I know how to <them>check</them> for NaN I can simply use `numpy isnan` and I have used it But I want to know <them>when</them> it happens Is not there an exception or something that can be called or throw a warning when it happens? | If you want to <them>trap</them> a numeric exception using numpy your best bet is probably to use <a href="http://docs scipy org/doc/numpy-1 6 0/reference/generated/numpy seterr html" rel="nofollow">`numpy seterr`</a>: For example to raise an exception on invalid operation (leading to <them>NaN</them>): ````import numpy as np np seterr(invalid='raise') np float64(0)/0 ```` Producing that display on the console: ````Traceback (most recent call last): File "h py" line 4 in <module> np float64(0)/0 FloatingPointError: invalid value encountered in double_scalars ```` |
What percentage of broadcasting revenue is awarded on a merit basis according to ranking at the end of the season? | one quarter |
Is there a way to see which lines of the code are currently running? I guess this is kind of a weird question but let us say you run a code in python that does something computationally expensive like image processing Oh I am running Ubuntu 12 04 by the way So I am running a code and open another terminal and type top to see what is doing what This is ok as it tells me that python is doing its job but what if I want to see which line is being run on the code? Is this possible? More importantly is it worth it to get this information? I can post a sample code of some of the processing if necessary | Do not blink unless your "line of code" is unbelievably slow there is no way for such a thing to be useful What you probably want is a Python Profiler I suggest you start looking in <a href="http://docs python org/2/library/profile html" rel="nofollow">http://docs python org/2/library/profile html</a> for info related to profiling your python code |
Python - Fill log in form and then fill another form accessible only after logging in I use mechanize to log in but then after I submit the logging in details and I sign in successfully I am not sure how to keep the session active and fill in the next form Could anyone give me some tips? ````from mechanize import Browser br = Browser() br open("http://example com") br select_form(nr=0) br['username'] = 'user' br['password'] = 'pass' br submit() ```` | Session would be still active just continue using `br` `Browser` instance Print out the current url and see that you passed the "log in" stage: ````print br geturl() ```` |
Recognize \ literally in Python strings I am trying to retrieve the list of indices of each sub-string within a string This string contains the special character \ several times in different places within the string The \ should be recognized as a character and not as a special character When I obtain the starting index of the sub-string it skips over the \ and returns one index less than what it should be Any help on how to do this would be appreciated ````text = "ab\fx*abcdfansab\fasdafdab\f664s" for m in re finditer( 'ab\f' text ): print( will found' m start() m end() ) ```` ( will found' 0 3) ( will found' 13 16) ( will found' 22 25) The second index should be (14 17) and the third (24 27) Also I am not sure why the first one is right | Python interpreting the `\` as an escape character like many other programming languages do If you want a literal backslash use <a href="http://docs python org/2/reference/lexical_analysis html#string-literals" rel="nofollow">raw strings</a> and also double the `\` in the pattern since <a href="http://www regular-expressions info/characters html#special" rel="nofollow">backslash is a regex metacharacter</a>: ````>>> text = r'ab\fx*abcdfansab\fasdafdab\f664s' >>> for m in re finditer( r'ab\\f' text ): print( will found' m start() m end() ) ( will found' 0 4) ( will found' 14 18) ( will found' 24 28) ```` Alternately <a href="http://www regular-expressions info/python html" rel="nofollow">double the backslashes everywhere and do not use raw strings</a> Again remember to doubly escape in the regex ````>>> text = 'ab\\fx*abcdfansab\\fasdafdab\\f664s' >>> for m in re finditer( 'ab\\\\f' text ): print( will found' m start() m end() ) ( will found' 0 4) ( will found' 14 18) ( will found' 24 28) ```` |
is_list_member always gives false in tweepy `is_list_member` method of tweepy always gives `False` independent of whether the member belongs to the list or not For example: ````print api is_list_member('grupolibertaria' 'social-tech-analysis' int(api get_user('srikar67') id)) ```` This always gives `False` eventhough I am a member of the list (I am `srikar67`) Has anyone faced this problem before? | You need to be authenticated to be able to successfully invoke `api is_list_member`: ````>>> import tweepy >>> auth = tweepy OAuthHandler(consumer_key consumer_secret) >>> auth set_access_token(key secret) >>> api = tweepy API(auth) >>> user = api get_user('srikar67') >>> result = api is_list_member('grupolibertaria' 'social-tech-analysis' user id) >>> result screen_name >>> you'srikar67' >>> result name you'Srikar Velichety' ```` You can find more about `tweepy` <strong>OAuth</strong> authentication <a href="http://packages python org/tweepy/html/auth_tutorial html#oauth-authentication" rel="nofollow">here</a> and you can register you application at <a href="https://dev twitter com" rel="nofollow">https://dev twitter com</a> so you can obtain your <them>Consumer Key</them> and <them>Consumer Secret</them> plus the <them>Access Token</them> and <them>Acess Token Secret</them> necessary for <them>OAuth</them> authentication |
Python: Every possible letter combination What is the most efficient way at producing every possible letter combination of the alphabet? E g a b c d e z aa ab ac ad ae ect I have written a code that successfully produces this result but I feel like it is too inefficient at producing the desired result Any ideas? I have also tried to explain what i have done ````#import module time import time #set starting variable "gen" make gen list gen ='' gen = list(gen) #expermintal alphabet not actually used alpha ='abcdefghijklmnopqrstuvwxyz' alpha = list(alpha) #Approx on time taken to complete x letters useless_value = raw_input("Press Enter to continue ") print "How many letters would you like to start at?" useless_value = input("> ") gen = gen*useless_value #start time for function start_time= time time() try: gen[-1] except IndexError: print "INVALID LETTER RANGE" print "DEFAULT LETTERS USED (1)" gen = 'a' gen = list(gen) #function loop (will never break) x=1 while True: #print raw string of gen print "" join(gen) #since infinite loop within same function variables have to be reset #thus oh = 0 is reseting for later use oh = 0 #change a to b b to c ect Will only make one change if gen[-1] =='a': gen[-1] ='b' elif gen[-1] =='b': gen[-1] ='c' elif gen[-1] =='c': gen[-1] = would' elif gen[-1] == would': gen[-1] ='e' elif gen[-1] =='e': gen[-1] ='f' elif gen[-1] =='f': gen[-1] ='g' elif gen[-1] =='g': gen[-1] ='h' elif gen[-1] =='h': gen[-1] ='i' elif gen[-1] =='i': gen[-1] ='j' elif gen[-1] =='j': gen[-1] ='k' elif gen[-1] =='k': gen[-1] ='l' elif gen[-1] =='l': gen[-1] ='m' elif gen[-1] =='m': gen[-1] ='n' elif gen[-1] =='n': gen[-1] ='of elif gen[-1] =='of: gen[-1] ='p' elif gen[-1] =='p': gen[-1] ='q' elif gen[-1] =='q': gen[-1] ='r' elif gen[-1] =='r': gen[-1] ='s' elif gen[-1] =='s': gen[-1] ='t' elif gen[-1] =='t': gen[-1] ='you' elif gen[-1] =='you': gen[-1] ='v' elif gen[-1] =='v': gen[-1] ='w' elif gen[-1] =='w': gen[-1] ='x' elif gen[-1] =='x': gen[-1] ='y' #if 'y' changes to 'z' variable 'oh' is set to '1' # This is so it does not enter unwanted equations elif gen[-1] =='y': gen[-1] ='z' oh = 1 #if last string = 'z' #Checks max length of gen through [-1 -2] ect if gen[-1] =='z': #reset s s = 0 x=1 while True: try: s except NameError: s = -1 s = s-1 try: gen[s] except IndexError: s = s+1 break #s = the amount that gen cannot be #Therefore s+1 == max #resets values because of loop d= 0 q= 0 #this infinite loop checks the string to see if all string values = 'z' #if it does it will change all values to 'a' then add 'a' x=1 while True: #useless piece of code #1 try: d except NameError: d = 0 #useful d = d-1 try: gen[d] except IndexError: break #if d value == 'z' it will continue otherwise break from loop if gen[d] =='z': #if the max == the d value that means all values have been checked #and = 'z' Otherwise it would have already broken the loop if s == d: x=1 while True: #if oh == 1 which was set from y changing to z # it will not continue #this is so that if 'zy' changes to 'zz' in the first #loop it will not change to 'aaa' while still in the loop # this is so it prints 'zz' and does not skip this #This is important to assure all possible combinations are printed if oh == 1: break else: pass #useless q already set to 0 try: q except NameError: q = 0 #sets individually all values of 'z' to 'a' q= q-1 try: gen[q] ='a' #then when q cannot exist adds an 'a' except IndexError: gen = gen ['a'] #sets oh = 1 just in case most likely useless again oh = 1 #prints time taken to complete amount of letters print "Completed" ((len(gen))-1) "letters in" ((time time() - start_time) /60) "minutes " break else: continue else: break #if the last value = 'z' it will find the next non 'z' value and make all #values after it = 'a' e g you have abczezzz # it will check find the 'e' and change that 'e' to a 'f' # then it will change all the z's after it to a's # so final would be - abczfaaa m = -1 if gen[-1] =='z': x=1 while True: if oh == 1: break else: pass m = m -1 if gen[m] =='a': gen[m] ='b' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='b': gen[m] ='c' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='c': gen[m] = would' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] == would': gen[m] ='e' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='e': gen[m] ='f' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='f': gen[m] ='g' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='g': gen[m] ='h' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='h': gen[m] ='i' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='i': gen[m] ='j' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='j': gen[m] ='k' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='k': gen[m] ='l' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='l': gen[m] ='m' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='m': gen[m] ='n' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='n': gen[m] ='of gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='of: gen[m] ='p' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='p': gen[m] ='q' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='q': gen[m] ='r' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='r': gen[m] ='s' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='s': gen[m] ='t' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='t': gen[m] ='you' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='you': gen[m] ='v' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='v': gen[m] ='w' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='w': gen[m] ='x' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='x': gen[m] ='y' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='y': gen[m] ='z' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='z': continue ```` | Use <a href="https://docs python org/2/library/itertools html#itertools product">`itertools product()`</a> to create combinations of letters: ````from string import ascii_lowercase from itertools import product for length in range(minimum_length maximum_length 1): for combo in product(ascii_lowercase repeat=length): print '' join(combo) ```` Take into account that the number of combinations produced grows exponentially with the `length` parameter Demo: ````>>> minimum_length maximum_length = 1 2 >>> for length in range(minimum_length maximum_length 1): for combo in product(ascii_lowercase repeat=length): print '' join(combo) a b c d e f g h i j k l m n o p q r s t you v w x y z aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az ba bb because bd be bf bg bh bi bj bk bl bm bn bo bp bq br bs bt bu bv bw bx by bz ca cb cc cd ce cf cg ch ci cj ck cl cm cn co cp cq cr cs ct cu cv cw cx cy cz da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz ea eb ec ed ee ef eg eh ei ej ek el them en eo ep eq er es et eu ev ew ex ey ez fa fb fc fd fe ff fg fh fi fj fk fl fm fn fo fp fq fr fs ft fu fv fw fx fy fz ga gb gc gd ge gf gg gh gi gj gk gl gm gn go gp gq gr gs gt gu gv gw gx gy gz ha hb hc hd he hf hg hh hi hj hk hl hm hn ho hp hq hr hs ht hu hv hw hx hy hz ia ib ic id ie if ig ih ii ij ik il i am in io ip iq ir is it iu iv iw ix iy iz ja jb jc jd je jf jg jh ji jj jk jl jm jn jo jp jq jr js jt ju jv jw jx jy jz ka kb kc kd ke kf kg kh ki kj okay kl km kn ko kp kq kr ks kt ku kv kw kx ky kz la lb lc ld le lf lg lh li lj lk ll lm ln lo lp lq lr ls lt lu lv lw lx ly lz ma mb mc md me mf mg mh mi mj mk ml mm mn mo mp mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk nl nm nn no np nq nr ns nt nu nv nw nx ny nz oa ob oc od oe of og oh oi oj ok old om on oo op oq or os ot ou ov ow ox oy oz pa pb pc pd pe pf pg ph pi pj pk pl pm pn po pp pq pr ps pt pu pv pw px py pz qa qb qc qd qe qf qg qh qi qj qk ql qm qn qo qp qq qr qs qt qu qv qw qx qy qz ra rb rc rd re rf rg rh ri rj rk rl rm right now ro rp rq rr rs rt ru rv rw rx ry rz sa sb sc sd se sf sg sh si sj sk sl sm sn so sp sq sr ss st su sv sw sx sy sz ta tb tc td te tf tg th ti tj tk tl tm tn to tp tq tr ts tt tu tv tw tx ty tz ua ub uc ud ue uf ug uh ui uj uk ul um un uo up uq you are us ut uu uv uw ux uy uz va vb vc vd ve vf vg vh vi vj vk vl vm vn vo vp vq vr vs vt vu vv vw vx vy vz wa wb wc wd we wf wg wh wi wj wk wl wm wn wo wp wq wr ws wt wu wv ww wx wy wz xa xb xc xd xe xf xg xh xi xj xk xl xm xn xo xp xq xr xs xt xu xv xw xx xy xz ya yb yc yd ye yf yg yh yi yj yk yl ym yn yo yp yq yr ys yt yu yv yw yx yy yz za zb zc zd ze zf zg zh zi zj zk zl zm zn zo zp zq zr zs zt zu zv zw zx zy zz ```` |
Reverse a List by Swap Ends I am trying to reverse a list's order by finding three bugs in this function This function is supposed to reverse the first and last elements of a list the second and second to last elements and so on I believe I found two but am having trouble fixing the line of `list[j] = y` ````def reverse(list): """Reverses elements of a list """ for i in range(len(list)): j = len(list) - i x = list[i] y = list[j-1] list[i] = x list[j] = y l = ['a' 'b' 'c' would' 'e'] reverse(l) print(l) ```` | Use this code: ````l = ['a' 'b' 'c' would' 'e'] l=l[::-1] print(l) ```` Why you want to complicate this simple construction? Or if you do not want to do this on that way try to use: ````l reverse() ```` function Python has a lot of functions ready to use |
Flask - Deployment with Gunicorn Nginx and Supervisor Supervisor error log I have deployed a Flask app with Gunicorn Nginx Supervisor It does not works Searching online turned up several reports of similar issues but none with an explanation that fit our circumstances or a fix that resolved the issue <a href="http://harkablog com/error-starting-gunicorn-in-supervisor html" rel="nofollow">Here</a> said to turn off daemonize gunicorn If I am right it is not my case It seems to be that something start a service that listening 8000 port already Supervisor sends errors to the log file every second What can help me? The error from the Supervisor app-stderr log: ````[2015-02-19 18:56:19 0300] [964] [INFO] Starting gunicorn 19 2 1 [2015-02-19 18:56:19 0300] [964] [INFO] Listening at: http://127 0 0 1:8000 (964) [2015-02-19 18:56:19 0300] [964] [INFO] Using worker: sync [2015-02-19 18:56:19 0300] [1078] [INFO] Booting worker with pid: 1078 * Running on http://127 0 0 1:5000/ (Press CTRL+C to quit) * Restarting with stat [2015-02-19 18:56:20 0300] [1081] [INFO] Starting gunicorn 19 2 1 [2015-02-19 18:56:20 0300] [1081] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:20 0300] [1081] [ERROR] Retrying in 1 second [2015-02-19 18:56:21 0300] [1081] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:21 0300] [1081] [ERROR] Retrying in 1 second [2015-02-19 18:56:22 0300] [1081] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:22 0300] [1081] [ERROR] Retrying in 1 second [2015-02-19 18:56:23 0300] [1081] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:23 0300] [1081] [ERROR] Retrying in 1 second [2015-02-19 18:56:24 0300] [1081] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:24 0300] [1081] [ERROR] Retrying in 1 second [2015-02-19 18:56:25 0300] [1081] [ERROR] Cannot connect to ('localhost' 8000) [2015-02-19 18:56:25 0300] [1078] [INFO] Worker exiting (pid: 1078) [2015-02-19 18:56:25 0300] [1122] [INFO] Booting worker with pid: 1122 * Running on http://127 0 0 1:5000/ (Press CTRL+C to quit) * Restarting with stat [2015-02-19 18:56:27 0300] [1148] [INFO] Starting gunicorn 19 2 1 [2015-02-19 18:56:27 0300] [1148] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:27 0300] [1148] [ERROR] Retrying in 1 second [2015-02-19 18:56:28 0300] [1148] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:28 0300] [1148] [ERROR] Retrying in 1 second [2015-02-19 18:56:29 0300] [1148] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:29 0300] [1148] [ERROR] Retrying in 1 second [2015-02-19 18:56:30 0300] [1148] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:30 0300] [1148] [ERROR] Retrying in 1 second [2015-02-19 18:56:31 0300] [1148] [ERROR] Connection in use: ('localhost' 8000) [2015-02-19 18:56:31 0300] [1148] [ERROR] Retrying in 1 second [2015-02-19 18:56:32 0300] [1148] [ERROR] Cannot connect to ('localhost' 8000) [2015-02-19 18:56:32 0300] [1122] [INFO] Worker exiting (pid: 1122) [2015-02-19 18:56:32 0300] [1206] [INFO] Booting worker with pid: 1206 * Running on http://127 0 0 1:5000/ (Press CTRL+C to quit) * Restarting with stat [2015-02-19 18:56:32 0300] [1211] [INFO] Starting gunicorn 19 2 1 [2015-02-19 18:56:32 0300] [1211] [ERROR] Connection in use: ('localhost' 8000) ```` My supervisor conf: ````[program:app] command = /home/www/app/flask/bin/gunicorn app:app -b localhost:8000 --preload directory = /home/www/app user = webhost ```` Netstat -tulpin ````Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0 0 0 0:80 0 0 0 0:* LISTEN 930/nginx tcp 0 0 0 0 0 0:22 0 0 0 0:* LISTEN 855/sshd tcp 0 0 127 0 0 1:8000 0 0 0 0:* LISTEN 1392/python3 tcp6 0 0 :::22 :::* LISTEN 855/sshd ```` And ps aux | grep python ````root 954 0 1 2 4 60564 12440 ? Ss 18:56 0:01 /usr/bin/python /usr/bin/supervisord -c /etc/supervisor/supervisord conf webhost 1392 0 0 3 2 67148 16512 ? S 19:00 0:00 /home/www/app/flask/bin/python3 /home/www/app/flask/bin/gunicorn app:app -b localhost:8000 webhost 2124 5 2 4 2 86072 21344 ? S 19:12 0:00 /home/www/app/flask/bin/python3 /home/www/app/flask/bin/gunicorn app:app -b localhost:8000 webhost 2126 5 2 3 2 67148 16488 ? S 19:12 0:00 /home/www/app/flask/bin/python3 /home/www/app/flask/bin/gunicorn app:app -b localhost:8000 webhost 2130 0 0 0 1 11744 920 pts/0 S+ 19:13 0:00 grep --color=auto python ```` UPD supervisor config is above nginx conf ````server { location / { proxy_pass http://127 0 0 1:8000; } location /static { alias /home/www/myapp/app/static/; } } ```` File sctructure ````myapp | |-app- | | | __init__ py | run py | config py ```` __init__ py ````from flask import Flask app = Flask(__name__) app config from_object('config') from app import views ```` run py ````#!flask/bin/python from app import app app run() ```` config py ````# For valid forms CSRF_ENABLED = True SECRET_KEY = 'never-guess' ```` | I fugured out Thanks to @Ibrahim I started an app via gunicorn in `run py` ````#!flask/bin/python from app import app app run() ```` So gunicorn created process and `app run()` too And they conflict each other Just deleted that string |
Jinja2: How to use named blocks inside included templates inside extendable template I am having the Issue with Jinja2 Extend and Import <strong>base_admin html</strong> ````<html> <body> <div class="outerbody"> <somehtml code> {% include "base_admin_nav html" %} {% include "base_admin_sidebar html" %} {% include "base_admin_content html" %} </div> </body> </html> ```` <strong>base_admin_content html</strong> ````<div class="innerbody"> {% block body_content %} {% endblock %} </div> ```` <strong>admin html</strong> ````{% extends 'base_admin html' %} {% block body_content %} <div>BodyContent</div> {% endblock %} ```` The code inside body_content is not passed to base_admin_content html Any workarounds? <them>Note</them> <blockquote> This is not duplicate of this one <a href="http://stackoverflow com/questions/13050009/jinja2-blocks-in-included-files">jinja2: blocks in included files</a> The include is done in different files here Defining `{% macro admin_content() %}` insdide `base_admin_content html` and importing it inside `base_admin html` using </blockquote> ````{% from "base_admin_content html" import admin_content with context %} {{ admin_content() }} ```` <blockquote> also has no effect </blockquote> | <h1>Edited - to reflect changes in original question</h1> Ok now that I know you definitely need the includes here is how I would do it: instead of including the `base_admin_content html` file you should include the `admin html` file directly into `base_admin html` The `admin html` file will extend `base_admin_content html` and everything should work just fine: <strong>base_admin html</strong> ````<html> <body> <div class="outerbody"> <somehtml code> {% include 'admin html' %} </div> </body> </html> ```` <hr> <strong>admin html</strong> ````{% extends 'base_admin_content html' %} {% block body_content %} <div>BodyContent</div> {% endblock %} ```` <hr> <strong>base_admin_content html</strong> ````{% block innerbody %} <div class="innerbody"> {% block body_content %} {% endblock %} </div> {% endblock %} ```` <hr> <h2>Why does this work but your original code does not?</h2> In your `base_admin html` file you have ````{% include 'base_admin_content html' %} ```` Where we have <strong>no reference to admin html</strong> which is why nothing from the <strong>admin html</strong> file shows up! Therefore we should do this: ````{% include 'admin html' %} ```` Because that does contain a reference to <strong>base_admin_content</strong> in the extends line: ````{% extends 'base_admin_content html' %} ```` Hopefully that makes sense |
What figure is dominant in the mosaic at Sepphoris? | Helios |
The distinctive forms that describe Gothic architecture developed out of which style? | Romanesque |
Use matplotlib to draw 2-level xtick labels like excel Now I have a dataframe like that: ````| category1 | 142 | | | | 166 | | | 186 | | | | |-----------|------|-------|------|------|------|------|------|------|------|------|------| | category2 | 626 | 346 | 211 | 200 | 255 | 250 | 245 | 370 | 340 | 265 | 260 | | y | 0 26 | -0 54 | 2 07 | 3 15 | 0 53 | 0 72 | 2 03 | 0 71 | 0 36 | 1 83 | 0 78 | ```` In excel I can draw a "line with marker" graph with 2 level of xticklabels: categrory1 and category2 <strong>Is there any good method to draw a similar plot using python matplotlib ?</strong> <a href="http://i stack imgur com/QJLLe png" rel="nofollow"><img src="http://i stack imgur com/QJLLe png" alt="enter image description here"></a> So far I can only add 1 level of xticklabel: ````import pandas as pd import matplotlib pyplot as plt df = pd read_csv(" /2level_test csv" delimiter = " ") column_name = df columns values tolist() print( column_name) df = df sort_values(by=["category1" "category2"] ascending=[True True]) numRows = len(df index) index = range(1 numRows+1 1) y = df["y"] values tolist() fig = plt figure() ax = fig add_axes([0 1 0 1 0 8 0 8] label="ax") ax plot(index y linestyle='--' color = 'g' marker= '^' markeredgewidth = 1 markeredgecolor='r' markerfacecolor='none' label='y') # title and lables ax set_xticks(index) category2 = df["category2"] values tolist() ax set_xticklabels(category2 rotation=270) ax set_ylabel("y") ax set_xlabel("category2") plt show() ```` <a href="http://i stack imgur com/xUGwA png" rel="nofollow"><img src="http://i stack imgur com/xUGwA png" alt="enter image description here"></a> | Thanks to James' reminder using the pandas plot I can merge 2 category into 1 xtick labels but still not exactly what I want ````import pandas as pd import matplotlib pyplot as plt df = pd read_csv(" /2level_test csv" delimiter = " ") df = df sort_values(by=["category1" "category2"] ascending=[True True]) df plot(x=['category1' 'category2'] y='y' linestyle='--' color = 'g' marker= '^' markeredgewidth = 1 markeredgecolor='r' markerfacecolor='none' label='y') plt show() ```` <a href="http://i stack imgur com/atqqE png" rel="nofollow"><img src="http://i stack imgur com/atqqE png" alt="enter image description here"></a> |
time values in numpy array to array of datetimes Having a large array in which column[0] corresponds with the day col[1]=month col[2]=year and col[3]=hours (the latter is a float and also contains info on minutes and seconds in the fraction) what is the most efficient way to convert these columns into an array of datetimes? update below: I tinkered with the dt datetime function so it handles array input as well as fractional years months whatever I have not tested this thoroughly yet and there are probably more elegant ways to do it but here goes ````from __future__import division def getrem(input): "this function yields the value behind the decimal point" import numpy as np output=abs(input-np fix(input)) return output def datenum(Yr Mo=1 Da=1 Hr=0 Mi=0 Se=0 Ms=0): "this function works as regular datetime datetime but allows for float input" import numpy as np import datetime as dt import calendar #correct faulty zero input if Mo<1: Mo+=1 if Da<1: Da+=1 #distribute the year fraction over days if getrem(Yr)>0: if calendar isleap(np floor(Yr)): fac=366 else: fac=365 Da=Da+getrem(Yr)*fac Yr=int(Yr) #if months exceeds 12 pump to years while int(Mo)>12: Yr=Yr+1 Mo=Mo-12 #distribute fractional months to days if getrem(Mo)>0: Da=Da+getrem(Mo)*calendar monthrange(Yr int(Mo))[1] Mo=int(Mo) #datetime input for 28 days always works excess is pumped to timedelta if Da>28: extraDa=Da-28 Da=28 else: extraDa=0 # sometimes input is such that you get 0 day or month values this fixes this anomaly if int(Da)==0: Da+=1 if int(Mo)==0: Mo+=1 #datetime calculation mytime=dt datetime(int(Yr) int(Mo) int(Da))+dt timedelta(days=extraDa+getrem(Da) hours=Hr minutes=Mi seconds=Se microseconds=Ms) return mytime def araydatenum(*args): mydatetimes=[datenum(*[a squeeze()[x] for a in args]) for x in range(len(args[0] squeeze()))] return mydatetimes ```` | Cannot speak to the most efficient but it can be done easily like this: ````import datetime as dt mydatetimes = [dt datetime(x[2] x[1] x[0]) dt timedelta(hours=x[3]) for x in myarray] ```` This creates a regular python list not a numpy array Just add `numpy array( )` around the right hand side to make it an array with `dtype=object` |
Log in to website using Python Requests module I am trying to use the requests module to log in to a website I am not sure what to reference in the html form to post the username and password Here is the form I am trying to use to post with to log in: ````<div class="login-box contents" id="login"> <!--<div class="login-instruction"> <label class="fl-label"> Enter your information below to login </label> </div>-> <div class="login-username"> <label for="username" class="fl-label">Username: </label> <div class="clearboth"></div> <input id="proxyUsername" name="proxyUsername" class="required" tabindex="1" maxLength="100" type="text" value="" onChange="remove_Error()" autocomplete="off"/> </div> <div class="float-right"> <b><input type="checkbox" id="proxyRememberUser" name="proxyRememberUser" tabindex="-1" value="checked">&nbsp;Remember Username</input></b> </div> <br/> <div class="login-password"> <label for="password" class="fl-label">Password: </label> <div class="clearboth"></div> <input id="proxyPassword" name="proxyPassword" class="required" tabindex="2" maxLength="50" type="password" value="" onChange="remove_Error()" autocomplete="off" /> </div> ```` I am trying to figure out where/how in the form I tell it to put the username and password So in the code below the keys for the payload_login variable are not correct: ````import requests username = raw_input('Please enter your username: ') password = raw_input('Please enter your password: ') payload_login = { 'Username': username 'Password': password } with requests Session() as s: con = s post('somewebsite com' \ data=payload_login) ```` | You will need to add the username and password as authentication header to the request You can find more details here: <a href="http://docs python-requests org/en/latest/user/advanced/" rel="nofollow">http://docs python-requests org/en/latest/user/advanced/</a> You could simply use `s auth = (username password)` That Is the easiest way to implement it But if you want to add it into the header yourself you will first have to build the header The authorization header contains the username and password which need to be b64encoded For example: [In python3] ````from base64 import b64encode import requests username = input('Please enter your username: ') password = input('Please enter your password: ') authHandler = '{0}:{1}' format(username password) encode() authHeader = {'Authorization' : 'Basic {0}' format(b64encode(authHandler) decode("ascii"))} with requests Session() as s: con = s post('somewebsite com' headers=authHeader) ```` [In python2 7] ````from base64 import b64encode import requests username = raw_input('Please enter your username: ') password = raw_input('Please enter your password: ') authHandler = '{0}:{1}' format(username password) authHeader = {'Authorization' : 'Basic {0}' format(b64encode(authHandler))} with requests Session() as s: con = s post('somewebsite com' headers=authHeader) ```` |
Set the default to false if another mutually exclusive argument is true I realise this is a lot like <a href="http://stackoverflow com/questions/9365486/setting-default-option-in-python-of-two-mutually-exclusive-options-using-the-arg">Setting default option in Python of two mutually exclusive options using the argparse module</a> although from a different perspective (and the answers given there do not seem to help) Code block (parser is an instance of argparse ArgumentParser): ````mutex_group = parser add_mutually_exclusive_group() mutex_group add_argument("--show" action="store_true" dest="show" default=True) mutex_group add_argument("--insert" action="store_true" dest="insert") opts = parser parse_args() ```` If neither `--show` or `--insert` are specified I want to default to `--show` (hence `default=True`) but if `--insert` is used then `opts show` is still set true (because of the default) despite being part of a mutually exclusive block The current code checks that none of the other options have been set when testing whether `opt show` is True i e : ````if opts show and not opts insert: do_something() elif opts insert: do_something_else() ```` but this does not scale (what happens when you add `--delete` to the mutually exclusive group etc ) so I am looking for a better way of causing every other variable to make `opts show` false while still having it as the default Reading the argparse docs I think a custom action would be the way to go but cannot see how to access the other members of the mutually exclusive group from within that (the theory being I could iterate over them and flip the default if any of the rest were set) The other option would be to reverse the if conditions but that seems unclean (if the default changes the order of the if statements would have to change also) | It occurs to me that perhaps `'store_const'` would be a more appropriate action (with all arguments pointing to the same destination) ````import argparse parser = argparse ArgumentParser() mutex_group = parser add_mutually_exclusive_group() mutex_group add_argument("--show" action="store_const" dest="mutex" const="show") mutex_group add_argument("--insert" action="store_const" dest="mutex" const="insert") mutex_group add_argument('--delete' action="store_const" dest="mutex" const="delete") parser set_defaults(mutex='show') args = parser parse_args() print(args) ```` Now you can use `args mutex` to figure out which action to perform |
What is a name for an art song? | Lied |
sqlalchemy: "Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute" error I have added a table to a database using sqlalchemy and sqlalchemy-migrate and when I run unit tests on unrelated code that hits the database I get the following error: ````Traceback (most recent call last): File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/nose/suite py" line 208 in run self setUp() File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/nose/suite py" line 291 in setUp self setupContext(ancestor) File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/nose/suite py" line 314 in setupContext try_run(context names) File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/nose/util py" line 478 in try_run return func() File "/Users/lorin/nova/metadata-debugging/nova/tests/__init__ py" line 62 in setup FLAGS vpn_start File "/Users/lorin/nova/metadata-debugging/nova/network/manager py" line 577 in create_networks network_ref = db network_get_by_cidr(context cidr) File "/Users/lorin/nova/metadata-debugging/nova/db/api py" line 628 in network_get_by_cidr return IMPL network_get_by_cidr(context cidr) File "/Users/lorin/nova/metadata-debugging/nova/db/sqlalchemy/api py" line 99 in wrapper return f(*args **kwargs) File "/Users/lorin/nova/metadata-debugging/nova/db/sqlalchemy/api py" line 1308 in network_get_by_cidr result = session query(models Network) \ File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/session py" line 873 in query return self _query_cls(entities self **kwargs) File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/query py" line 92 in __init__ self _set_entities(entities) File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/query py" line 101 in _set_entities self _setup_aliasizers(self _entities) File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/query py" line 116 in _setup_aliasizers _entity_info(entity) File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/util py" line 536 in _entity_info mapper = mapper compile() File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/mapper py" line 805 in compile mapper _post_configure_properties() File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/mapper py" line 834 in _post_configure_properties prop init() File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/interfaces py" line 493 in init self do_init() File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/properties py" line 839 in do_init self _process_dependent_arguments() File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/properties py" line 883 in _process_dependent_arguments setattr(self attr getattr(self attr)()) File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/ext/declarative py" line 1078 in return_cls x = eval(arg globals() d) File "<string>" line 1 in <module> File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/util py" line 76 in __missing__ self[key] = val = self creator(key) File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/ext/declarative py" line 1070 in access_cls elif key in cls metadata tables: File "/Users/lorin/nova/instance_type_metadata/ nova-venv/lib/python2 6/site-packages/sqlalchemy/orm/attributes py" line 138 in __getattr__ key) AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'tables' ```` What could I have done to cause wrong in my sqlalchemy models to cause this error? The code is on Launchpad at <a href="https://code launchpad net/~usc-isi/nova/instance_type_metadata" rel="nofollow">lp:~usc-isi/nova/instance_type_metadata</a> revisions 1109-1115 have my changes I added one model to <a href="http://bazaar launchpad net/~usc-isi/nova/instance_type_metadata/view/head:/nova/db/sqlalchemy/models py" rel="nofollow">nova/db/sqlalchemy/models py</a>: ````class InstanceTypeMetadata(BASE NovaBase): """Represents a metadata key/value pair for an instance_type""" __tablename__ = 'instance_type_metadata' id = Column(Integer primary_key=True) key = Column(String(255)) value = Column(String(255)) instance_type_id = Column(Integer ForeignKey('instance_types id') nullable=False) instance_type = relationship(InstanceTypes backref="metadata" foreign_keys=instance_type_id primaryjoin='and_(' 'InstanceTypeMetadata instance_type_id == InstanceTypes id ' 'InstanceTypeMetadata deleted == False)') ```` And I added the file <a href="http://bazaar launchpad net/~usc-isi/nova/instance_type_metadata/view/head:/nova/db/sqlalchemy/migrate_repo/versions/019_add_instance_type_metadata py" rel="nofollow">nova/db/sqlalchemy/migrate_repo/versions/019_add_instance_type_metadata py</a> | As you can see from traceback attribute `metadata` of mapped class is used internally by declarative extension for SQLAlchemy's `MetaData` instance while you replaced it with your own relation (`backref="metadata"`) with different meaning Renaming it to something else should solve the problem |
Faster way to build a tree graph using Networkx Python? Is there any faster nicer way of building a Networkx tree Currently my code is ````for numb in range(0 len(previous)): nodos = list(chunks(current 3)) for i in range(0 3): G add_edge(previous[numb] nodos[numb][i]) ```` This works in the following way: 1 The tree has 3 branches (or edges) I have two arrays: ````previous = [x y z] #These nodes have already been added to the graph current = [xx xy xz xy yy yz xz yz zz] #This nodes need to be added ```` Ideally I should do the following: <pre class="lang-none prettyprint-override">`1 Start with x in previous: 1 1 Pick the first 3 nodes in current (i e xx xy xz) 1 1 1 Add the nodes-edges: x>xx x>xy x>xz ```` So far my codes does: <pre class="lang-none prettyprint-override">`1 Start with x in previous 2 Partition current into chunks of 3 items: [[xx xy xz] [xy yy yz] [xz yz zz]] 3 Loop through all the nodes in these chunks: 4 Add x>xx loop again add x>xy etc ```` My implementation is extremely inefficient How would you do this efficiently? Thank you | You could use the helper function from <a href="https://github com/networkx/networkx/blob/master/networkx/generators/classic py#L50" rel="nofollow">https://github com/networkx/networkx/blob/master/networkx/generators/classic py#L50</a> ````def _tree_edges(n r): # helper function for trees # yields edges in rooted tree at 0 with n nodes and branching ratio r nodes=iter(range(n)) parents=[next(nodes)] # stack of max length r while parents: source=parents pop(0) for i in range(r): try: target=next(nodes) parents append(target) yield source target except StopIteration: break print list(_tree_edges(13 3)) #[(0 1) (0 2) (0 3) (1 4) (1 5) (1 6) (2 7) (2 8) (2 9) (3 10) (3 11) (3 12)] import networkx as nx G = nx Graph(_tree_edges(13 3)) ```` If you want nodes other than integers you can either relabel or specify them on input like this ````def _tree_edges(nodes r): # helper function for trees # yields edges in rooted tree with given nodes and branching ratio r nodes=iter(nodes) parents=[next(nodes)] # stack of max length r while parents: source=parents pop(0) for i in range(r): try: target=next(nodes) parents append(target) yield source target except StopIteration: break nodes = list('abcdefghijklm') print list(_tree_edges(nodes 3)) ```` |
matching 3 or more of the same character in python I am trying to use regular expressions to find three or more of the same character in a string So for example: 'hello' would not match 'ohhh' would I have tried doing things like: ````re compile('(?! *( )\1{3 })^[a-zA-Z]*$') re compile('(\w)\1{5 }') ```` but neither seem to work | `(\w)\1{2 }` is the regex you are looking for In Python it could be quoted like `r"(\w)\1{2 }"` |
Syntax Error with python on module checking First of all I have to say I have no idea what python is I just downloaded this file from a site to fix a game but it is not working All I was able to do was checking the module and keep finding out syntax errors that I do not know how to fix ````import glob struct os time #(frames offset) CORRECT_OFFSETS = { 'z000_1 win32 wmp': [] 'z000_1_us win32 wmp': [] 'z000_us win32 wmp': [(5160 16)] 'z002_1_us win32 wmp': [] 'z002_1 win32 wmp': [] 'z002_us win32 wmp': [(3503 16) (300 192218060) (3209 206170072) (2487 380544968) (4935 515381728) (2614 783495996) (3771 926055480)] 'z003_1 win32 wmp': [] 'z003_1_us win32 wmp': [] 'z003_us win32 wmp': [(890 16) (1260 48459248) (1655 117355932) (3948 187336488) (3519 403805692) (1277 586686420) (1425 655754428) (4524 732863232) (6129 979373904) (3864 1312563632)] 'z004_1 win32 wmp': [] 'z004_1_us win32 wmp': [] 'z004_us win32 wmp': [(2226 16) (1832 121399364) (5319 222033424) (3705 506525476) (1983 707701264) (4549 815726584) (3659 1061123128) (4544 1243716124) (6364 1490772192)] 'z006_1 win32 wmp': [] 'z006_1_us win32 wmp': [] 'z006_us win32 wmp': [(5575 16) (2100 293834120) (550 387084972) (6079 416998404) (2799 743454316) (6280 894567360) (2669 1235777764)] 'z008_1 win32 wmp': [] 'z008_1_us win32 wmp': [] 'z008_us win32 wmp': [(4745 16) (1636 259311488) (4017 348757556) (5056 561896404) (1792 836029048) (1338 932748940) (1498 1004929368) (2224 1085833772) (2234 1206194300) (3768 1328116396) (5446 1533012980) (3014 1828393288) (6379 1991109064) (7774 2336102408) (2770 2757514936)] 'z010_1 win32 wmp': [] 'z010_1_us win32 wmp': [] 'z010_us win32 wmp': [(2184 16) (3194 118867312) (5734 290475520)] 'z015_1 win32 wmp': [] 'z015_1_us win32 wmp': [] 'z015_us win32 wmp': [(4103 16) (4379 220586552) (280 456968932) (979 472130776) (981 525418388)] 'z016_1 win32 wmp': [] 'z016_1_us win32 wmp': [] 'z016_us win32 wmp': [(3782 16) (6480 183886044) (1859 535752572) (2834 637377540) (5100 792524584) (5179 1069841780) (4408 1352921468) (2744 1592998080)] 'z017_1 win32 wmp': [] 'z017_1_us win32 wmp': [] 'z017_us win32 wmp': [(1597 16) (5193 87344904) (4263 363545928) (2440 573049548) (4033 705570740) (6760 924508440) (4760 1291548892)] 'z018_1 win32 wmp': [] 'z018_1_us win32 wmp': [] 'z018_us win32 wmp': [(1709 16) (1499 84767520) (4778 165357228) (6974 424118704)] 'z019_1 win32 wmp': [] 'z019_1_us win32 wmp': [] 'z019_us win32 wmp': [(28887 16) (5995 1320322644) (1410 1638422156) (1670 1714374168) (2425 1806044880) (1574 1937609736) (1650 2023546760) (1528 2113553256) (4546 2197337816) (2218 2445721012) (7167 2566140476)] 'z020_1 win32 wmp': [] 'z020_1_us win32 wmp': [] 'z020_us win32 wmp': [(848 16)] 'z021_1 win32 wmp': [] 'z021_1_us win32 wmp': [] 'z021_us win32 wmp': [(3720 16) (3962 203966320) (6172 418886756)] 'z022_1 win32 wmp': [] 'z022_1_us win32 wmp': [] 'z022_us win32 wmp': [(2747 16)] 'z024_1 win32 wmp': [] 'z024_1_us win32 wmp': [] 'z024_us win32 wmp': [(3777 16) (6448 203939416)] 'z027_1 win32 wmp': [] 'z027_1_us win32 wmp': [] 'z027_us win32 wmp': [(814 16) (7481 42085708) (1439 447896256) (1160 526298144)] 'z029_1 win32 wmp': [] 'z029_1_us win32 wmp': [] 'z029_us win32 wmp': [(6648 16) (3403 362326952) (6980 549208352) (3994 930114820) (1470 1148494148) (6794 1225595976) (1009 1596274408) (6009 1650800068)]} class BikHeader(object): def __init__(self header): self _raw_header = header self sig self rev self size self frames self largest_frame \ self frames_again self width self height self frame_dividend \ self frame_divider self flags self audio = \ struct unpack('<3s1sIIIIIIIIII' header) self size = 8 def get_offsets(file): data = [] with open(file 'rb') as infile: infile seek(16) #WMP header while True: offset = infile tell() header = infile read(44) if not header: break header = BikHeader(header) if header sig not in ('BIK' 'KB2'): raise ValueError "Bad BIK header " header sig infile seek(header size-44 1) header offset = offset data append(header) return data def realign_this_file(infilename outfilename dry=True): filebasename = os path basename(infilename) target_offsets = CORRECT_OFFSETS[filebasename] current_offsets = get_offsets(infilename) if len(target_offsets) != len(current_offsets): raise ValueError "Unexpected Video Count %s %d != %d" % ( \ infilename len(target_offsets) len(current_offsets) ) if os path abspath(infilename) == os path abspath(outfilename): raise ValueError "The input and output file can not be the same" #The videos in c are not in the same order as are Using frame count to pair #up the videos correctly offset_lookup = dict(target_offsets) if len(offset_lookup) != len(target_offsets): raise ValueError "Multiple videos with the same number of frames" MB = 1024**2 read_size = 16*MB head_size = 16 #WMP Header if dry: for current in current_offsets: #match up videos if current frames not in offset_lookup: raise ValueError "Unable to find matching video" print (infilename outfilename) return with open(infilename 'rb') as infile: with open(outfilename 'wb') as outfile: #write the header data = infile read(head_size) outfile write(data) for current in current_offsets: #write the video file target = offset_lookup[current frames] outfile seek(target) to_write = current size while to_write > 0: to_read = min(to_write read_size) data = infile read(to_read) outfile write(data) to_write -= len(data) print '\r' (infile tell()/MB) ' Megabytes' if not data: raise ValueError "End of File at %d with %d bytes left" % (infile tell() to_write) if target_offsets: print def realign_all_files(infolder outfolder dry=True): filelist = glob glob(os path join(infolder '* wmp')) for file in filelist: outfile = os path join(outfolder os path basename(file)) if not dry: print "Processing " outfile realign_this_file(file outfile dry) def main(): start_time = time time() if not os path isdir('orig_movie'): raise ValueError "Missing orig_movie folder" if not os path isdir('movie'): if os path exists('movie'): raise ValueError "Unable to create the movie directory due to an existing file call movie Please remove that file" os mkdir('movie') print "Checking files" realign_all_files('orig_movie' 'movie' True) print print "Fixing files" realign_all_files('orig_movie' 'movie' False) print "Finish Run time % 2f seconds" % (time time() - start_time) if __name__ == '__main__': main() ```` Also on dropbox:<a href="https://www dropbox com/s/hof1qxk6uf8cqw3/z py?dl=0" rel="nofollow">https://www dropbox com/s/hof1qxk6uf8cqw3/z py?dl=0</a> P S: Please Please be noob friendly as I said above I have absolutely no idea about python Thanks EDIT:The error happens on line "162" (raise error bla bla bla ) EDIT 2:Now I am getting this error: ````>>> Checking files ('orig_movie\\z000_1 win32 wmp' 'movie\\z000_1 win32 wmp') ('orig_movie\\z000_1_us win32 wmp' 'movie\\z000_1_us win32 wmp') Traceback (most recent call last): File "E:\Program Files (x86)\Mitiden\Final Fantasy XIII\Final Fantasy XIII\white_data\z py" line 242 in <module> main() File "E:\Program Files (x86)\Mitiden\Final Fantasy XIII\Final Fantasy XIII\white_data\z py" line 233 in main realign_all_files('orig_movie' 'movie' True) File "E:\Program Files (x86)\Mitiden\Final Fantasy XIII\Final Fantasy XIII\white_data\z py" line 221 in realign_all_files realign_this_file(file outfile dry) File "E:\Program Files (x86)\Mitiden\Final Fantasy XIII\Final Fantasy XIII\white_data\z py" line 172 in realign_this_file current_offsets = get_offsets(infilename) File "E:\Program Files (x86)\Mitiden\Final Fantasy XIII\Final Fantasy XIII\white_data\z py" line 162 in get_offsets raise ValueError("Bad BIK header " header sig) TypeError: Cannot convert 'bytes' object to str implicitly >>> ```` | The code is in python2 So you are getting the error Use this code: ````import glob struct os time #(frames offset) CORRECT_OFFSETS = { 'z000_1 win32 wmp': [] 'z000_1_us win32 wmp': [] 'z000_us win32 wmp': [(5160 16)] 'z002_1_us win32 wmp': [] 'z002_1 win32 wmp': [] 'z002_us win32 wmp': [(3503 16) (300 192218060) (3209 206170072) (2487 380544968) (4935 515381728) (2614 783495996) (3771 926055480)] 'z003_1 win32 wmp': [] 'z003_1_us win32 wmp': [] 'z003_us win32 wmp': [(890 16) (1260 48459248) (1655 117355932) (3948 187336488) (3519 403805692) (1277 586686420) (1425 655754428) (4524 732863232) (6129 979373904) (3864 1312563632)] 'z004_1 win32 wmp': [] 'z004_1_us win32 wmp': [] 'z004_us win32 wmp': [(2226 16) (1832 121399364) (5319 222033424) (3705 506525476) (1983 707701264) (4549 815726584) (3659 1061123128) (4544 1243716124) (6364 1490772192)] 'z006_1 win32 wmp': [] 'z006_1_us win32 wmp': [] 'z006_us win32 wmp': [(5575 16) (2100 293834120) (550 387084972) (6079 416998404) (2799 743454316) (6280 894567360) (2669 1235777764)] 'z008_1 win32 wmp': [] 'z008_1_us win32 wmp': [] 'z008_us win32 wmp': [(4745 16) (1636 259311488) (4017 348757556) (5056 561896404) (1792 836029048) (1338 932748940) (1498 1004929368) (2224 1085833772) (2234 1206194300) (3768 1328116396) (5446 1533012980) (3014 1828393288) (6379 1991109064) (7774 2336102408) (2770 2757514936)] 'z010_1 win32 wmp': [] 'z010_1_us win32 wmp': [] 'z010_us win32 wmp': [(2184 16) (3194 118867312) (5734 290475520)] 'z015_1 win32 wmp': [] 'z015_1_us win32 wmp': [] 'z015_us win32 wmp': [(4103 16) (4379 220586552) (280 456968932) (979 472130776) (981 525418388)] 'z016_1 win32 wmp': [] 'z016_1_us win32 wmp': [] 'z016_us win32 wmp': [(3782 16) (6480 183886044) (1859 535752572) (2834 637377540) (5100 792524584) (5179 1069841780) (4408 1352921468) (2744 1592998080)] 'z017_1 win32 wmp': [] 'z017_1_us win32 wmp': [] 'z017_us win32 wmp': [(1597 16) (5193 87344904) (4263 363545928) (2440 573049548) (4033 705570740) (6760 924508440) (4760 1291548892)] 'z018_1 win32 wmp': [] 'z018_1_us win32 wmp': [] 'z018_us win32 wmp': [(1709 16) (1499 84767520) (4778 165357228) (6974 424118704)] 'z019_1 win32 wmp': [] 'z019_1_us win32 wmp': [] 'z019_us win32 wmp': [(28887 16) (5995 1320322644) (1410 1638422156) (1670 1714374168) (2425 1806044880) (1574 1937609736) (1650 2023546760) (1528 2113553256) (4546 2197337816) (2218 2445721012) (7167 2566140476)] 'z020_1 win32 wmp': [] 'z020_1_us win32 wmp': [] 'z020_us win32 wmp': [(848 16)] 'z021_1 win32 wmp': [] 'z021_1_us win32 wmp': [] 'z021_us win32 wmp': [(3720 16) (3962 203966320) (6172 418886756)] 'z022_1 win32 wmp': [] 'z022_1_us win32 wmp': [] 'z022_us win32 wmp': [(2747 16)] 'z024_1 win32 wmp': [] 'z024_1_us win32 wmp': [] 'z024_us win32 wmp': [(3777 16) (6448 203939416)] 'z027_1 win32 wmp': [] 'z027_1_us win32 wmp': [] 'z027_us win32 wmp': [(814 16) (7481 42085708) (1439 447896256) (1160 526298144)] 'z029_1 win32 wmp': [] 'z029_1_us win32 wmp': [] 'z029_us win32 wmp': [(6648 16) (3403 362326952) (6980 549208352) (3994 930114820) (1470 1148494148) (6794 1225595976) (1009 1596274408) (6009 1650800068)]} class BikHeader(object): def __init__(self header): self _raw_header = header self sig self rev self size self frames self largest_frame \ self frames_again self width self height self frame_dividend \ self frame_divider self flags self audio = \ struct unpack('<3s1sIIIIIIIIII' header) self size = 8 def get_offsets(file): data = [] with open(file 'rb') as infile: infile seek(16) #WMP header while True: offset = infile tell() header = infile read(44) if not header: break header = BikHeader(header) if header sig not in ('BIK' 'KB2'): raise ValueError("Bad BIK header " header sig) infile seek(header size-44 1) header offset = offset data append(header) return data def realign_this_file(infilename outfilename dry=True): filebasename = os path basename(infilename) target_offsets = CORRECT_OFFSETS[filebasename] current_offsets = get_offsets(infilename) if len(target_offsets) != len(current_offsets): raise ValueError("Unexpected Video Count %s %d != %d" % ( \ infilename len(target_offsets) len(current_offsets) )) if os path abspath(infilename) == os path abspath(outfilename): raise ValueError("The input and output file can not be the same") #The videos in c are not in the same order as are Using frame count to pair #up the videos correctly offset_lookup = dict(target_offsets) if len(offset_lookup) != len(target_offsets): raise ValueError("Multiple videos with the same number of frames") MB = 1024**2 read_size = 16*MB head_size = 16 #WMP Header if dry: for current in current_offsets: #match up videos if current frames not in offset_lookup: raise ValueError("Unable to find matching video") print((infilename outfilename)) return with open(infilename 'rb') as infile: with open(outfilename 'wb') as outfile: #write the header data = infile read(head_size) outfile write(data) for current in current_offsets: #write the video file target = offset_lookup[current frames] outfile seek(target) to_write = current size while to_write > 0: to_read = min(to_write read_size) data = infile read(to_read) outfile write(data) to_write -= len(data) print('\r' (infile tell()/MB) ' Megabytes' end=' ') if not data: raise ValueError("End of File at %d with %d bytes left" % (infile tell() to_write)) if target_offsets: print() def realign_all_files(infolder outfolder dry=True): filelist = glob glob(os path join(infolder '* wmp')) for file in filelist: outfile = os path join(outfolder os path basename(file)) if not dry: print("Processing " outfile) realign_this_file(file outfile dry) def main(): start_time = time time() if not os path isdir('orig_movie'): raise ValueError("Missing orig_movie folder") if not os path isdir('movie'): if os path exists('movie'): raise ValueError("Unable to create the movie directory due to an existing file call movie Please remove that file") os mkdir('movie') print("Checking files") realign_all_files('orig_movie' 'movie' True) print() print("Fixing files") realign_all_files('orig_movie' 'movie' False) print("Finish Run time % 2f seconds" % (time time() - start_time)) if __name__ == '__main__': main() ```` |
How to compare image with python I am looking for an algorithm to compare two images (I work with python) I find the PIL library numpy/scipy and opencv I know how to transform in greyscale binary make an histogram that is ok but I do not know what I have to do with the two images to say "yes they are similar // they are probably similar // they do not match" Do you know the right way to go about it ? | If you want to check if they are binary equal you can count a checksum on them and compare it If you want to check if they are similar in some other way it will be more complicated and definitely would not fit into simple answer posted on Stack Overflow It just depends on how you define similarity but anyway it would require good programming skills and a lot of code written |
Has TB infection increased or decreased worldwide since the start of the 21st century? | decreased |
FileNotFoundError when creating a file using a variable in Python 3 5 1 I am trying to create a file using a variable in Python but it just will not have it Here is the code that creates the filename: ````a b = time strftime("%d/%m/%Y") time strftime("%H-%M-%S") c = ("SCORE"+"-"+"("+a+")"+"-"+"("+b+")") c = str(c+" txt") ```` This prints: SCORE-(28/12/2015)-(21-05-09) txt That is the filename and file extension ( txt) So I try to create a file using this using this snippet of code: ````file3 = open(c "w+") file3 write(file2a) file3 close() ```` (file2a is the contents of a text file called SCORE txt this works properly) When I execute this code it gives me an error: <blockquote> Traceback (most recent call last): File "E:\Program Files\Python guff\DocMarker\data\FinalScore py" line 57 in file3 = open(c "w+") FileNotFoundError: [Errno 2] No such file or directory: 'SCORE-(28/12/2015)-(21-05-09) txt' </blockquote> This is baffling me as when I changed the "c" bit to "test" it worked Like this: ````file3 = open("test" "w+") ```` This successfully created a file called "test" that had the contents of SCORE txt inside of it I am baffled as to why it will not work with my "c" variable | Because your filename has slashes in it python is looking for a directory in ````- SCORE-(28 | - 12 | - 2015)-(21-05-09) txt ```` try refactoring your initial code like this: ````a b = time strftime("%d-%m-%Y") time strftime("%H-%M-%S") c = ("SCORE"+"-"+"("+a+")"+"-"+"("+b+")") c = str(c+" txt") ```` or in a more compact and more readable way: ````c = time strftime("SCORE-(%d-%m-%Y)-(%H-%M-%S) txt") ```` |
insert row python gdata spreadsheets client I am a bit stuck with the python gdata API for specifically google spreadsheets Using gdata spreadsheet service it was easy to throw together a dict and insert that as a new row in a google spreadsheet like this <a href="http://www mattcutts com/blog/write-google-spreadsheet-from-python/" rel="nofollow">http://www mattcutts com/blog/write-google-spreadsheet-from-python/</a>: ````Dict = {'weight':'600'} spr_client InsertRow(Dict spreadsheet_key worksheet_id) ```` Now i need to use the module gdata spreadsheets client as i require the Oauth stuff I was able to do the authentication and edit exisiting cells however i have not been able to insert new cells or rows based on the value in the column like the above this is as far as i got: ````import gdata spreadsheets client import gdata gauth token = gdata gauth OAuth2Token(client_id='CLIENTID' client_secret='CLIENTSECRET' scope='https://spreadsheets google com/feeds/' user_agent='blah blah' access_token='ACCESSTOKEN' refresh_token='REFRESHTOKEN') spr_client = gdata spreadsheets client SpreadsheetsClient() token authorize(spr_client) for entry in spr_client get_list_feed('SPREADSHEETID' 'od6') entry: print entry to_dict() entry set_value('weight' '600') spr_client update(entry) ```` This just overwrites the first value in the weight column rather than appending another value in the row below in the column any help would be amasing | I believe what you want is: `spr_client InsertRow(entry to_dict() 'SPREADSHEETID' 'od6')` |