Menu
  • HOME
  • TAGS

Python3:socket:TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes'

sockets,python-3.x

Normal string formatting cannot be used for bytes. I think the way to go about it is - you'd have to first generate a string, format it and then convert it to bytes with appropriate encoding. So the following changes should work change sock.send(b'Hello %s!' % data) to reply =...

python 3 error with print function syntax

python,python-3.x,printing

The code works fine in Python 2. If you are using Python 3, there is an issue with last line, because print is a function. So, because of where you've put the close parenthesis, only the first part is actually passed to print. Try this instead print("len(list6[1]):", len(list6[1])) ...

TypeError: object is not JSON serializable in DJango 1.8 Python 3.4

python,json,django,python-3.x,serialization

You have to serialize your student objects list, try something like this: from django.http import HttpRequest,HttpResponse from django.http import JsonResponse from json import dumps from django.core import serializers def get_stats(request): if request.method == "POST": srch_dropV = request.POST['srch_dropAJ'] else: srch_dropV = '' if(srch_dropV == 'Green'): students = GreenBased.objects.all() if(srch_dropV == 'Yellow'):...

Python bruteforce combinations given a starting string

python,python-3.x,brute-force

Taking the original code from the itertools man page copy the code for the combinations_with_replacement code but replace line 7 with new indices starting from your entered word. inputStr='acc' indices=[pool.index(l) for l in inputStr] And then run the rest of the code from the man page. EDIT: For a complete...

Installing Python 3 Docker Ubuntu error command 'x86_64-linux-gnu-gcc

python,python-3.x,amazon-web-services,docker

You should install python3-pip in your Dockerfile and then run pip3 install -r requirements.txt

Django runserver not serving some static files

django,python-3.x

According to the Django documentation regarding static/: This should be an initially empty destination directory for collecting your static files from their permanent locations into one directory for ease of deployment; it is not a place to store your static files permanently. You should do that in directories that will...

Label keeps on appearing

python-3.x,tkinter

Try something like this instead of creating a new label every time: import Tkinter as tk class Window(): def __init__(self, root): self.frame = tk.Frame(root) self.frame.pack() self.i = 0 self.labelVar = tk.StringVar() self.labelVar.set("This is the first text: %d" %self.i) self.label = tk.Label(self.frame, text = self.labelVar.get(), textvariable = self.labelVar) self.label.pack(side = tk.LEFT)...

Python MVC style GUI Temperature Converter

python,user-interface,python-3.x,model-view-controller,tkinter

You have two mistakes here: 1 - In your Counter.py file and in your Convert class methods, you are not return the right variables, instead of return celsius you should return self.celsius and same goes for self.fahrenheit 2 - In Controller.py file: self.view.outputLabel["text"] = self.model.convertToFahrenheit(celsius) This will not update the...

Python3 after cursor.execute it stopped?

mysql,python-3.x

Below is how I get my trouble solved. Using array to append all the processed data and use executemany to save them at once. In beforehand, have to modify mysql config max_allowed_packet = 500M A pain but valuable lesson. Answer: - import base64 import struct import pymysql.cursors import sys import...

Trivial functors

python,python-3.x,functor

The operator module has operator.attrgetter() and operator.itemgetter() that do just that: from operator import attrgetter, itemgetter sorted(some_dict.items(), key=itemgetter(1)) sorted(list_of_dicts, key=itemgetter('name')) map(attrgetter('name'), rows) These functions also take more than one argument, at which point they'll return a tuple containing the value for each argument: # sorting on value first, then on...

Music21 Midi Error: type object '_io.StringIO' has no attribute 'StringIO'. How to fix it?

python,python-3.x,music21

You may be right... I think the error may actually be in Music21, with the way it handles importing StringIO Python 2 has StringIO.StringIO, whereas Python 3 has io.StringIO ..but if you look at the import statement in music21\midi\realtime.py try: import cStringIO as stringIOModule except ImportError: try: import StringIO as...

How to have multiple text widgets with scrollbars in a frame on tkinter

python,python-3.x,tkinter

Two issues (apart from the messed-up indentation which probably just happened when pasting your code): The frame was bound to the returned value of a function rather than to a function itself. You can fix this with a lambda function. You're trying to create a complex layout with pack(). Try...

