w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » PYTHON » Page 1
Convert tuple to string after parsing html file
The issue is that each item in the list called urls is a tuple. A tuple is a container for other items and is also immutable. When you do item + " ", you are asking the interpreter to concatenate a tuple and a string which is not possible. What you want to do instead is inspect the tuple and select one of the fields in each item to write to the outfile: with open("1.txt", "w+") as outfile: f

Categories : Python

Where do I place the validation exception code in my pyramid app?
1) Anywhere in your project directory. I made a new file called exceptions.py where I place all my HTTP status code and validation exceptions. I placed this file in the same directory as my views.py, models.py, etc. 2) That bad taste in your mouth is Python, because importing methods is the Pythonic way to go about using classes and functions in other files, rather than some sort of magic. Might

Categories : Python

Using `raw_id_fields` to select related objects in the admin
It seems you've misunderstood how the link works. Django doesn't offer a selection for reverse foreign keys. From the Item admin you could select the Category like that. But not the other way around. One workaround would be to use a project that adds custom widgets such as Django Tags Input which adds a tag-like input field to your admin. In this case the configuration would look something like

Categories : Python

Python, dynamically change the order of nested loops
Well, I usually conditionally assign to the target of the loops. You could also use an associative array containing the assignments. if SOMECONDITION1: target1 = js target2 = ks target3 = ls elif SOMECONDITION2: target1 = ks target2 = ls target3 = js elif SOMECONDITION3: target1 = ls target2 = js target3 = ks for j in js: for k in ks: for l in ls:

Categories : Python

Flask RESTful Destroy User Token
Rather than a garbage token simply encode no data: def generate_auth_token(username=None, expiration=600): gen_serial = Serializer(secret_key, expires_in=expiration) data = {'username': username} if username is not None else {} return gen_serial.dumps(data) Then you can have an invalidate endpoint that requires a login and returns a token without a username: def invalidate(self):

Categories : Python

Python Regex Match WillCard as the end of a word
That's probably because  is for word boundaries, not just characters. The following pattern will only give matches for what you initially specified (a word ending in * that doesn't have it in the middle or beginning) (?m)(?<!w|*)w+?*(?=[^w]|$) Works in RegexBuddy when tested against this string: word *word wo*rd word* *word* words Check for yourself If all you wanted was something to c

Categories : Python

Is there a way to create key based on counts in Spark
How about using zipWithIndex? Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition receives the largest index. This is similar to Scala's zipWithIndex but it uses Long instead of Int as the index type. This me

Categories : Python

Python Request Stream
I found following link. This seems to work great for me. http://koaning.github.io/html/scapingdynamicwebsites.html

Categories : Python

How can I embed two fields together in serializer
You can use a nested serializer to make this work. class FSerializer(serializers.Serializer): value = serializers.Field(source="f_value") metric = serializers.Field(source="f_metric") class MyModelSerializer(serializers.ModelSerializer): somefield = serializers.Field() f = FSerializer(source="*") This should give you the nested output you are looking for. You can find more inf

Categories : Python

Project Structure for Python projects with MySQL queries?
Have you thought about using a template system like Jinja2? I've used it to store and use templates for a variety of situations (ranging from web development to automatic code generation) and it works very well. You could have your SQL queries in template files, and load and fill them as you wish.

Categories : Python

Finding the most tree-like hierarchy that explains the data
Here is undirected graph with your dataframe. Edge (x,y) means that there was some data line such that both x,y was mentioned. For example - last line "A1,B4,C2" added edges (A1,B4), (B4,C2), (A1,C2) Now it's possible to sort A,B,C according to your wishes. Finding the hierarchy with the least number of (extra) multi-parent edges We can bruteforce all arrangements (it's quite fast for N

Categories : Python

Matplotlib: Making 2D Gaussian contours with transparent outermost layer
Try using levels. def plot_countour(x,y,z): # define grid. xi = np.linspace(-2.1, 2.1, 100) yi = np.linspace(-2.1, 2.1, 100) ## grid the data. zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic') levels = [0.2, 0.4, 0.6, 0.8, 1.0] # contour the gridded data, plotting dots at the randomly spaced data points. CS = plt.contour(xi,yi,zi,len(levels),linewi

Categories : Python

Python: How to get a variable's value updated every call?
You'd have to make a function for that. Something like this should suffice? epoch = lambda: int(time.time()*1000) print epoch() time.sleep(2) print epoch() You could also encase this into a class and make a @property out of it, so that you can get a value without using brackets ()

Categories : Python

