text
stringlengths
226
34.5k
Upload file to MS SharePoint using Python OneDrive SDK Question: Is it possible to upload a file to the **Shared Documents** library of a **Microsoft SharePoint** site with the **[Python OneDrive SDK](https://github.com/OneDrive/onedrive-sdk-python)**? **[This documentation](https://dev.onedrive.com/readme.htm)** says...
"Extra data" error trying to load a JSON file with Python Question: I'm trying to load the following JSON file, named `archived_sensor_data.json`, into Python: [{"timestamp": {"timezone": "+00:00", "$reql_type$": "TIME", "epoch_time": 1475899932.677}, "id": "40898785-6e82-40a2-a36a-70bd0c772056", "name":...
Converting a nested array into a pandas dataframe in python Question: I'm attempting to convert several dictionaries contained in an array to a pandas dataframe. The dicts are saved as such: [[{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.309886', u'longitude': u'0.496902'},u...
Exchanging out specific lines of a file Question: I don't know if this should be obvious to the more tech savvy among us but is there a specific way to read a line out of a text file, then edit it and insert it back into the file in the original location? I have looked on the site but all the solutions I find seem to b...
RotatingFileHandler does not continue logging after error encountered Question: Traceback (most recent call last): File "/usr/lib64/python2.6/logging/handlers.py", line 76, in emit if self.shouldRollover(record): File "/usr/lib64/python2.6/logging/handlers.py", line 150, in shouldRollover ...
How to pass data from one page to another page in python tkinter? Question: my program is this.. import tkinter as tk from tkinter import * TITLE_FONT = ("Helvetica", 18, "bold") class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs...
Remote build doesn't install dependencies using python 3.2 standard runtime Question: i'm uploading a worker to iron worker running Python 3.2 with in the standard environment, using my own http client directly (not the ruby or go cli) according to the REST API. However, despite having a .worker file along with my pyth...
Where is my below python code failing? Question: if the function call is like: backwardsPrime(9900, 10000) then output should be [9923, 9931, 9941, 9967]. Backwards Read Primes are primes that when read backwards in base 10 (from right to left) are a different prime. It is one of the kata in Codewars and on submitting ...
python preserving output csv file column order Question: The issue is common, when I import a csv file and process it and finally output it, the order of column in the output csv file may be different from the original one,for instance: dct={} dct['a']=[1,2,3,4] dct['b']=[5,6,7,8] dct['c']=[9...
How to include __build_class__ when creating a module in the python C API Question: I am trying to use the [Python 3.5 C API](https://docs.python.org/3/c-api/) to execute some code that includes constructing a class. Specifically this: class MyClass: def test(self): print('test') ...
C++ uses twice the memory when moving elements from one dequeue to another Question: In my project, I use [pybind11](https://github.com/pybind/pybind11) to bind C++ code to Python. Recently I have had to deal with very large data sets (70GB+) and encountered need to split data from one `std::deque` between multiple `st...
How to run a zeppelin notebook using REST api and return results in python? Question: I am running a zeppelin notebook using the following REST call from python: `import requests requests.post('http://x.y.z.x:8080/api/notebook/job/2BZ3VJZ4G').json()` The output is {u'status': u'OK'} But I want to return some results...
selenium.common.exceptions.WebDriverException: Message: Service Question: I had a trouble when i use selenium to control my Chrome. Here is my code: from selenium import webdriver driver = webdriver.Chrome() When i tried to operate it ,it runs successfully at first,the Chrome pop on the screen....
can we call python script in node js and run node js to get call? Question: python.py from pymongo import MongoClient from flask import Flask app = Flask(__name__) host = "10.0.0.10" port = 8085 @app.route('/name/<string:name>',methods=['GET','POST']) def ...
Python handle 'NoneType' object has no attribute 'find_all' error with if else statement Question: I am using beautifulsoup4 to grab stock data and send to a spreadsheet in python. The problem I am having is that I cannot get my loop to skip over attributes that return None. So what I am needing is the code to add null...
Remove newline characters that appear between curly brackets Question: I'm currently writing a text processing script which contains static text and variable values (surrounded by curly brackets). I need to be able to strip out newline characters but only if they appear between the curly brackets: `Some text\nwith a {...
How to remove 'selected' attribute from item in ModelChoiceField? Question: ModelChoiceField adds attribute `selected` in HTML, if object from choices list has FK to parent object. How\where can I remove this 'selected' attribute in order to get just list of choices? Want to mention, that I need to remove just 'select...
convert coordinates into binary image python Question: I made a GUI in which I can load an image from disk and convert the mouse motion ( drawing the contours ) into coordinates. Now I need to convert the coordinates into a binary image and I don't know how. Here is my code: from Tkinter import * fro...
(Python) How to find the index of the maximum value of a list? Question: The instructions for the program: To create an empty list and fill it with 20 random integers between 1-500 inclusive, print the list on a single line, and print the maximum value of that list on a separate line. The max value function cannot be u...
connecting to a remote server and downloading and extracting binary tar file using python Question: I would like to connect to a remote server, download and extract binary tar file into a specific directory on that host. I am using python 2.6.8 1. What would be a simple way to ssh to that server? 2. I see the belo...
Timing blocks of code - Python Question: I'm trying to measure the time it takes to run a block of instructions in Python, but I don't want to write things like: start = time.clock() ... <lines of code> ... time_elapsed = time.clock() - start Instead, I want to know if there is a wa...
OSError: .pynative/... : file too short Question: When I try to apply OCRopus (a python-based OCR tool) to a TIFF image, I get the following python error: Traceback (most recent call last): File "/usr/local/bin/ocropus-nlbin", line 10, in <module> import ocrolib File "/usr/local/l...
elementTree is not opening and parsing my xml file Question: seems like `vehicles.write(cars_file)` and `vehicles = cars_Etree.parse(cars_file)` are having a problem with the file name: import argparse import xml.etree.ElementTree as cars_Etree # elementTree not reading xml file properly ...
DoesNotExist at /admin/login/ Question: DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: https://tehb123.pythonanywhere.com/admin/login/?next=/admin/ Django Version: 1.9.3 Exception Type: DoesNotExist Exception Val...
selenium python webscrape fails after first iteration Question: Im iterating through tripadvisor to save comments(non-translated, original) and translated comments (from portuguese to english). So the scraper first selects portuguese comments to be displayed , then as usual it converts them into english one by one and ...
Initialize variable depending on another variables type Question: In Python 2.7 I want to intialize a variables type depending on another variable. For example I want to do something like: var_1 = type(var_2) Is there a simple/fast way to do that? Answer: Just create another instance ...
Parse dates and create time series from .csv Question: I am using a simple csv file which contains data on calory intake. It has 4 columns: `cal`, `day`, `month`, year. It looks like this: cal month year day 3668.4333 1 2002 10 3652.2498 1 2002 11 3647.8662 1 20...
Get Pixel count using RGB values in Python Question: I have to find count of pixels of RGB which is using by RGB values. So i need logic for that one. Example. i have image called image.jpg. That image contains width = 100 and height = 100 and Red value is 128. Green is 0 and blue is 128. so that i need to find how m...
python append() and remove html tags Question: I need some help. My output seems wrong. How can I correctly append the values of dept, job_title, job_location. And there are html tags with the values of dept. how can I remove those tags. my code response = requests.get("http://hortonworks.com/careers/op...
How to modify the XML file using Python? Question: Actually I have got the XML string and parse the string to get the attributes from it. Now I want my XML file to change, viewing the attributes. Like I want to change the color of the stroke. Is there any way? How I will change and then again save the file. ...
Attempted relative import beyond toplevel package Question: Here is my folder structure: Mopy/ # no init.py ! bash/ __init__.py bash.py # <--- Edit: yep there is such a module too bass.py bosh/ __init__.py # contains from .. import bass bsa...
Python SQLite removes/escapes part of regular expression pattern in user defined function Question: I did a simple replace implementation for regular expressions in python sqlite3: import sqlite3, re db = sqlite3.connect(':memory:') c = db.cursor() c.executescript(""" create table t2...
Python "list index out of range" other rule works Question: I have tried to make a script to read out a csv file and determine some information. Now I receive an error: Traceback (most recent call last): File "/home/pi/vullijst/vullijst.py", line 26, in <module> startdate = datetime.dateti...
Python: Connecting list values with array values Question: I have created a tornado plot taking inspiration from [here](http://stackoverflow.com/questions/32132773/a-tornado-chart- and-p10-p90-in-python-matplotlib). It has input variables labelled on the y-axis (a1,b1,c1...) and their respective correlation coefficient...
subprocess.Popen process stdout returning empty? Question: I have this python code input() print('spam') saved as `ex1.py` in interactive shell >>>from subprocess import Popen ,PIPE >>>a=Popen(['python.exe','ex1.py'],stdout=PIPE,stdin=PIPE) >>> a.communicate() ...
Sublime 3 Plugin Storing Quick Panel Return Val Question: I'm trying to write a simple plugin that generates a quick panel based on some list, waits for the user to select an item, and then performs an action based on the value the user selected. Basically, I'd like to do the following: class ExampleComm...
Generate X random integers between Y and Z? Question: Is there a function in Python (I'm working with SageMath) to get 10 random integers between 0 and 30, for instance, without repeating them? Answer: import random random.sample(range(31), 10)
Random comma inserted at character 8192 in python "json" result called from node.js Question: I'm a JS developer just learning python. This is my first time trying to use node (v6.7.0) and python (v2.7.1) together. I'm using restify with python- runner as a bridge to my python virtualenv. My python script uses a RAKE N...
Selecting all elements that meet a criteria using selenium (python) Question: Using selenium, is there a way to have the script pick out elements that meet a certain criteria? What I'm exactly trying to do is have selenium select all Twitch channels that have more than X viewers. If you inspect element, you find this:...
Import os doesn't not work in linux Question: I just want to install the [suds library](https://pypi.python.org/pypi/suds), but suddenly it wasn't proceeding because it was not finding the `os` library, so I tried to open my python and it results me an error. When I import the `os` library and there are some errors dur...
Django Allauth and urls Question: I have a dev environment for a test of Django. I am running Python 3.5.2 out of a "local" `pyenv` install. I have Django 1.10.2. I discovered the `allauth` registration plugin yesterday and have been playing with it but have hit a snag. My site is "dev.my.domain.com". The intent is th...
Requiring tensorflow with Python 2.7.11 occurs ImportError Question: I tried `pip install tensorflow` on OS X El Capitan and it succeeded. However, if I tried to import tensorflow, ImportError occured. Please tell me when you know. >>> import tensorflow Traceback (most recent call last): File "<s...
How to make replacement in python's dict? Question: The goal I want to achieve is to exchange all items whose form is `#item_name#` to the from `(item_value)` in the dict. I use two `dict` named `test1` and `test2` to test my function. Here is the code: test1={'integer_set': '{#integer_list#?}', 'integer...
broken dropdown menu code Question: I was following <https://www.youtube.com/watch?v=PSm-tq5M-Dc> a tutorial for doing a drop-down menu in a gui. In the video the code works but i can't get mine too, I think it may have something to do with different python versions. from tkinter import * def d...
Spark - PySpark sql error Question: I have a simple pyspark code but i can't run it. I try to run it on Ubuntu system and I use PyCharm IDE. I would like to connect to Oracle XE Database and I want to print my test table. Here comes my spark python code: from pyspark import SparkContext from pyspark...
How to create angular2 jwt token in angular2 Question: I need to create a jwt in angular2. How do I do that? I am using this for an api service. jwt_token = ? I can create in python with no issue. Answer: **Normally tokens are generated on the server-side !! If you are creating them on client si...
XML Processing not working Question: I am trying to extract data from a sensor (it communicate with "xml type" strings) and convert it to csv. With my actual code i already write xml files, but the data come in single rows (from root to /root it is). Dunno if this is the reason but i get a **elementtree.parse error ju...
How to stop or interrupt a function in python 3 with Tkinter Question: I started with programming in python just a few months ago and I really love it. It's so intuitive and fun to start with. Data for starting point: I have a linux mashine on which runs python 3.2.3 I have three buttons on GUI to start a function wit...
How do I call an Excel VBA script using xlwings v0.10 Question: I used to use the info in this question to run a VBA script that does some basic formatting after I run my python code. [How do I call an Excel macro from Python using xlwings?](http://stackoverflow.com/questions/30308455/how-do-i-call-an-excel- macro-fro...
How do I write a doctest in python 3.5 for a function using random to replace characters in a string? Question: def intoxication(text): """This function causes each character to have a 1/5 chance of being replaced by a random letter from the string of letters INSERT DOCTEST HERE """ ...
geckodriver executable needs to be in path Question: I have read previous questions asked on this topic and tried to follow the suggestions but I continue to get errors. On terminal, I ran export PATH=$PATH:/Users/Conger/Documents/geckodriver-0.8.0-OSX I also tried export PATH=$P...
'helloworld.pyx' doesn't match any files Question: I am a beginner in python and I have just got familiar with cython as well. I am using Anaconda on Windows 64-bit. I am trying to run the "helloworld" example as follows: 1- I build a helloworld.pyx file containing: print("Hello World") 2- I b...
counter not inceasing in python Question: I have looked at other while loops and am stuck on why this one is not working. points = int(input('How many points: ')) while True: u_cnt, c_cnt = 0, 0 if u_cnt < points or c_cnt < points: if u < c: c_cnt += 1 ...
Cannot import urllib in Python Question: I would like to import `urllib` to use the function '`request`'. However, I encountered an error when trying to download via Pycharm: > "Could not find a version that satisfies the requirement urllib (from > versions: ) No matching distribution found for urllib" I tried `pip i...
root.query_pointer()._data causes high CPU usage Question: I'm a total noob in Python, programming and Linux. I wrote a simple python script to track usage time of various apps. I've noticed that after some time python is going nuts utilizing 100% of the CPU. Turns out it's the code obtaining mouse position is causing ...
MiniBatchKMeans OverflowError: cannot convert float infinity to integer? Question: I am trying to find the right number of clusters, `k`, according to silhouette scores using `sklearn.cluster.MiniBatchKMeans`. from sklearn.cluster import MiniBatchKMeans from sklearn.feature_extraction.text import Has...
Dictionary key and value flipping themselves unexpectedly Question: I am running python 3.5, and I've defined a function that creates XML SubElements and adds them under another element. The attributes are in a dictionary, but for some reason the dictionary keys and values will sometimes flip when I execute the script....
Python Flask: RQ Worker raising KeyError because of environment variable Question: I'm trying to setup a redis queue and a worker to process the queue with my flask app. I'm implementing this to handle a task that sends emails. I'm a little confused because it appears that the stack trace is saying that my 'APP_SETTING...
PHP equivalent of Python's `urljoin` Question: What is the PHP equivalent for building a URL from a base URL and a potentially-relative path? Python provides [`urlparse.urljoin`](https://docs.python.org/2/library/urlparse.html#urlparse.urljoin) but there does not seem to be any standard implementation in PHP. The clos...
python calling variables from another script into current script Question: I'm trying to call a variable from another script into my current script but running into "variable not defined" issues. botoGetTags.py 20 def findLargestIP(): 21 for i in tagList: 22 #remove all...
Django, viewing models from different app Question: I am super new to python programming and django and i got the basics out of the way. I created a project with two apps, home and video. In my video models.py i have the following data: class Video(models.Model): name = models.CharField(max_lengt...
create file containing '/' in file name in python Question: how can I create a file in python if the filename contains '/' url='https://www.udacity.com/cs101x/index.html' f=open(url,'w') f.write('123') f.close() above code produces an error as Traceback (most recent call ...
What is axis in Python with Numpy module? Question: when I use np.stack, sometimes have to use axis, like axis=1. I don't understand what the axis means for it. for exmaple, c1 = np.ones((2, 3)) c2 = np.zeros((2, 3)) c = np.stack([c1, c2], axis = 1) this shows like, array([[[...
Dictionary removing duplicate along with subtraction and addition of values Question: New to python here. I would like to eliminate duplicate dictionary key into just one along with performing arithmetic such as adding/subtracting the values if duplicates are found. **Current Code Output** > {('GRILLED AUSTRALIA ANGU...
Python Indention Block? Why? Question: I have tried untabifying region.. and did not mix spaces/tabs.. What could be wrong here? When I run the module it traces to `if result["geo"]:` and says "There's an error in your program: expected an indention block" from twitter import * import sys im...
digits to words from sys.stdin Question: I'm trying to convert digits to words from std input (txt file). If the input is for example : 1234, i want the output to be one two three four, for the next line in the text file i want the output to be on a new line in the shell/terminal: 1234 one two three four 56 five six Th...
Convert QueryDict into list of arguments Question: I'm receiving via POST request the next payload through the view below: class CustomView(APIView): """ POST data """ def post(self, request): extr= externalAPI() return Response(extr.addData(request.da...
How to detect fast moving soccer ball with OpenCV, Python, and Raspberry Pi? Question: This is the code. I am trying to detect different types of soccer ball using OpenCV and python. Soccer ball could of different colors. I can detect the ball if it is not moving. But, the code does not work if the ball is moving fast....
Nonewline python Question: I am trying to print random numbers using random , but when I try to print the output in one line using `end= " "` the output doesnt show anything until I break the program. import random import time while True: x = random.randint(1,6) print(x, end=" ") ...
python csv new line Question: iam using this code to convert db table to csv file, it is converting in to csv but instead of new line / line breck its using double quotes , can someone help me import MySQLdb import csv conn = MySQLdb.connect(user='root', db='users', host='localhost') cursor ...
Trying to Solve Numerical Diff Eq Using Euler's Method, Invalid Value Error Question: I am trying to learn it from this website: <http://nbviewer.jupyter.org/github/numerical-mooc/numerical- mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb> I was trying to code it with as little help as possible, but I...
Python - First and last character in string must be alpha numeric, else delete Question: I am wondering how I can implement a string check, where I want to make sure that the first (&last) character of the string is alphanumeric. I am aware of the `isalnum`, but how do I use this to implement this check/substitution? ...
Building a function of a random variable dynamically in python Question: I have some random variables using `scipy.stats` as follows: import scipy.stats as st x1 = st.uniform() x2 = st.uniform() Now I would like make another random variable based on previous random variables and make some c...
How to call a variable inside main function from another program in python? Question: I have two python files first.py and second.py first.py looks like def main(): #some computation first_variable=computation_result second.py looks like import first def main(): ...
Interpolate without having negative values in python Question: I've been trying to create a smooth line from these values but I can't have negative values in my result. So far all the methods I tried do give negative values. Would love some help. import matplotlib.pyplot as plt from scipy.interpolate...
Python program asks for input twice, doesn't return value the first time Question: Here is my code, in the `get_response()` function, if you enter 'y' or 'n', it says invalid the first time but then works the second time. How do I fix this? import random MIN = 1 MAX = 6 def main()...
GAE (Python) Best practice: Load config from JSON file or Datastore? Question: I wrote a platform in GAE Python with a Datastore database (using NDB). My platform allows for a theme to be chosen by the user. Before _every_ page load, I load in a JSON file (using `urllib.urlopen(FILEPATH).read()`). Should I instead save...
Unable to access modified value of imported variable Question: I am new to python and have some problem understanding the scope here. I have a python module A with three global variables : XYZ = "val1" ABC = {"k1" : "v1", "k2" : "v2"} PQR = 1 class Cls_A() : def sm_fn_A(self) : ...
Catch anything and save it into a variable Question: I'm wondering if there is a keyword for "all" in python `except`. I've ran into this seemingly simple problem: try: #do stuff except any as error: print('error: {err}'.format(err=error)) I know that you can do `except:` to cat...
Remote command does not return python Question: I am rebooting a remote machine through Python, as it is a reboot, the current ssh session is killed. The request is not returned. I am not interested in the return though. os.command('sshpass -p password ssh user@host reboot') The code is performing the reboot, however...
python receive image over socket Question: I'm trying to send an image over a socket - I'm capturing an image on my raspberry pi using pycam, sending to a remote machine for processing, and sending a response back. On the server (the pi), I'm capturing the image, transforming to an array, rearranging to a 1D array and...
How do I print a variable within a class' if statement? Question: I'm trying to print a variable in Python using the following code: from time import sleep import random class Hero: def __init__(self,name): self.name = name if name == "rock": ...
Saving image in python Question: I'm new to python. What I want to do is to read in an image, convert it to gray value and save it. This is what I have so far: # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, h...
Django 1.10.2 error "NoReverseMatch at " ,"Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found." Question: I am new to python & Django. I am getting one error and have absolutely no idea how to solve it. Any help will be appreciated. [![enter image description here](ht...
Word document to python-docx Question: **Objective:** I use a word template to which I want to pass paragraph values from python. **Pipeline:** The pipeline involves using python-docx and sending output paragraph to python docx;thus, creating a docx file. from docx import Document from docx.shared i...
How to smooth lines in a figure in python? Question: So with the code below I can plot a figure with 3 lines, but they are angular. Is it possible to smooth the lines? import matplotlib.pyplot as plt import pandas as pd # Dataframe consist of 3 columns df['year'] = ['2005, 2005, 2005, 20...
Why z3c.RML ignores the pageSize Attribute of <template> Question: I am trying to get an A4-Landscape output file. The Document i am modifying is A4-Portrait, so i thought simple switch: **_pageSize="(21cm, 29.7cm)"_** to **_pageSize="(29.7cm, 21cm)"_** , but nothing happend. I then fount an Attribute: **_rotation="90...
Matplotlib axis not displayed Question: The python code (python 2.7) running on windows 7 shown below results in the following inconsistent behaviour with respect to the display of axis which I do not understand: 1 - a window is opened and a plot without an axis is displayed showing a point 2 - on closing the window, ...
Using external class methods inside the imported module Question: My python application consists of various _separate_ processing algorithms/modules combined within a single (Py)Qt GUI for ease of access. Every processing algorithm sits within its own module and all the communication with GUI elements is implemented w...
Python read lines from a file and write from a specific line number to another file Question: I want to read the lines from a file and write from a specific line number to another file. I have this script, which writes all the read lines. I need to skip the first four lines and write the rest to another fils. Any ideas...
Python type checking not working as expected Question: I'm sure I'm missing something obvious here, but why does the following script actually work? import enum import typing class States(enum.Enum): a = 1 b = 2 states = typing.NewType('states', States) def ...
Python HTML source code Question: I would like to write a script that picks a special point from the source code and returns it. (print it) import urllib.request Webseite = "http://myip.is/" html_code = urllib.request.urlopen(Webseite) ...
python os.walk and unicode error Question: two questions: 1\. why does In [21]: ....: for root, dir, file in os.walk(spath): ....: print(root) print the whole tree but In [6]:...
Python: [Errno 2] No such file or directory - weird issue Question: I'm learning with a tutorial [Create your own shell in Python](https://hackercollider.com/articles/2016/07/05/create-your-own-shell- in-python-part-1/) and I have some weird issue. I wrote following code: import sys import shlex ...
Python - insert lines on txt following a sequence without overwriting Question: I want to insert the name of a file before each file name obtained through glob.glob, so I can concatenate them through FFMPEG by sorting them into INTRO+VIDEO+OUTRO, the files have to follow this order: INSERTED FILE NAME FILE INSERTE...
I am using Kivy in Python and only the last button has it's embedded objects appearing Question: I apologize in advance if my question is stupid or obvious, but I have been researching this over and over and am coming up with nothing. I am currently using Kivy and have multiple buttons in a gridlayout, which is in a sc...
Python code to return total count of no. of positions in which items are differing at same index Question: A=[1,2,3,4,5,6,7,8,9] B=[1,2,3,7,4,6,5,8,9] I have to compare these two lists and return the count of no. of location in which items are differing using one line python code. For example: the output should be 4 ...
How do I find the location of Python module sources while I can not import it? Question: The answer in [How do I find the location of Python module sources?](http://stackoverflow.com/questions/269795/how-do-i-find-the- location-of-python-module-sources) says just import it and print its `__file__`. But my question is t...
Not Fount :/media/app/images/my_image.png Question: image not found but the image exist at exact location . print(profile.image.url) #/media/app/images/my_image.png prints the image location but when i used in my template , other column are current but image is not found profile ...
finding a special path string in HTML text in python Question: I'm trying to extract a path in an HTML file that I read. In this case the path that I'm looking for is a logo from google's main site. I'm pretty sure that the regular expression I defined is right, but I guess I'm missing something. The code is: ...