Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
9,900 | 66,041,645 | Optimize recursive function | <p>I've got a problem. I have a highly recursive function, which will take years to execute as the datasets become increasingly larger. Do you have an idea, how to optimize it, so it might run in a few minutes?</p>
<pre><code>DatenListeE124_DurchschnittMandate = {}
for Daten in DatenListeE124:
if Da... | <p>The solution somebody else pointed out was to use:
'''
itertools.product(DatenListeE124_Durchschnitt[Schlüssel], repeat=3)'''
which works really nice and fast!</p> | python|recursion|optimization | 0 |
9,901 | 38,780,485 | How to use pandas read_excel() for excel file with multi sheets? | <p>I have one excel file with many sheets. There is only one column in every sheet, which is column A. I plan to read the excel file with <code>read_excel()</code> method. Hier is the code:</p>
<pre><code>import pandas as PD
ExcelFile = "C:\\AAA.xlsx"
SheetNames = ['0', '1', 'S', 'B', 'U']
# There are five... | <p>Why are you using <code>sheetname=str(SheetNames[Page])</code>?</p>
<p>If I understand your question properly I think what you want is:</p>
<pre><code>import pandas as PD
excel_file = r"C:\\AAA.xlsx"
sheet_names = ['0', '1', 'S', 'B', 'U']
for sheet_name in sheet_names:
df = pd.read_excel(excel_file, heade... | python|pandas | 1 |
9,902 | 51,744,409 | Renaming .png files python | <p>Beginner question:</p>
<p>I am trying to rename .png files using:</p>
<pre><code>import os
os.rename('x.png','y.png')
</code></pre>
<p>The error I get is: </p>
<blockquote>
<p>WindowsError: [Error 2] The system cannot find the file specified.</p>
</blockquote>
<p>I am in the right directory, and so are the f... | <p>It's most likely that you got the <code>Can't find file</code> error because <code>'x.png'</code> isn't the absolute path.</p>
<p>Explicitly call <code>path</code> and <code>os.path.join(path, filename)</code> prior to calling the rename and it will work.</p>
<p>Try this:</p>
<pre><code>os.rename(os.path.join(os.... | python|file|rename | 0 |
9,903 | 10,062,408 | Smallest way to expand a list by n | <p>i want to expand a list</p>
<pre><code>[1,2,3,4]
</code></pre>
<p>by <em>n</em></p>
<p>e.g. for n = 2:</p>
<pre><code>[1,1,2,2,3,3,4,4]
</code></pre>
<p>I'm searching for the smallest possible way to achieve this without any additional librarys.
Its easy to do a loop and append each item n times to a new list..... | <pre><code>>>> l = [1,2,3,4]
>>> [it for it in l for _ in range(2)]
[1, 1, 2, 2, 3, 3, 4, 4]
</code></pre> | python|list | 13 |
9,904 | 68,196,672 | Visual Studio Code Error message: from bs4 import BeautifulSoup ModuleNotFoundError: No module named 'bs4' | <p>I am new to webscraping, and I want to use beautifulsoup in order to do so, but whenever I try to import <code>BeautifulSoup</code> from <code>bs4</code>, I get the error message in the title. I have pip installed <code>bs4</code> from my own terminal, as well as, on visual studio code, and still get the same error.... | <p>The packages you installed into <code>python39</code> environment:</p>
<pre><code>c:\users\austin\appdata\local\programs\python\python39\lib\site-packages
</code></pre>
<p>But you execute the python file with <code>python in WindowsApp</code> environment:</p>
<pre><code>c:\users\austin\appdata\local\microsoft\window... | python|visual-studio-code|beautifulsoup | 0 |
9,905 | 63,289,606 | Resolving a variable dynamically in python | <p>Say I have a string -</p>
<p><code>my_str = "From {country} with Love"</code></p>
<p>Variable <code>country</code> is not available at the moment and is set at a later stage to</p>
<p><code>country = "Russia"</code>.</p>
<p>Now
Can I print string with the inline variable value dynamically resolve... | <pre><code>my_str = "From {} with Love"
country = "Russia"
print(my_str.format(country))
</code></pre>
<p>If you like to work with names you can also do:</p>
<pre><code>my_str = "From {country} with Love"
country = "Russia"
print(my_str.format(country=country))
</code></pre> | python|f-string|dynamic-variables | 5 |
9,906 | 32,592,950 | Python OpenCV Template Matching error | <p>I've been messing around with the OpenCV bindings for python for a while now and i wanted to try template matching, i get this error and i have no idea why</p>
<pre><code>C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\imgproc\src\templmatch.cpp:910: error: (-215) (depth == CV_8U || depth == CV_32F... | <p>Pay attention to the error message:</p>
<blockquote>
<p>error: (-215) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function cv::matchTemplate</p>
</blockquote>
<p>It means the data type of the image should be CV_8U or CV_32F, and it should have 3 or less ... | python|opencv | 27 |
9,907 | 32,182,405 | How to use PostgreSQL in multi thread python program | <p>I am using psycopg2 (2.6) connect to PostgreSQL database in a multi-threading python program.</p>
<p>When queue size in program increase, select queries get error "no results to fetch", but inserts records to db works very well. </p>
<p>example code:</p>
<pre><code>class Decoders(threading.Thread):
def __init... | <p>Are you creating a connection for each thread? If you have multiple threads you need a connection for each one (or a pool with locking mechanisms around the connections) otherwise you will have all sorts of weird issues.</p>
<p>Which is why you would not have issues in multiprocessing, since each process will be cr... | python|multithreading|psycopg2|python-multithreading | 6 |
9,908 | 28,375,948 | memory overflow in Python using pymc | <p>Following apparently simple code for MCMC in Python causes a huge memory usage (>15GB) even though I use pickle backend. This happens whenever I use arrays of observed variables in pymc. Any idea on why this is happening?</p>
<pre><code>import pymc as pymc
import numpy as np
N = 17
numC = 5
A = np.zeros([N,N])
A[... | <ol>
<li>from personal experience, pickle can be extremely fat in memory with large objects, and it usually inflates and grows without releasing memory as I've seen.</li>
<li>can try to use <a href="https://pypi.python.org/pypi/memory_profiler" rel="nofollow">memory profiler</a> to check where the memory growth occurs,... | python|pymc|mcmc | 0 |
9,909 | 28,205,504 | python can't seem to get a list to return properly | <pre><code> def best_wild_hand(hand):
dictSuit = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':11, 'Q':12, 'K':13, 'A':14 }
listofLists = []
blackJoker = "?B"
list1 = [x + "S" for x in dictSuit]
index = len(hand)
if blackJoker in hand:
newHand = hand
... | <p>I think After your code execution, the listofLists will be:</p>
<pre><code>[newHand, newHand, newHand, ..., newHand]
</code></pre>
<p>But the newHand changed every time the loop processed, Finally, the listOfList will contains many the same newHand. You can write you loop block like this:</p>
<pre><code>if blackJ... | python|list | 1 |
9,910 | 44,333,218 | Plotting a large number of stacked spheres generated from python-- mayavi? paraview and pyevtk? How to transmute .npy to .vtk? | <p>I want to produce plots like this, except with many more particles. Matplotlib is woefully inadequate. </p>
<p><a href="https://i.stack.imgur.com/tWZqK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tWZqK.png" alt="from google"></a></p>
<p>Right now I am using mayavi in python 3.5 running thro... | <p><a href="https://i.stack.imgur.com/r9lg7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r9lg7.png" alt="solved"></a></p>
<p>Ok, I solved my own problem. This image is made using paraview, after converting numpy arrays to a .vtu object using pyevtk. </p>
<p>Out of the box, the repository did not... | python|vtk|mayavi | -1 |
9,911 | 44,330,084 | OpenCv imwrite doesn't work because of special character in file path | <p>I can't save an image when the file path has special character (like "é" for example).</p>
<p>Here is a test from Python 3 shell :</p>
<pre><code>>>> cv2.imwrite('gel/test.jpg', frame)
True
>>> cv2.imwrite('gel/ééé/test.jpg', frame)
False
>>> cv2.imwrite('gel/eee/test.jpg', frame)
True
<... | <p>You can first encode the image with OpenCV and then save it with numpy <code>tofile()</code> method since the encoded image is a one-dim numpy ndarray:</p>
<pre><code>is_success, im_buf_arr = cv2.imencode(".jpg", frame)
im_buf_arr.tofile('gel/ééé/test.jpg')
</code></pre> | python|python-3.x|opencv | 8 |
9,912 | 32,684,451 | How do you rerun "tox" on python file changes? | <p>I have a tox configuration that runs all my tests, pep8 checks, and coverage checks. I run tox manually pretty much every time I save changes to my code. Tox runs the tests and coverage reports via "nosetests."</p>
<p>How do I make the re-running of tox happen automatically when changes are saved to python files an... | <p>I'm going to try "tdaemon" like this:</p>
<pre><code>$ tdaemon.py --test-program=tox
</code></pre> | python|testing|tox | 0 |
9,913 | 34,730,823 | Getting an unexpected newline when printing lines from a file | <p>Pretty straight forward question here...I'm looking to append my regex match to the same line, not a new line in the file. I thought I had done this correctly, but the result is still printing to a new line:</p>
<p>Result:</p>
<pre><code>1,2,BreakingBad,4,5,6...
,BreakingBad
</code></pre>
<p>What I want:</p>
<pr... | <p>There are a few more things that are not overly Pythonic, though they'd be more suited in a code review.<br>
Since it would become too long for a comment, I just put it as an answer.</p>
<p>Summary:</p>
<ul>
<li><p>use the <code>with</code> context manager. This saves you the hassle of <code>try ... finally</code>... | python|regex|append|line | 3 |
9,914 | 34,803,234 | Sqlalchemy: subquery in FROM must have an alias | <p>How can I structure this sqlalchemy query so that it does the right thing?</p>
<p>I've given everything I can think of an alias, but I'm still getting:</p>
<pre><code>ProgrammingError: (psycopg2.ProgrammingError) subquery in FROM must have an alias
LINE 4: FROM (SELECT foo.id AS foo_id, foo.version AS ...
</code><... | <p>You are almost there. Make a <a href="http://docs.sqlalchemy.org/en/latest/core/selectable.html#">"selectable"</a> subquery and join it with the main query via <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.join"><code>join()</code></a>:</p>
<pre><code>foo_max_time_q = selec... | python|postgresql|select|sqlalchemy|psycopg2 | 30 |
9,915 | 27,369,546 | How can I use the same callback function to trace multiple variables? | <p>I would like to display the value of several <code>StringVar()</code> with some formatting on Labels.</p>
<pre><code>import tkinter as tk
keys = range(2) # 2 for simplicity
root = tk.Tk()
myVars = {key: tk.StringVar() for key in range(5)}
myStrVars = {key: tk.StringVar() for key in range(5)}
def callback0(*args)... | <p>You can send the key and the input to the function. This is a truncated version and a little different than your code but does what I think you want.</p>
<pre><code>import tkinter as tk
from functools import partial
def callback(key, var, *args):
print "callback var =", key, var.get()
##myStrVars[key].set... | python|python-2.7|callback|tkinter|trace | 2 |
9,916 | 23,144,712 | How to create files to and open files from a sub directory in Python? | <p>I am a beginner at Python programming (2.7; and Pygame) and I was wondering; how do you create and read files from a sub directory? In other words, I want to take sprite images, data, BGM, etc. from a sub directory named 'Data'. So, for example, if I wanted to use Pygame to open a sprite file in the sub directory 'D... | <p>Use the os.path.join function to get the path of the file.
Add</p>
<pre><code>import os
</code></pre>
<p>at the beginning of your code. Use it like this:</p>
<pre><code>char_idle = pygame.image.load(os.path.join("Data", "char_idle.png"))
</code></pre>
<p>You could also provide the path as "Data/char_idle.png" (... | python|python-2.7|pygame|sprite | 0 |
9,917 | 23,191,611 | Can anybody suggest me some graph generating ways using python/django/jquery/javascript | <p>I also want to save the generated graph as an image (or generate image of graph) for appending to pdf..I tried <strong>jqplot(jquery)</strong>,<strong>cairoplot(python)</strong> but that is not satisfying my requirements.</p> | <p>I don't know if there is a single plugin to solve both these requirement but if you are fine with using more than one plugin try <strong>Google Charts</strong> for plotting the graph and <strong>HTML2CANVAS</strong> for saving its image as png.</p>
<ul>
<li><a href="https://developers.google.com/chart/" rel="nofoll... | javascript|jquery|python|django | 0 |
9,918 | 23,112,284 | Convert nltk Tree to JSON representation | <p>I would like to convert the following nltk Tree representation into JSON format:</p>
<p><img src="https://i.stack.imgur.com/FbJCU.png" alt="nltk Tree structure"></p>
<p>Desired output:</p>
<pre><code>{
"scores": {
"filler": [
[
"scores"
],
[
... | <p>It looks like the input tree may contain children with the same name. To support the general case, you could convert each <code>Tree</code> into a dictionary that maps its name to its children list:</p>
<pre><code>from nltk import Tree # $ pip install nltk
def tree2dict(tree):
return {tree.node: [tree2dict(t) ... | python|json|tree|nltk | 3 |
9,919 | 7,885,254 | Python code generator | <p>I want to be able to perform code generation of python given an AST description.</p>
<p>I've done static analysis of C and built AST visitors in python, so I feel relatively comfortable manipulating a syntax tree, but I've never attempted code generation before and am trying to determine the best practice for gener... | <p>You may want to take a look at the <code>2to3</code> tool, developed by the Python code devs to automatically convert Python 2 code to Python 3 code. The tool first parses the code to a tree, and then spits out "fixed" Python 3 code from that tree. </p>
<p>This may be a good place to start because this is an "offic... | python|code-generation|abstract-syntax-tree | 18 |
9,920 | 779,384 | Python Multiprocessing: Sending data to a process | <p>I have subclassed <code>Process</code> like so:</p>
<pre><code>class EdgeRenderer(Process):
def __init__(self,starter,*args,**kwargs):
Process.__init__(self,*args,**kwargs)
self.starter=starter
</code></pre>
<p>Then I define a <code>run</code> method which uses <code>self.starter</code>.</p>
<... | <p>On unix systems, multiprocessing uses os.fork() to create the children, on windows, it uses some subprocess trickery and serialization to share the data. So to be cross platform, yes - it must be serializable. The child will get a new copy.</p>
<p>That being said, here's an example:</p>
<pre><code>from multiproces... | python|multiprocessing | 8 |
9,921 | 41,814,934 | Matplotlib scatter plot legend, as separate image | <p>I am using <code>ax.scatter(x,y,c=color, s=size, marker='*', label="mylabel")</code> to plot 4 symbols in a scatter plot (markers are <code>','</code>, <code>'o'</code>,<code>'*'</code>, and <code>'^'</code>) each with differing sizes and colors.</p>
<p>I have tried calling <code>ax.legend()</code> and, although I ... | <p>Here is what i found:
I had to modify the code I found to not include a figure call. After plotting the scatter (ax.scatter) I called:</p>
<pre><code>handles,labels = ax.get_legend_handles_labels()
</code></pre>
<p>After plotting the main plot and closing the figure I called a new figure:</p>
<pre><code>fig_legen... | python|python-2.7|matplotlib|scatter-plot | 6 |
9,922 | 70,765,973 | Can you explain why none is printing in output? | <pre><code>def great(a,b,c):
if(a>b and a>c):
print("a is greater")
elif(b>a and b>c):
print("b is greater")
else:
print("c is greater")
a=great(12,3,1)
print(a)
</code></pre>
<p><strong>Can you explain why none is printing in... | <p>In python indentation matters,
Your Function Call is not Properly indented that is why it is not printing anything</p>
<pre><code>def great(a,b,c):
if(a>b and a>c):
print("a is greater")
elif(b>a and b>c):
print("b is greater")
else:
print("c i... | python|python-3.x|python-2.7|if-statement | 1 |
9,923 | 71,065,783 | how i can get data from binance on Vscode | <p>I'm trying to get data from binance client using python on VSCode .</p>
<pre><code>from binance import Client
import config
key = config.API_KEY
secret = config.API_SECRET
client = Client(key, secret)
info = client.get_symbol_info("BTCUSDT")
</code></pre>
<p>I tryed the same code on google collab and it... | <p>uninstall and reinstall python-binance</p> | python|binance|binance-api-client | 0 |
9,924 | 33,586,687 | architecture on google cloud platform for scientific web application | <p>I have an apps coded in python/pandas/scipy which can be launched by anyone authorized. I want to use Google Cloud Platform to host it but I can't find a good way to set up this.</p>
<p>Since I want my app to be a web app, part of this is hosted on google app engine, but since google app engine does not seem compa... | <p>You can host your application on <a href="https://cloud.google.com/appengine/docs/managed-vms/" rel="nofollow">Managed VMs</a>. Applications that run on managed VMs are not subject to the restrictions imposed on the sandboxed runtimes (Java, Python, PHP, and Go).</p>
<p>You can also choose the hosting environment (... | python|google-app-engine|pandas|architecture|google-compute-engine | 1 |
9,925 | 46,637,792 | While loop with two input invocations | <p>I am learning Python and I am having trouble with while loops. I have a sample code below and it includes a while loop. What I am want to do here is print “Ha! You’ll never guess” every time the correct name is not predicted, but I also want the code to print “No! how did you guess?” when the right name is predicted... | <p>Which System do you use? I tested your code, after I corrected the indentation and I get no errors or warnings.</p>
<pre><code>print("You will never win the game, for Scooby dooby doo! is my name.")
rumple = input("Guess my name: ")
while rumple != "Rumplestiltskin":
print("Ha! You'll never guess!")
rumple... | python|while-loop | 0 |
9,926 | 46,745,993 | search and replace with line in document | <p>I am trying to write a code that searches and replaces with a line in the document. i have:</p>
<pre><code>import re
x = open(r'F:\1\xxx.txt')
string = open(r'F:\1\xxx.txt').read()
Lines = x.readlines()
new_str = re.sub('zzz1', (Lines[1]) , string)
new_str = re.sub('zzz2', (Lines[2]) , string)
open(r'F:\1\xxx2.txt... | <p>working solution:</p>
<p>import re
x = open(r'F:\1\xxx.txt')
Lines = x.readlines()</p>
<p>repldict = {'zzz1':(Lines[0]).strip(), 'zzz2':(Lines[1]).strip()}
def replfunc(match):
return repldict[match.group(0)]</p>
<p>regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open(r'F:\1\xxx.txt') as fin... | python | 0 |
9,927 | 67,777,788 | How do I make a process modify a list passed to it in python? | <p>I have some code that will download some json from an api. I have to go through many pages and requests.get is very slow so I'm trying to use multiprocessing to speed things up. Here is my code:</p>
<pre><code>def worker(mod, offset, totalpages, arr):
stuff = []
for i in range(offset, totalpages, mod):
... | <p>use <code>multiprocessing.Manager()</code> to create a <code>list</code> that all threads can access</p> | python | 0 |
9,928 | 30,197,376 | Combine two lists of dicts, adding the values together | <p>I want to combine two lists of multiple dicts into a new list of dicts, appending new dicts to the final list, and adding together the 'views' values if encountered.</p>
<pre><code>a = [{'title': 'Learning How to Program', 'views': 1,'url': '/4XvR', 'slug': 'learning-how-to-program'},
{'title': 'Mastering Prog... | <p>You need to convert your input dictionaries to <code>(title: count)</code> pairs, using them as keys and values in a <code>Counter</code>; then after summing, you can convert these back to your old format:</p>
<pre><code>from collections import Counter
summed = sum((Counter({elem['title']: elem['views']}) for elem... | python|list|dictionary | 2 |
9,929 | 61,562,138 | How to use two seperate dataloaders together? | <p>I have two tensors of shape <code>(16384,3,224,224)</code> each. I need to multiply these two together. Obviously these two tensors are too big to fit in GPU ram. So I want to know, how should I go about this, divide them smaller batches using slicing or should I use two separate dataloaders?(I am confused, how to u... | <p>I'm still not sure I totally understand the problem, but under the assumption that you have two big tensors <code>t1</code> and <code>t2</code> of shape <code>[16384, 3, 224, 224]</code> already loaded in RAM and want to perform element-wise multiplication then the easiest approach is</p>
<pre><code>result = t1 * t... | deep-learning|pytorch|tensor | 1 |
9,930 | 65,556,673 | Pytest - Can't access imported class' attributes? | <p><strong>Problem Summary:</strong>
When trying to access class methods of a class/Luigi tasks that I am trying to test, it states that the class does not have the methods I am trying to use.</p>
<p><strong>More Detail:</strong>
I am attempting to test a class/Luigi task I have written. I am trying to import the class... | <p>The definition of <code>_helper_method_1</code> lacks a <code>self</code> parameter. In order to call <code>base._helper_method_1(...)</code>, you need to add <code>self</code>, or tag it with <code>@classmethod</code> or <code>@staticmethod</code>. I would expect another error message, but perhaps pytest muddles it... | python|python-3.x|unit-testing|pytest|luigi | 0 |
9,931 | 43,206,881 | IndexError but I don't know what is wrong | <pre><code>opponent = [1, 1, 1, 1, 1, 1]
</code></pre>
<p>I want just the first element in my list 'opponent', therefore I then code:</p>
<pre><code>opponent = int(opponent[0])
</code></pre>
<p>I use this to then count the number of 'opponent's there are in one of my other lists.</p>
<pre><code>if wongames.count(op... | <p>Your list of opponents is called <code>opponent</code>, and later on in your code you do:</p>
<pre><code>opponent = int(opponent[0])
</code></pre>
<p>overriding the earlier <code>opponent</code> list, so now the <code>opponent</code> name refers to an integer instead.</p>
<p>Next time you do the same again:</p>
... | python | 3 |
9,932 | 37,009,287 | Using pandas .append within for loop | <p>I am appending rows to a pandas DataFrame within a for loop, but at the end the dataframe is always empty. I don't want to add the rows to an array and then call the DataFrame constructer, because my actual for loop handles lots of data. I also tried <code>pd.concat</code> without success. Could anyone highlight wha... | <p>Every time you call append, Pandas returns a copy of the original dataframe plus your new row. This is called quadratic copy, and it is an O(N^2) operation that will quickly become very slow (especially since you have lots of data).</p>
<p>In your case, I would recommend using lists, appending to them, and then ca... | python|pandas|append|concat | 61 |
9,933 | 4,128,555 | How to build/compile C++, Java and Python projects? | <p>Let's say I have a bunch of small targets in different programming languages (C++, Java, Python, etc), with inter programming language dependencies (Java project depends on a C++, Python depends on C++). How can one build/compile them?</p>
<p>I tried scons and more recently gyp. I don't remember what issues I had w... | <p>I would pick one of the more configurable build tools like ant or maven, as a starting point.</p>
<p><a href="http://ant.apache.org/" rel="nofollow">Ant</a> is highly configurable, and worst case you can use it to exec another build process (like, make, or whatever you normally use for C++).</p>
<p><a href="http:/... | java|c++|python|build|scons | 2 |
9,934 | 48,232,121 | Subtract from each cell in pandas dataframe based on value | <p>I have a df like this-- it's a dataframe and all values are floats:</p>
<pre><code>data=np.random.randint(3000,size=(10,1))
data=pd.DataFrame(data)
</code></pre>
<p>For each value, if it's between 570 and 1140, I want to subtract 570.
If it's over 1140, I want to subtract 1140 from the value. I wrote this function... | <p><strong>Setup</strong></p>
<pre><code>data
0
0 1863
1 2490
2 2650
3 2321
4 822
5 82
6 2192
7 722
8 2537
9 874
</code></pre>
<p>First, let's create masks for each of your conditions. One pandaic approach is using <code>between</code> to retrieve a mask for the first condition - </p>
<pre><cod... | python|pandas | 2 |
9,935 | 51,119,621 | How to read a file in Python | <p>I have a file on my computer called test. It's a .py file. I only have 2 things in the file.</p>
<pre><code>'Is this working?
"Probably not."
</code></pre>
<p>When I try to read it I get this:</p>
<pre><code>>>>t = open('test')
>>>t
<_io.TextIOWrapper name='test' mode='r' encoding='cp1252'... | <p>General syntax to read the file in python is
oparend =open("filename","filemode")</p>
<p>Basic file modes are: r,w,a,r+,w+,a+, rb, wb</p>
<p>You can read the file in following modes
r,a+,w+,r+
But criteria is different in different modes.
For example file with name of file.txt
Can read by the following syntax
F=... | python|file | 1 |
9,936 | 17,599,175 | Python list([]) and [] | <pre><code>from cs1graphics import *
from math import sqrt
numLinks = 50
restingLength = 20.0
totalSeparation = 630.0
elasticityConstant = 0.005
gravityConstant = 0.110
epsilon = 0.001
def combine(A,B,C=(0,0)):
return (A[0] + B[0] + C[0], A[1] + B[1] + C[1])
def calcForce(A,B):
dX = (B[0] - A[0])
dY ... | <p><code>list(chain)</code> returns a shallow copy of <code>chain</code>, it is equivalent to <code>chain[:]</code>.</p>
<p>If you want a shallow copy of the list then use <code>list()</code>, it also used sometimes to get all the values from an iterator.</p>
<p>Difference between <code>y = list(x)</code> and <code>y... | python|arrays|list | 16 |
9,937 | 64,203,533 | Keeping punctuation as its own unit in Preprocessed Text | <p>what is the code to split a sentence into a list of its constituent words AND punctuation? Most text preprocessing programs tend to remove punctuations.</p>
<p>For example, if I enter this:</p>
<blockquote>
<pre><code>"Punctuations to be included as its own unit."
</code></pre>
</blockquote>
<p>The desired... | <p>You might want to consider using a Natural Language Toolkit or <code>nltk</code>.</p>
<p>Try this:</p>
<pre><code>import nltk
sentence = "Punctuations to be included as its own unit."
tokens = nltk.word_tokenize(sentence)
print(tokens)
</code></pre>
<p>Output: <code>['Punctuations', 'to', 'be', 'included'... | python|text|punctuation | 1 |
9,938 | 70,639,186 | Unable to use the user defined element in the if-elif statements | <p>I just want to convert minutes or days given by the user into hours.
It is showing that "minute is not defined". When I print the user input, minute is getting printed, but when I want to use that "minute" given by user in the if statement, then it is showing an error.</p>
<pre><code>t_in = input... | <p>You wrote the minute without the "", which means the minute is a variable, but you don't have a minute variable. You should write the minute in "" because it is a string, not a variable.</p>
<pre><code>t_in = input("Is your input in minute or hr or day? ")
print (t_in)
t = input("E... | python|if-statement | 0 |
9,939 | 72,909,653 | append new data entered by user in a loop to an existing data frame | <p>I have a python program that displays texts to be labeled by the user. After the user add labels to the displayed text, the program should be able to create a new data frame with the text presented to the user for labelling in the first column and the labels entered by the user in the second column. This new data fr... | <p>There are two parts to why this is not working as intended.
Error 1: the <code>df_new_labels</code> is created anew for every text. Instead, the new text and its labels should be appended to existing lists.
Error 2: when creating the DataFrame with <code>df_new_labels=pd.DataFrame(df_new_labels)</code>, pandas autom... | python|pandas|dataframe|for-loop | 1 |
9,940 | 73,057,432 | How can I calculate the difference between two timestamps using micropython? | <p>I have a raspberry pi pico and a DS3231 real time clock hooked up to it. I'm able to receive the current time in BCD and format it in a string by Hours:Minutes:seconds "00:00:00" using the DS3231 sample code that has been provided from the waveshare wiki <a href="https://www.waveshare.com/wiki/Pico-RTC-DS... | <p>You can find <a href="https://github.com/micropython/micropython-lib/tree/master/python-stdlib/datetime" rel="nofollow noreferrer">datetime</a> in the <a href="https://github.com/micropython/micropython-lib" rel="nofollow noreferrer">micropython-lib</a> repository, a collection of curated (by the MicroPython core te... | micropython|real-time-clock|raspberry-pi-pico | 0 |
9,941 | 55,682,051 | What features could help to classify the end of sentence? Sequence classification | <h1>Problem:</h1>
<p>I have pairs of sentences that lack a period and a capitalized letter in between them. Need to segment them from each other. I'm looking for some help in picking the good features to improve the model.</p>
<h1>Background:</h1>
<p>I'm using <code>pycrfsuite</code> to perform sequence classificati... | <p>Since your classes are very imbalanced due to the nature of the problem, I would suggest using weighted loss, where the loss for the P tag is given a higher value than those of the S class. I think the problem might be that due to the equivalent weight of both classes, the classifier not give enough attention to tho... | python|machine-learning|nlp|nltk|crf | 1 |
9,942 | 66,672,575 | Seaborn lineplot plot all entries (lines) separately using one grouping variable for coloring | <p>I am trying to plot all the entries in a dataframe by using one variable for legend purposes. My dataframe looks like:</p>
<p><a href="https://i.stack.imgur.com/qOLzs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qOLzs.png" alt="enter image description here" /></a></p>
<p>If I try to plot by sns... | <p>Ok, I used a different approach, by using default pandas plot function (not as fast nor simple as I wanted, but it works).</p>
<pre><code>from matplotlib.lines import Line2D
fig, ax = plt.subplots()
colors = sns.color_palette()
puntos = dfnew['Punto'].unique()
for n, punto in enumerate(puntos):
subset = dfnew[dfn... | python|pandas|plot|seaborn | 0 |
9,943 | 64,697,241 | Replacing values of rows with same ID with max date | <p>Below is script for a simplified version of the df in question:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'id': ['1', '1','2','2','3','3','4','4','5','6','7'],
'product1_expiry_date' : ['-','-','2020-11-28','2020-11-13','-',
... | <p>Convert <code>Id</code> to index, then convert all columns to datetimes and use <code>max</code> per index:</p>
<pre><code>f = lambda x: pd.to_datetime(x, errors='coerce')
df1 = df.set_index('id').apply(f).max(level=0)
print (df1)
product1_expiry_date product2_expiry_date
id ... | python|pandas | 0 |
9,944 | 64,823,230 | Validating multiple wtf forms separately, within same page template. Flask | <p>I am a beginner working with Flask and wtforms. I have been able to develop a basic login system with Flask-Login and wtforms, with separate routes/forms with no problem. What I am trying to create now is a registration page that contains more that one form to be validated in the same registration html page.</p>
<p>... | <p>In the view function, you validate the first form in this way:</p>
<pre><code>if request.method == 'GET':
if access_cd_form.submit.data and access_cd_form.validate_on_submit():
</code></pre>
<p>Here the <code>form.validate_on_submit()</code> is a shortcut for <code>request.method in ['POST', 'PUT', 'PATCH', 'DELE... | python|flask|wtforms | 0 |
9,945 | 65,270,246 | Pandas - Problem reading a datetime64 object from a json file | <p>I'm trying to save a Pandas data frame as a JSON file. One of the columns has the type datetime64[ns]. When I print the column the correct date is displayed. However, when I save it as a JSON file and read it back later the date value changes even after I change the column type back to datetime64[ns]. Here is a ... | <pre><code>df = pd.read_json("test.json")
df[0] = pd.to_datetime(df[0], unit='ms')
print("\ndf\n")
print(df)
print("\ndf dtypes\n")
print(df.dtypes)
</code></pre>
<p>will give you</p>
<pre><code>df
0
0 2000-01-01
df dtypes
0 datetime64[ns]
dtype: object
</code></pre>
<p>Th... | python|pandas | 1 |
9,946 | 62,755,040 | Python: Filtering data from Json file based on some json object? | <p>I have this file with Json data as shown below</p>
<pre><code>{
"tags": [],
"imageheight": 1024,
"imagewidth": 1920,
"children": [
{
"tags": [
"occluded>10",
"unsure_orientation"
],
"x0": 447,
... | <p>x['tags'] is of type list, so if you want test that this list contains only one item <code>"occluded>10"</code>, you can compare <code>["occluded>10"] == x['tags']</code>.</p>
<p>For example:</p>
<pre><code>import json
d = {
"tags": [],
"imageheight": 1024,
"... | json|python-3.x|list|lambda|filter | 0 |
9,947 | 61,894,963 | Pytorch Loaded model giving inconsistent results | <p>I am playing around with code from this Github repository <a href="https://github.com/jindongwang/Pytorch-CapsuleNet" rel="nofollow noreferrer">https://github.com/jindongwang/Pytorch-CapsuleNet</a>.</p>
<p>After training the model for 5 epochs, I got an accuracy of 99.2% on the test dataset. So I saved model using ... | <p>I don't think there is anything wrong with the way you saved or the way you load your model.</p>
<p>But I happened to see the same problem because I didn't initialise some parameters, so they were stuck to 'None' even after loading the state dict. </p>
<p>I would suggest to look into the loaded state_dict to see i... | python-3.x|pytorch | 0 |
9,948 | 70,135,826 | separate the values of columns | <p>I have the following data frame and I want to separate it based on commas</p>
<pre><code>df1 = pd.DataFrame(
{
"column0": ["xx, aa", "xx, aa"],
"column1": ["yy","yy"],
"column2": ["cc, xx", "cc, xx"]... | <p>You'd probably need to prepare your data for that as you have generated key names and string processing. For example, you can do this:</p>
<pre class="lang-py prettyprint-override"><code>d = {"column0": ["xx, aa"],
"column1": ["yy"],
"column2": ["cc, x... | python|dataframe | 0 |
9,949 | 11,346,002 | Compare two datetimes and get day difference | <p>I have an array of dates. I am comparing the objects of the array (B) to a control (A). How do I check if B's age is 10 days when compared to A? Ideally, I would like to be able to declare a variable as the difference in days. Thanks.</p> | <p>This Python code template will compute the difference in days:</p>
<pre><code>import datetime
d1 = datetime.datetime(2012, 7, 1)
d2 = datetime.datetime(2012, 7, 5)
diff = d2 - d1
print diff.days
</code></pre> | python | 8 |
9,950 | 56,518,156 | In Django, When I updated the published date How I get the link from get_absolute_url is updated? | <p>I built a Django blog application and I updated the published date
I found a result from get_absolute_url function is not updated
it always get the original link </p>
<p>models.py</p>
<pre><code>#-- models.py --
#Create custom manager
from django.db import models
from django.utils import timezone
from django.contr... | <p>Your publish field does not get updated from the code I can see. How do you edit your post? Via a form in the frontend? If so, your view code should update the publish field after save.</p>
<p>Your publish function should be:</p>
<pre><code>class Post(models.Model):
....
def publish(self):
self.pu... | python|django | 0 |
9,951 | 72,551,215 | Python Process won't stop by calling kill method | <p>So I'm trying having a self-made led-controller (raspberry pi).</p>
<p>The Controller should be able to play different scenes which were pre-defined by myself.
Now to the main problem...</p>
<p>The controller runs as TCP server and gets his scene-changes by tcp messages.
i coded a lot of scenes which need to run in ... | <p>The variable process is only defined in the</p>
<pre><code>if data=="on"
</code></pre>
<p>While you use the variable process in the</p>
<pre><code>if data=="off
</code></pre>
<p>It has not been defined. Is that done intentionally?</p>
<p>Furthermore what do you mean by the code isn't working. Do you g... | python|tcp | 0 |
9,952 | 59,165,398 | Accessing variables from super blocks in Jinja2 | <p>I have been trying to design a multi-section report document, with a primary template:</p>
<pre><code><html>
<body>
{% include "SectionA.html" %}
{% include "SectionB.html" %}
...
</body>
</html>
</code></pre>
<p>Where each of the included <code>SectionX.html</code> files ex... | <p>You can use the <a href="https://jinja.palletsprojects.com/en/2.10.x/templates/#include" rel="nofollow noreferrer"><code>include</code></a> tag instead to render the content of <code>base.html</code> in the current namespace.</p>
<p>So <code>base.html</code> should simply set default values for common variables:</p... | python|html|inheritance|scope|jinja2 | 0 |
9,953 | 35,470,480 | PYMC Deterministic variable with parent as class attribute | <p>I am trying to create a PYMC Deterministic variable that looks like the following.</p>
<pre><code>@pymc.deterministic
def tau(s = sigma):
return 1.0/(s**2)
</code></pre>
<p>However, in my case, the model parameters (PYMC Stochastic variables) are defined as class attributes. As a result, <code>sigma</code> is ... | <p>Thanks to <a href="https://stackoverflow.com/questions/19787928/passing-parameters-to-deterministic-variables-pymc">this</a> mildly related question, I was able to figure out a way to capture class attributes as parents to a PYMC Deterministic variable. The solution is to use PYMC's <a href="http://pymcmc.readthedoc... | python|python-2.7|pymc | 1 |
9,954 | 58,837,928 | Parsing periods in a column dataframe | <p>I have a csv with one of the columns that contains periods:</p>
<p>timespan (string): PnYnMnD, where P is a literal value that starts the expression, nY is the number of years followed by a literal Y, nM is the number of months followed by a literal M, nD is the number of days followed by a literal D, where any of ... | <p>Like with Python's builtin <code>map</code>, Pandas also has that method. You can check its documentation <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer">here</a>. Since you already have your function ready which takes a single parameter and retur... | regex|python-3.x|pandas | 0 |
9,955 | 49,053,610 | Python : how to pass argument to thread job (callback) | <p>I am implementing thread with callback in Python. I have problem don't know how to pass the arguments to thread job. </p>
<p>What I have done:</p>
<pre><code>import time
import threading
class BaseThread(threading.Thread):
def __init__(self, callback=None, callback_args=None, *args, **kwargs):
target... | <p><a href="https://gist.github.com/amirasaran/e91c7253c03518b8f7b7955df0e954bb" rel="nofollow noreferrer">Original GitHub Code</a>
<br /> This will allow you to pass an initial parameters into the thread.</p>
<pre><code>import time
import threading
class BaseThread(threading.Thread):
def __init__(self, callback... | multithreading|python-2.7|callback | 0 |
9,956 | 60,092,625 | How to resolve "name 'imdb' is not defined" error | <p>I'm trying to create "<em>text classification with TensorFlow Hub: Movie reviews</em>" model. Below is my code:</p>
<pre><code>import tensorflow as td
from tensorflow import keras
import numpy as np
data = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = data.load_data(num_words=10000)
... | <p>Try this -</p>
<pre><code>import tensorflow as tf
import tensorflow_datasets as tfds
dataset, information = tfds.load('imdb_reviews/subwords8k', with_info=True, as_supervised=True)
train_dataset, test_dataset = dataset['train'], dataset['test']
</code></pre> | python|tensorflow | 0 |
9,957 | 67,076,837 | Python Docker SDK Inside Kubernetes | <p>I followed this link - <a href="https://docs.docker.com/engine/api/sdk/examples/" rel="nofollow noreferrer">https://docs.docker.com/engine/api/sdk/examples/</a> and the docker SDK worked fine while I was using Docker containers. Now that I have moved to K8s, when I run the code I get error like "Container Not F... | <p>You can't use the Docker API from inside Kubernetes; you need to use the <a href="https://kubernetes.io/docs/reference/using-api/" rel="nofollow noreferrer">Kubernetes API</a> instead. You can do many of the same things you might have done with the Docker API using the Kubernetes API (launch new Jobs, query existin... | docker|kubernetes|dockerpy|kubernetes-python-client|python-docker | 2 |
9,958 | 65,603,767 | asyncio : How to queue object when an exception occurs | <p>Hi I have to process several objects queued 5 at time.
I have a queue of 5 items.
Sometimes process fails and an exception occurs:</p>
<pre><code>async def worker(nam):
while True:
queue_item = await queue.get()
</code></pre>
<p>Worker starts the process loop and tries to process items</p>
<pre><code>try:
... | <p>Yes, you can re-queue an object <em>at the end</em> of the queue for processing. A simple
example based on your code:</p>
<pre><code>import asyncio
from random import randrange
async def download(item):
print("Process item", item)
if randrange(4) == 1: # simulate occasional event
await ... | python|exception|queue|python-asyncio|telethon | 3 |
9,959 | 51,011,010 | Constructors in kivy | <p>I am quite new to kivy. While practicing with online examples, I noticed that many of their widget classes don't have constructors. I just want to ask what is significance of constructors in kivy widgets, n when to use them.</p> | <p>You don't need to declare a constructor unless you need to do something specific. For example, our <a href="https://github.com/kivy/kivy/blob/master/kivy/uix/widget.py#L322" rel="nofollow noreferrer">Widget class have a constructor</a> that does lot of stuff, like applying the properties, create the widget canvas, a... | python|python-3.x|kivy | 2 |
9,960 | 3,465,017 | question about python names using a default parameter value | <p>I was reading this today: <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values" rel="nofollow noreferrer">http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values</a> and I can't seem to understand what's happening under the hoo... | <blockquote>
<p>when is the function definition stage?</p>
</blockquote>
<p>Look at <a href="http://docs.python.org/reference/compound_stmts.html#index-802" rel="nofollow noreferrer">"Function definitions"</a> in the Python reference:</p>
<blockquote>
<p><strong>Default parameter values are evaluated when the... | python|variables | 3 |
9,961 | 50,427,591 | How do I parallelize this using Python multiprocessing? | <p>I've coded a 1 vs rest classifier in Python that trains 11 different classifiers, one for each class. The code is shown below:</p>
<pre><code>def onevsrest(X_train,y_train,lamb):
beta=[]
beta_init=np.zeros(X_train.shape[1])
for i in range(1,12):
print(i)
y=np.copy(y_train)
y[y !=... | <p>You can "partial" your function. Example:</p>
<pre><code># multiple arguments function
def calc(a, b, c):
return a + b + c
# prepare a single argument partial function, freezing `b` and `c`
from functools import partial
calc2 = partial(calc, b=3, c=7)
from multiprocessing import Pool
p = Pool(5)
print(p.map(c... | python|parallel-processing|large-data|multiclass-classification | 1 |
9,962 | 50,615,763 | Dictionary key, value pairs of a cell to columns whose name is key and row is value in Pandas | <p>I found it very hard to frame the question using the right words.. But I hope I've done a good job..</p>
<p>Here is an example that I artificially created so you can reproduce it in your console.</p>
<pre><code>example = pd.DataFrame([['a', [{'a1': 1,
'a2': {'amount': 20, 'currency': 'USD'}, 'a3': 57},
... | <pre><code>from pandas.io.json import json_normalize
rows = list(example.index)
mainDf = pd.DataFrame()
for index in rows:
listing = example.at[index, "column2"]
df = pd.DataFrame()
for i in listing:
l = (json_normalize(i))
df = df.append(l)
otherCols = list(example.... | python|python-3.x|pandas|dictionary | 0 |
9,963 | 69,298,347 | Django request not recognized | <p>I am currently learning Django with video tutorials and I came across a problem I can't get rid of.
I am in the views file of one of my apps and when I try to use "request" it tells me '"request" is not definedPylancereportUndefinedVariable'</p>
<pre><code>from django.http import HttpResponse
fro... | <p><code>request</code> is the first parameter of a view function, you thus need to specify this explicitly:</p>
<pre><code># ↓ request parameter
def home_view(request, *args, **kwargs):
return render(request, 'home.html', {})</code></pre> | python|django|django-templates|pylance | 0 |
9,964 | 55,182,614 | Extract data from list using a delimiter | <p>I have a set of 10 python lists in the below format:</p>
<pre><code>[ABC*DEF*123>~123*999*HHH]
[PQR*RST*567>~AWS*999*POI]
[XYZ*TGT*234>~2352*245*HFT]
[STU*DEF*789>~654*345*QQQ]
</code></pre>
<p>I am trying to extract data from the above list such that the final output is a Dataframe and <strong>expect ... | <p>You can start by creating a dataframe with the lists of strings as rows and split each string by <code>~</code> using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split</code></a>. You can then slice the result selecting only th... | python|string|pandas|list | 6 |
9,965 | 45,595,562 | SQL Alchemy update table using list of dicts with bindparam not working | <p>I'm trying to perform an update based on a list of dictionaries using bindparam, but I'm not sure why this example isn't working:</p>
<pre><code>import sqlalchemy
from sqlalchemy import Table, exc, and_
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.expression import bindparam
from sqla... | <p>Ignoring all the surrounding functionality – and errors – and focusing on the update we can simplify your example to something along the lines of</p>
<pre><code>In [2]: t = Table('demo_table', metadata,
...: Column('trigger_service', String()),
...: Column('package_name', String()))
In [5... | python|python-2.7|sqlalchemy | 5 |
9,966 | 44,812,822 | Return searchlight vectors for a given numpy array | <p>Consider a 3D numpy array <code>D</code> of dimension, say, (30 x 40 x 50). For each voxel <code>D[x,y,z]</code> I want to store a vector that contains neighboring voxels within a certain radius (including the <code>D[x,y,z]</code> itself).</p>
<p>(As an example here is a picture of such a sphere of radius 2: <a hr... | <p>Since you say the data structure is too large, you'll likely have to compute the vector on the fly for a given voxel. You can do this pretty quickly though:</p>
<pre><code>class SearchLight(object):
def __init__(self, M_in, radius):
self.M_in = M_in
m, n, k = self.M_in.shape
# compute t... | python|arrays|numpy|multidimensional-array | 1 |
9,967 | 46,342,621 | How to get the hive server side error msg using PyHive sqlalchemy? | <p>I have a sql like</p>
<pre><code>select * from log where concat_ws('-',year,month,day) between 2017-09-13 and 2017-09-19
</code></pre>
<p>which is wrong because of not having 2017-09-13 and 2017-09-19 surrounded by ''.</p>
<p>In beeline, it will result the error msg like</p>
<blockquote>
<p>Error: Error while ... | <p>I got this, 2017-09-13 is valid Hive syntax. It just means integer subtraction. The error in beeline is about something else.</p> | python-3.x|logging|sqlalchemy|pyhive | 0 |
9,968 | 54,910,515 | Showing a picture in python | <p>I'm trying to show a figure, in PyCharm, that is in my working directory, but it either doesn't work or only works with this code:</p>
<pre><code>img = mpimg.imread('Figure_1.png')
plt.imshow(img)
plt.show()
</code></pre>
<p>with this result:
<img src="https://i.stack.imgur.com/9VAel.png" alt="1]"></p>
<p>I just ... | <p>Some quick workarounds: to remove the axes, do <code>plt.axes('off')</code>. To make the picture fit the frame, set the aspect ratio to <code>'auto'</code> and create a figure with the same aspect ratio as your original image (i'd say it's roughly 4:1?). Use <code>tight_layout</code>to make sure all of your image is... | python|matplotlib|pycharm | 0 |
9,969 | 41,107,630 | Autocomplete in embedded IPython | <p>I'm using <code>InteractiveShellEmbed</code> from <code>IPython.terminal.embed</code> to embed IPython in my app. All works rigth, but autocomplete not works with modules. For example: <code>import rand[TAB]</code> doesn't completes to <code>import random</code>.
What can I do to fix this?</p>
<p>My code:</p>
<pre... | <p>The autocomplete functionality seems to be working for me for iPython 5.1.0 with python 2.7.6. What version of iPython are you using? Do you have the same issue if you just use 'from IPython import embed' and then call 'embed()' in your app where you want?</p>
<p>---Update:</p>
<p>Try making an explicit instance: ... | python|autocomplete|ipython|interactive-shell | 0 |
9,970 | 29,287,432 | Multidimensional list match in python | <p>This has caused some serious headache today.
Suppose I have two instances of my object, instance A and instance B. These come with properties is the form of a list. Say the two properties for A are</p>
<pre><code>a1 = [1, 2, 3, 4, 5]
a2 = [10, 20, 30, 40, 50]
</code></pre>
<p>and those for B:</p>
<pre><code>b1 = ... | <p>You can use a combination of <code>zip</code>, <code>set</code> and <code>enumerate</code>:</p>
<pre><code>>>> a1 = [1, 2, 3, 4, 5]
>>> a2 = [10, 20, 30, 40, 50]
>>> b1 = [5, 7, 3, 1]
>>> b2 = [50, 20, 30, 20]
>>> a12 = set(zip(a1, a2))
>>> [i for i, e in enumer... | python | 4 |
9,971 | 52,436,814 | Add custom text message after break line | <p>The below code snippet sends email with status.
If I want to add another line break with text as Sent from Scheduler.
What could be the possible way ?</p>
<pre><code>def send_email(status,message):
date = str(datetime.now().date())[-5:].replace('-', '/')
yag.send(to=TO_EMAIL,subject="{} Rebuild Code: {}".fo... | <p>Please try this updated code.</p>
<p><strong>Update</strong>:</p>
<pre><code>def send_email(status,message):
date = str(datetime.now().date())[-5:].replace('-', '/')
message = "{}\n{}".format(message, 'Sent from Scheduler'
yag.send(to=TO_EMAIL,subject="{} Rebuild Code: {}".format(date, status),contents... | python|yagmail | 0 |
9,972 | 47,898,531 | How to convert JSON into excel file with multisheet? | <p>I have a set of 300+ JOSN files like location_X.json, location_Y.json,... and so on with structure like in file location_X.json I have</p>
<pre><code> {"Cardiologist": [{"name": "Dr. AB", "url": "https://www....-cardiologist?specialization=Cardiologist", "photo": [], "image": "https://images1-....jpg/thumbnail", "a... | <p>you may try Pandas. Its documentation: <a href="https://pandas.pydata.org/" rel="nofollow noreferrer">https://pandas.pydata.org/</a></p>
<p>Basically, what you should do is:</p>
<pre><code>import pandas as pd
import json
json_data = json.load(open('<your_json_file>'))
data = pd.read_json(json_data)
excel_fil... | python|json|excel|csv|xls | 1 |
9,973 | 43,363,991 | Replace column with the count of specific character | <p>I have a data frame that contains a column as the following:</p>
<pre><code>1 string;string
2 string;string;string
</code></pre>
<p>I would like to iterate through the hole column and replace the values with the count of ";" +1 (number of strings) to get:</p>
<pre><code>1 2
2 3
</code></pre>... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.count.html" rel="nofollow noreferrer"><code>str.count</code></a> function:</p>
<pre><code>print (df)
col
1 string;string
2 string;string;string
df['col'] = df['col'].str.count(';') + 1
print (... | python|pandas|numpy | 1 |
9,974 | 48,539,195 | list of columns in common in two pandas dataframes | <p>I'm considering merge operations on dataframes each with a large number of columns. Don't want the result to have two columns with the same name. Am trying to view a list of column names in common between the two frames:</p>
<pre><code>import pandas as pd
a = [{'A': 3, 'B': 5, 'C': 3, 'D': 2},{'A': 2, 'B': 4, 'C'... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.intersect1d.html" rel="noreferrer"><code>numpy.intersect1d</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="noreferrer"><code>intersection</code></a>:</p>
<pre><code>a = np.inters... | python|python-3.x|pandas | 40 |
9,975 | 53,242,872 | Python program won't run correctly when opened from folder or desktop, but works fine when run in IDLE | <p>I have created a simple task-timing program in which the user presses a key to start a timer, and again to stop. The program displays the time elapsed. This all works fine when i run the program, however after this I have the time and task name saved to a file. When run in IDLE (and NetBeans), this save works perfec... | <p>Is there any chance that you can open a command-prompt/terminal-session and execute from there? That would let you grab the trace.</p>
<p>I'm guessing quant has the right of it and you're running into a access/permissions hurdle of some kind. You can also try saving to a filename that doesn't exist yet; maybe it'... | python|stopwatch|traceback | 0 |
9,976 | 72,054,511 | I have trouble with FTX api | <p>I want to get my balance using the FTX api.<p>
Refer to the Python sample code in the <a href="https://docs.ftx.com/?python#authentication" rel="nofollow noreferrer">api docs</a> and change it as follows.<p>
But it returns an error message.<p>
<b>{"success":false,"error":"Not logged in: Inva... | <p>Try changing the url to ftx.us
and the headers to</p>
<pre><code>'FTXUS-KEY': accessKey,
'FTXUS-SIGN': signature,
'FTXUS-TS': str(ts)
</code></pre> | python|api|python-requests | 0 |
9,977 | 68,523,348 | How to apply statististical tests (functions) on pandas dataframe on combination of subsets of data | <p>I have dataframe which is similar to this one.</p>
<pre><code>import pandas as pd
import string
import random
def generate_example_dataframe()-> pd.DataFrame:
"""
This simple function will generate simple dataframe in long format
"""
num = 20 # number of regions udsed... | <p>im also learn other methods from others' answers. i made a solution like this below...</p>
<pre><code># grouping
df['grouping']=df['region']+"_"+df['group']+"_"+df['condition']
for i in df.grouping.unique():
print(i)
t='result_'+i
locals()[t]=stats.ttest_1samp(df.loc[df['grouping']=... | python|pandas|pandas-groupby|statistical-test | 0 |
9,978 | 68,605,299 | ValueError: Cannot convert non-finite values (NA or inf) to integer | <pre><code>df.dtypes
name object
rating object
genre object
year int64
released object
score float64
votes float64
director object
writer object
star object
country object
budget float64
gross float64
company object
runtime float64... | <p>Assuming that the budget does not contain infinite values, the problem may be because you have nan values. These values are usually allowed in floats but not in ints.</p>
<p>You can:</p>
<ol>
<li>Drop na values before converting</li>
<li>Or, if you still want the na values and have a recent version of pandas, you ca... | python|pandas|numpy | 8 |
9,979 | 10,666,304 | Splitting by "," in python | <p>I am trying to split a string by commas ","</p>
<p>For example:</p>
<pre><code>"hi, welcome" I would like to produce ["hi","welcome"]
</code></pre>
<p>however:</p>
<pre><code>"'hi,hi',hi" I would like to produce ["'hi,hi'","hi"]
"'hi, hello,yes','hello, yes','eat,hello'" I would like to produce ["'hi, hello,ye... | <p>You can use the csv module with the <code>quotechar</code> argument, or you can convert your inputs to use the more standard <code>"</code> character for their quote character.</p>
<pre><code>>>> import csv
>>> from cStringIO import StringIO
>>> first=StringIO('hi, welcome')
>>> ... | python|regex|string | 16 |
9,980 | 62,488,326 | How to change button style generated by jinja loop.with bootstrap | <p>I have question on which I can not find answer. I have code that through the loop generate me list of buttons. Button clicked should change its style (background color solid). Html code is made with bootstrap. What can be done to change style of clicked button, when in code structure I have only one link? Below plea... | <p>You have to pass the value of selected list from the view function, let's call it <code>active_list</code>. Then you can test during the loop whether the current item is the selected one:</p>
<pre><code>{% for list in lists %}
<a href="{{ url_for('homepage', list_type=list) }}"
class="btn bt... | python|html|css|jinja2 | 1 |
9,981 | 62,649,364 | Unable to get the summary while building custom model using tensorflow | <p>I have a very simple model as shown below:</p>
<pre><code>import tensorflow as tf
class Model(tf.keras.Model):
def __init__(self, input_shape=None, name="cus_model", **kwargs):
super(Model, self).__init__(name=name, **kwargs)
def build(self, input_shape):
self.dense1 = tf.... | <p>I was able to build the network by modifying the line</p>
<pre><code>model.build(input_shape=input_shape) # Note the .build call
</code></pre>
<p>with</p>
<pre><code>_ = model(tf.zeros([1,10]))
</code></pre>
<p>From <a href="https://www.tensorflow.org/tutorials/customization/custom_layers#implementing_custom_layers"... | python|tensorflow|tensorflow2.0 | 4 |
9,982 | 61,900,938 | Django Template - List not rendering properly | <p>I have the following list which is sent to django template using render function: <code>["9.8 m/s", "9.9 m/s", "1.0 m/s"]</code>.</p>
<p>When the list is printed in javascript function, it shows as: <code>[&quot;9.8 m/s&quot;, &quot;9.9 m/s&quot;, &quot;1.0 m/s&quot;]</code></p>
<p>I have u... | <p>The template engine will HTML <em>escape</em> the strings it renders. You can avoid that with the <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe" rel="nofollow noreferrer"><strong><code>|safe</code></strong> template filter</a>:</p>
<pre><code>var options = {{ option<b>|safe</b> }};
fo... | javascript|python|django|python-3.x|django-templates | 1 |
9,983 | 62,034,224 | Why calling an Azure ML classification model via a webservice API not returning probability scores? | <p>I am new to Azure and also a very low-code budding data scientist (which doesn't seem to be going in my favour). Anyways! I trained a model a couple of days ago with Azure AutoML in ML Studio and registered the most succesful model as a webservice with endpoints. Now, when I call this model using the following Pytho... | <p>This link should help: <a href="https://docs.microsoft.com/en-us/azure/machine-learning/data-science-virtual-machine/how-to-track-experiments" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/machine-learning/data-science-virtual-machine/how-to-track-experiments</a></p>
<pre><code>from azureml.core i... | python|azure | 0 |
9,984 | 61,742,289 | Python : Value does not increase of variable in for and if loop | <p>The code is very simple, but I am not sure why the code is not increasing the value of variable num.</p>
<pre><code>def cal(string):
num = 0
for w in string:
if w.isupper():
num = + 1
print(num)
print(cal('My Name'))
</code></pre>
<p>it's print the value of num as 1 and answer sh... | <p>You are setting <code>num</code> to 1 each time instead of incrementing it. To increment it, use <code>num += 1</code>.</p> | python|string|for-loop | 3 |
9,985 | 61,814,610 | Ipywidgets not interacting in "while True" loop | <p>1)This is the code snippet that I am trying to run.The main idea is that, I want the ipywidgets to be interactive, while the data is constantly being fetched from the data source. And the data is being updated at certain interval using the while loop.The objective is to plot the principal components interactively by... | <p>A fairly rudimentary example that shows how you can run a loop whilst polling for widget changes, but it's not really my area of expertise.</p>
<p>Drag the slider whilst the values are printing and you should see the printed value change to reflect current slider position.</p>
<pre class="lang-py prettyprint-overr... | while-loop|jupyter-notebook|python-3.5|ipywidgets|voila | 1 |
9,986 | 61,802,717 | How to run multiprocess on a windows server with pl/python 3? | <p>I am running a trigger function on INSERT/UPDATE that would create a new process that sends a post request to an api. </p>
<p>on a Ubuntu + PostgresQL 12 docker container running I was able to get the new process to form without an issue with the below code</p>
<pre><code>pid=os.fork()
... do some logic
req = urll... | <p><code>fork()</code> is not supported by <a href="https://docs.python.org/2/library/multiprocessing.html#windows" rel="nofollow noreferrer">windows</a>. </p>
<p>You can achieve the same using the <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow noreferrer">multiprocessing</a> module: ... | python|python-3.x|windows|postgresql|plpython | 2 |
9,987 | 70,272,188 | Duplication of id values in another column in same table django | <p>I am working on one python(django framework) project in which i have one user model which has 1000 users. I want to make one another column named priority id and need to put default id values in that priority id column accordingly (you can see it below).</p>
<div class="s-table-container">
<table class="s-table">
<t... | <pre><code>def save(self, *args, **kwargs):
self.priority_id = self.id
return super().save(*args, **kwargs)
</code></pre> | python|django|django-models|django-admin | 0 |
9,988 | 70,039,432 | How to find date with regular expresions | <p>I have to find some date inside an string with a regular expresions in python</p>
<pre><code>astring ='L2A_T21HUB_A023645_20210915T135520'
</code></pre>
<p>and i'm trying to get the part before the T with shape <code>xxxxxxxx</code> where every x is a number.</p>
<pre><code>desiredOutput = '20210915'
</code></pre>
... | <p>If the astring's format is consistent, meaning it will always have the same shape with respect to the date, you can split the string by '_' and get the last substring and get the date from there as such:</p>
<pre><code>astring ='L2A_T21HUB_A023645_20210915T135520'
date_split = astring.split("_"). # -->... | python | 3 |
9,989 | 70,156,883 | I'm using re.split() and trying to join the elements but it doesn't work. Why is it? | <p>I have a problem and I can't find reason why.
I want to divide the string into 3 parts, and the condition is "integer+Letter+*(optional)"
it works well when the number is one digit, but it doesn't work when the number is two digits.</p>
<p>This is my code:</p>
<pre><code>import re
dartResult = '10S*3T2D*'
... | <p>Why don't you simply define all the elements in your regex?</p>
<pre><code>import re
dartResult = '10S*3T2D*'
out = re.findall(r'\d+\w\*?', dartResult)
</code></pre>
<p>output:</p>
<pre><code>>>> out
['10S*', '3T', '2D*']
</code></pre>
<p>regex:</p>
<pre><code>\d+ # one or more digits
\w # one char... | python|split|python-re | 2 |
9,990 | 63,391,844 | Download GIS data using owslib | <p>I want to create a geopandas dataframe from a url using owslib:</p>
<pre><code>from owslib.wfs import WebFeatureService
url = 'https://somesecreturl.com/geoserver/wms?&authkey=79sd7a9sd-sda798-4531-a8a9-454hj5h3453' #(I've changed the authkey)
wfs = WebFeatureService(url=url)
</code></pre>
<p>Last line is caus... | <p>The "solution" was to uninstall Anaconda and install an older version (Anaconda3-2019.03)</p>
<p>then install packages:</p>
<ul>
<li>geopandas</li>
<li>owslib</li>
</ul>
<p>And update pyproj package</p> | python|anaconda | 0 |
9,991 | 63,518,441 | How to read a bearer token from postman into Python code? | <p>I am trying to create an API that receives arguments from postman. The body of the api contains two arguments:</p>
<pre><code>{
"db":"EUR",
"env":"test"
}
</code></pre>
<p>I parsed these two arguments in the code as below:</p>
<pre><code>parser = reqparse.RequestParser... | <p>The Bearer token is sent in the headers of the request as 'Authorization' header, so you can get it in python flask as follows:</p>
<pre><code>headers = flask.request.headers
bearer = headers.get('Authorization') # Bearer YourTokenHere
token = bearer.split()[1] # YourTokenHere
</code></pre> | python|flask|flask-restful | 10 |
9,992 | 56,603,131 | find_all only scrape the last value | <p>I am trying to scrape a website and I am using find_all but it only returns the last div in the page and ignores the other two! Any idea? </p>
<p>Here is the inspected source by chrome inspector:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippe... | <p>I was able to fix it by looping through id:</p>
<pre><code> for match in soup.find_all('div', id="listDesc"):
print(match.text)
</code></pre> | python|web-scraping|beautifulsoup | 1 |
9,993 | 18,209,697 | pexpect-how to handle the permission denied exception | <p>Could you please help me to correct my python script. The following script is performing scp to target host using python pexpect module. If I get Permission denied exception I want to handle with a local array variable, containing list of password, and proceed with the scp.</p>
<pre><code>local_pass = ["test123","w... | <p>Well, your code looks quite complicated and unreadable.. Why are you solving already solved problems?</p>
<p>I would recommend using the <a href="https://github.com/NetAngels/openssh-wrapper" rel="nofollow">openssh-wrapper</a> module, in combination with ssh keys. This makes life easy:</p>
<p>Your code would then ... | python | 1 |
9,994 | 66,224,399 | Python Negative time difference | <p>I am new to django. I want to calculate the total time. My model counts the time difference - and stores, the view counts the time sum.
It works. But if the time difference is negative(01:00 - 21:00), then I get an error(time data '-1 day, 4:00:00' does not match format '%H:%M:%S'). according to the idea it should b... | <p>If you want to compute the total hours in a <code>datetime.timedelta</code> object, which is what you get when you compute the difference between to <code>datetime.datetime</code> objects, you can use <code>total_seconds</code>:</p>
<pre><code>td = datetime.datetime.now() - datetime.datetime(2021, 2, 15)
total_hrs ... | python|django | 1 |
9,995 | 65,951,082 | How to use db functions in Tortoise ORM | <p>I am trying to write a simple query but using PSQL functions CURRENT_DATE and INTERVAL, for instance:</p>
<pre class="lang-py prettyprint-override"><code>users = await User.filter(created_at__gt="CURRENT_DATE - INTERVAL '30 DAYS'")
</code></pre>
<p>How to make it work? Thanks</p> | <p>Unfortunately, Tortoise ORM processes different queries differently.
For instance:</p>
<ul>
<li>for <code>update</code> query you can use just a string value:</li>
</ul>
<pre class="lang-py prettyprint-override"><code>await User.filter(id=user_id).update(updated_at="now()")
</code></pre>
<ul>
<li>for <code... | python|sql|database|psql|tortoise-orm | 2 |
9,996 | 72,590,361 | SqlAlchemy db.Enum: How to detect it and retrieve the values | <p>I have a function to add a column to a model:</p>
<pre><code>def col(_type, label = "", **kwargs):
c = db.Column(_type, **kwargs)
c.info = {"label":label, "type":""}
return c
</code></pre>
<p>I use it like:</p>
<pre><code> # Job Type
class JTEnum(enum.E... | <p>The first issue I'm seeing in your code is that you default to <code>JTEnum.full.name</code>, which should be the Enum element not its name, then you need to iterate the underlying Enum class of the SQLAlchemy Enum.</p>
<pre class="lang-py prettyprint-override"><code>import enum
import sqlalchemy as db
class JTEn... | python|enums|sqlalchemy | 2 |
9,997 | 68,233,466 | SHAP Exception: Additivity check failed in TreeExplainer | <p>I am trying to create shap values for a single row for the local explanation but I am consistently getting this error. I tried various methods but still couldn't able to fix them.</p>
<p>Things I did so far -</p>
<p>created the randomized decision tree model -</p>
<pre><code>from sklearn.ensemble import ExtraTreesRe... | <p>I'm still not sure why you are transposing or trying to change the shape of your input, as that is not in <a href="https://github.com/slundberg/shap/tree/master/notebooks" rel="nofollow noreferrer">the examples</a>, but I think the solution below should exemplify using <a href="https://scikit-learn.org/stable/module... | python|machine-learning|shap | 2 |
9,998 | 59,103,456 | How to catch exceptions that occur inside a C++ programm that is called using a python subprocess.checkout() call? | <p>I am trying to catch an exception that occurs inside a c++ Programm which i call from a python script using subprocess.checkout() command, but it does'nt seem to work as i intend. Although the Exception is caught, it doesnt have the necessary Information about the cause of exception. I want to print out the exceptio... | <blockquote>
<p>I am trying to catch an exception that occurs inside a c++</p>
</blockquote>
<p>Integer division by zero doesn't generate a C++ exception. On Linux it raises <code>SIGFPE</code> signal.</p>
<p>python3 formats <code>subprocess.CalledProcessError</code> exception better:</p>
<pre><code>Command '['/lh... | python|c++|exception|subprocess | 1 |
9,999 | 62,114,645 | How to build OneHot Decoder in python | <p>I have <code>encoded</code> my <strong>images(masks)</strong> with dimensions <em>(img_width x img_height x 1)</em> with <code>OneHotEncoder</code> in this way:</p>
<pre><code>import numpy as np
def OneHotEncoding(im,n_classes):
one_hot = np.zeros((im.shape[0], im.shape[1], n_classes),dtype=np.uint8)
for i, un... | <p>You have typos with commas and dots with some of your items (e.g. your first list should be <code>[0.1, 0.2, 0.5]</code> instead of <code>[0.1, 0.2, 0, 5]</code>).</p>
<p>The fixed list is:</p>
<pre class="lang-py prettyprint-override"><code>l = [
[[0.1,0.2,0.5],[0.2,0.4,0.7],[0.3,0.5,0.8]],
[[0.3,0.6,... | python|numpy|decoding|one-hot-encoding | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.