swig pass list of tuples into C++ function
If it were me doing this in SWIG I'd try to write the least amount of weird extra code possible. So my initial approach would be to write some Python code to handle the heterogeneous list and figure out which add_TYPE to call for each entry in the list. As an example: %module test %{ #include <iostream> #include <limits> %} %include <std_string.i> %inline %{ struct MyObj {

Categories : Python

How can python wait for a batch SGE script finish execution?
From your code you want the program to wait for job to finish and return code, right? If so, the qsub sync option is likely what you want: http://gridscheduler.sourceforge.net/htmlman/htmlman1/qsub.html

Categories : Python

Passing variables between Powershell commands in a python script
If the two commands can be run together then just run them together, but as you say you have to run them separately you could try using Export-Clixml to save the object to a file then Import-Clixml to reload it. Here's a working example: #!/usr/bin/env python3 import base64, subprocess, sys def powershell(cmd, input=None): cmd64 = base64.encodebytes(cmd.encode('utf-16-le')).decode('ascii').s

Categories : Python

programmatically add pandas DataFrame name to columns
From the linked question, you can do something like this. Multiple names can point to the same DataFrame, so this will just grab the "first" one. def first_name(obj): return [k for k in globals() if globals()[k] is obj and not k.startswith('_')][0] In [24]: first_name(name_of_df) Out[24]: 'name_of_df'

Categories : Python

Heroku Python binary library dependency
I don't know, but maybe the answer is this: With the amazing help of @PadraicCunningham I managed to find the solution. The problem turned out to be that heroku-buildpack-apt installs things in a newly created folder /app/.apt/ which was not in the PYTHONPATH. So I added the relevant folder to my PYTHONPATH on heroku as follows: heroku config:add PYTHONPATH=/app/.apt/usr/lib/python2.

Categories : Python

Chain celery tasks and pass return from one task to another implicitly
You need to change the job part a bit: @shared_task def job(): chain = (task1.s() | task2.s() | task3.s() ) result = chain().get() return result Since the execution of one is dependent on it's preceding task you don't get anything by applying it asynchronously. You can start job asynchronously however.

Categories : Python

Registering VCS root in PyCharm from within virtual environment?
Ok since no one has answered my question, I wrote this simple script that I added in my path folder in utils. So when I execute this in my project root folder, the VCS roots get added in pycharm upon restart. https://github.com/virogenesis/pycharm_vcsrootgenerator

Categories : Python