Understanding Super() in python

python,python-3.x,tkinter

Yes, I believe the author could have used super() . The main advantage of super comes with multiple inheritance, this may interest you...

Python - Why is my list turning into a tuple when passing it to a method with varargs (keywordonly)

python,python-3.x,varargs

You need to unpack the list in the function call with the * operator: foo.accept(*values) ...

Error Hashing + Salt password

python,authentication,python-3.x,hash,salt

You can do salt = salt.decode("utf-8") after salt is encoded to convert it to string.

How to parse this string?

python,python-3.x

#!/usr/bin/env python3 # coding: utf-8 s = """00 1f [email protected] 00c 00e 00N 00> 00E 00O 00F 002 00& 00* 00/ 00) 00 1f 00 1c 00 00 00 17 00\r 00 08 00 03 00 f8 ff ea ff e1 ff e1 ff e0 ff da ff d2 ff...

Wrapping Functions in Python 3.4 missing required positional argument

python,python-3.x,flask,flask-login

login_role_required should be a function that returns a decorator function, which in turn takes a single argument—the decorated function—and returns a modified function. So it should look like this: def login_role_required(req_roles = None): if req_roles is None: req_roles = ['any'] def decorator (f): def decorated_view(*args, **kwargs): # … return f(*args,...

index() Method Not Accepting None as Start/Stop

python,python-3.x

This is a bug with how the arguments are being parsed. See issue #1259 and issue #11828 for the same bug with string methods, and issue #13340 for lists. Yes, the documentation implies that the indices are used in roughly the same way as a slice, and the internal utility...

Pass function call as a function argument

python,python-2.7,python-3.x

The functions are returning tuples, because return only gives back one item. You can "unpack" the tuple returned by prepending it with an asterisk. The syntax will look like this: print function1(*function2(1,2)) ...

Set comprehensions in Python and testing for membership in the set being created

python,python-3.x,set-comprehension

You misunderstood; the set comprehension is a distinct expression, separate from the assignment. The expression produces a new set() object that then will be assigned to newSet, replacing the old set() object you had. As such, as you iterate and build the set, the previous and separate set() object bound...

re.split return None in function but normaly works OK

python,python-3.x,split

Your function does not return a value so it returns None as all python functions that don't specify a return value do: def whois(k, i): k = str(k[i]) print (k) whois = subprocess.Popen(['whois', k], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ou, err = whois.communicate() who = str(ou) print (who.find('NetName:')) who = re.split('NetName:', who)[1] who...

argparse optional value for argument

python,python-3.x,command-line-interface,argparse

You can do this with nargs='?': One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string...

LXML - parse td content within tr tag

python,html,python-3.x,lxml

Use range and format for i in range(1,5): contentA = tree.xpath("//table[@class='yfnc_tabledata1']/tr[1]/td/table/tr[2]/td[{i}]".format(i=i))[0].text_content().strip() print(contentA) Output Total Revenue 31,821,000 30,871,000 29,904,000 for i in range(1,5): contentB = tree.xpath("//table[@class='yfnc_tabledata1']/tr[1]/td/table/tr[3]/td[{i}]".format(i=i))[0].text_content().strip() print(contentB) Output Cost of Revenue 16,447,000 16,106,000 15,685,000 EDIT In [22]: d = {} In [23]: d.setdefault('Revenue', []) Out[23]: [] In [24]: for i in...

How do I output the acronym on one line

python,python-3.x

Pass end='' to your print function to suppress the newline character, viz: for l in line.split(): print(l[0].upper(), end='') print() ...

Why does round(5/2) return 2?

python,python-3.x,python-3.4

if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Quoting the documentation for the round function. Hope this helps :) On a side note, I would suggest always read the doc when...

Python3 csv DictWriter: writing through bz2 fails (TypeError: 'str'/buffer interface)

python,python-3.x,python-3.4

