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 |
|---|---|---|---|---|---|---|
7,600 | 38,506,481 | How can I edit an object without saved it in Django | <p>There is a problem with my Django project, when I add an object it saves immediatly after that I will be redirected by object id to <strong>server_edit</strong> where I can fill fields. If I fill no fields and push "back" (go to previous page) browser button object will be saved without any data even if <strong>Save... | <p>You should avoid saving object and <strong>then</strong> filling it with data in different view.</p>
<p>Try using generic edit views such as CreateView/EditView or FormView with Django forms (<a href="https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-editing/" rel="nofollow">https://docs.djangopro... | python|django|django-forms | 1 |
7,601 | 30,923,324 | pandas dataframe drop columns by number of nan | <p>I have a dataframe with some columns containing nan. I'd like to drop those columns with certain number of nan. For example, in the following code, I'd like to drop any column with 2 or more nan. In this case, column 'C' will be dropped and only 'A' and 'B' will be kept. How can I implement it?</p>
<pre><code>impor... | <p>There is a <code>thresh</code> param for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html#pandas.DataFrame.dropna" rel="noreferrer"><code>dropna</code></a>, you just need to pass the length of your df - the number of <code>NaN</code> values you want as your threshold:</p>
... | python|pandas | 35 |
7,602 | 40,167,612 | How to keep only the noun words in a wordlist? python NLTK | <p>I have a wordlist, which consists many subjects. The subjects were auto extracted from sentences. I would like to keep only the noun from the subjects. As u can see some of the subjects have adj which i want to delete it.</p>
<pre><code>wordlist=['country','all','middle','various drinks','few people','its reputatio... | <p>First your list is a result of not well tokenized text so i tokenized them again
then search <code>pos</code> of all words to find nouns which pos contains NN :</p>
<pre><code>>>> text=' '.join(wordlist).lower()
>>> tokens = nltk.word_tokenize(text)
>>> tags = nltk.pos_tag(tokens)
>>... | python|nltk|text-processing|wordnet|pos-tagger | 3 |
7,603 | 52,267,945 | How do I differentiate labels when configuring them in tkinter? | <p>Basically, I'm trying to make a list of variables that update themselves each second, but I can only get the last label to update. I'm not too familiar with tkinter and nothing was helping me. I think the main issue is that I've got it in a def, but I don't know any other way, if someone can help me fix my issue, or... | <p>You could use a dictionary to store all your labels, as dictionaries allow for mappings between keys and values. An example of what this might look like for you:</p>
<pre><code>self.labels = {} #Creates an empty dictionary
self.labels["points"] = Label(master, text=Points, anchor='w')
self.labels["points"].pack.pac... | python|tkinter|label|configure | 1 |
7,604 | 51,612,604 | Can't link Python libraries inside C program | <p>I want to run a basic python script inside a C program using Eclipse. This is the code:</p>
<pre><code>#include <Python.h>
int main(int argc, char *argv[])
{
Py_SetProgramName(argv[0]); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
... | <p>Typically <code>-l</code> doesn't require the <code>lib</code> prefix or the <code>.so</code> suffix...</p>
<p>Try using <code>-lpython2.7</code> instead of <code>-llibpython2.7</code>.</p> | python|c|eclipse|linker-errors | 1 |
7,605 | 63,405,505 | How do I make it so when everytime I call a function in the Command Prompt I don't need to open the file again? | <p>Good day people, I want to make a simple dice roll app in which when you press Enter it will print a dice face. My question is: how can I make it so I don't need to open the file again (python dice_roll.py)? I'm a beginner so please don't bully me. Thanks.</p>
<pre><code>import random
def dice1():
print("_... | <p>A simple way is to wrap the main logic inside an infinite loop, and break from it when the user enters a specific word, e.g.</p>
<p>Replace this code:</p>
<pre><code>enter = input("Press Enter to roll the dice")
if enter == "":
roll_dice()
</code></pre>
<p>With this:</p>
<pre><code>while Tru... | python | 0 |
7,606 | 36,485,907 | More Pythonic way of adding attributes to class? | <p>I'm working with datasets from two different webpages, but for the same individual - the data sets are legal info on. Some of the data is available on the first page, so I initialize a Defendant object with the proper info, and set the attributes that I don't currently have the data for to <code>null</code>. This... | <p>First, use default values for any arguments that you're setting to null. This way you don't even need to specify these arguments when instantiating the object (and you can specify any you do need in any order by using the argument name). You should use the Python value <code>None</code> rather than the string <code>... | python|python-2.7|oop | 4 |
7,607 | 19,631,706 | python xml parsing; multiple xml files | <p>I have multiple xml files with similar elements. How to extract the child elements from multiple files? I wrote a sample code which extracts the required elements from a single file but I need to extract from multiple xml files.the major problem here is it should print the required feilds only if admin-server-name e... | <p>Put your code to function and call it for all files.</p>
<pre><code>#!/usr/bin/python
import sys
from xml.dom.minidom import parse
import xml.dom.minidom
def parse_file(filename):
DOMTree = xml.dom.minidom.parse(filename)
domain=DOMTree.documentElement
name=domain.getElementsByTagName("domain-version"... | python|xml|xml-parsing | 0 |
7,608 | 13,334,370 | Django with postgresql - manage.py syncdb returns errors | <p>I'm starting with Django. I had some site set up with SQLite working but after changing DB engine to postgresql manage.py syncdb returns errors.I've been googling for 2 days but still nothing works for me.Postgres user 'joe' has superuser rights and local 'joe' db exists. </p>
<p>Postgresql is running:</p>
<pre><c... | <p>My suggestion would be to go to <code>django.db.backends.postgresql_psycopg2.base</code> and insert a <code>print query</code> so that <code>CursorWrapper</code> looks like.</p>
<pre><code>class CursorWrapper:
...
def execute(self, query, args=None):
print query # New print statement here
tr... | python|django|postgresql | 1 |
7,609 | 13,630,392 | Structuring Decorators in PHP | <p>I'm sort of a novice developer trying to expand my toolbox and learn some more tricks. I recently came across a pattern in Python called "decoration" and I was wondering if/how I could implement this in PHP as I have an existing PHP code base.</p>
<p>Here is a short example of what I mean:</p>
<pre><code>import ti... | <p>Basically no, it's not supported in PHP in any way at all. As far as I know, it's not even on the roadmap for future PHP versions.</p>
<p>Of interest, and slightly relevant: The closest I could think of in PHP-land to what you're after is if you use phpUnit to test your code. phpUnit implements something along thes... | php|python|decorator | 2 |
7,610 | 43,841,463 | Why did I receive lots of warning message when running the TensorFlow example? | <p>I am following the tutorial: <a href="https://www.tensorflow.org/get_started/get_started" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/get_started</a></p>
<p>Why did I receive lots of errors as below? Also, the final loss score is different. The documentation says:</p>
<pre><code>{'global_step'... | <p>It has been clearly mentioned that you are using a temporary folder to store your model. To fix this issue you just have to make a change in the estimator statement. Change</p>
<pre><code>estimator=tf.estimator.LinearRegressor(feature_columns = feature_columns)
</code></pre>
<p>to</p>
<pre><code>estimator=tf.esti... | tensorflow|jupyter | 1 |
7,611 | 53,567,594 | greatest difference of any 3 given numbers-make code effective | <p>I did this in vocareum lab for python but I did not get full points for the correctness and got full points for syntax. Any suggestions on how to make my code more efficient without using inbuilt python functions? Thanks a ton for your help.</p>
<p>Task: find the greatest difference of any given 3 numbers without u... | <p>Just redefine the functions in a reasonable way.</p>
<pre><code>def my_max(a, b):
return a if a >= b else b
</code></pre>
<p>so you can do:</p>
<pre><code>def greatest_difference(a, b, c):
diffs = b-a, c-b, c-a
# avoids the use of the `abs` built-in
for i, diff in diffs:
if diff < 0... | python | 0 |
7,612 | 71,238,211 | Ticklabel wrong in go.Figure | <p>I have build a go.Bar-Figure from a data frame with a time series index. I'm using the resample("Y").sum() function to show values for every of of each category. It works fine. But the tick label is wrong.
As you can see the tick label shows for example "2008". But the summarised values are in th... | <p>This is my solution for a correct label using tick mode, tick0 dtick:</p>
<pre><code>fig_jahr.add_trace(go.Bar(x=df_jahresniederschlag.index,y=df_jahresniederschlag["Wert"], name=name)
fig_jahr.update_xaxes(
tickangle = 45,
title_text = "Jahr",
title_font =... | python|pandas|plotly|bar-chart | 0 |
7,613 | 52,771,402 | Python 3 get child elements (lxml) | <p>I am using lxml with html:</p>
<pre><code>from lxml import html
import requests
</code></pre>
<p>How would I check if any of an element's children have the class = "nearby"
my code (essentially): </p>
<pre><code>url = "www.example.com"
Page = requests.get(url)
Tree = html.fromstring(Page.content)
resultList = Tre... | <p>I tried to understand why you use <code>lxml</code> to find the element. However <code>BeautifulSoup</code> and <code>re</code> may be a better choice.</p>
<pre><code>lxml = """
<p class="result-info">
<span class="result-meta">
<span class="nearby">
... #th... | python|html|python-requests | 1 |
7,614 | 47,903,710 | autodoc: base classes are shown with full name instead of respecting the import | <p>I hope I find a solution here for this quite intricate problem.</p>
<p>I use sphinx and intersphinx to document my project.</p>
<p>I have a class that inherits from mongoengine.Document.</p>
<p>When I build sphinx docs using sphinx-apidoc and the sphinx-build (via the autogenerated Makefile by sphinx-quickstart),... | <p>The <code>__module__</code> attribute holds the name of the module in which the class was defined. The value of <code>Document.__module__</code> is "mongoengine.document".</p>
<p>The attribute is writable, so a workaround is to add the following line to the code:</p>
<pre><code>Document.__module__ = "mongoengine"
... | python|python-sphinx | 1 |
7,615 | 47,725,949 | JSON pretty printing isn't working in Python | <p>As far as I can tell, this code should work.</p>
<pre><code>import json
with open('path', 'r') as infile:
data = json.load(infile)
print(json.dumps(data, indent=4))
</code></pre>
<p>But it doesn't. I get this:</p>
<pre><code>"b'{\"Markets\":[{\"ID\":2461,\"Name\":\"Who will be elected German chancellor in... | <p>How did you produce this file? It's not a JSON object, it's a <em>JSON string</em> containing a <em>Python repr</em> containing a string of your original JSON. Or something like that. Which you can tell because of all the extra backslashes and the leading <code>b'</code> character.</p>
<p>This works:</p>
<pre><cod... | python|json | 2 |
7,616 | 34,317,070 | Reading characters from a file into a list causing problems | <p>I have some code which chooses a random word from a list of words and displays it on a label. The user then has to retype this word correctly to score a point.
I decided to use a text file to store the words and read it into a list in the program but this is causing problems.</p>
<pre><code>try:
from tkinter im... | <p>I think the error comes from here:</p>
<pre><code>with open("WORDS_FILE.txt") as f:
WORDS = list(f.readlines()) #Carriage return is given in each line.
</code></pre>
<p>In this part, you read each line of the file and create a list of it, using <code>list</code> constructor. However, each line has a carriage r... | python|list|file|tkinter | 0 |
7,617 | 72,697,000 | Elegant way of finding expressions | <p>I have some troubles finding some <strong>clear</strong> and <strong>readable</strong> solution to my problem.
So I have some messages that all have the same format :</p>
<pre class="lang-py prettyprint-override"><code>message = "sender -> receiver : message_name [param1 : value1, ..., param_n : value_n] \
L... | <p>You can definitely use regex, but it is probably good to know if that is always the format (is the message code generated? are the spaces always the same? are <code>Loop</code>, <code>Par</code>, and <code>Par_id</code> always there? are the numbers always integers?). If so, the regex can be quite simple (not sure a... | python|string | 1 |
7,618 | 39,466,757 | Fill MISSING values only in a dataframe (pandas) | <p>What I have in a dataframe:</p>
<pre><code>email user_name sessions ymo
a@a.com JD 1 2015-03-01
a@a.com JD 2 2015-05-01
</code></pre>
<p>What I need:</p>
<pre><code>email user_name sessions ymo
a@a.com JD 0 2015-01-01
a@a.com JD 0 2015-02-01
a@a.com JD 1... | <p>I try create more general solution with <code>periods</code>:</p>
<pre><code>print (df)
email user_name sessions ymo
0 a@a.com JD 1 2015-03-01
1 a@a.com JD 2 2015-05-01
2 b@b.com AB 1 2015-03-01
3 b@b.com AB 2 2015-05-01
mbeg = pd.period... | python|pandas | 2 |
7,619 | 39,637,407 | How do I prevent `format()` from inserting newlines in my string? | <p>It might be my mistake, but <code>cmd = 'program {} {}'.format(arg1, arg2)</code> will always get a newline between the two args... like this
<code>program 1\n2</code></p>
<p>what should i do to put them in one line (<code>cmd</code> need to be passed to system shell)?</p> | <p><code>arg1</code> contains <code>\n</code>. Use <a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="nofollow">strip()</a></p>
<pre><code>cmd = 'program {} {}'.format(arg1.strip(), arg2.strip())
</code></pre> | python|string-formatting | 3 |
7,620 | 16,077,535 | Django modelchoicefield submit | <p>I have a form that is shown as a dropdown list at the template. When the user selects one option, a javascript function is called and the page reloaded.
I want to capture the value of the selected option using request.POST.get(...), but I can't manage to set the submission as POST. I have found some approaches usin... | <p>Submit the form on change</p>
<pre><code>class CronForm(forms.Form):
days = forms.ModelChoiceField(queryset=Date.objects.all().order_by('alias'),
widget=forms.Select(attrs={"onChange":'submit()'}))
</code></pre>
<p>And edit your template to</p>
<pre><code><form method=post>
</code></pre> | javascript|python|html|django|html-select | 5 |
7,621 | 16,123,529 | Handling all but one exception | <p>How to handle all but one exception?</p>
<pre><code>try:
something
except <any Exception except for a NoChildException>:
# handling
</code></pre>
<p>Something like this, except without destroying the original traceback:</p>
<pre><code>try:
something
except NoChildException:
raise NoChildExce... | <p>The answer is to simply do a bare <code>raise</code>:</p>
<pre><code>try:
...
except NoChildException:
# optionally, do some stuff here and then ...
raise
except Exception:
# handling
</code></pre>
<p>This will re-raise the last thrown exception, with original stack trace intact (even if it's been ... | python|exception|exception-handling|error-handling | 77 |
7,622 | 32,061,589 | Function arguments inheriting defaults from other function | <p>Let's say there's a function in a Python library (let's call it <code>mymodule</code>):</p>
<pre><code>def some_func(a,b='myDefaultValue'):
return some_computation
</code></pre>
<p>and then there's another function in another module that calls it,</p>
<pre><code>import mymodule
def wrapper(a,b):
return so... | <p>You can use <a href="https://docs.python.org/2/faq/programming.html#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" rel="nofollow noreferrer">argument unpacking</a> to accomplish this:</p>
<pre><code>In [1]: def some_func(a,b='myDefaultValue'):
...: print a, b
...:
In [2]: def... | python | 2 |
7,623 | 38,592,504 | Convert a list of lists into a nested dictionary | <p>I am trying to convert a list of lists into a nested dictionary:</p>
<p>My code:</p>
<pre><code>csv_data={}
for key, value in csv_files.iteritems():
if key in desired_keys:
csv_data[key]=[]
for element in value:
csv_data[key].append(element[1:])
</code></pre>
<... | <p>Suppose I demonstrate the use of <code>zip()</code> on one of your keys, <code>Network</code>:</p>
<pre><code>>>> network = [
['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'],
['0.3', '0.1', '0.3']
]
</code></pre>
<p><code>zip()</code>ing the two lists will yield a set of tuples that can be turn... | python|list|dictionary | 4 |
7,624 | 38,845,494 | AttributeError: 'module' object has no attribute 'doc | <p>i am a beginner and i trying to model system dynamic model using python programming.the problem is when i trying to print the components of the sd model, the error message comes out like this: </p>
<pre><code>"AttributeError: 'module' object has no attribute 'doc'"
</code></pre>
<p>my code:</p>
<pre><code>import ... | <p>That may be my fault - I had to move the <code>.doc()</code> function to the model object instead of the components object as a way to work towards including Vensim macros properly. If it's still an issue, may want to update to the latest release (0.7.4). If that doesn't help either, then we may have to fix somethin... | python|python-2.7|ipython | 0 |
7,625 | 40,750,287 | How to recursively traverse a tree and create a list of visited nodes in python | <p>I have defined a class Tree which consists of a list of TreeNodes as below:</p>
<pre><code>class Tree(object):
def __init__(self, name, nodes):
self.name = name
self.nodes = nodes
class TreeNode(object):
def __init__(self, name, parent):
self.name = name
self.parent = parent... | <p>Stepping through the method using a <a href="https://docs.python.org/2/library/pdb.html" rel="nofollow noreferrer">debugger</a> is very helpful in working out the path that the code takes.</p>
<p>Using this I can see that the method initially follows the else branch, it is only the child call to <code>self.allParen... | python|algorithm|recursion|tree | 1 |
7,626 | 68,078,989 | '>' not supported between instances of 'QuerySet' and 'int' in Django | <p>this is my code:</p>
<pre><code> now = datetime.datetime.now()
before_requests = MyModel.objects.filter(expired_at__lte=now)
if before_requests < 0:
# some code
</code></pre>
<p>and i have this error:</p>
<pre><code>DateTimeField MyModel.expired_at received a naive datetime (2021-06-22 11:34:44.810749)... | <pre><code>from django.utils import timezone
before_requests = MyModel.objects.filter(expired_at__lte=timezone.now())
</code></pre> | python|django | 0 |
7,627 | 26,119,088 | Convert number to corresponding words | <p>I need to develop a piece of code that converts a number to the corresponding words, e.g. <code>1</code> -> <code>"One"</code>, <code>2</code> -> <code>"Two"</code></p>
<p>Is there any function in Python to do this task?</p> | <p>The answer to this question is "no". There is no function <strong>in Python</strong> to do this task.</p>
<hr>
<p>If you "have to <strong>develop code</strong> to do it" (your words), then using a builtin wouldn't really be a valid solution, perhaps?</p>
<p>If you have to develop code to do it, you need better s... | python|python-2.7 | 2 |
7,628 | 2,016,006 | Search a file for strings from a second file | <p>I have two files. The first file contains a list of 6 character keys (SA0001, SA1001, etc.). The second file contains a list of dates and amounts where the first six positions will match the key in the first file. I want to verify that every key in the first file has at least one match in the second file. There may ... | <p>Use sets instead:</p>
<pre><code>set1=set(line[:6] for line in open('file1.txt'))
set2=set(line[:6] for line in open('file2.txt'))
not_found = set1 - set2
if not_found:
print "Some keys not found: " + ', '.join(not_found)
</code></pre> | python | 3 |
7,629 | 32,281,830 | Can't install jpeg because conflicting ports are active: libjpeg-turbo | <p>I am running into an issue with libjpeg-turbo trying to install vsftpd with Mac Ports. I'm running on OS X 10.10.5.</p>
<pre><code>David-Laxers-MacBook-Pro:phoenix_pipeline davidlaxer$ conda -V
conda 3.16.0
David-Laxers-MacBook-Pro:phoenix_pipeline davidlaxer$ java -version
java version "1.8.0_05"
Java(TM) SE Ru... | <p>The problem is that both the <code>libjpeg-turbo</code> and the <code>jpeg</code> port in MacPorts provide <code>libjpeg.dylib</code> and corresponding headers (consequently, they conflict with each other and cannot be installed simultaneously), but the <code>jpeg</code> port ships <code>libjpeg.9.dylib</code>, whic... | python|ftp|macports | 4 |
7,630 | 43,960,257 | too many values to unpack calling cv2.findContours | <p>I am a python beginner . I was trying to run this code :</p>
<pre><code>#applying closing function
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
closed = cv2.morphologyEx(th3, cv2.MORPH_CLOSE, kernel)
#finding_contours
(cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_S... | <p>It appears that you're using OpenCV version 3.x, while writing code intended for the 2.x branch. There were some API changes between those two branches. Since you're using Python, you have a handy help available -- make sure to use it, along with the documentation.</p>
<p>OpenCV 2.x:</p>
<pre><code>>>> im... | python|python-2.7|opencv | 10 |
7,631 | 32,989,841 | Pushing the PubMed Data to Kafka | <p>In the PubMed Data Source, I need to push the Output into a Kafka queue..Each source could be viewed as a Kafka Topic. (I know the concepts in Kafka and explored Kafka using Python) </p>
<p>I am able to view the PubMed Data(s) through FireFTP. </p>
<p>Can anyone help how to proceed forward?</p> | <p>You will want to use a service that downloads the data from FTP and spools it to Kafka. Apache Flume does exactly that. It' s quite easy to configure. You can either use a customer source for FTP <a href="https://github.com/keedio/flume-ftp-source" rel="nofollow">https://github.com/keedio/flume-ftp-source</a> or use... | python|ftp|apache-kafka|pubmed|kafka-python | 0 |
7,632 | 32,848,973 | Python, Numpy, User Guide 1.9.1. 'StringIO' what is correct alternative with later python release? | <p>Beginner - have been self learning over last 12 months to use Terminal (on Mac OSX10.10.5), Unix basics, R, Python, and python associated modules and applications. Using Python 3.4.3 |Anaconda 2.1.0 (x86_64). </p>
<p>I am working through the numpy-user-1.9.1.pdf (<a href="https://docs.scipy.org/doc/numpy/numpy-user... | <p>You're right that <code>StringIO</code> is <a href="https://docs.python.org/3.0/whatsnew/3.0.html" rel="nofollow">no longer available in Python3</a>. It's been replaced by the <code>io</code> module.</p>
<p>Instead of this in Python 2:</p>
<pre><code>import numpy as np
from StringIO import StringIO
data = "1, 2, 3... | python|numpy | 2 |
7,633 | 34,570,768 | identical dicts giving error in test cases | <p>DRF API response.data</p>
<pre><code>respone.data = {'created': 1, 'status': 1}
</code></pre>
<p>and other data is from serializer.</p>
<pre><code>MySerializer(user_obj, context={'request': self.request}).data
{'created': 1, 'status': 1}
self.assertEqual(d1,d2) gives difference. Apparently there is no difference... | <p>DRF's Serializer <code>.data</code> method return an OrderedDict which is subclass of dict:</p>
<pre><code>return OrderedDict([
(field_name, field.get_value(self.initial_data))
for field_name, field in self.fields.items()
if (field.get_value(self.initial_data) is not empty) and... | python|django-rest-framework | 0 |
7,634 | 12,583,595 | whats wrong with my function that im trying to write to a txt.file? | <p>Im a newbie and im stumped. I asked another <a href="https://stackoverflow.com/questions/12582907/how-can-i-write-this-function-that-mostly-prints-to-a-file">question</a> and i tried the solution and im hitting another error. In this question ill include my whole code to be as specific as possible. I would love to j... | <p>You need to turn your old <code>print "Power:", pow, pow_mod()</code> line into a string to append:</p>
<pre><code>sheet.append("Power: " + str(pow) + ' ' + pow_mod())
</code></pre>
<p>Or use a formatter:</p>
<pre><code>sheet.append("Power: {0} {1}".format(pow, pow_mod()))
</code></pre>
<p>because <code>.append(... | python|python-2.7 | 4 |
7,635 | 12,270,645 | Can you make a python subprocess output stdout and stderr as usual, but also capture the output as a string? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/4335587/wrap-subprocess-stdout-stderr">Wrap subprocess' stdout/stderr</a> </p>
</blockquote>
<p>In <a href="https://stackoverflow.com/questions/9859446/subprocess-output-to-stdout-and-to-pipe">this question... | <p>This example seems to work for me:</p>
<pre><code># -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
import subprocess
import sys
import select
p = subprocess.Popen(["find", "/proc"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = []
stderr = []
while True:
reads = [p.stdout.fileno(), p.stderr.... | python|subprocess | 38 |
7,636 | 12,370,968 | Frame range into chunks | <p>How to make certain frame range (ie. 1-100) break into 4 equal frame ranges (like 1-25, 26-50, 51-75, 75-100 or anything similiar). I need first and last digit from every chunked frame range.</p> | <pre><code>def chunk_range(first, last, howmany):
size = ((last - first + 1) + (howmany - 1)) // howmany
while first <= last:
next = first + size
yield first, min(next - 1, last)
first = next
list(chunk_range(1, 100, 4))
</code></pre>
<p>returns</p>
<pre><code>[(1, 25), (26, 50), (... | python|range|frame|chunks | 4 |
7,637 | 7,968,406 | How can I make the icons in an IconView spread out evenly? | <p>I have a gtk.IconView with several icons in it. Sometimes I will resize the window to see more icons. When I do this, the extra space generated isn't distributed evenly between all the columns. Instead, it all gets put on the right until there's enough space for a new column.</p>
<p>I'm not seeing anything in <a hr... | <p>We have encountered that problem in Ubuntu Accomplishments Viewer, and as we managed to solve it, I'll present our solution.</p>
<p>The trick is to <strong>place the GtkIconView in a GtkScrolledWindow</strong>, and set it's hscrollbar_policy to "always". Then, a check-resize signal has to be used, to react when the... | python|resize|gtk|window|pygtk | 1 |
7,638 | 332,255 | Difference between class foo and class foo(object) in Python | <p>I know <code>class foo(object)</code> is an old school way of defining a class. But I would like to understand in more detail the difference between these two.</p> | <p>Prior to python 2.2 there were essentially two different types of class: Those defined by C extensions and C coded builtins (types) and those defined by python class statements (classes). This led to problems when you wanted to mix python-types and builtin types. The most common reason for this is subclassing. If... | python | 52 |
7,639 | 41,710,046 | SVD++ vectorization with numpy or tensorflow | <p>I want to implement SVD++ with numpy or tensorflow. <br>
( <a href="https://pdfs.semanticscholar.org/8451/c2812a1476d3e13f2a509139322cc0adb1a2.pdf" rel="nofollow noreferrer">https://pdfs.semanticscholar.org/8451/c2812a1476d3e13f2a509139322cc0adb1a2.pdf</a> ) <br>
(4p equation 4)</p>
<p><a href="https://i.stack.imgu... | <p>Try this. </p>
<pre><code>sum_y = []
for user in range(num_users):
mask = np.repeat(r[user,:][None,:],latent_dim, axis=0)
sum_y.append(np.sum(np.multiply(y, mask),axis=1))
sum_y = np.asarray(sum_y)
r_hat = (np.dot(q.T,sum_y.T)).T
print r_hat
</code></pre>
<p>It eliminates the enumerate loop, and also the ... | python|numpy|tensorflow|vectorization|svd | 0 |
7,640 | 47,251,952 | How to install Python ttk themes | <p>This is my first post on SO, so please feel free to correct me if I'm doing anything wrong!</p>
<p>I am making a simple GUI for my Raspberry Pi (that runs Raspbian stretch) on Windows (because I can use PyCharm on there).
I am would like to install third party themes from <a href="https://github.com/RedFantom/ttkth... | <p>appJar's support for ttk is still in development, but you can try overriding the default style:</p>
<pre><code>from ttkthemes import ThemedStyle
app = gui(useTtk=True)
app.ttkStyle = ThemedStyle(app.topLevel)
app.ttkStyle.set_theme("plastik")
</code></pre>
<p>This tells appJar to use ttk, but then replaces the sty... | python-3.x|tkinter|ttk | 4 |
7,641 | 70,904,128 | Python print hyperlink in gnome-terminal | <p>I can use this special escape sequence to print a hyperlink in bash:</p>
<pre class="lang-sh prettyprint-override"><code>echo -e '\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n'
</code></pre>
<p>Result (Link I can click on):</p>
<pre class="lang-sh prettyprint-override"><code>This is a link
</code></pre>
<p... | <p>From <a href="https://stackoverflow.com/a/21786287/1765658">This answer</a>, after some tries:</p>
<pre><code>print('\x1b]8;;' + 'http://example.com' + '\x1b\\' + 'This is a link' + '\x1b]8;;\x1b\\\n' )
</code></pre>
<p>Then better:</p>
<pre><code>print( '\x1b]8;;%s\x1b\\%s\x1b]8;;\x1b\\' %
( 'http://example... | python|hyperlink|gnome-terminal | 2 |
7,642 | 11,706,633 | Create and arrange class instances into grid | <p>I want to arrange instances of a Room class into a grid for use in a game. Here is the class:</p>
<pre><code>class Room:
def __init__(self, name, x, y):
self.name = name
self.pos = (x, y)
</code></pre>
<p>What is the best way to assign x and y values to instances so that no two instances are th... | <pre><code>import itertools
for i, j in itertools.product(xrange(3), repeat=2):
room = Room("%s %s" % (i, j), i, j)
</code></pre>
<p>Cheers.</p> | python|class|loops|data-structures | 5 |
7,643 | 58,267,386 | how to plot 8x8 correlation matrix | <p>I am trying to plot an <code>8x8 correlation matrix</code> between the different feature scores and the corresponding chances of admit. May I know how I am supposed to do so?</p>
<pre><code>import tensorflow as tf
import numpy as np
import pylab as plt
from sklearn.model_selection import train_test_split
from sklea... | <p>What about </p>
<pre><code>import matplotlib.pyplot as plt
cors = df.corr()
plt.matshow(cors)
plt.yticks(range(cors.shape[1]), cors.columns, fontsize=7)
plt.xticks(range(cors.shape[1]), cors.columns, fontsize=7, rotation=90)
plt.colorbar()
</code></pre>
<p>to use all except "Serial No" column use this cors instead... | python|python-3.x|pandas | 1 |
7,644 | 58,424,864 | How Can Static Variables Within a Python Class Be Used in an Instance of the Class | <p>In other languages, static variable are only accessible through the class name, and do not relate at all to an instance of that class.</p>
<p>I've been following the Django <a href="http://polls.apps.PollsConfig" rel="nofollow noreferrer">Polls App Tutorial</a>. It seems that when a model is declared, the fields o... | <p>From what I know, <code>models.Model</code> has a meta class called <code>ModelBase</code>. So before a <code>Question</code> class create, the meta class will be triggered and attach attributes to a class. So when the class <code>Question</code> is created, it's already have that attribute and value. <code>Question... | python|django | 2 |
7,645 | 58,567,606 | Why is this Boolean false? | <p>Why is Python saying that 'e' is not found in strvowel?</p>
<p>I have tried formatting the string as:
'aeiouAEIOU' but that doesn't work either</p>
<pre><code>vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
strvowel = "'a' 'e' 'i' 'o' 'u' 'A' 'E' 'I' 'O' 'U'"
if w[0] not in vowel:
PLw = []
... | <p>Assuming that variable <code>w</code> is the word <code>yesterday</code> per your example, a good way to search for it would be to define a function and return the first occurance.</p>
<pre class="lang-py prettyprint-override"><code>vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
w = "yesterday"
def find... | python|string|list|loops|iteration | 1 |
7,646 | 33,722,076 | Adding a new index row to an existing dataframe and sorting by it | <p>I have a large pandas dataframe, with time series data and a rather large multiindex. Said index contains various information about the time series, such as for example location, datatype and so on.</p>
<p>Now I want to add a new row to the index, with an integer (or float, doesnt really matter), containing a dista... | <pre><code>In[1]:
import pandas as pd
import numpy as np
header=pd.MultiIndex.from_product(
[['location1','location2'],['S1','S2','S3']],
names=['loc','S'])
df = pd.DataFrame(np.random.randn(5, 6),
index=['a','b','c','d','e'], columns = header)
print(df)
Out[1]:
loc location1 ... | python|sorting|pandas|indexing|multi-index | 2 |
7,647 | 33,679,771 | Homebrew python formula pip installation | <p>The Homebrew python formula says it installs pip & setuptools, but pip isn't in my path, and the following find doesn't return any results:</p>
<pre><code>sudo find / -name pip -type f
</code></pre>
<p>How can I get pip & setuptools to work on my machine? It's running OS X 10.11.1.</p>
<p><strong>Update<... | <p>Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include pip by default, so you may have pip already.</p>
<p>SetupTools -- Easily download, build, install, upgrade, and un-install Python packages</p>
<p>Please look, <a href="https://pypi.python.org/pypi/setuptools" rel="nofollow">https://py... | python|python-2.7|pip|homebrew|setuptools | 1 |
7,648 | 46,961,454 | python custom exception defined in other module is not caught | <p>Let me sum up :</p>
<p>I have a module containing two classes (note : this module is in a package) : </p>
<p>a custom Exception :</p>
<pre><code>class MYAUTHError(Exception):
def __init__(self, *args, **kwargs):
print('--- MYAUTHError!!! ---')
</code></pre>
<p>and a class using this exception (here a... | <p>By trying to reproduce in a small example, I realized that it comes from my module organization... <strong>EDIT : And a wrong way to import module inside a packlage</strong></p>
<p>Let sum up with a example : there are 2 packages (pack1 and pack2).
The organization on filesystem is this :</p>
<pre><code>a_directory
... | python|exception|exception-handling | 3 |
7,649 | 30,118,944 | How to run bash script with commands in tests in vagrant? | <p>Running commands or script lines with simple tests, like <code>-e</code>, in <code>vagrant</code> using the <code>ssh</code> subcommand works fine (e.g. </p>
<pre><code>vagrant ssh -c 'if ! [ -e file.deb ] ; then wget http://a.b/file.deb; fi'
</code></pre>
<p>as soon as string comparison and command execution <cod... | <p>With knowledge of <a href="https://stackoverflow.com/questions/305035/how-to-use-ssh-to-run-shell-script-on-a-remote-machine">How to use SSH to run a shell script on a remote machine?</a> it's possible to connect to vagrant using</p>
<pre><code>ssh -p [port] -i [keyfile] vagrant@localhost 'bash -s' < script.sh
... | python|linux|bash|vagrant | 0 |
7,650 | 27,885,243 | How do max and min function work? | <p>I have below dictionary:</p>
<pre><code>d = {1: 'zz', 2: 'we', 'as': 'dfda', 'x': 'zyz'}
</code></pre>
<p>And <code>max</code> and <code>min</code> return following:</p>
<pre><code>max(d)
'x'
min(d)
1
</code></pre>
<p>How do <code>max</code> and <code>min</code> really work in this case?</p> | <p><code>max</code> and <code>min</code> work on iterables. If you try to convert a dictionary into an iterable, you get back its keys. So, <code>max(d)</code> is sort of the same as <code>max(1,2,'as','x')</code>. There are some details on the ordering of the various builtin types <a href="https://docs.python.org/3/li... | python|python-2.7 | 2 |
7,651 | 43,294,421 | Binary mask from tf.nn.top_k indices for 4-D tensor in Tensorflow? | <p>I have a 4-D tensor of shape (10, 32, 32, 128). I want to generate a binary mask for all top N elements. </p>
<pre><code>arr = tf.random_normal(shape=(10, 32, 32, 128))
values, indices = tf.nn.top_k(arr, N=64)
</code></pre>
<p>My question is how to get a binary mask of same shape as <code>arr</code> using the <cod... | <p>If someone is looking for the answer: here it goes.</p>
<pre><code>K = 64
arr = tf.random_normal(shape=(10, 32, 32, 128))
values, indices = tf.nn.top_k(arr, k=K, sorted=False)
temp_indices = tf.meshgrid(*[tf.range(d) for d in (tf.unstack(
tf.shape(arr)[:(arr.get_shape().ndims - 1)]) + [K])], indexing='ij')
... | tensorflow | 3 |
7,652 | 48,620,526 | How to use webdriver as context manager | <p>I'm trying to use <code>ChromeDriver</code> within with block to make the code look better and get rid of using <code>driver.quit()</code> command in the end. However, It doesn't seem to work. As soon as the browser opens, it throws the following error. Perhaps, I doing something wrong. Ain't there any way to do so?... | <p>Now it's added to selenium (<a href="https://github.com/SeleniumHQ/selenium/pull/5919" rel="noreferrer">SeleniumHQ/selenium#5919</a>) so you can simply use the original approach from your question:</p>
<pre><code>from selenium import webdriver
with webdriver.Chrome() as wd:
res = wd.get('https://stackoverflow.... | python|python-3.x|selenium|selenium-webdriver|web-scraping | 24 |
7,653 | 20,319,091 | gevent Open Shift force HTTPS | <p>I have a web.py app running on OpenShift via gevent using the Python 2.7 community cart. I want to force all connections to go through https. There is a good tutorial on OpenShift for doing this with apache, but what about for gevent?</p>
<p>Here is my app.py, it's basically the default one from the Python 2.7 co... | <p>I'd suggest using nginx to terminate SSL (https) connections and proxy requests to your application. Here is the simple nginx config</p>
<pre><code>user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
access_log /var... | python|https|web.py|openshift|gevent | 1 |
7,654 | 67,166,529 | Office365 IMAP sometimes fetching new emails not working | <p>I connect to outlook.office365.com for synchronizing emails by library IMAPClient (Python). By IDLE mechanizm I receive changes on server for example new email in folder INBOX. After that I fetch for mails with UID {last_synced_uid}:* - this should give me all mails after last sync (UID are always incremented).</p>
... | <p>I will answer my own question - selecting the same folder on IMAP connection many times could generate this problem.</p> | python|office365|imap|imapclient | 0 |
7,655 | 4,563,757 | Cannot run any multiprocessing script in PythonWin | <p>I have updated this question to show my problem in a multiprocessing script that doesn't run from PythonWin (by pressing F5), but runs from command prompt.
My script:-</p>
<pre><code>"""
File Name: simple multiprocess example.py
Description:
A very basic multiprocessing script to show the use of daemon.
There are t... | <p>You need to save the code you want to run in a .py file. multiprocessing does not support execution of code that was merely entered in the interactive mode.</p> | python|multiprocessing | 4 |
7,656 | 48,035,961 | How to hide the next parameter appearing to the url in Django? | <p>When I am starting my Django project from the login page the url is showing like this:</p>
<pre><code>http://127.0.0.1:8000/login/?next=/
</code></pre>
<p>But what i want only this:</p>
<pre><code>http://127.0.0.1:8000/login
</code></pre>
<p>What is the way to hide this next parameter appearing to the url?
I hav... | <p>This behavior is located in the <a href="https://github.com/django/django/blob/master/django/contrib/auth/mixins.py#L35" rel="nofollow noreferrer">AccessMixin</a> in django.contrib.auth.</p>
<p>If you dislike it - inherit from <code>LoginRequiredMixin</code> and overwrite <code>redirect_field_name</code> to return ... | python|django | 1 |
7,657 | 51,241,445 | How to filter records for fixed, regular blocks of time in PySpark? | <p>I'm interested in capturing user behaviour during specific hours of the day, everyday. Suppose I have a dataframe with the columns</p>
<pre><code>+-------+-----+----------+
| start | end | activity |
+-------+-----+----------+
</code></pre>
<p>Both <code>start</code> and <code>end</code> are in Unix timestamps. Is... | <p>The below solution works for your problem</p>
<p>Create a DataFrame, assuming you have unix timestamp</p>
<pre><code>l1 = [(1541585700,1541585750,'playing'), (1531305900,1541589300, 'fishing'), (1541589400,1541589500,'working'),(1530919800, 1530923400, 'across-night')]
df = sqlContext.createDataFrame(l1, ['start',... | python|dataframe|pyspark | 0 |
7,658 | 17,318,868 | How to extract programmatically video frames? | <p>I need programmatically extract frames from mp4 video file, so each frame goes into a separate file. Please advise on a library that will allow to get result similar to the following VLC command (<a href="http://www.videolan.org/vlc/" rel="nofollow noreferrer">http://www.videolan.org/vlc/</a>):</p>
<pre><code>vlc v... | <p>Consider using the following <a href="http://popscan.blogspot.fr/2012/08/reading-and-processing-video-frames.html" rel="nofollow">class</a> by Popscan. The usage is as follows:</p>
<pre><code>VideoSource vs = new VideoSource("file://c:\test.avi");
vs.initialize();
...
int frameIndex = 12345; // any frame
BufferedI... | java|python|haskell|erlang|video-processing | 1 |
7,659 | 64,184,162 | cant display data from mysql db in a html page | <p>here is the routing code:</p>
<pre><code>@app.route("/notice_disp" , methods=['POST','GET'])
def notice_disp():
cur=mysql.connection.cursor()
result=cur.execute("SELECT * FROM notices")
if result > 0:
data=cur.fetchall()
c... | <p><code>fetchall()</code> returns a list of <a href="https://docs.python.org/3/library/stdtypes.html?highlight=tuple#tuple" rel="nofollow noreferrer">tuples</a>. Therefore you have to use brackets to access each tuple's elements:</p>
<pre><code>{% for row in data %}
<tr>
<td>{{ row[0] }}</td>
... | python|html|mysql|flask | 1 |
7,660 | 70,474,507 | Connect nodes to neighbours via line of sight (straightline) | <p>So I have a structure that is similar to a maze, but with much more open space. And for each node in the structure, I would like to find all it's 'neighbours' (nodes are neighbours if they are in line of sight, i.e no walls blocking the straight line between them).</p>
<p>Here is a little image to help explain what ... | <p>You might want to read Monge's book on projective geometry :)</p>
<p>Let's use an occlusive screen around each node, a square is computationally easy, a circle needs more math. The screen is a collection of edges that hide space from the node. The screen.occlude() method takes one of your walls as input an calculat... | python|algorithm|path-finding|a-star|maze | 1 |
7,661 | 73,145,923 | Update screen on button click Django | <p>Say I have a screen that looks like this:</p>
<pre><code>Times clicked: 0
[button]
</code></pre>
<p>And every time I click the button, the times clicked would increment by 1. How would I go about doing this?</p> | <p>You've tagged this question with django and django forms, so I'll ignore javascript based solutions and assume you want this to be persistent and universal (in that every user sees the same number).</p>
<p>assuming an app called count_things</p>
<p>start with count_things/models.py</p>
<pre><code>from django.db impo... | python|django|django-forms | 1 |
7,662 | 55,840,819 | Changing QLabel on a push of a button each time its pressed it's overwrited | <p>I want to print out the average of a set of 3 numbers the user inputs. However ever time I push the button the text overlaps eachother</p>
<pre class="lang-py prettyprint-override"><code>def Comp
Average = QtGui.QLabel("The Students Average is " + str(self.average), self)
Average.move(400,300)
Average.s... | <p>You are creating a new QLabel each time you press the button, instead you must reuse the QLabel.</p>
<pre class="lang-py prettyprint-override"><code>from PyQt4 import QtCore, QtGui
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.average_l... | python|pyqt|pyqt4|qlabel|qpushbutton | 0 |
7,663 | 55,741,782 | Deliver a parameter from betweenness_centrality in Networkx | <p>When using the <code>betweenness_centrality(G, k=None, normalized=True, weight=None, endpoints=False, seed=None)</code>, how could I give the parameter <code>weight</code> form a graph <code>G(G=nx.graph())</code>?</p>
<pre><code>betweenness_weight_dic={}
betweenness_weight_dic=nx.closeness_centrality(G,weight='wei... | <p>You need to have edge attributes and pass the name of the edge attribute to the betweenness centrality function, which use the weights for calculating the shortest path. A small example:</p>
<pre><code>import networkx as nx
g = nx.Graph()
# add edge with the implicit edge attributes weight
g.add_weighted_edges_fro... | python|networkx | 0 |
7,664 | 55,799,693 | Issues with streaming tweets using tweepy and Sentiment analysis | <p>I'm a beginner Python programmer I am finding it hard to figure out a simple Tweepy Streaming api.</p>
<p>Basically I am trying to do the below.</p>
<ol>
<li><p>Stream tweets in Portuguese language.</p></li>
<li><p>Show the sentiment of each tweets.</p></li>
</ol>
<p>I am unable to stream language tweets.
Could s... | <p>This code can help you achieve your goal:</p>
<p><a href="https://github.com/RubensZimbres/Repo-2017/blob/master/NLP%20Twitter%20Streaming%20Mood" rel="nofollow noreferrer">NLP Twitter Streaming Mood</a></p>
<p>It collects data from Twitter and analyzes mood. However, if you want to develop a sentiment analysis in... | python|machine-learning|tweepy|sentiment-analysis|textblob | 0 |
7,665 | 73,250,109 | Click on Twitter Bookmarks button | <p>I've been trying to delete some bookmarks on Twitter using Selenium and Python, but I can't seem to click on the Share / Bookmarks button.
I've tried to use this:</p>
<pre><code>username_field = driver.find_element(By.XPATH, '//*[@id="id__3xn6pz81l9d"]/div[4]/div/div/div/svg')
username_field.click()
time.s... | <p>This was the solution on my case:</p>
<pre><code> wait = WebDriverWait(driver, 10)
username_field = wait.until(EC.element_to_be_clickable((By.XPATH, '//div[contains(@aria-label, "Share Tweet")]//descendant::*[local-name()="svg"]')))
username_field = driver.find_element(By.XPATH, '//div... | python|selenium-chromedriver | 0 |
7,666 | 49,972,165 | Bad disparity map using OpenCV | <p>I'm trying to calculate a disparity map using openCV3 in python but the result is not satisfactory. I made sure that the calibration and rectification are done correctly:</p>
<p><a href="https://i.stack.imgur.com/bcQYp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bcQYp.png" alt="rectification ... | <p>I figured out what was going on and why Matlab was performing so much better.
The disparity map in my original post was obtained by using StereoBM method of openCV, while Matlab uses StereoSGBM. After I switched to StereoSGBM the results look much better and identical to what I get from Matlab.</p> | python|opencv|computer-vision|stereo-3d|disparity-mapping | 1 |
7,667 | 66,468,736 | Python - Phishing dataset file not being detected even though it exists | <p>I am working on a Machine Learning Project which filters spam/phishing emails out of all emails. For this, I am using the SpamAssassin dataset. The dataset contains different mails in this format:</p>
<p><a href="https://i.stack.imgur.com/FmteP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FmteP... | <p>It is because you are not reading the file from that directory.
<code>os.listdir</code> will only give you a list of file names not an absolute path</p>
<p>You will have to do something like this to point to the base directory</p>
<pre><code>base_dir = "C:/Users/keert/Downloads/Spam_Assassin/spam"
for file... | python-3.x|file-import | 2 |
7,668 | 66,480,871 | compare two numpy array | <p>I am trying to compare two 1d numpy arrays for mismatch as follows.
I have this working with partial success.</p>
<pre><code>import numpy as np
a= np.array([0,1,2,3,4,13])
b= np.array([0,1,2,3,4,10,11,12])
mis = max( np.sum(~np.isin(b,a)), np.sum(~np.isin(a,b)))
print(mis)
</code></pre>
<p>output: 3</p>
<p>expected ... | <p>Why are you taking the max of the two sums instead of adding the sums? You are only grabbing the missing entries from a single array (the larger one) by doing that, when you clearly want both.</p>
<pre><code>mis = np.sum(~np.isin(b,a)) + np.sum(~np.isin(a,b))
</code></pre> | python|arrays|numpy | 3 |
7,669 | 66,608,073 | How to setup TF 2.4 Training data with generator or other means | <p>I have a model setup with one input and two outputs. I am trying to use any of</p>
<ol>
<li><a href="https://www.tensorflow.org/guide/data#consuming_python_generators" rel="nofollow noreferrer">tf.data.Dataset.from_generator</a></li>
<li><a href="https://www.tensorflow.org/guide/keras/train_and_evaluate#other_input_... | <p>I figured out the solution to this using generators. I was able to first create a generator yielding numpy arrays that the model could be trained on directly, and then create a tf.data dataset from a slightly modified version of that generator.</p>
<p>The solution was to output just 3 numpy arrays per batch like
<co... | python|tensorflow|nlp|tensorflow2.x | 0 |
7,670 | 64,751,096 | Count number of null rows for ungrouped orders with Pandas | <p>I have a dataset where <strong>every row is attributed to one product</strong>. As you can see, order_name 1140 is counted twice, because the user purchases 2 products with the order #1140.
I would like to count how many transactions (order_name) does not have a discount code (equal NaN).</p>
<pre><code> order_na... | <p>First I created a function that returns 0 if there is a discount code and 1 otherwise. Then I run it for every order so agg is a DataFrame where the index is the <code>order_name</code> and the value is 1 if this order does not have discount code and 0 otherwise. In order to count the number of orders that do not ha... | python|python-3.x|pandas|pandas-groupby | 1 |
7,671 | 65,093,473 | Python, How to delete brackets in the column of the data frame while there's strings between brackets | <p>Python, How to delete brackets in the column of the data frame while there's strings between brackets.</p>
<p>I have a data frame named as df_movies and looks like :</p>
<pre><code> movieId title genres
0 1 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy
1 2 ... | <p>Use <code>.str.extract</code>:</p>
<pre><code>df['title'].str.extract(r'\((.*)\)')
</code></pre> | python | 0 |
7,672 | 71,814,142 | Pass your own function to Pandas table | <p>I need to pass several conditions to Pandas dataframe. I have a table with cars and the year they were manufactured. For example:</p>
<pre><code>Opel Corsa 2007
BMW X5 2017
Ford Mondeo 2015
</code></pre>
<p>Based on the current year (2022) I need to set specific labels on every car.
For example: if a car is 0 to 5 y... | <p>Try <a href="https://pandas.pydata.org/docs/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a></p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from datetime import date
current_year = date.today().year
df['label'] = pd.cut(
(current_year - df['year']),
... | python|pandas|dataframe|function | 0 |
7,673 | 72,094,211 | How can I make it so that a value becomes "NULL" if there's an Exception? | <p>I'm storing data from an API (that I then store as a pickle) and sometimes there are errors due to missing fields. I'm wondering how I can make it so that it only targets the problematic variable and logs its value as "NULL".</p>
<p>The issue is that I'm storing 6 different variables, so if a single one of... | <p>Instead of accessing the keys directly using square brackets try using <code>get()</code> it returns a default value of <code>None</code> if the key is not found.</p>
<p>See this answer for more info <a href="https://stackoverflow.com/a/11041421/3125312">https://stackoverflow.com/a/11041421/3125312</a></p>
<p>You c... | python|loops|exception|try-catch | 1 |
7,674 | 68,459,002 | Tracking decorated methods of children classes in python | <p>In python, how can I setup a parent class to track methods with a specific decorator for each child seperatly? A quick code snippet of what I am trying to do:</p>
<pre><code>class Parent:
decorated_func_dict = {} #dictionary that stores name->func for decorated functions
def get_func_by_decorator_name(sel... | <p>A decorator is not something that makes a function look pretty. It is a callable that ingests an object (not only functions), does some arbitrary operations, and returns a replacement object.</p>
<p>In this case, your decorator should be storing references to function objects in a dictionary somewhere. The problem i... | python|python-3.x|python-decorators | 1 |
7,675 | 71,543,827 | understanding tensorflow Recommending movies: retrieval / usage of : in python class /usage of : in python function | <p>I was reading and trying to work with below documentation from tensorflow
<a href="https://www.tensorflow.org/recommenders/examples/basic_retrieval?hl=sl" rel="nofollow noreferrer">https://www.tensorflow.org/recommenders/examples/basic_retrieval?hl=sl</a></p>
<p>In this we have implementation of <code>MovielenseMode... | <p>Its an type annotation, check this link here <a href="https://docs.python.org/3/library/typing.html" rel="nofollow noreferrer">https://docs.python.org/3/library/typing.html</a>. Here self.movie_model is supposed to be an instance of tf.keras.Model it is very useful and helpful as python is dynamically typed language... | python-3.x|tensorflow|documentation | 0 |
7,676 | 71,560,227 | Unhandled Runtime Error RangeError: byte length of Float32Array should be a multiple of 4 | <p>I'm trying to fetch my custom model in my next.js app, the model.json file and the group1-shard1of61 is in the same folder inside the API folder. I getting these errors:</p>
<p>Unhandled Runtime Error RangeError: byte length of Float32Array should be a multiple of 4
GET http://localhost:3000/api/model/group1-shard1o... | <p>you're manually serving <code>model.json</code> via api request, but that does not make it auto-magically serve shards as well, so of course it complains with error 404 (not found).</p>
<p>in general, don't serve you model.json manually (don't do <code>res.send()</code>), place it in public folder and let next serve... | reactjs|next.js|tensorflow.js | 0 |
7,677 | 61,793,290 | When cloning my edited forked git repository the changes are not reflected and original repository is cloned instead | <p>my goal is to fork an original repository,edit it, and then clone it on my beaglebone black.</p>
<p>Here are the links to the existing repositories:
<a href="https://github.com/adafruit/Adafruit_Python_BNO055" rel="nofollow noreferrer">https://github.com/adafruit/Adafruit_Python_BNO055</a>
<a href="https://github.c... | <p><code>dependency_links</code> were declared obsolete and finally <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html#dependencies-that-aren-t-in-pypi" rel="nofollow noreferrer">removed</a> in <code>pip</code> 19.0. The replacement for it is <code>install_requires</code> with special syntax (supporte... | python|git|github|git-clone|git-fork | 0 |
7,678 | 71,345,524 | Linear Regression Practice | <p>I'm trying to run a basic linear regression,
However I've encountered en error like this when I run my code.</p>
<pre><code>Traceback (most recent call last):
File "/Users/brian_kang/Documents/Webtools/Project_Alliance_Data/Code/Python/Predictive_modelling/predictive_modelling.py", line 113, in <modul... | <p>I do not have the reputation for commenting, sorry :(</p>
<p>You seem to have everything in place, it's your main function that's need a bit of fixing.</p>
<p>You call the function:</p>
<pre><code>linear_regression(train_x, train_y, test_x, test_y)
</code></pre>
<p>before the function that actually gives you those i... | python|pandas | 0 |
7,679 | 70,024,197 | Taking integral of a function in CPLEX | <p>I try to model a MIP model in CPLEX. I have a function that includes decision variables and I need to take integral of this function to compute its expected value. Is there any way to take integral a function in CPLEX? Thank you!</p> | <p>with piecewise linear you can approximate any function and rely on Mathematical Programming.</p>
<p>See <a href="https://github.com/AlexFleischerParis/opltipsandtricks/blob/master/interpolatewithpiecewiselinear.mod" rel="nofollow noreferrer">Interpolate any function</a> in <a href="https://www.linkedin.com/pulse/tip... | python|optimization|cplex|opl | 0 |
7,680 | 35,689,584 | Beginner Python - Answering with either a string or a variable in a loop | <p>My code so far:</p>
<pre><code>prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your tic... | <p>If <code>age</code> is <code>'quit'</code>, you will break anyway. Therefore, you can just use <code>if</code> for the next one instead. As long as you do that anyway, you can make it an int after that <code>if</code>:</p>
<pre><code>while True:
age = input(prompt)
if age == 'quit':
break
age... | python|string|while-loop|integer | 1 |
7,681 | 67,654,519 | Selenium problem [don't show up error](download few items) | <p>I'm in need of a solution to my code, I tried to web scraping a dynamic web page call easy.cl and just get 4 items and sometimes none (only when I download title, cant download price because don't show anything). Well, anyhow, I need a guide of where is my error, because Selenium don't show me any in my result (Subl... | <p>The load more products button appears on the bottom of the page, out of the visible screen, so possibly after the element is presented (loaded) you need to scroll to that element before clicking it</p>
<pre><code>from selenium.webdriver.common.action_chains import ActionChains
boton = WebDriverWait(driver, 10).unt... | python-3.x|selenium|selenium-webdriver|web-scraping | 1 |
7,682 | 67,092,396 | Hierarchical clustering termination | <p>To my understanding, Agglomerative Hierarchical clustering starts by clustering the points that are closest to each other. I am trying to get the different clustering results where only a certain percentage of the data has been clustered for comparison. i.e. 40%, 50%, 60%...</p>
<p>So I need a way to terminate the h... | <p>Based on the <a href="https://scikit-learn.org/stable/modules/clustering.html#hierarchical-clustering" rel="nofollow noreferrer">Scikit-learn documentation:</a></p>
<blockquote>
<p>The AgglomerativeClustering object performs a hierarchical clustering using a bottom up approach: each observation starts in its own clu... | python|scikit-learn|hierarchical-clustering | 0 |
7,683 | 65,585,930 | Cannot run pipenv after successfully installing it | <p>I know this has been asked before and I reviewed the previous posts, but none of those solved my issue.</p>
<p>I'm new to programming so I may get the terminology mixed up but I will try to explain in as much detail as I can.</p>
<p>I am running Python 3.8 on Visual Studio Code. I installed pipenv successfully:</p>
... | <p>You may need to add pipenv to you path variable. Check out the note section in <a href="https://pipenv-fork.readthedocs.io/en/latest/install.html#pragmatic-installation-of-pipenv" rel="nofollow noreferrer">the docs</a>. It actually describes how to get the right location to add on Windows:</p>
<blockquote>
<p>On W... | python|pipenv | 1 |
7,684 | 65,760,885 | The catch_error_str function isn't catching errors when the input is a integer. - Python | <p>Please don't be too harsh because I'm new to coding. The problem I'm having is that the function catch_error_str does not work. For example, when I enter "2" as an input then it says last_name is 2 instead of catching the error.</p>
<pre><code>def catch_error_str():
unvalid = True
while unvalid:
... | <p>Python don't have a problem to covert a number to a string and because of that, there is no error rasing.<br>
You can try</p>
<pre><code>def catch_error_str():
unvalid = True
while unvalid:
try:
string = str(input())
if not string.isalpha():
raise Va... | python | 2 |
7,685 | 65,856,096 | Adding a function to a string in a pandas dataframe | <p>I have a data frame that contains a column with countries.
I want to convert the country names to capital cities.
Example of how the function works:</p>
<pre class="lang-py prettyprint-override"><code>from countryinfo import CountryInfo
CountryInfo('Lebanon').capital()
</code></pre>
<p>Would return <code>Beirut... | <p>you can use the <code>lambda</code> function and <code>pd.apply()</code> like this:</p>
<pre class="lang-py prettyprint-override"><code>from countryinfo import CountryInfo
df['Capital'] = df['country'].apply(lambda x : CountryInfo(x).capital()
</code></pre>
<p>Here you can put your own <code>df's column name</code> ... | python|pandas|dataframe | 2 |
7,686 | 50,853,726 | How to change date format from Month Date,Year to MM/dd/YYYY using python | <p>I have monthe date, year for ex : January 1,2018 or June 14,2018, now i want to convert them as 01/01/2018, 06/14/2018.
can anybody help me on this using python.</p> | <p>I have found the answer, </p>
<pre><code>oldformat = 'June 13, 2018'
datetimeobject = datetime.strptime(oldformat,'%B %d, %Y')
newformat = datetimeobject.strftime('%m/%d/%Y')
print newformat
</code></pre> | python | 0 |
7,687 | 61,209,834 | Why can't I use a dataframe's numerical index in a calculation with apply and pandas DateOffset? | <p>I need to create a column in a dataframe, containing dates 3 months from each other.</p>
<p>I tried using df.apply with pandas.DateOffset and the numerical index of the dataframe, but I get this error:</p>
<blockquote>
<p>TypeError: cannot perform <strong>rmul</strong> with this index type: Index</p>
</blockquot... | <p>Since you're applying with <code>axis=1</code>, <code>x</code> is a row. And each row is a series indexed by the dataframe's column. So you want <code>name</code>, not <code>index</code>:</p>
<pre><code>df['dates']= df.apply( lambda x: my_date + pd.DateOffset(months = 3 * x.name), axis=1)
</code></pre>
<p>Output:<... | python|pandas|dataframe|date|apply | 1 |
7,688 | 58,124,143 | Combined vectorized functions in Numba | <p>I'm using Numba (version 0.37.0) to optimize code for GPU.
I would like to use combined vectorized functions (using @vectorize decorator of Numba).</p>
<p>Imports & Data:</p>
<pre><code>import numpy as np
from math import sqrt
from numba import vectorize, guvectorize
angles = np.random.uniform(-np.pi, np.pi, ... | <p>I think you can only call <code>device=True</code> functions from other cuda functions:</p>
<blockquote>
<p><a href="http://numba.pydata.org/numba-doc/dev/cuda/ufunc.html#example-calling-device-functions" rel="nofollow noreferrer">3.13.2. Example: Calling Device Functions</a></p>
<p>All CUDA ufunc kernels ha... | gpu|vectorization|numba|dispatch|numpy-ufunc | 3 |
7,689 | 57,644,159 | Doc2vec matrix representation | <p>Using Doc2vec, I would like to see the impact of each word in the generated matrices.</p>
<p>Is there a way to see the detail representation of a matrix i.e.
the content of the matrix and mostly what is represented by each row and each column? </p>
<p>For example this way I can see the matrix representation but n... | <p>As a "dense embedding", the individual dimensions of a <code>Doc2Vec</code> (or <code>Word2Vec</code>) vector don't have clearly-describable interpretations. </p>
<p>The vectors are just in relative positions that work well for the training task – and fortunately for us, those same relative positions can correlate ... | python|word-embedding|doc2vec | 0 |
7,690 | 22,695,787 | Unable to push app in heroku | <p>I am trying to push app in heroku. I run following command-- git push heroku master</p>
<p>and got folloing error</p>
<pre><code>Initializing repository, done.
Counting objects: 3523, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (3373/3373), done.
Writing objects: 100% (3523/3523), 13.9... | <p>Your deploy is failing because of the subprocess call you're making in your code. The path that you're trying to run doesn't exist on Heroku.</p>
<p>You might want to either remove those call, or rewrite it in such a way that it works.</p> | git|python-2.7|heroku | 0 |
7,691 | 57,077,839 | Reading and graphing data from a messy file using first 2 and last string of the lines | <p>If there are any similar questions with answers, please comment it down. So far, I have seen questions like this for Java but not Python after browsing.</p>
<p>I am trying to take the data from a messy file (with no headers), read and graph it. The important <strong><em>columns</em></strong> are <strong><em>#6 (for... | <p>Starting with your sample data read in using<code>pd.read_clipboard(sep='\s', header=None)</code> and saved using <code>df.to_dict()</code>, this seems to be (if I understand correctly) a fairly straightforward application of <code>.loc</code> with boolean conditions, and then plotting (here, <a href="https://seabor... | python-3.x|matplotlib|graph|read-data | 1 |
7,692 | 36,148,502 | Why are unparanthesized tuples in generators not allowed in the expression field? | <pre><code># why is the following invalid
x = (k, v for k, v in some_dict.items())
# but if we wrap the expression part in parentheses it works
x = ((k, v) for k, v in some_dict.items())
</code></pre>
<p>I looked through the documentation and didnt seem to find anything on this? What could possible be confusing the p... | <p>Look at <code>x = (k, v for k, v in some_dict.items())</code>:</p>
<pre><code>x = (k, v for k, v in some_dict.items())
x = ((k, v) for k, v in some_dict.items())
x = (k, (v for k, v in some_dict.items()))
</code></pre>
<p>Parentheses are needed to remove the ambiguity.</p>
<p><code>x = ('%s:%s:%s' % (k, v, k) for... | python|python-3.x|syntax|generator | 5 |
7,693 | 19,738,528 | Cascading hadoop streaming mapreductions with binary data | <p>I'm having trouble to figure out how to use the binary output for a hadoop streaming mapreduction as the input for another hadoop streaming mapreduction.</p>
<p>echo.py:</p>
<pre><code>import sys
while True:
buffer = sys.stdin.read(1024)
if not buffer:
break
sys.stdout.write(buffer)
sys.stdout.flush()... | <p>For your first job, your input looks like text, so you can skip the <code>-inputformat</code> and specifying your inputs and outputs as <code>typedbytes</code>. You should end up with a <code>SequenceFile</code> that uses <code>org.apache.hadoop.io.Text</code> for both the keys and the values. At present, it may b... | python|binary-data|hadoop-streaming | 0 |
7,694 | 43,535,536 | Why do I have to change integers to strings in order to iterate them in Python? | <p>First of all, I have only recently started to learn Python on codeacademy.com and this is probably a very basic question, so thank you for the help and please forgive my lack of knowledge.</p>
<p>The function below takes positive integers as input and returns the sum of all that numbers' digits. What I don't unders... | <p>Integers are not sequences of digits. They are just (whole) numbers, so they can't be iterated over.</p>
<p>By turning the integer into a string, you created a sequence of digits (characters), and a string <em>can</em> be iterated over. It is no longer a number, it is now <em>text</em>.</p>
<p>See it as a represen... | python|python-2.7 | 3 |
7,695 | 29,997,635 | Selecting Multiple Selectors for increased specificity in Selenium Using Python | <pre><code><input class="radio-field" type="radio" checked="checked" value="0" name="value(WoundCareDone)">
</code></pre>
<p>Hey guys I just have a tiny question.</p>
<p>I want to select the xpath of name. It would go like this //input[@name="value(WoundCareDone)"] right?</p>
<p>so how I want to include the va... | <p>Like this:</p>
<pre><code>//input[@name="value(WoundCareDone)" and @value = "0"]
</code></pre> | python|selenium|xpath | 0 |
7,696 | 36,932,396 | Python data descriptor did not work as instance variable? | <p>As the official demo described <a href="https://docs.python.org/2/howto/descriptor.html#descriptor-example" rel="nofollow">here</a>, the following code will print <code>Retrieving var "x"</code>.</p>
<pre><code>class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and pri... | <p>The descriptor how-to is wrong here. The <a href="https://docs.python.org/2/reference/datamodel.html#implementing-descriptors" rel="nofollow">Python data model</a> has the correct description:</p>
<blockquote>
<p>The following methods [<code>__get__</code>, <code>__set__</code>, and <code>__delete__</code>] only ... | python|python-2.7|descriptor | 3 |
7,697 | 70,429,553 | Why is my subtract function working in a static context when I haven't used the @staticmethod decorator? | <p>So, I did not know what static methods were so i searched it up and i made this</p>
<pre><code>class Calculator:
def __init__(self,num1,num2):
self.num1 = num1
self.num2 = num2
@staticmethod
def add(x,y):
result = x + y
return result
def sub(x,y):
result = x-... | <p>You don't see the difference because you didn't instantiate an object (<code>Calculator</code> is the class, <code>Calculator()</code> is an object).</p>
<p>See the following snippet:</p>
<pre><code>class Calculator:
@staticmethod
def add(x,y):
result = x + y
return result
def sub(x,y):
... | python|static-methods | 2 |
7,698 | 70,443,707 | how to use on_ready from discord.py? | <p>Hello I have trouble using the API discord.py, I try to display in the console the message received, but every time the function on_reday returns no message.</p>
<pre><code>#imports
import discord
TOKEN = "TOKEN"
client=discord.Client()
@client.event
async def on_message(message):
t... | <pre><code>@client.event
async def on_ready():
await client.change_presence(status=discord.Status.online,
activity=discord.Game("?help"))
print("Bot is ready")
</code></pre>
<p>this will print ready when the bot will be online, it will change the status and ... | python|api|discord | 0 |
7,699 | 69,985,874 | Why is the curses module not installing via pip? | <p>I have been trying to install the curses module using the command "pip install windows-curses" but it does not seem to be working and it errors out saying:</p>
<pre><code>ERROR: Could not find a version that satisfies the requirement windows-curses (from versions: none)
ERROR: No matching distribution foun... | <p>Currently the latest version of windows-curses is <a href="https://pypi.org/project/windows-curses/2.2.0/" rel="nofollow noreferrer">2.2.0</a> and it <a href="https://pypi.org/project/windows-curses/2.2.0/#files" rel="nofollow noreferrer">provides</a> wheels for Python 3.6-3.8 and no source code.</p>
<p>Most probabl... | python|windows|terminal|pip|curses | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.