Python Input 0 automatically
I think this is what you are looking for: n1 = raw_input('Εισάγετε Λεφτά :') or 0 n2 = raw_input('Εισάγετε Πλυσίματα Μέσα - Έξω :') or 0 n3 = raw_input('Εισάγετε Πλυσίματα Μηχανών :') or 0 n4 = raw_input('Εισάγετε Πλυσίματα Εξωτερικά :') or 0 n5 = raw_input('Εισάγετε Τι Ποσό Πήρε ο Σπύρο

Categories : Python

How can I specify the server where an egg is?
It is possible indicate where to retrieve the egg from including the full path to it in the find-lings parameter. The following example is taken from the pip docs: eggs = PILwoTk find-links = http://dist.plone.org/thirdparty/PILwoTk-1.1.6.4.tar.gz

Categories : Python

What is the difference between contiguous and non-contiguous arrays?
A contiguous array is just an array stored in an unbroken block of memory: to access the next value in the array, we just move to the next memory address. Consider the 2D array arr = np.arange(12).reshape(3,4). It looks like this: In the computer's memory, the values of arr are stored like this: This means arr is a C contiguous array because the rows are stored as contiguous blocks of memor

Categories : Python

How to perform HTTPS Calls in Pycurl?
According to the pycURL documentation, your post data needs to be key value pairs and url encoded: post_data = {'field': 'value'} # Form data must be provided already urlencoded. postfields = urlencode(post_data) # Sets request method to POST, # Content-Type header to application/x-www-form-urlencoded # and data to send in request body. c.setopt(c.POSTFIELDS, postfields)

Categories : Python

Error: Maximum recursion depth on using flask-babel method with Nereid
Finally I got the solution and here is how I reach there. Problem with recursion depth error with flask is its not easy to get root cause of problem, so with hit and trial approach I got tail of the problem. Method call flow is like this: dateformat filter > format_date() > to_user_timezone() > get_timezone() Now get timezone method is overridden here as: def get_timezone(): """ Retur

Categories : Python

Python - Monkey Patching weird bug
The issue was not having the right signature for one of the functions. It was resolved by changing the argument passed to the MonkeyPatch function as en empty dictionary {} instead of 'None' value which is kind of specific to my code. The reason the I was initially hitting the issue was, as the current function's call(cli.port_register) was failing when the parameters where passed to port_registe

Categories : Python

Execute bash file from Python
The program is executed in the current working directory as reported by os.getcwd(). For a command line program, its typically the directory you are in when you run the program. To run a command in the same directory as your python script, use the __file__ variable to figure out where you are: import os import envoy my_path = os.path.dirname(os.path.abspath(__file__)) envoy.run('./scripts.sh', c

Categories : Python

Writing a CSV from Flask framework
You need to add newlines. Anyway, your method of making csvs (printing the list and removing brackets from it) is not the best way to do it. Try this instead: csvList = ' '.join(','.join(row) for row in csvList) Or use the csv module: import io, csv dest = io.StringIO() writer = csv.writer(dest) for row in csvList: writer.writerow(row) # Now dest is a file-like object containing your cs

Categories : Python

Python 3 email body encoding
The problem is that many email clients (including Gmail) send non-ascii emails in base64. stdin on the other hand passes everything into a string. If you parse that with Parser.parse(), it returns a string type with base64 inside. Instead the optional decode argument should be used on the get_payload() method. When that is set, the method returns a bytes type. After that you can use the builtin d

Categories : Python

Get colorbar ticklabels
This gives you the ticks on the scale of the y-axis of the colorbar, which has limits (0.0, 1.0) cbar.ax.get_yticks() This is what you need: np.interp(cbar.ax.get_yticks(), cbar.ax.get_ylim(), cbar.get_clim()) The result is: array([ 10., 20., 30., 40., 50., 60., 70., 80., 90.])

Categories : Python

defining a function which calls another function for a variety of strings python
It only "works on the first string in the list" because you return from inside the loop. Keep track of your result outside of the loop. def test_find_anagrams(): stringlist = [('aces'), ('sidebar'), ('adverb'), ('fuels'), ('hardset'), ('praised')] result = [] for str1 in stringlist: result.extend(word for word in get_dictionary_word_list() if anagram(word,str1)) return re

Categories : Python

Python check if force closed
You can't. A process can't read it's own exit code. That would not make much sense. But in order to force process shutdown the OS has to send a signal to that process. As long as it is not SIGKILL and/or SIGSTOP then you can intercept it via signal library. SIGKILL and SIGSTOP cannot be blocked, e.g. if someone does kill -9 then there's nothing you can do. To use signal library: import signal im

Categories : Python

Python local class leak
Neither method will lead to leaks. The lifetime of Python objects is governed by reference counting; if there are no references left, the object is removed. In all cases here are the instances and classes in your Outer.AppendToMenu() method only referenced by locals, and will not lead to leaks. In both your cases, the counts for the class and instance are as follows: class _Inner creates the c

Categories : Python

Python3 Django -> HTML to PDF
You could use Weasyprint. You could easily render directly. You could do something like that: html = HTML(string=htmlstring) main_doc = html.render() pdf = main_doc.write_pdf() return HttpResponse(pdf, content_type='application/pdf') To render your Django view to HTML, you could simply use the shortcut render_to_string(self.template_name, context, context_instance=RequestConte

Categories : Python

Create a map using pymongo
You can approach like this, for itm in db.collection.find(): print {itm.pop('b'): itm} Here collection is the name of your collection in the database. If you iterate over the pymongo cursor object you will get dict type object which you can modify like normal python dict.

Categories : Python

Take In Input from User and Display the same input on the same page
First off you aren't passing the form to the template in articles(). You need to have something along the lines of: args['form'] = YourForm() In your first view function. Also, in your create view you do this: a.user = User.objects.get(username = request.user.username) Which does an unnecessary database lookup of the user again, you can just do this to be clearer and faster: a.user = requ

Categories : Python

Python GUI using tkinter and db connection
ttk.Label(mainframe, text = notice).grid(column = 1, row = 6) Changing the value of the string notice won't update the text in this label. You need to use a StringVar for this. notice = Tkinter.StringVar() ttk.Label(mainframe, textvariable = notice).grid(column = 1, row = 6) Then, instead of doing notice = "whatever" in your functions, do notice.set("whatever"). Alternatively, don't have a

Categories : Python

Monty Hall-Not Running
To many brackets and you do not need brackets in python. Try changing: if ((not(i == car) and not(i == guess1)): to if i != car and i != guess1:

Categories : Python

Remove all rows of lines between two stings from xml file using python
Use a SAX parser such as xml.sax. This gives you callbacks as it scans the XML file for each of the various xml tags or 'events' (ie opening a tag, closing a tag, seeing an attribute, seeing some data, etc). Keep track of whether you are in part of the XML file you do or do not want to keep (or delete) as you get these callbacks. Stream the data into a new file if you are in "keeping" mode, and do

Categories : Python




© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.