Note that the bz2.open defaults to binary mode. This is in contrast to the regular Python built-in open which defaults to text mode. To solve your error, you simply need to open the file in text mode, not the default binary mode. Change the with bz2.open(... mode='w'...) to with bz2.open(......

Pyqt - Add a QMenuBar to a QMainWindow which is in another class

python-3.x,pyqt,pyqt5

QMainWindow comes with its default QMenuBar, but you cant set a new one with QMainWindow.setMenuBar() More informations in the Qt Documentation...

XML to custom Class

python,python-3.x

What about something like this? This is basically what you're doing in your "I'd like to do something like..." example. Attributes on scope objects default to None, and then get set using the attribute/xpath dictionary xmlPaths. There's some stuff going on in your code that I'm not sure about (for...

Addition of two dates on python 3

python,csv,datetime,python-3.x

Once you have both the values in two variables, new_date and new_time, you could simply combine them to get the datetime, like this, >>> new_date = dt.datetime.strptime(row[0], "%Y.%m.%d") >>> new_time = dt.datetime.strptime(row[1], "%H:%M").time() >>> >>> dt.datetime.combine(new_date, new_time) datetime.datetime(2005, 2, 28, 17, 38) Note:- Avoid using date and time as variable...

The command “sudo apt-get install python-dev, python3-dev” failed and exited with 100 during

python,python-2.7,python-3.x,command-line,pip

Based on your error log, the main issue is that apt-get is interpreting your attempt to install separate packages with the comma as part of the name of python-dev. To install multiple packages with apt-get just separate them with a space. However, based upon the continued discussion in the chat...

Scroll through a tkinter frame or window [duplicate]

python-3.x,scroll,tkinter,scrollbar

I don't think Frames support scrolling (there is no .yview method.) You could put a canvas which does support scrolling in place of or inside the frame to hold the contents of your page and get the scrolling you are after. This is a very good, comprehensive tkinter resource that...

Execute multiple command lines with multiple arguments

python,windows,batch-file,python-3.x

May be changing / to \\ in Popen can help.

How to access a class's property using a partialmethod?

python,python-3.x,descriptor

A partialmethod object will only handle descriptor delegation for the function object, no for any arguments that are descriptors themselves. At the time the partialmethod object is created, there is not enough context (no class has been created yet, let alone an instance of that class), and a partialmethod object...

How can I customize the offset in matplotlib

python-3.x,matplotlib

Indeed, as Andreus correctly answered, %.1e would give you what I would understand as scientific formatting of the tick values as printed on the axes. However, setting a FormatStrFormatter switches off what is called the scientific formatting feature of the default formatter, where the exponent is not formatted with each...

How to have parameters to a button command in tkinter python3 [duplicate]

python,function,python-3.x,tkinter

You are looking for the lambda keyword: from tkinter import * index={'Food':['apple', 'orange'], 'Drink':['juice', 'water', 'soda']} Names=['Food', 'Drink'] def display(list): for item in list: print(item) mon=Tk() app=Frame(mon) app.grid() for item in Names: Button(mon, text=item, command= lambda name = item: display(index[name])).grid() mon.mainloop() You have to use name = item so that...

Cleaner regex for removing characters before dot or slash

python,regex,python-3.x

re.sub(r"^[^.-]*[.-]\s*","",some_string) You can try this....

Python3 input() error: can't initialize sys standard streams

ubuntu,python-3.x

Magic number is the term for the first two bytes of an executable file. It is used to determine how the executable should be loaded. The magic number is also used in *.pyc files that are compiled from the *.py files. It says what version of bytecode is used inside....

subprocess python 3 check_output not same as shell command?

python-3.x,subprocess

shlex.split() syntax is different from the one used by cmd.exe (%COMSPEC%) use raw-string literals for Windows paths i.e., use r'c:\Users' instead of 'c:\Users' you don't need shell=True here and you shouldn't use it with a list argument you don't need to split the command on Windows: string is the...

Python custom sort

python,sorting,python-3.x

Python already has the wrapper you describe, it's called functools.cmp_to_key

Quotes within quotes

python,string,python-3.x,double-quotes

In Python you can create multiline strings with """...""". Quoting the documentation for strings, String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. In your first case, ""s"" is parsed like this "" (empty string literal) s "" (empty string literal) Now, Python doesn't know...

Python3 - sorting a list

python,list,python-3.x

list.remove() removes the first occurrence of the value, not all such values. As a result you'll first add both 1 values to sort, remove one of the two 1 values, then add the remaining 1 value to sort again: >>> lst = [4,5,5,1,6,1] >>> copy = lst.copy() >>> sort =...

If a block of code creates an error, do x; if not, do y (Python)

python,python-3.x

Sounds like you're looking for exceptions https://docs.python.org/2/tutorial/errors.html # checkError: becomes try # some test if x > 0: raise AssertionError("Something failed...") print("The block of code works!") except: print("The block of code does not work!") Something like that...

Finding the number of letters in a sentence?

python,python-3.x

Change n = words.count(x) to n = i.count(x) does the trick. Reason You are saying i is your one word in each iteration.So you have to use i.count(x) to get count of x in i ...

Python file processing?

python,python-3.x

You need to convert your converted string grades to floats (or int) average =(float(grade_1) + float(grade_2)+ float(grade_3))/3.0 average = str(average) ...

writing a tkinter scrollbar for canvas within a class

python,python-3.x,tkinter

Your problem starts here: frame.bind('<Configure>', self.OnFrameConfigure(parent=canvas)) You are immediately calling the OnFrameConfigure function. That is not how you use bind. You must give a reference to a callable function. Since you're using a class, you don't need to pass parent in, unless you have this one function work for multiple...

Getting Error on Running brand New project from Pycharm on Mac

django,python-3.x

As I see from your error you have Python 3.5 install Try insatalling Python 3.3 or Python 3.4 because Djagno 1.8 not supporting Python 3.5 see this link for table that gives version compatibility with difrrent version of Python and Django...

Python 3 random.randint() only returning 1's and 2's

function,python-3.x,random,dice

this line if die == 'a' or 'A': will always return True. That is because the way the items are grouped, it is the same as if (die == 'a') or ('A'): and 'A' (along with any string except "") is always True. Try changing all those lines to if...

Python 3 filtering directories by name that matches specific pattern

python,regex,python-3.x,directory,filtering

import os import re result = [] reg_compile = re.compile("test\d{8}") for dirpath, dirnames, filenames in os.walk(myrootdir): result = result + [dirname for dirname in dirnames if reg_compile.match(dirname)] As advised I will explain (thanks for the -1 btw :D) the compile("test\d{8}) will prepare a regex that matches any folder named test...

Why is rounding done like this? [on hold]

python,python-3.x,rounding

You should have a look at how floats are handled, and what limitations they have. https://docs.python.org/3/tutorial/floatingpoint.html is a Python specific explanation. In your particular example, Python chooses to use a representation that has a limited number of digits (depends on the Python version). Internally, different float values may share the...

Works in shell but not as a program?

python,python-3.x

Your function never returns the values, so they are discarded again. Add a return statement: def main(): infile = open("studentinfo.txt", "r") return infile.read() Also, in the interactive interpreter, all expression results are echoed automatically unless the result is None. In regular scripts, you'll have to print results explicitly: print(main()) ...

multiple iteration of the same list

python,python-2.7,python-3.x,numpy,shapely

Without downloading shapely, I think what you want to do with lists can be replicated with strings (or integers): In [221]: data=['one','two','three'] In [222]: data1=['one','four','two'] In [223]: results=[[],[]] In [224]: for i in data1: if i in data: results[0].append(i) else: results[1].append(i) .....: In [225]: results Out[225]: [['one', 'two'], ['four']] Replace...

XML file parsing - Get data from a child of a child

python,xml,parsing,python-3.x

For printing all display names , You should try - dnames = entry.findall(".//DisplayName") for x in dnames: print(x.text) For getting the specific display name under <Scalar> , you can do the below- name = entry.find('./Scalar/DisplayName').text print(name) ...

How to avoid user to click outside popup Dialog window using Qt and Python?

qt,user-interface,python-3.x,dialog,qt-creator

use setModal() like so; dialog.setModal(1); Or; dialog.setModal(true); ...

How to detect certain numbers from a dice roller?

python,python-3.x,dice

Roll it into a function, since it's reusable. import random def roll_die(): return random.randint(1,6) then just test. result = roll_die() if result == 1: # forfeit attack however you're doing that else: # roll between 2-6 # do whatever your game logic has you doing. ...

Callable not defined for django.db.models field default

python,django,python-3.x,django-models

You shouldn't use this method to set your default value, rather than override the save method of the model and use it there. For example: class User(models.Model): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, default=uuid.uuid1) def make_slug(self): return self.first_name + self.last_name[0] def save(self, *args, **kwargs): self.slug =...

Need Help in Python Variable updation (Pygame module)

python,python-2.7,variables,python-3.x,pygame

You are confusing the event KEYUP with the UP key. The event KEYUP occurs when a key (any key) is released. The event KEYDOWN occurs when any key is pressed down. In you code, this means that when the UP key is pressed down, the speed is set to 0.1,...

RTC to Git Migration using rtc2git - https://github.com/WtfJoke/rtc2git

git,python-2.7,python-3.x,rtc

Python 3.3.5 installation fixed this issue for me. Downloaded from - https://www.python.org/downloads/release/python-335/

My simple client crash everytime it tries to connect to my python socket server

python,sockets,python-3.x,serversocket

There are two issues in your server/client programs. You server has two accept() calls, before the while loop and inside the while loop , this causes the server to actually wait for two connections before it can start receiving any messages from any client. The socket.sendall() function takes in bytes...

Setting unique=True on a ForeignKey has the same effect as using a OneToOneField

python,django,python-3.x,django-models,django-1.8

primary_key implies unique=True. So, as the warning says, you should probably be using a OneToOneField.

sys.argv in a windows environment

python,windows,python-3.x

You are calling the script wrong Bring up a cmd (command line prompt) and type: cd C:/Users/user/PycharmProjects/helloWorld/ module_using_sys.py we are arguments And you will get the correct output....

Python3 create files from dictionary

file,python-3.x,dictionary

Remove the if not len(key) != len(aDict) and the break. What you probably wanted to do is stopping the loop after iterating all the keys. However key is one of 'OG_1', 'OG_2', 'OG_XX', it's not a counter or something like that. Replace open("key", "w") with open(key + ".txt", "w")....

TCL parsing a list of arguments to an external call

python,python-3.x,tcl

I don't know if the Tcl interpreter in your system is recent. If it is, you should be able to use python $python_app_name {*}$python_app_args to get the arguments as separate strings. The {*} prefix is a syntactic modifier that splices the items in a list as separate arguments. Example: list...

xmlrpclib error 'module not found' when trying to access gandi api

python,api,python-3.x,xml-rpc

I am not sure if you did give out your real API key, but I urge you to change it ASAP. In any case, in Python, top level variables/names do not come from thin air - they're introduced either by import or the assignment statement (x = 123), (or some...

Multiple random choices with different outcomes

python,python-3.x,random

The line: randgend = random.choice(gend) makes randgend a single random choice from [ 'male', 'female' ], you're basically writing: randgend = 'male' # or female, whichever gets picked first If you want it to be a function that returns a different random choice each time, you need: randgend = lambda:...

Python 3.3 TypeError: can't use a string pattern on a bytes-like object in re.findall()

python-3.x,web-crawler

You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8'). See Convert bytes to a Python String...

Why does '12345'.count('') return 6 and not 5?

python,python-3.x,count

count returns how many times an object occurs in a list, so if you count occurrences of '' you get 6 because the empty string is at the beginning, end, and in between each letter. Use the len function to find the length of a string....

multiprocessing.Pool with maxtasksperchild produces equal PIDs

python,python-3.x,multiprocessing,pid

You need to also specify chunksize=1 in the call to pool.map. Otherwise, multiple items in your iterable get bundled together into one "task" from the perception of the worker processes: import multiprocessing import time import os def f(x): print("PID: %d" % os.getpid()) time.sleep(x) complex_obj = 5 #more complex axtually return...

scipy.integrate.quad gives wrong result on large ranges

python,python-3.x,scipy,integration,quad

The reason here is that your function is only very strongly peaked in a very small region of your integration region and is effectively zero everywhere else, quad never finds this peak and thus only see's the integrand being zero. Since in this case you know where the peaks are,...

tkinter showerror creating blank tk window

python-3.x,tkinter,messagebox,tkmessagebox

from Tkinter import * from tkMessageBox import showerror Tk().withdraw() showerror(title = "Error", message = "Something bad happened") Calling Tk().withdraw() before showing the error message will hide the root window. Note: from tkinter import * for Python 3.x...

Pylint Error when using metaclass

python,python-3.x,vim,pylint,syntastic

In the docs under 4.2. Q. The python checker complains about syntactically valid Python 3 constructs...: A. Configure the python checker to call a Python 3 interpreter rather than Python 2, e.g: let g:syntastic_python_python_exec = '/path/to/python3' ...

Split long column into several columns and print them side by side

python,python-3.x,multiple-columns

For Python3 , You can try this function if you need column wise printing - def listPrinter(lst, cols): l = len(lst) rs = int(l/cols) for i in range(rs): for j in range(cols): print(lst[i + rs*j] , end='\t') print('') Please note, the argument lst to the above function is the list...

Efficient & Pythonic way of finding all possible sublists of a list in given range and the minimum product after multipying all elements in them?

python,list,python-2.7,python-3.x,reduce

First, given the list and the index range, we can get the sublist A[i : j + 1] [66, 77, 88] For positive integers a and b, a * b is no less than a or b. So you don't need to do multiplying, it's not possible that multiplying of...

weird behaviour of late import and scopes

python,python-3.x,cpython

This is nothing special about import statements. It's just how the scoping works in Python. If you're assigning a value to a label, it is local to the scope unless explicitly defined global. Try this code - a = 2 def start(): print a a = 3 start() This also...

Receiving “NO CARRIER” error while tring to make a call using GSM modem in Python

python,python-3.x,gsm,at-command,modem

I found the origin of the error : The syntax is ATD+98xxxxxxxxxx; followed by terminating string. I was forgotten to put semicolon at the end after the number. So I replace phone.write(b'ATD"'+recipient.encode() +b'"\r') with phone.write(b'ATD"'+recipient.encode() +b';"\r') And now it works fine. Based on the brackets in this documents, I thought...

Put a QLineEdit() into a QTreeWidgetItem()

python,python-3.x,pyqt,pyqt5

It should suffice to set your item flags to include ItemIsEditable: self.item.setFlags(self.item.flags() | Qt.ItemIsEditable) You can also configure the EditTriggers to start editing as you like, e.g. upon double-clicking an item: treeView.setEditTriggers(QtGui.QAbstractItemView.DoubleClicked) Double-clicking an item in your treewidget should now bring up an editor - which by default is simply...

Nested maps in Python 3

python,python-3.x,lambda

Python 3's map returns a map object. You need to convert it to list explicitly: f1_b = list(map(lambda x: list(map(lambda t:t.strip(), x.split(',', 1))), lst)) Though in most cases you should prefer list comprehensions to map calls: f1_a = [[t.strip() for t in x.split(',', 1)] for x in lst] Keep in...

What is a reliable isnumeric() function for python 3?

python,regex,validation,python-3.x,isnumeric

try: float(w.get()) except ValueError: # wasn't numeric ...

django-admin startproject not working with python3 on OS X

python,django,osx,python-2.7,python-3.x

Recommended: Try using virtualenv and initiate your environment with Python3. Or a quicker solution is to use python interpreter directly to execute django-admin: <path-to-python3>/python /usr/local/bin/django-admin startproject mysite ...

Python 3.4: List to Dictionary

python,list,python-3.x,dictionary

You can use unpacking operation within a dict comprehension : >>> my_dict={i:j for i,*j in [l[i:i+4] for i in range(0,len(l),4)]} >>> my_dict {'Non Recurring': ['-', '-', '-'], 'Total Other Income/Expenses Net': [33000, 41000, 39000], 'Selling General and Administrative': [6469000, 6384000, 6102000], 'Net Income From Continuing Ops': [4956000, 4659000, 4444000], 'Effect...

Converting list to array with NumPy asarray method

python,csv,python-3.x,numpy

Try this: from pandas import read_csv data = read_csv('country.csv') print(data.iloc[:,1].mean()) This code will convert your csv to pandas dataframe with automatic type conversion and print mean of the second column. ...

What's the fastest way to compare datetime in pandas?

python,python-3.x,numpy,pandas,datetime64

If you call set_index on pdata to date_2 then you can pass this as the param to map and call this on tdata['date_1'] column and then fillna: In [51]: tdata['TBA'] = tdata['date_1'].map(pdata.set_index('date_2')['TBA']) tdata.fillna(0, inplace=True) tdata Out[51]: TBA date_1 0 0 2010-01-04 1 2 2010-01-05 2 0 2010-01-06 3 0 2010-01-07...

How to make the Sieve of Eratosthenes faster?

python-3.x,primes,sieve-of-eratosthenes,number-theory

Always try to measure empirical complexity of your code at several ranges. Your code is slow because of how you find the set difference, and that you always convert between set and list and back. You should be using one set throughout, and updating it in place with sete.difference_update(range(p*p,n,p*2)) To...

“Initializing” a constant containing a file in python?

python,python-3.x

A common approach in Python is to initialize a variable to None if it is not being used yet. This is a signal to the future readers of your code that you want that variable to exist, but it won't be until later that it is used. infile = None...

Return to main fuction in python

python-3.x,def

As suggested by tobias_k, you should add the contents of choices() into a while loop. I also found some other problems: False does not equal "False", so your while loop never runs. You use terms like mylist, mylist1, and mylist2 - it's better to rename these to choosing_list, appending_list, and...

How to create an item list to use multiple times on a Jinja2 template page?

python,python-3.x,for-loop,flask,jinja2

As pointed out by Peter Wood in the comments, points is a generator: You need to turn it into a list: list(graph.find()) Thanks!...

csv.writerows() puts newline after each row

python,csv,python-3.x

This problem occurs only with Python on Windows. In Python v3, you need to add newline='' in the open call per: Python 3.3 CSV.Writer writes extra blank rows On Python v2, you need to open the file as binary with "b" in your open() call before passing to csv Changing...

“Initializing” variables in python?

python,python-3.x

The issue is in the line - grade_1, grade_2, grade_3, average = 0.0 and fName, lName, ID, converted_ID = "" In python, if the left hand side of the assignment operator has multiple items to be allocated, python would try to iterate the right hand side that many times and...

Regex: match “group3.*group1” if group2 is not between groups 3 and 1

regex,python-3.x,regex-negation,regex-lookarounds

^.*?(?:g31|g32)(?!.*?(?:g21|g22)).*?(?:g11|g12).*$ Try this.See demo: https://regex101.com/r/hI0qP0/9#python...

Python 3.4 : LXML : Parsing Tables

python,python-3.x,datatables,lxml

Rather than use a huge long XPath as generated by Chrome, you can just search for a table with the yfnc_tabledata1 class; there is just the one: >>> tree.xpath("//table[@class='yfnc_tabledata1']") [<Element table at 0x10445e788>] Get to your <td> from there: >>> tree.xpath("//table[@class='yfnc_tabledata1']//td[1]")[0].text_content() 'Period EndingDec 31, 2014Dec 31, 2013Dec 31, 2012\n \n...

Trouble outputing file size to a label from a listbox in Python 3

python-3.x,operating-system

There are couple problems in your code, You always re-assign fileSizeStr. You need to concatenate new values. You need to check if fileSize greater than or equal to 1024, not smaller. New fileSize should be remainder of the first calculation, not the result of it. Also, checking from larger one...

Cancel last line iteration on a file

python,python-3.x,for-loop,file-io

In python3, the 'for line in file' construct is represented by an iterator internally. By definition, a value that was produced from an iterator cannot be 'put back' for later use (http://www.diveintopython3.net/iterators.html). To get the desired behaviour, you need a function that chains together two iterators, such as the chain...

The event loop is already running

python,python-3.x,pyqt,pyqt4

I think the problem is with your start.py file. You have a function refreshgui which re imports start.py import will run every part of the code in the file. It is customary to wrap the main functionality in an ''if __name__ == '__main__': to prevent code from being run on...

python contextmanager newline issue

python,python-3.x,contextmanager

The problem is probably due to buffering of stdout. You need to manually flush it for the message to be displayed. In Python 3.3+, the print function has a flush argument: from contextlib import contextmanager import time @contextmanager def msg(m): print(m + "... ", end='', flush=True) t_start = time.time() yield...