text
stringlengths
226
34.5k
Explain time and space complexity of two python codes. Which one is the best? (Non- subjective) Question: These codes gives the sum of even integers in a list without using loop statement. I would like to know the time complexity and space complexity of both codes. which is best? CODE 1: class EvenSum: ...
PySide and Python - How to browse a folder and write the file name? Question: I would like to press a button and than open a file browser and write down selected file in a label. I have this function which I call when the button is pressed: @Slot() def browse_folder(self): self.fn...
python requests ssl handshake failure Question: Every time I try to do: requests.get('https://url') I got this message: import requests >>> requests.get('https://reviews.gethuman.com/companies') Traceback (most recent call last): File "<stdin>", line 1, in <module> ...
Automating powerpoint using python. How to access format axis objects Question: Currently I'm working on Python to automate a powerpoint file. I'm using win32com.client to access the various objects needed. However I haven't been able to find any documentation on chart objects. can someone point me in the right directi...
gdata autentication trouble python Question: I ran for awhile a python script to post articles on my blogspot blog. everything ran smoothly until I started to get this auth error RequestError: {'status': 401, 'body': 'User does not have permission to create new post', 'reason': 'Unauthorized'} I re...
Comparing tuple elements against integers with Python Question: I am having a hard time converting data. I select the data from my database, which is returned in tuple format. I try to convert them using `list()`, but all I get is a list of tuples. I am trying to compare them to integers which i receive from parsing my...
django render the same page after post Question: I am trying to create a form that gets JSON inputs through a textarea(textarea1) and then processes it and prints the response back in another text area(textarea2) while still showing the original json input from textarea1. I have the code that takes the input computes t...
Why is PyCharm unable to find the correct verion of pip to install a Python module? Question: OSX: 10.9.5 PyCharm: 4.5 I am working on project in PyCharm IDE, using the 2.7.3 Python interpreter and need to import the`psycopg2` module. I tried to install the module with PyCharm, but it failed and asked me to do it man...
How to retreive values from list: python Question: **Summary:** I have a list list = [ { 'id': '1', 'elements': 'A', 'table': 'maps/partials/a.html', 'chart': 'maps/partials/charts/a.html', }, { ...
Error reading csv file using rpy2 in python Question: I cannot seem to be able to run the following code and get the error: rpy2.rinterface.RRuntimeError: Error in paste(r.base_dir, r.inp_file, ".csv", sep = "") : object 'r.base_dir' not found I get the same error even if I replace r.base_di...
Replace object in json with another json file using python Question: I currently have two json files that I need to combine using python. Essentially I want to replace the choices array in file 1 with the array in file 2 using python. How do I go about doing this? File 1 is: { "choice_list": { ...
Is using the args syntax in Python multiprocessing always necessary? Question: I am learning up on methods of multiprocessing in Python and have found myself with a question. Consider the following example: import multiprocessing as mp def worker(n): print('worker %d' % n) return...
How can I load an image using Python Pillow? Question: I load an image this way: from PIL import Image im = Image.open('test.png') gives me the following error: IOError: [Errno 2] No such file or directory: 'test.png' I have saved the image 'test.png' on the desktop. So wh...
Python analog of mvrnorm's empirical setting when generating a multivariate distribution? Question: So in `R`'s `MASS` package there is a function called `mvrnorm` for generating multivariate distributions. It has an argument called `empirical` which, when set to to TRUE, mu (means) and sigma (covariance matrix) specif...
Max Distance between 2 points in a data set and identifying the points Question: I have a matrix consisting of x,y,z coordinates of several points. I would like to find the extremum points i.e. the two points that are farthest apart. I could figure out a way in matlab, but i need it in Python Here is the code in matl...
How to speed up web scraping with nested urllib2.urlopen() in Python? Question: I have the following code to gather the number of words there are in each chapter of a book. In a nutshell, it opens the url of each book, then the urls of each chapter associated with the book. import urllib2 from bs4 im...
appending a class to list results in appending str error python Question: So I my program has a class with a persons name. I am trying to have the program read it off from a input file and then read it and arrange it into classes. While I am trying to appened the class to a list. It gives me this error: AttributeError:...
Permission Denied when load Firefox Extension in WebDriver Question: I'm creating a python script with selenium webdriver. I need to use an extension in firefox, but when I test with a little script, the script produces an error like this: Traceback (most recent call last): File "C:\Users\User\Desk...
Softmax choice probabilities with Categorical in PyMC3 Question: I am trying to perform a parameter estimation for a single parameter of a softmax choice function in the following scenario: In each trial, three option values are given (e.g., [1,2,3]), and a subject makes a choice between the options (0, 1 or 2). The s...
Python: Iterative subdirectory line count Question: I'm attempting to count the number of lines in two separate directories that are formatted differently and compare the results. The text files needed are all within a single directory in the the first dir, but the second one has subdirectories that I need to iterate t...
sphinx back up one directory Question: I have followed this [guide](http://www.marinamele.com/2014/03/document-your- django-projects.html) to set up Sphinx. My directories are as follows: /cms-service /documentation /modules models.rst The guide tells to place the path to th...
matplotlib: generate a new graph in a new window for subsequent program runs Question: I have a Python program that generates graphs using matplotlib. I am trying to get the program to generate a bunch of plots in one program run (the user is asked if they want to generate another graph) all in separate windows. Any wa...
Convert datetime.datetime object to days since epoch in Python Question: I've got a `pandas.Series` object that might look like this: import pandas as pd myVar = pd.Series(["VLADIVOSTOK 690090", "MAHE", NaN, NaN, "VLADIVOSTOK 690090", "2000-07-01 00:00:00"]) `myVar[5]` is parsed as a `datetime....
python decorator function with arguments Question: I've read and understood this article about function decorators: <https://www.artima.com/weblogs/viewpost.jsp?thread=240845> Specifically I'm talking about the section "Decorator Functions with Decorator Arguments" I'm running into a problem, though. I'm trying to wri...
Prevent cherrypy from logging access Question: I'm trying to set up a logger to only catch my ERROR level messages, but my logger always seems to write `INFO:cherrypy.access` messages to my log file, which I dont want. I tried setting the `log.error_file` global, and using the standard python logging module `logging.ba...
Wlst how to assign output of listAppStripes() to grantAppRole() Question: I'm new to Python and WLST. I'm trying to write a Python script that retrieves the the Application Stripes for a deployed application and assigned it to appStripes values in the grantAppRole. For example: 1. Connect to Admin Server 2. Deplo...
Executing ansible playbook AttributeError: 'str' object has no attribute 'set_playbook_basedir' Question: **Hello,** **_I have a two part question._** **First Part:** I'm trying to execute a playbook from a python script that downloads a playbook and executes it. I know the playbook works because i've tested it. Howe...
Using user defined variables/functions in eval [Python 3.4.2]? Question: I have a calculator (python 3.4.2) that can do normal operations using eval. def calculator(user_input): if any(c not in config.valid_cal_chars for c in user_input): print("- Invalid Equation | Bad characters") ...
Global Variables with threading in python Question: By threading a process as in this code: import threading import time def loop(): global bbcount bbcount = 0 while True: bbcount += 1 print "This is a Loop" time.sleep(1) i...
choosing random directories in PC using Python Question: I'm using python 3.x and I don't know how to make my script randomly choose directories in the same PC to copy files. I want it to copy the files in the random directories. What should I do to make it happen? from sys import argv import o...
How to use sign-in quota (plus.login scope) for Google Plus Question: I wrote a scraper to get some of the users' public contents. This scraper fetches the comments, plusoners, resharers, and the user's post. The free quota is 10,000 requests/day if you use API key: service = apiclient.discovery.build...
Optimize Python Script to parse xml Question: I'm parsing the US Patent XML files (downloaded from [Google patent dumps](https://www.google.com/googlebooks/uspto-patents-redbook.html)) using Python and Beautifulsoup; parsed data is exported to MYSQL database. Each year's data contains close to 200-300K patents - which...
Decoding Hex char string in python Question: I'm trying to interface a software with python via a TCP connection. The software is AGWPE (in fact, it's soundmodem, but they share the same API). When I ask the software for "normal" packets, everything fine, but when I ask for "raw" packets, the hex bytes the tcp connecti...
Don't know where is error. Code returns False with no reason Question: can you tell me, why this code returns False? I've just started learning python and have no clue why this doesn't work. #!/usr/bin/python from math import * lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 7...
Android drawables are not recognized by AndroidStudio if I use dpi subfolders Question: I have just started the [Treehouse](http://www.teamtreehouse.com) Android development course, I have also asked this question on their forums without any luck. **DATA** * AndroidStudio v 1.2.2, the course is based on v0.86 I thi...
Opening raw images on Python resulting in a different image compared to ImageJ Question: I wrote this script to open a raw image and do some processing. import numpy as np import matplotlib.pyplot as plt PATH = "C:\Users\Documents\script_testing_folder\\" IMAGE_PATH = PATH +"simulation01\\15...
"Failed building wheel for py-bcrypt" when pip installing flask-user Question: I'm trying to pip install the various extensions for Flask. So far they've all succeeded, and I've had no problems installing flask, flask-bcrypt, etc. with the exception of flask-user. When I try to pip install flask-user, the first error ...
many-to-many relationship in sqlalchemy Question: I just switched from MySQL to SQLalchemy and I have to say that it is more difficult to get my head around sqlalchemy than I thought. Currently I have some trouble with a many-to-many relationship. I have users and queries in my model. A user can have many queries and a...
Need some help on how to implement an restfull api app based on golang Question: My coding skills are a bit low :) Recently i started learning golang and how to handle an Api communication app. Have been having a great time learning it by myself, golang is revealing itself as a challenging language with great rewards i...
parsing with expression including a newline in python Question: I was trying to parsing some html files, in which I want to extract some value called "Total Cash", but these html come in two different forms: 1. `...Total Cash (mrq):</td> <td class="yfnc_tabledata1">8.71B</td>...` 2. `...Total Cash (mrq):</td> <td...
Suppressing logger messages below a certain level in Python Question: I worked on one system with a repo that imported lots of libraries. These used the Python logger facility. I would only receive messages for events logger.error and higher. I moved to a different system and cloned the same repos (and libraries). Now...
How to test Pl/Python PostgreSQL procedures with Travis CI? Question: I'm trying to set up CI for some PL/Python PostgreSQL procedures in Travis CI. I've tried several ways: 1) With the legacy infrastructure I've tried to just assume, that PL/Python is already installed, but it had not succeed: The co...
Set timeout for Python socket when sending data out Question: I would like to set timeout for Python socket client. That means, socket client connects to server then sends data within 1 second. If it takes more than 1 second, the method would raise some kind of exception or error. Here is my source code: ...
Method of Runge-Kutta in Python Question: I wrote a code about runge-kutta method in python, but every time when the program realizes any calculus the program require the differential equation. this is my code: from math import * import numpy as np #Initial Values n=input("Enter the num...
Django project not working with Apache and mod-wsgi Question: I created a droplet(cloud server) on DigitalOcean and with no-ip.com I gave it the hostname - project.ddns.net.By ssh(ing) into the droplet I installed pip and virtualenv. Inside /var/www/ I created a virtualenv and cloned the repository from github of my p...
scikit learn - converting features stored as strings into numbers Question: I'm currently dipping my toes into machine learning using the scikit-learn python library and am trying to use some .CSV data in the format Date Name Average_Price_SA 1995-01-01 Barking And Dagenham...
Reading from text file with HTML and Javascript Question: We currently have a python script that uses the Twitter API to generate a text file with a user's latest tweets. We now need to somehow display them in a webpage, so we attempted to use an XMLHttpRequest to read the local text file and display it. Formatting is...
Working interactively in Python Question: Is there any way to switch to 'interactive' mode within a Python script, similar to the "keyboard" function in Matlab? I am aware of iPython, but I don't think it would allow me to 'pause' at some point in a script, e.g., within a for-loop, switch to interactive mode based on a...
Understanding syntax in Python Question: I am trying to use PodSixNet library in Python to implement a multiplayer game. As I have seen a few tutorials online, the server file is as follows: import PodSixNet.Channel import PodSixNet.Server from time import sleep class ClientChannel(PodSi...
TypeError: an integer is required (got type str) Question: I am new to Python and Flask. I am working my way throught this tutorials: <http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web- forms> Right now i am getting an error for which i can't find a fix for. I have reinstalled Python 3.4.3 and re...
Python Internal Server Error Question: I'm new to Python Web Development and I have written the following code and uploaded into the root of my server (`public_html`) folder: import web urls = ('/','index') app = web.application(urls, globals()) class index: def GET(self): ...
Python Poplib Error Question: This is the code import poplib from email import parser pop_conn = poplib.POP3_SSL('pop.gmail.com') pop_conn.user('[email protected]') pop_conn.pass_('password') messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] messages =...
saving a structure of a list with the data in a text file using Python Question: I have a list of lists of tuples which I want to save in a text file as a string and later read it from another Python script and use ast.literal_eval to transform it from string to list. My question is if its possible to write in a text ...
Error on creating cassandra cluster with ccm (Cassandra Cluster Manager ) Question: I am trying to follow tutorials on Cassandra academy and this is what I get when trying to run ccm to create a Cassandra cluster. ~/cassandra$ ccm create demo_1node -v 2.2.0 -n 1 -s -d Downloading http://archive.apach...
python lxml get parent element when you know child text with xpath Question: I have the following xml file: _test.xml_ <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <SubmitTransaction xmlns="http://www.someaddress.com/someendpoint"> <objTransac...
Python and tile based game: limiting player movement speed Question: I've been putting together an isometric tile-based RPG using Python and the Pyglet library. I've run into the following problem, however: My player movement is based on positions on the three-dimensional array that consists of tiles. To limit movemen...
NameError: name 'value_from_name' is not defined Question: I'm trying to use beautiful soup 4 to parse html for a login page and get tokens from that page. import requests from bs4 import BeautifulSoup session = requests.Session() login_page_html = BeautifulSoup(session.get('https:...
python code to control GPIO at specific times Question: I want to build an irrigation automation system based on a Raspberry Pi. I have a script that generates a .CSV file based on the input parameters of the sprinkeling schedule (station no, time/station, use/not use rain sensor, etc.). The .CSV file looks like this:...
cx_freeze fails to include Cython .pyx module Question: I have a Python application to which I recently added a Cython module. Running it from script with pyximport works fine, but I also need an executable version which I build with cx_freeze. Trouble is, trying to build it gives me an executable that raises ImportEr...
How to specify number of characters in each line in python? Question: I have fasta file that contains two gene sequences and what i want to is to remove the fasta header (line starting with ">"), concatenate the rest of the lines and output that sequence in length of 50 characters per line. I made some progress but got...
Python neural network accuracy - correct implementation? Question: I wrote a simple neural net/MLP and I'm getting some strange accuracy values and wanted to double check things. This is my intended setup: features matrix with 913 samples and 192 features (913,192). I'm classifying 2 outcomes, so my labels are binary ...
ValueError: negative number cannot be raised to a fractional power in iterable list - Python Question: We have a list of 10 points of coord. x and y as follow: NOTE: Here we iterate through the lists of x,y and br without using numpy.array because in the far future, I will replicate this into Fortran77. ...
Python's SimpleHTTPServer started in a thread won't close the port Question: I have the following code: import os from ghost import Ghost import urlparse, urllib import SimpleHTTPServer import SocketServer import sys, traceback from threading import Thread, Event ...
Using import our script with Python Question: I don't know how explain what I want do so I think with code example you can understand. y.py y = 0 import printy printy.py import y print y NameError: name 'y' is not defined When I call scripts with imp...
Numpy array mean function did not exclude masked element in mean computation Question: I am new in python programming, please forgive me if my question is too basic. But I am trying to use masked_array to calculate the mean of three arrays to produce a third array without using the elements with values less than zero. ...
Python - How to read previous lines while reading csv file? Question: I want to read rows in excel table but when I want, during reading process, I would like to stop reading forward and I want to read previous lines (backward reading)? How can I go previous rows again? import csv file = open('f...
python.net import clr throws invalid pointer error Question: When i am trying to import clr in my python code i get the following error: *** Error in `python': free(): invalid pointer: 0xb0f1a120 *** Stacktrace: at <unknown> <0xffffffff> at (wrapper managed-to-native) Python.Runtime....
How to count elapsed time on Python Question: I have the following code: def base(nomor) day = localtime.tm_wday time = localtime.tm_hour no = str(nomor) dosen = cek_dosen(no) if dosen == 'null': no_dosen() elif dosen != 'null': ada_...
Python vs perl sort performance Question: **_Solution_** This solved all issues with my Perl code (plus extra implementation code.... :-) ) In conlusion both Perl and Python are equally awesome. use WWW::Curl::Easy; Thanks to ALL who responded, very much appreciated. **_Edit_** It appears that t...
Locating max value in a list Question: I'm very new to Python programming and I've been tasked by an online friend to write code to solve the following problem: 'imagine a board game and you have to roll 2 dices.Write a program to roll the dices 100 times and find out which value (of both dices) appears most' My atte...
save the user input to existing text file everytime running the script python? Question: I'm trying to save the user input into one text file(I want to keep the record for a month). But I'm not sure how to keep the old user input because every time I re-run the script new user input is automatically written on old-use...
Python-Pygame Level Select Pages Question: I'm trying to create a typing game. You know that point in many apps,where there is a level select, and there are several pages. Yeah, I'm trying to do that. Every time I select the button to move to the next page of level selections, it heads to the last page, and then starts...
PL/Python with Anaconda Question: I've got Anaconda installed on a Ubuntu and would like to use some of it's modules in PL/Python. However, every time I call scipy, it errors with _ImportError: No module_ named scipy.stats. How do I get the Anaconda to work with PL/Python? UPDATED: Below is the code & the error CREA...
YAML with Python using PyYAML Question: I am trying to follow these two examples: [Parsing a YAML file in Python, and accessing the data?](http://stackoverflow.com/questions/8127686/parsing-a-yaml-file-in- python-and-accessing-the-data) [YAML parsing and Python?](http://stackoverflow.com/questions/6866600/yaml- parsi...
Python 3.x's dictionary view objects and matplotlib Question: In python 3.x `keys()`, `values()` and `items()` return [views](https://docs.python.org/3/library/stdtypes.html#dict-views). Now while views certainly have [advantages](http://stackoverflow.com/a/8960727/1622937), they also seem to cause some compatibility i...
Initiate a Python Script via a Website (Click of a Button) Question: I have a small web panel on which I would like to control a python script that continuously collects data from a sensor (while loop). I would like to be able to start and stop this script by simply clicking a button. I know of a method of enabling the...
How to test django session in django unittest? Question: I have created view: def forgot_password(request): """ Actions when user forgot password. :param request: object :return: redirect to views.home() or 'loginsys/forgot.html' with form, message """ message = None if reques...
OSError: [WinError 10022] An invalid argument was supplied Question: Im making a port scanner it through's this message here is my code but it checks one port 21 i have pasted output below import socket import os host = input("Enter the host name or ip : ") s = socket.socket() s.settimeou...
Python datetime.datetime from time.structtime difference Question: I use feedparser to grab the entries from some RSS feeds. The entries have a published_parsed field which are parsed by feedparser into time.structtime. I use this function to convert the time.structtime into a datetime.datetime: def pub...
Missing needed parameter state Python social auth Email Validation Question: I am using python social auth with django app. In email validation, the link received on the mail works fine in the same browser from which authentication was initiated but it show `Missing needed parameter state` in different browser.Did anyb...
RabbitMQ consumer connection dies after 90 seconds idle Question: I have a RabbitMQ task queue and a Pika consumer to consume these tasks (with acks). The problem is that the connection dies after 90 seconds Idle but my tasks will often take longer than that. That means that while tasks are still being computed they ar...
uploading image to server php to python Question: I am converting my code from php to python and want to find the equivalent in python. My android application sends a base64 encrypted image and folder name. The script should decode it and save it to my server. The php is <?php // Get image strin...
Q: wx MouseEvent doing nothing Question: So im been working a little while with wx on python. For my problem I made a little code in order to show you what i need. import wx while True: if wx.MouseEvent().LeftIsDown() == True: print True I have been trying several variations with no...
Automatically strip the number in front of python codes when pasting Question: When I am reading an ebook or website, instead of inefficiently writing all the codes, I can obviously copy and paste the python codes. But about sometimes the format of the python code has a **number, a period, and a space** in front of the...
Python time.sleep syntax error Question: I'm writing a short program that makes it look like the computer is being hacked. I'm going to run it and leave the computer lying around and see how people react. However, I am getting this syntax error when I try to use `time.sleep.` can someone please help? ...
Parsing html page with lxml in python Question: i want to parse this Xpath query with lxml in python. .//*[@id='content_top']/article/div/table/tbody/tr[5]/td/p/text() I checked the xpath query in Firepath (the firebug extension for xpath),and it works,but my python code show me nothing. Here's the...
python daemon signal does not work Question: I wrote a python daemon script and registered some signal handlers , but when i use `kill -1 pid` , i found that signal handler does not work. Any body know why? Here is the script: test.py: #!/usr/bin/env python import sys, time from daemon im...
What does the first argument of the imp.load_source method do? Question: I'm reading [this](http://stackoverflow.com/questions/67631/how-to-import-a- module-given-the-full-path) SO question about importing modules from absolute path. An answer suggest to use following code: import imp foo = imp.load_...
Passing PHP variable into a Python script not working Question: I am trying to call a simple python script from a php script. The result I am getting is just a single word while my actual input is a long text/sentence. The php script should return the entire sentence; it currently outputs only "The" Python script ...
cProfile with imports Question: I'm currently in the process of learn how to use cProfile and I have a few doubts. I'm currently trying to profile the following script: import time def fast(): print("Fast!") def slow(): time.sleep(3) print("Slow!") def ...
How can I efficiently compute the md5 sum of an iterable of bits in Python? Question: Consider the code below. It converts an image to line art and then computes the md5sum of the bits. I don't know a better to do this than with a generator expression producing individual bits. But then how can I feed the result to md5...
How can I make a Post Request on Python with urllib3? Question: I've been trying to make a request to an API, I have to pass the following body: { "description":"Tenaris", "ticker":"TS.BA", "industry":"Metalúrgica", "currency":"ARS" } Altough the code seems to be right and it fi...
How to share variables among python scripts Question: I am having trouble making variables accessible among different python scripts. I have three scripts: shared.py test1.py test2.py In `shared.py`, I define a dictionary `devices` and initialize it. devices = {} In `test1.py`, I import `shared.p...
Python mutliprocessing: Timestamp of a process Question: I am using python multiprocessing module. I need to see the timestamp at which a process starts and the timestamp at which a process ends. If I do this: ... processes = [Process(target=topo.func1, args=(host,servers,q)) for x in range(1...
Loop over multiple .csv files python/pandas Question: I have two folders that contain +50 .csv files, I want to process al those files in my python code with pandas. At the beginning of my code I load two different .csv files: Location1 = path\tasks_01.csv' Location2 = path\resource_01.csv'...
Define imports and Python project structure to allow running locally and when installed Question: I am working on a Python project and started using a setup.py file to install it. I followed some guides on how to structure the project and everything is working great after installing it. My problem is that I "lost" the...
Error when serve Django 1.8 Applications with Apache2 and mod_wsgi on Ubuntu 14.04 Question: I am trying to serve my django project with Apache2 and mod_wsgi and I am stuck. Everything works fine until I try to integrate mod_wsgi. I am using python 3. The relevant coding are as below: * * * ## Apache2.conf ...
Is there a pythonic way to check whether OS is a 64bit Ubuntu? Question: Is there a pythonic way to check whether OS is a 64bit Ubuntu? Currently, I've been doing it as such: import os def check_is_linux(distro, architecture, err_msg): try: this_os = os.popen('lsb_release -d...
Split path in Python Question: How I could split this: C:\my_dir\repo\branch to: ['C:\my_dir', rest_part_of_string] where `rest_part_of_string` can be one string or could be splitted every `\`. I don't care about rest, i just want first two elements together. Answer: Using [r...
Search and return lines in a file with matching keyword in python Question: I have used regex to isolate a particular keyword in a line taken from a file. I want to search the entire file and return groups of lines which have the same keyword. I am a little confused about this, and I was wondering if there is a direct...