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 |
|---|---|---|---|---|---|---|
10,300 | 53,773,205 | Python Regex to remove Numbers and Surrounding Spaces? | <p>Given a string like:</p>
<pre><code>'Foo他有一支 20 老枪 16。'
'Bar他有一支 20老枪 16。'
'Baz他有一支20 老枪 16。'
</code></pre>
<p>How can I use <code>re.sub</code> to remove the number, and the spaces surrounding the number, to return:</p>
<pre><code>'Foo他有一支老枪。'
'Bar他有一支老枪。'
'Baz他有一支老枪。'
</code></pre>
<p>I would like to retain Ch... | <p>You can use a regex pattern matching digits and surrounding spaces: <code>r'\s*\d+\s*'</code>.</p>
<p>Code example:</p>
<pre><code>import re
text_clean = re.sub(r'\s*\d+\s*', '', text)
</code></pre>
<p>See the <a href="https://regex101.com/r/ZC83GF/2" rel="nofollow noreferrer">regex101</a> demo (in particular, th... | python|regex|python-3.x | 2 |
10,301 | 54,267,930 | Reading a pandas data frame having unequal columns in observations | <p>I am trying to read this small data file,
Link - <a href="https://drive.google.com/open?id=1nAS5mpxQLVQn9s_aAKvJt8tWPrP_DUiJ" rel="nofollow noreferrer">https://drive.google.com/open?id=1nAS5mpxQLVQn9s_aAKvJt8tWPrP_DUiJ</a></p>
<p>I am using the code - </p>
<pre><code>df = pd.read_table('/Data/123451_date.csv', se... | <p>It looks like the data you use has some garbage in it. Precisely, rows 1-33 (inclusive) have additional, unnecessary (non-GPS) information included. You can either fix the database by manually removing the unneeded information from the datasheet, or use following code snippet to skip the rows that include it:</p>
<... | python|pandas|csv | 1 |
10,302 | 9,143,354 | Create from list of strings list of class instances py2.7 | <p>My code creats only the last instance times len(list) how can i change this to create every instance separatly? :|</p>
<pre><code> @staticmethod
def impWords():
tempFile = open('import.txt','r+')
tempFile1 = re.findall(r'\w+', tempFile.read())
tempFile.close()
for i in range(0,len(tempFile1)):
... | <p>Assuming that <code>word</code> is an instance of <code>Word</code>, you should create a new one in each iteration, like this:</p>
<pre><code>@staticmethod
def impWords():
with open('import.txt','r+') as tempFile:
#re
tempFile1 = re.findall(r'\w+', tempFile.read())
# using enumerate her... | python|oop|list|class|instance | 2 |
10,303 | 39,094,686 | Pytest command line argument for @pytest.mark.parametrize | <p>Is it possible to find command line arguments in pytest with distributed test execution?</p>
<pre><code>py.test -n 16 tests/tests_*****.py --env="TestEnvironemnt" --html=XYZ/Reports.html
</code></pre>
<p>os.sys.argv is giving as '-c' in my code , if am executing my pytest code </p> | <p>The question is not very clear but I assume you want to add an option "--env" and read its value.</p>
<p>The way to do it is:</p>
<ol>
<li>Create a file <strong>conftest.py</strong> in your project (if it does not exist yet) and add the option <em>--env</em></li>
</ol>
<hr>
<pre><code>#conftest.py
def pytest_add... | python|pytest | 0 |
10,304 | 37,360,953 | Python Access caller's global() | <p>I have a function to access the globals() of a Python script. I have move teh function into a class of its own. Now the function is only able to access the globals() of the class, not of the calling script.</p>
<p>Question: How can a function in a class access the globals() of the script which called it?</p>
<p>Than... | <p>Although you <em>technically</em> can access globals of a caller via stack frame introspection, you are really going about things wrong here.</p>
<p>Instead of relying on globals, rely on <em>instance state</em>. Have the caller create your class and pass in <em>all the required data</em> at that time, and you stor... | python|class|global | 1 |
10,305 | 34,400,120 | How to get the current page URL in the requests library? | <p>I'm in a loop, navigating paged search results. The next button never disappears. I want to keep clicking it until the URL no longer changes. I imagine I will need a requests session? I want to do something like this:</p>
<pre><code>new_url = soup.find("blahblah")['href']
if session.current_url == new_url:
retu... | <p>On the response object, there is a <code>.url</code> property that you can use to access the URL of the current page.</p> | python|python-requests | 10 |
10,306 | 65,990,547 | I've made an anagram function in python, I cannot figure out how to get the output to look like this: "Key": word1, word2, word3 etc | <pre><code>with open('words.txt', 'r') as read:
line = read.readlines()
key_list = []
def make_anagram_dict(line):
word_list = {}
for word in line:
word = word.lower()
key = ''.join(sorted(word))
if key in word_list and len(word) > 5:
word_list[key].append(word)
... | <p>To get the exact same output, you can try :</p>
<pre><code>if __name__ == '__main__':
word_list = make_anagram_dict(line)
for key, words in word_list.items():
if len(words) > 1:
print('Key:')
print(key)
print()
print('Words:')
print('\n,... | python | 0 |
10,307 | 39,710,796 | Infer the length of a sequence using the CIGAR | <p>To give you a bit of context: I am trying to convert a sam file to bam</p>
<pre><code>samtools view -bT reference.fasta sequences.sam > sequences.bam
</code></pre>
<p>which exits with the following error</p>
<pre><code>[E::sam_parse1] CIGAR and query sequence are of different length
[W::sam_read1] parse error ... | <p>I suspect the reason there isn't a tool to fix this problem is because there is no general solution, aside from performing the alignment again using software that does not exhibit this problem. In your example, the query sequence aligns perfectly to the reference and so in that case the CIGAR string is not very inte... | python|module|bioinformatics|samtools|bam | 2 |
10,308 | 39,870,925 | Most elegant way to calculate completion times for a list of jobs in Python | <p>I have a list of jobs in form of <code>[(weight, length)]</code>, e.g.</p>
<pre><code>[(99, 1), (100, 3), (100, 3), (99, 2), (99, 2)]
</code></pre>
<p>But much larger. </p>
<p>And i've written a function that schedules them according to different keys that I pass as a parameter. This means that for each job I cal... | <p>You want to use the <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow"><code>itertools.accumulate()</code> iterable</a> to produce the acumulative weight of your lengths:</p>
<pre><code>from itertools import accumulate
def schedule(jobs_list, sort_key):
sorted_jobs ... | python|list|python-3.x|list-comprehension | 3 |
10,309 | 16,442,764 | How to load portable .NET library within Iron Python script? | <p>I have serious troubles loading a portable .NET library (to be used in standard .NET and Silverlight environment) from a Python script.</p>
<p>.NET DLL file version is 4.0.3.319.233 (System.Core.DLL), IronPython is 2.7.1, running in 32bit/x86 mode. Visual Studio 2010 with C# under .NET 4. Microsoft .NET update KB24... | <p>The FileNotFoundException is an indication that something is loading the assemblies using Assembly.LoadFile instead of Assembly.LoadFrom, but not handling assembly policy correctly. I'm not sure how Python code in Visual Studio works, but if you are able to run any bootstrapper code before the portable assembly has ... | python|.net|portable-class-library | 0 |
10,310 | 16,107,281 | Display a default value in form fields Django | <p>How does django display the default value in a textfield to form.</p>
<pre><code><input type="text" name="{{ form.username}}" value="{{ costumer.username}}"><p>
</code></pre>
<p>it shows a textfield follow by costumer.username in browser, I want to have the username as default value in the textfield, H... | <p>Use initial parameter to a form:</p>
<pre><code>form = Form(initial={'username': costumer.username})
</code></pre>
<p>and to display input in template you need just this:</p>
<pre><code>{{ form.username }}<br/>
</code></pre>
<p><a href="https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-v... | python|django|django-forms | 6 |
10,311 | 31,870,776 | Prevent multiple toplevels from opening? | <p>I have a object oriented tkinter program set up.
I have initialized a variable to store <code>Toplevel()</code> in as</p>
<pre><code>self.toplevel = None
</code></pre>
<p>Then when I create the actual <code>Toplevel</code> window I simply assign it to the variable:</p>
<pre><code>self.toplevel = Toplevel()
</code... | <p>Check this <a href="https://stackoverflow.com/questions/111155/how-do-i-handle-the-window-close-event-in-tkinter">How do I handle the window close event in Tkinter?</a></p>
<p>Assign the value <code>None</code> to <code>self.toplevel</code> after the <code>Toplevel</code>closes usign a callback function <code>TopCl... | python|python-3.x|tkinter | 2 |
10,312 | 31,776,051 | Using Django model's post_save for manual cache invalidation: do foreign keys trigger save()? | <p>This seems like a pretty simple question but I'm having trouble finding the answer to it:</p>
<p>Do Django models with a foreign key ever call the save() method of the model they're pointing to when <em>they</em> are saved/changed?</p>
<p>I'm working on a model for SAT exams being taken, graded and scored--the las... | <p>Answer: no, they do not do that. </p>
<p>I should listen to the QuestionResponse objects.</p>
<p>Thanks @ozgur for this answer.</p> | python|django|caching|django-models|django-signals | 2 |
10,313 | 38,647,525 | Why does Pygame Movie Rewind Only on Event Input | <p>I'm working on a small script in Python 2.7.9 and Pygame that would be a small display for our IT department. The idea is that there are several toggle switches that indicate our current status (in, out, etc) , some information about our program at the school, and play a short video that repeats with images of the ... | <p>You need to take the code for replaying the movie out of the for loop that gets current events. Do this for that code and any other code you want to happen continuously without waiting for an event by moving the code 4 spaces to the left.</p>
<p>Like so:</p>
<pre><code>while not done:
for event in pygame.event... | python|pygame | 0 |
10,314 | 38,567,853 | Codingbat make_bricks timed out with while loop in python | <p>My goal is:
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks.</p>
<p>My code is:</p>
<pre><code>def make_bricks(small, big, goal):
if small + 5*... | <p>Just categorise the if statements according to whether the big bricks are cumulatively bigger or smaller than the goal.</p>
<pre><code>def make_bricks(small, big, goal):
if (5*big) >= goal:
return (goal%5) <= small
if (5*big) < goal:
return (goal - 5*(big)) <= small
</code></pre> | python|python-3.x | 0 |
10,315 | 68,131,503 | How do I automate Python to navigate to other directories | <p>I am trying to make a code in Python where when it runs it will search a directory and its sub-directories for files ending with a file extension ".pdm". I want to note this is not on a personal computer but on a cloud provider. The variable current_dur is just a starting point to narrow down the search. T... | <p>Have you tried using <code>os.walk()</code>?</p>
<pre><code>import os
current_dur = r'\\dmn1.MIR.com\MIRFILE\FS159\FIRSCODB\IR Data Modeling\PIR\IR - Information Report'
pdm_files = []
for root, dirs, files in os.walk(current_dur):
for file in files:
if file.endswith('.pdm'):
pdm_files... | python|command-line|automation | 2 |
10,316 | 1,461,392 | Is it Pythonic for a function to return an iterable or non-iterable depending on its input? | <p>(Title and contents updated after reading Alex's answer)</p>
<p>In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters.</p>
<p>For example <code>struct.unpack</code> always returns a tuple even if it co... | <p>If you are going to be returning iterators sometimes, and single objects on others, I'd say return always an iterator, so you don't have to think about it. </p>
<p>Generaly, you would use that function in a context that expects an iterator, so if you'd have to check if it where a list to iterate or an object to do ... | python|return-value | 12 |
10,317 | 32,231,324 | How to accept a list query parameter with standard format in DRF using django_filters | <p>I want to be able to accept a list query param using the standard <code>application/x-www-form-urlencoded</code> format, as stated in <a href="https://stackoverflow.com/a/9176496/4650346">https://stackoverflow.com/a/9176496/4650346</a>. For example to filter products by a list of categories, I would like to use:</p>... | <p>This is a <em>kind-of dirty</em> fix I made to temporarily solve the problem. I extended the <code>DjangoFilterBackend</code> to override the <code>filter_queryset</code> method so whenever a field came in the form of <code>category[]</code>, I add the <code>category</code> field to the request.query_params.</p>
<p... | python|filter|django-rest-framework|query-parameters|multiple-choice | 1 |
10,318 | 44,226,010 | Security/Connection Issue with Selenium Webdriver in Python [WinError 10061] | <p>I'm building a crawler and finding a strange issue with when I try to use a get command:</p>
<pre><code>drive.get("http://google.com")
</code></pre>
<p>This will throw the error:</p>
<blockquote>
<p>ConnectionRefusedError: [WinError 10061] No connection could be made
because the target machine actively refuse... | <p>Here is the Answer to your Question:</p>
<p>I don't see any major issue in your code. Having said that, as you have initialized the webdriver instance as <code>driver</code>, you may consider using the same <code>driver</code> to open the url "<a href="http://google.com" rel="nofollow noreferrer">http://google.com<... | python|selenium | 0 |
10,319 | 44,284,595 | Check, if items of one dataframe are inside a range, defined in another dataframe | <p>I have a defined range:</p>
<pre><code>df = pd.DataFrame([["1", "10"], ["11", "67"], ["90", "115"]], columns=['start', 'end'])
</code></pre>
<p>And a list of strings:</p>
<pre><code>df2 = pd.DataFrame([["1"], ["3"], ["31"], ["70"], ["71"], ["90"], ["99"], ["100"], ["200"]], columns=['reference'])
</code></pre>
<... | <pre><code>ranges = pd.DataFrame([["1", "10"], ["11", "67"], ["90", "115"]], columns=['start', 'end']).astype(int)
items = pd.DataFrame([["1"], ["3"], ["31"], ["70"], ["71"], ["90"], ["99"], ["100"], ["200"]], columns=['reference']).astype(int)
</code></pre>
<h1>Make a <code>DataFrame</code> with results</h1>
<pre><c... | python|pandas | 1 |
10,320 | 44,341,683 | How to concatenate a Python dictionary | <p>My questions refers to a "concatenation" of a Python dictionary. For example: I have a dictionary <code>di = {1:'AB', 2:'BC',3:'CD'}</code>, and I want with one command <code>print(____)</code> to get the output <code>'ABCD'</code>.</p>
<p>Any suggestions?</p> | <p>Try This One.</p>
<pre><code>print(''.join(str(e) for e in list(sorted(set(di[1]+di[2]+di[3]))))
</code></pre> | python|dictionary | 1 |
10,321 | 32,811,370 | Selenium won't click a button with python? | <p>please can someone help me with this,</p>
<p>I can't get selenium to click a button with python. I'm on python 3.4 and using Firefox 42</p>
<p>the browser opens but that's all</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("ht... | <p>It helps to inspect <code>driver.page_source</code> to see the HTML <em>as the driver sees it</em>.</p>
<pre><code>driver.get("http://www.speedyshare.com/")
content = driver.page_source
with open('/tmp/out', 'wb', encoding='utf-8') as f:
f.write(content)
</code></pre>
<p>You'll see in /tmp/out:</p>
<pre><code... | python|selenium | 6 |
10,322 | 13,889,281 | default value 0 in foreign key field raising error | <p>I set default value as 0 in foreign key field in Django model. But it is raising IntigrityError (1048, "Column 'country_id' cannot be null")</p>
<p>Hi, I have code like:</p>
<pre><code>class TestModel(models):
name = models.CharField(max_length=255, blank=True)
reg_from = models.CharField(max_length=255, b... | <p>It's raising an error because there isn't an object in your Country models that has a <code>PK = 0</code>. </p>
<p>If you do not want to set your field to <code>null</code> then simply create a Country object with <code>pk=0</code> like: <code>Country.objects.create(name='No Country', pk=0)</code>.</p>
<p>Although... | python|django|django-models | 1 |
10,323 | 14,038,510 | Boost python argument error | <p>I just define a function as below and export it to python by using boost.python.</p>
<p>I have a doubt what is the corresponding type of [File* local_conf] in python.</p>
<pre><code>size_t curl_conf(const char* conf_url,FILE *local_conf)
{
return 0;
}
BOOST_PYTHON_MODULE(curl_conf)
{
using name... | <p>As quick google search and I found this blog article that seems to exactly answer your question : <a href="http://bfroehle.com/2011/10/file-and-boost-python/" rel="nofollow">http://bfroehle.com/2011/10/file-and-boost-python/</a></p>
<p>You have to write a small wrapper as there is no direct conversion.</p>
<p>An e... | c++|python|boost | 1 |
10,324 | 34,471,102 | Python NameError: name 'include' is not defined | <p>I'm currently developing a website with the framework Django (I'm very beginner), but I have a problem with Python: since I have created my templates, I can't run server anymore for this reason (the stack trace points to a line in file <em>urls.py</em>):</p>
<pre><code><stacktrace>
...
path('apppath/', include... | <p>Guessing on the basis of whatever little information provided in the question, I think you might have forgotten to add the following import in your <code>urls.py</code> file.</p>
<pre><code>from django.conf.urls import include
</code></pre> | python|django|nameerror | 268 |
10,325 | 34,664,240 | Refreshing or re-running a class in Python 2.7 | <p>I have a class that retrieves values from a configuration file and a function that adds them. I call the class, change values then run the function to write them. When I call the class afterwards the values are not updated. I check the config file and the values have changed. Is there a way to get it to re-read the ... | <p>Your <code>a</code> is a class attribute, so it is only created once, at the time you define the class. Do this instead:</p>
<pre><code>class read_conf_values(object):
def __init__(self):
parser = ConfigParser.ConfigParser()
parser.read('configuration.conf')
self.a = parser.get('asectio... | python|function|python-2.7|class|configuration | 0 |
10,326 | 27,333,493 | numbers in a list (python) | <p>Is it possible to put numbers toghether from a list?</p>
<pre><code>>>> ['A', '3', '4']
['A', '34']
>>> ['3', 'A', '4']
['A', '34']
>>> ['A', '4', '3']
['A', '43']
</code></pre>
<p>I tried to make strings but I never know how much numbers there are... otherwiste I could do:</p>
<pre><... | <p>You can use the <code>string</code> method <code>isdigit</code> to see if a string is composed only of numbers. So basically you can collect all the non-numbers in a list, then <code>join</code> all the numbers and add them as a single element.</p>
<pre><code>>>> l = ['A', '3', '4', 'B', '6']
>>> ... | python|list|count | 1 |
10,327 | 27,076,250 | Slicing Python strings | <p>I'm currently trying to slice a specific string into parts but alway getting out of index errors.</p>
<p>The string is:</p>
<pre><code>columnData = "001.001.000.100.000.000.000"
myClassInstance = MyClass(
param1 = columnData[0:3],
param2 = columnData[4:3],
param3 = columnData[8:3],
param4 =... | <p>i think what you are trying to do is:</p>
<p>columnData[4:7]
columnData[8:11]
etc.</p>
<p>I think it's better to just to</p>
<blockquote>
<p>split_column_data = columnData.split('.')</p>
</blockquote>
<p>which splits the string at each <code>.</code> in the string. and returns a list</p>
<blockquote>
<p><code>>&g... | python|string|slice | 3 |
10,328 | 12,277,051 | PyQt 4 : setupUi() unbound method error | <p>I am starting to learn to use PyQt4. I've got a simple gui window I want to show (nothing fancy).</p>
<p>Here's the code for that : </p>
<pre><code>import sys
from PyQt4 import QtGui
from test import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(s... | <p>You should inherit <code>Ui_MainWindow</code>:</p>
<pre><code>import sys
from PyQt4 import QtGui
from test import Ui_MainWindow
class MyForm(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
if __name__ == "__main__":
... | python|eclipse|pyqt4 | 3 |
10,329 | 1,290,205 | python regex help: unknown information to skip | <p>I'm having trouble with the needed regular expression... I'm sure I need to probably be using some combination of 'lookaround' or conditional expressions, but I'm at a loss.</p>
<p>I have a data string like:</p>
<pre><code>pattern1 pattern2 pattern3 unwanted-groups pattern4 random number of tokens pattern5 optiona... | <p>If all the data is in that format I'd go with <code>split</code> instead. I think it will be faster.</p>
<pre><code>
str = "regex1 regex2 regex3 unwanted-regex regex4 random number of tokens regex5 optregex1 optregex2 more unknown unwanted junk separated with white spaces optregex3 optregex4 etc"
parts = str.split(... | python|regex | 4 |
10,330 | 867,219 | Python Class Members Initialization | <p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p>
<p>The scenario: I ... | <p>What you keep referring to as a bug is the <a href="http://docs.python.org/tutorial/classes.html" rel="noreferrer">documented</a>, standard behavior of Python classes.</p>
<p>Declaring a dict outside of <code>__init__</code> as you initially did is declaring a class-level variable. It is only created once at first,... | python|class|initialization | 61 |
10,331 | 940,822 | Regular expression syntax for "match nothing"? | <p>I have a python template engine that heavily uses regexp. It uses concatenation like:</p>
<pre><code>re.compile( regexp1 + "|" + regexp2 + "*|" + regexp3 + "+" )
</code></pre>
<p>I can modify the individual substrings (regexp1, regexp2 etc).</p>
<p>Is there any small and light expression that matches nothing, whi... | <p>This shouldn't match anything:</p>
<pre><code>re.compile('$^')
</code></pre>
<p>So if you replace regexp1, regexp2 and regexp3 with '$^' it will be impossible to find a match. Unless you are using the multi line mode.</p>
<hr>
<p>After some tests I found a better solution</p>
<pre><code>re.compile('a^')
</code>... | python|regex | 149 |
10,332 | 57,445,899 | how to convert flattened array of RGB image(1-D) back to original image | <p>I have flattened 1D array of (1*3072) created from RGB image of dimension(32*32*3). I want to extract back the original RGB image of dimension(32*32*3) and plot it.</p>
<p>I have tried the solution suggested in <a href="https://stackoverflow.com/questions/38952853/how-to-convert-a-1-dimensional-image-array-to-pil-i... | <p>In order to interpret an array as an RGB image, it needs to have 3 channels. A channel is the 3rd dimension in the numpy array. So change your code to this:</p>
<p><code>img2 = Image.fromarray(arr.reshape(200,300,3), 'RGB')</code></p>
<p>I should mention that you talk about your flattened array being 1x3072, yet ... | numpy|matplotlib|deep-learning|python-imaging-library | 0 |
10,333 | 58,188,372 | different eigenvectors of the same hermitian matrix in matlab&python | <p>I'm trying to calculate eigenvalues and eigenvectors of a 3x3 hermitian matrix (named coh). Here is the matlab code I'm using,</p>
<pre class="lang-matlab prettyprint-override"><code>
coh = [0.327064707875252 + 0.00000000000000i -0.00770057737827301 + 0.0178948268294334i -0.00368526462214552 - 0.006150562701635... | <p>If you write <code>imag(D)</code>, you'll see that the imaginary component of the eigenvalues are in the order of 1e-18. That is within rounding error of 0 (when compared to the magnitude of the eigenvalues). But because MATLAB doesn't know the eigenvalues are supposed to be real-valued, it gives them to you as comp... | python|matlab | 0 |
10,334 | 46,844,444 | Python OpenCV: Cannot resize image | <p>I am using Python 3 and OpenCV 3. I am trying to use the EigenFace Recognizer which uses the same size images for the training and test dataset. I read the image from a webcam and I resize the images to 200 x 200 but it shows an error . </p>
<p>This is my code:</p>
<pre><code>faceDetect=cv2.CascadeClassifier('haar... | <p>OpenCV uses NumPy arrays as the fundamental datatype to represent images. Indeed NumPy has a <code>resize</code> method to "resize" the data, but you're not using it properly. By <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.html" rel="nofollow noreferrer">consulting the documentation<... | python|image|opencv|image-processing|image-resizing | 8 |
10,335 | 46,842,923 | multiprocessing.Pool.map_async doesn't seem to... do anything at all? | <p>So, I'm working on an application that has to check ~50 GB of data against a list of hashes every time it starts up. Obviously this needs to be parallelized, and I don't want the application hanging on a "LOADING..." screen for a minute and a half.</p>
<p>I'm using <code>multiprocessing.Pool</code>'s <code>map_asyn... | <p>Let's see what happen:</p>
<p>You are using a context manager to automatically "close" the <code>Pool</code>, but, what is important, if you check <code>Pool.__exit__</code>'s source code, you will find:</p>
<pre><code>def __exit__(self, exc_type, exc_val, exc_tb):
self.terminate()
</code></pre>
<p>It just ca... | python|python-multiprocessing | 8 |
10,336 | 46,820,909 | Random sample within a certain range in a list (array) | Python 3.x | <p>I have a list with many characters in it like such:</p>
<pre><code>list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q',
'r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9',
'0'," ",'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q... | <p>You can slice the array, to sample it.</p>
<pre><code>random.sample(seq[:26], k=8)
</code></pre> | python|python-3.x|list|random|range | 4 |
10,337 | 61,445,314 | How to discount Cashflows with variable discount rates and sum all cashflows | <p>I am trying to price a bond that will pay coupons (c) semiannually for 4 years (which means 8 coupon payments in total) and return the principal (p) amount along with the 8th payment (c+p). The discount rate (dr) to discount each cashflows will be different.</p>
<p>inputs:</p>
<blockquote>
<p>dr = [0.10, 0.12, 0... | <p>I have tried to avoid loops as much as possible:</p>
<pre><code>p = 1000
c = 2
T = 4
freq = 2
dr = [0.10, 0.12, 0.15, 0.22, 0.37, 0.6, 0.8, 0.85]
import numpy as np
cashflows = np.dot(p,[(c/100 + (i==freq*T-1)) for i in range(freq*T) ])
print(cashflows)
dcf = sum([cf[0]/((1+cf[1])**(i+1)) for i,cf in enumerate(z... | python|python-3.x|time-series|quantitative-finance|financialinstrument | 0 |
10,338 | 61,509,508 | Force virtualenvironment to create an empty environment | <p>I am new to virtualenvironment and an advanced beginner in python. </p>
<p>I am trying to run a jupyter notebook but it seems that when I create a virtualenvironment the jupyter kernel used is the one of my system and not the one of the virtualenvironment I created. </p>
<p>For this reason I am trying to understan... | <p>Main python installed in your system already have the packages in it. and when you try to create a virtual environment in your system, it create a copy of the main python environment.</p>
<p>you can uninstall all the packages from main python environment by running:</p>
<pre><code>pip uninstall <package name>... | python|virtualenv | -1 |
10,339 | 56,881,034 | How do I find an image similar to the input image from a directory? | <p>I have a python program which will detect images from webcam. Now, I want to compare the image recognized by the webcam with the images in my directory and check if the exact similar image is already existing or not.</p>
<p>I have tried using <a href="https://www.pyimagesearch.com/2014/12/01/complete-guide-building... | <p>Here i write a small script for you, hope that it could solve your problem</p>
<pre><code>import cv2
import os
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
def read_img_from_dir(directory, query_shape):
# query_shape is a tuple which contain the size (width, height) of query im... | python|opencv|image-recognition | 1 |
10,340 | 65,601,742 | Is there a way in Python to check for programs playing audio | <p>I have a small script I want to have running in the background that would pause Spotify music if any other program starts playing audio - e.g. video, browser, game..</p>
<p>I got the spotify part working even without their API using win32api and SendMessage, however I can't seem to find any way of cheching whether o... | <p>You can use Mic which could help with voice commands from your mouth as well.</p>
<pre><code>import numpy as np
import sounddevice as sd
def is_sound_playing_windows():
duration = 1000 # in seconds
recording = sd.rec(int(duration), channels=2, blocking=True)
volume_norm = np.linalg.norm(recording) * 1... | python|audio|spotify | 0 |
10,341 | 65,710,056 | Pip installing "win10toast" on vscode, module wont show up? | <p>When putting</p>
<pre><code>from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast("Sample Notification","Python is awesome!!!")
</code></pre>
<p>the error keep's saying "No module named 'win10toast'
I have downloaded it on my computer and everything should work, I... | <p>I deleted all prior versions of my python (3.6-3.8) and kept my newest one.</p> | python | -1 |
10,342 | 43,180,859 | Use custom image in QCursor | <p>I have a .bmp image that I would like to use as a cursor for my GUI. The <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qcursor.html" rel="nofollow noreferrer">QCursor Documentation</a> suggests that this is possible ("To create a cursor with your own bitmap, either use the QCursor constructor which takes a bitmap ... | <p>If it can help anyone googling to here, and provided you can give a value to <code>whatEverColor</code> to be the transparent color. In <code>__init__</code> :</p>
<pre><code>pm = QtGui.QPixmap('image.bmp')
bm = pm.createMaskFromColor(whatEverColor, Qt.MaskOutColor)
pm.setAlphaChannel(bm)
cursor = QtGui.QCursor(pm)... | python|image|pyqt|qcursor | 3 |
10,343 | 36,696,081 | Django custom formset validation with additional data from other forms | <p>To validate my formset, I need to use additional data (outside of formset). How do I pass that data to validation function when it is located in <code>BaseFormSet</code>. Along with my formset, the <code>request.POST</code> also contains the <code>country_id</code> I need for validation. Also I need the user from se... | <p>You can simply provide a custom <strong>init</strong> method for you formset:</p>
<pre><code>class BaseShippingTupleFormSet(BaseFormSet):
def __init__(country_id, user, *args, **kwargs):
self._country_id = country_id
self._user = user
super(BaseShippingTupleFormSet, self).__init__(*args,... | python|django|django-forms|formset|django-validation | 2 |
10,344 | 48,513,886 | How can I remove rows where frequency of the value is less than 5? Python, Pandas | <p>I have a dataframe with lots of rows. Sometimes are values are one ofs and not very useful for my purpose. </p>
<p>How can I remove all the rows from where columns 2 and 3's value doesn't appear more than 5 times?</p>
<p>df input</p>
<pre><code> Col1 Col2 Col3 Col4
1 apple tomato ba... | <p><strong>Global Counts</strong><br>
Use <code>stack</code> + <code>value_counts</code> + <code>replace</code> -</p>
<pre><code>v = df[['Col2', 'Col3']]
df[v.replace(v.stack().value_counts()).gt(5).all(1)]
Col1 Col2 Col3 Col4
0 1 apple tomato banana
2 1 apple tomato banana
3 1 apple to... | python|pandas | 6 |
10,345 | 4,291,285 | Make a form from models using ModelForm, Models have many Foreignkeys( one class is the foreign key for the other.) | <p>I wanted to make a form which should be showing all the fields defined in models, wether the fields include a foreign key to some other class in the models. I am using ModelForm to generate forms.</p>
<p>My models look like</p>
<pre><code>class Employee(Person):
nickname = models.CharField(_('nickname'), max_le... | <p><a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/" rel="nofollow">Here is the documentation</a>...</p>
<p>Basic usage is:</p>
<pre><code>class EmployeeForm(ModelForm):
class Meta:
model = Employee
fields = ('somefield','otherfield')
</code></pre>
<p>etc...</p>
<p>fields i... | python|django|forms | 0 |
10,346 | 4,495,090 | Python filter list to remove certain links from html source code | <p>I have html source code which I want to filter out one or more links and keep the others. </p>
<p>I have set up my filter with "*" as the wildcard:</p>
<pre><code><a*>Link1</a>‚ <a*>Link2</a>‚ or <a*>Link3</a>
<a*>A bad link*</a>
some text* <a*>update*</a&g... | <p>To remove <code><a></code> tags and keep only the text not contained within those tags:</p>
<pre><code>>>> from BeautifulSoup import BeautifulSoup as bs
>>> markup = """<a*>Link1</a> <a*>Link2</a> or <a*>Link3</a>
... <a*>A bad link*</a>
... so... | python|regex|beautifulsoup | 3 |
10,347 | 51,254,419 | How to create a 3d Heatmap from a discrete data set in Python? | <p>I have a large dataset of the form [(X1, Y1, Z1, VALUE1), (X2, Y2, Z2, VALUE2)...]. The geometry of the points is the surface of a cylinder, while there are many discrete points they come nowhere near being a full mesh.</p>
<p>I would like to create a basic plot, where each of the points is given an intensity of a ... | <p>Depending on how dense your point cloud is you may be able to get what you want with this (adjust the size parameter, s, to fill out the plot best for your data):</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(X, Y, Z, c=Value, lw=0, s=20)
plt.show... | python|matplotlib|plot|3d|heatmap | 4 |
10,348 | 64,561,010 | sending email via Oulook with ipyvuetify | <p>I am developing a little app where I would like to include a button that will open outlook email editor and presented the user with an empty content but a particular subject ready to be filled in by the user and sent back to a particular email.</p>
<p>Does anyone know how to do that?</p>
<p>What I was reading in dif... | <p>maybe try</p>
<pre><code>import ipyvuetify as v
v_btn = v.Btn(class_ = 'mx-2 light-blue darken-1',
href = 'mailto:vinoth@email.com?subject=title&body=The message',
target = '_blank',
children = ['send email?'])
v_btn
</code></pre>
<p>I removed the 'hre... | python|button|vuetify.js|mailto|ipywidgets | 2 |
10,349 | 64,246,063 | How can I get standardized factor loadings with the semopy package in python? | <p>I'm using the semopy python package to do confirmatory factor analysis, and have a couple of questions:</p>
<ol>
<li>How do I get standardised factor loadings?</li>
<li>Is there a way to get modification indices (to help adapt the model step by step)?</li>
<li>How do I get the correlations between the factors?</li>
... | <ol>
<li>There is a boolean argument <em>std_est</em> for the <em>inspect</em> method that adds a standardized estimates column to the returned DataFrame with parameters estimates.</li>
<li>See <a href="http://semopy.com/indices.html" rel="nofollow noreferrer">Fit Indices</a> at the semopy website</li>
<li>Do you mean ... | python|factor-analysis | 0 |
10,350 | 70,406,352 | Create a pivot table in pandas while adding up the number of occurrences in a column | <h3>Setup</h3>
<p>Suppose I have the following dataframe:</p>
<pre><code> fruit color region subregion
0 banana yellow CANADA TORONTO
1 pear red CANADA MONTREAL
2 banana red CANADA TORONTO
3 banana yellow CANADA TORONTO
4 banana yellow CANADA MONTREAL
5 apple red U... | <p>You can actually use <a href="https://pandas.pydata.org/docs/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer"><code>pd.get_dummies</code></a> for this.</p>
<pre><code>new_df = pd.get_dummies(df.set_index(['fruit', 'color']), prefix='', prefix_sep='').groupby(level=[0, 1]).sum().reset_index()
</code><... | pandas | 3 |
10,351 | 73,066,584 | How to iterate over external input list in pyomo objective function? | <p>I am trying to run a simple LP pyomo Concrete model with <code>Gurobi</code>solver :</p>
<pre><code>import pyomo.environ as pyo
from pyomo.opt import SolverFactory
model = pyo.ConcreteModel()
nb_years = 3
nb_mins = 2
step = 8760*1.5
delta = 10000
#Range of hour
model.h = pyo.RangeSet(0,8760*nb_years-1)
#Individu... | <p>You have a couple serious syntax and structure problems in your model. Not all of the elements are included in the code you provide, but you (minimally) need to fix these:</p>
<p>In this snippet, you are initializing the <em>value</em> of each variable to a list, which is invalid. Start with no variable initializa... | python|optimization|linear-programming|pyomo|gurobi | 0 |
10,352 | 66,702,080 | How can I attach all images file in directory using MIME | <pre><code>import smtplib
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
import os
project_name = "ถังเก็บน้ำดับเพลิง 350m3 บีพี"
notwearing = 5
... | <pre><code>sending_path = glob.glob(output_paths+"/*")
random.shuffle(sending_path)
for img_path in sending_path:
fp = open(img_path, 'rb')
msgImage2 = MIMEImage(fp.read())
message.attach(msgImage2)
</code></pre>
<p>done</p> | python|image|email|mime-types|mime | 0 |
10,353 | 52,975,908 | how to extract specific content from a text file in python? | <p>I am using the <code>geonames</code> zip code data file at <a href="http://download.geonames.org/export/zip/IT.zip" rel="nofollow noreferrer">this link</a>. A sample data from above file is as below:</p>
<pre><code>IT 67010 Barete Abruzzi AB L'Aquila AQ 42.4501 13.2806 4
IT 67012 Cagnano Amitern... | <p>You were pretty close!</p>
<p>I would just suggest indexing in directly since you know which column they are instead of trying to parse by slicing:</p>
<pre><code>with open('data.txt', 'r') as f:
data = f.readlines()
for line in data:
line_sequence = line.split()
zipcode, lat, long = line_sequence[1... | python|geonames | 4 |
10,354 | 53,013,555 | ValueError: Negative dimension size caused by subtracting 3 from 1 for 'conv1d_1/convolution/Conv2D | <p>Binary classification problem: I want to have One input layer(optional), One Conv1D layer then output layer of 1 neuron predicting either 1 or 0.
<br>Here is my model:</p>
<pre><code>x_train = np.expand_dims(x_train,axis=1)
x_valid = np.expand_dims(x_valid,axis=1)
#x_train = x_train.reshape(x_train.shape[0], 1, x_t... | <p>Convolution1D layers takes input in a format of [batch, steps, channels]</p>
<p>Your length of convolution window (kernel size) cannot be larger than number of steps.</p>
<p>Therefore if you want to use your defined input shape of:</p>
<pre><code>x_train.shape = (5,1,133906)
</code></pre>
<p>you need to change k... | python-3.x|keras|conv-neural-network|convolution|keras-layer | 9 |
10,355 | 71,661,707 | Get a word's function in a sentence PY | <p>my question is a bit tricky here, in fact i'm trying to identify the ROLE of a word in a given sentence, i manage to get something using nltk, the problem is that it's telling me what the word is, what i'm searching for is it's job. For example God Loves Apples would not return God as a subject in this given sentenc... | <p>You could use dependency parsing. NLTK is not ideal for this task, but there are alternatives like <a href="https://stanfordnlp.github.io/CoreNLP/" rel="nofollow noreferrer">CoreNLP</a> or <a href="https://spacy.io/" rel="nofollow noreferrer">SpaCy</a>. Both can be tested online (<a href="https://corenlp.run/" rel="... | python|sentence | 1 |
10,356 | 71,278,424 | Combine rows in pandas df as per given condition | <p>I have pandas df as shown</p>
<pre><code> Name Subject Score
Rakesh Math 65
Mukesh Science 76
Bhavesh French 87
Rakesh Science 88
Rakesh Hindi 76
Sanjay English 66
Mukesh English 98
Mukesh Marathi 77
</code></pre>
<p>I have to make another df including students who ... | <p>In pandas, there is a method <code>explode</code> that will take a column that contains lists and break them apart. We can do a sort of opposite of that by making list of your Subjects column. I pulled the idea here from <a href="https://stackoverflow.com/questions/64235312/how-to-implodereverse-of-pandas-explode-ba... | python|pandas|dataframe | 2 |
10,357 | 70,318,091 | python - read data from API and save into dataframe | <p>I am trying to read a list of stock ticker and get price from Tiingo, but it reads only the last item "MO" and save into dataframe "data". how can I get the price for a full list? thanks.</p>
<pre><code>lis=[
"AAPL",
"MSFT",
"AMZN",
"GOOGL",
"TSLA&quo... | <p>You're overwriting <code>data</code> on every iteration.</p>
<p>Try having data as a list:</p>
<pre><code>data = []
for i in lis:
try:
data.append(client.get_dataframe([i],
frequency='daily',
metric_name='close',
... | python|dataframe|api|tiingo | 0 |
10,358 | 70,025,900 | Pandas expand value counts after groupby as columns | <p>As part of feature engineering, I want to use the counts of a column after groupby as a feature of the model, This is what I have tried</p>
<pre><code>>>> import pandas as pd
>>> from collections import Counter
>>> df = pd.DataFrame({'col1':['a','b','a','c','a','b'],'col2':['val1','val2','... | <p>Yes there is, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>melt</code></a>+<a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a>:</p>
<pre><code>df2 = df.melt(id_vars='col1',... | python-3.x|pandas|dataframe|pandas-groupby | 3 |
10,359 | 56,802,747 | Scikit's LabelEncoder uses `numpy.int64` instead of integers in `inverse_transform` | <p>If you <code>fit</code> an <code>sklearn.preprocessing.LabelEncoder</code> with labels of type <code>int</code>, for some reason during <code>inverse_transform</code> it returns <code>numpy.int64</code> type labels.</p>
<pre class="lang-py prettyprint-override"><code>from sklearn.preprocessing import LabelEncoder
l... | <blockquote>
<p>Why would it do that?</p>
</blockquote>
<p>Because <code>transform</code> and <code>inverse_transform</code> return numpy arrays and</p>
<blockquote>
<p><a href="https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html" rel="nofollow noreferrer">An item extracted from an array, e.g., by index... | python|machine-learning|scikit-learn | 2 |
10,360 | 72,209,178 | Calculating income and expense by filtering according to the entered date | <p>I have a date picker and I will calculate income and expense based on this date. I want to add a parameter named random_date to my function in view.py. I want the user to set the end date. The start time will be today's date. For example, if the user has selected June 1 as the date, I want to sum the income and expe... | <p>you can access POST or GET parameters from your request like this:</p>
<p><code>request.GET.get('my_var')</code><br>
<code>request.POST.get('my_var')</code></p>
<p>your summary.html sample omits your form opening tag so here is a view you might use assuming that you are POSTing information to your view:</p>
<pre><co... | python|django | 1 |
10,361 | 61,303,488 | Feed 1 frame to 2 models in tensorflow | <p>I have two tensorflow models (A.pb, B.pb ).
I have two written two python codes. Both of these take same frame input and produce output. (Currently, I run both of them in different terminals.)</p>
<p>Since they take same image frame as inputs... Can I do something in tensorflow like:</p>
<p>In 1 single python fil... | <p>Yes you can run 2 different models in the same tensorflow file like this:</p>
<pre><code>graph_A = tf.Graph()
with graph_A.as_default():
# create or saver.restore tf variables here for model A
graph_B = tf.Graph()
with graph_B.as_default():
# create or saver.restore tf variables here for model B
# run mo... | python|multithreading|tensorflow|parallel-processing|ros | 0 |
10,362 | 69,315,753 | The efficient way to compare value between two cell and assign value based on condition in Numpy | <p>The objective is to count the frequency when two nodes have similar value.</p>
<p>Say, for example, we have a vector</p>
<pre><code>pd.DataFrame([0,4,1,1,1],index=['A','B','C','D','E'])
</code></pre>
<p>as below</p>
<pre><code> 0
A 0
B 4
C 1
D 1
E 1
</code></pre>
<p>And, the element Nij is equal to 1 if nodes... | <p>With numpy, you can use broadcasting:</p>
<h3>1D</h3>
<pre><code>a = np.array([0,4,1,1,1])
(a==a[:, None])*1
</code></pre>
<p>output:</p>
<pre><code>array([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 1, 1],
[0, 0, 1, 1, 1],
[0, 0, 1, 1, 1]])
</code></pre>
<h3>2D</h3>
<pre><code>a = np.arr... | pandas|performance|numpy | 1 |
10,363 | 55,312,198 | Can Python make an OS similar to Windows? | <p>I want to make a OS that could be gaming-friendly (like Windows) yet easy to use. I can already use Python perfectly fine, and I'm looking to see if I could make an OS with it. Is it possible? If not, what are some Python-like coding languages that I could use?</p>
<p>I've looked in to Buildroot but it uses the Mak... | <p>@Neutrino You in theory can, it's not an easy task you would first have to make the python bytecode interpreter sit directly on bare metal this still involves quite a bit of C. At that point you would have a micro-kernel with the rest of the operating system written in Python. People have prototyped this in years pa... | python|operating-system | 1 |
10,364 | 53,881,793 | Can't connect to www.example.com with https | <p>I'm trying to get started with the Yocto project Quick Build, and the first <code>bitbake</code> command is failing when it tries to check the network availability by fetching <code>https://www.example.com</code>. The error message is:</p>
<p><code>Fetcher failure for URL: 'https://www.example.com/'. URL https://ww... | <p>If you look at the output from the debugging commands in the question
you'll see that the domain <code>www.example.com</code> is resolving to at least
3 different IP addresses, and perhaps most importantly, different IP
addresses are being resolved depending on the protocol passed to wget.</p>
<p>A lot of googling ... | python|dns | 0 |
10,365 | 58,513,933 | matching content creating new column | <p>Hello I have a dataset where I want to match my keyword with the location. The problem I am having is the location "Afghanistan" or "Kabul" or "Helmund" I have in my dataset appears in over 150 combinations including spelling mistakes, capitalization and having the city or town attached to its name. What I want to... | <h2>Given the following:</h2>
<ul>
<li>Sentences from the New York Times</li>
<li>Remove all non-alphanumeric characters</li>
<li>Change everything to lowercase, thereby removing the need for different word variations</li>
<li>Split the sentence into a <code>list</code> or <code>set</code>. I used <code>set</code> be... | python|pandas|function | 0 |
10,366 | 44,771,087 | How do I increase the size of a rectangle if a key is pressed? | <p>Using pygame, I'm trying to create a simple mechanic which will increase a rectangle in the top right of my code, in this case it is a health bar. For now I want to make the bar increase everytime the button 'x' is clicked. Here is my code:</p>
<pre><code> DISPLAYSURF = DISPLAYSURF = pygame.display.set_mode((900... | <p>Here's an example of a health bar:</p>
<pre><code>import pygame
pygame.init()
w, h = 400, 400
screen = pygame.display.set_mode((w, h))
health = 0
while True:
screen.fill((0, 0, 0))
if pygame.event.poll().type == pygame.QUIT: pygame.quit(); break
keys = pygame.key.get_pressed()
if keys[pygame.K_x... | python|pygame | 0 |
10,367 | 38,404,633 | Reading YAML config file in python and using variables | <p>Say I have a yaml config file such as:</p>
<pre><code>test1:
minVolt: -1
maxVolt: 1
test2:
curr: 5
volt: 5
</code></pre>
<p>I can read the file into python using:</p>
<pre><code>import yaml
with open("config.yaml", "r") as f:
config = yaml.load(f)
</code></pre>
<p>Then I can access the varia... | <p>You can do this:</p>
<pre><code>class Test1Class:
def __init__(self, raw):
self.minVolt = raw['minVolt']
self.maxVolt = raw['maxVolt']
class Test2Class:
def __init__(self, raw):
self.curr = raw['curr']
self.volt = raw['volt']
class Config:
def __init__(self, raw):
... | python|yaml|config | 8 |
10,368 | 40,203,416 | Loading OpenCV Image To Scikit Learn | <p>I'm programming a machine learning script to take pictures and label it. I have my dataset in a folder and I add them into array and create another array for labels. when i try to use svm.fit it gives the error :</p>
<pre><code>File "scikit.py", line 43, in <module>
clf.fit(arrayimg, arraylabel)
File "/... | <p>I'm not an expert on the image processing side but I'm guessing that your <code>getImage</code> function is returning a 2d array for each image. Where as <code>sckit-learn</code> will be expecting a 1d array for each training instance. Assuming that all of your images are of the same size then the following should w... | python|opencv|scikit-learn | 0 |
10,369 | 52,051,798 | writing series of data in json file | <p>Am working in project on writing output in json file.I found json write code in web.But,it writes only the last value.It doesn't store the previous value`</p>
<p>the code am using:</p>
<pre><code>import json
data=0
for data in range(0,99):
print(data)
with open('data.json', 'w') as outfile:
json.d... | <p>You need to first create your structure, and then dump <em>all</em> of it in one go into a json file:</p>
<pre><code>import json
data = list(range(0, 99)) # You can just write range(99) instead of range(0, 99)
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
</code></pre>
<p>And the output:</... | python|json | 1 |
10,370 | 70,499,787 | Is the time complexity of string += "a" the same as string = string + "a"? | <p>In both statements, I am appending a character <code>"a"</code> to the string <code>s</code>:</p>
<ol>
<li><code>s += "a"</code></li>
<li><code>s = s + "a"</code></li>
</ol>
<p>Which statement has the better time complexity in Python?</p> | <p>They have the same time complexity.</p>
<p>In the general Python standard defined case: They both have the same time complexity of O(n), where n is the length of string <code>s</code>.</p>
<p>In practice, with the CPython implementation: They can in some cases both be O(1), because of an optimization that the interp... | python|time-complexity | 8 |
10,371 | 55,678,227 | How to switch images after animation? | <p>I have a couple of questions:</p>
<ol>
<li><p>I have animation of spinning ball which should be always on top of screen and screen should always show only half of it. I can do it but only by clicking buttom to call function which take ball to the right place. I need ball to be always in right place not only then i ... | <p>You can start the animation using <code>Clock.schedule_once()</code> as:</p>
<pre><code>def __init__(self, **kwargs):
super(OpenScreen, self).__init__(**kwargs)
Clock.schedule_once(self.z)
</code></pre>
<p>You will need to add a <code>dt</code> argument to the <code>z()</code> method and utilize the <code>... | python|oop|animation|kivy | 0 |
10,372 | 50,181,359 | islice and cycle with multiple levels | <p><strong>UPDATE</strong>:
Added the pattern required as asked
I have 2 lists and the expected output is different than the last time</p>
<pre><code>Numberset1 = [10,11,12]
Numberset2 = [1,2,3,4,5]
</code></pre>
<p>and i want to display output by manipulating the lists, the expected output is</p>
<pre><code>10 1 1
... | <p>Here's a version that accomplishes the task using <code>cycle</code> and <code>islice</code>. To make the code cleaner I've created a generator function <code>aligned_cycle</code> which cycles through the items yielded by <code>cycle</code> until we get the one we want to start the current cycle with.</p>
<p>This u... | python|python-3.x|itertools | 3 |
10,373 | 49,906,993 | How can I break the sleep when I pressed a button on tkinter | <p>I have a <code>sensor()</code> method, and I use <code>root.after(200, sensor)</code> to run it all the time. I also have a function <code>set_speed()</code> in it which can set the speed of motor. When the sensor detects something, it will run </p>
<pre><code>set_speed(100)
sleep(3)
set_speed(0)
</code></pre>
<p>... | <p>Problem solved. We can simply use another after to build another thread which will be run 3 seconds later and set the speed as 0.</p>
<pre><code> set_speed(100)
root.after(3000, stop)
.....
def stop():
set_speed(0)
</code></pre> | python|tkinter | 0 |
10,374 | 66,701,446 | pandas .plot.hist() with .groupby() | <p>I'm aware that <a href="https://stackoverflow.com/questions/41622054/stacked-histogram-of-grouped-values-in-pandas">this similar question</a> has been asked; however, I'm looking for further clarification to have better understanding of .groupby if it's possible.
<a href="https://raw.githubusercontent.com/mwaskom/se... | <p>Expanding on Quang's comment, you would want to bin the ages rather than grouping on every single age (which is what <code>df.groupby('age')</code> does).</p>
<p>One method is to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><strong><code>cut</code></s... | pandas|pandas-groupby|pivot-table|histogram | 2 |
10,375 | 64,162,961 | Visual Studio Code Python 3 Command/Install Error | <p>When I've been opening VS Code lately I've been getting this message saying</p>
<blockquote>
<p>The "python3" command requires the command line developer tools. Would you like to install the tools now?</p>
</blockquote>
<p>Everytime I click yes and the installer prompts me that it can't be found on the ser... | <p>According to your description and feedback, the cause of this problem is that the installation tool <code>pip</code> cannot be used. You can use the following methods to solve it:</p>
<ol>
<li>You can reinstall <code>pip</code> manually. <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow noreferrer">I... | python|python-3.x|visual-studio-code | 2 |
10,376 | 53,019,804 | Capacitated Vehicle Routing Problem with Time Windows crashing | <p>I am working on the sample code shared by Google OR Tools. This sample is for Capacitated Vehicle Routing Problem with Time Windows. </p>
<p>When I run the entire programme shared <a href="https://developers.google.com/optimization/routing/cvrptw" rel="nofollow noreferrer">here</a> . It runs fine and gives the outp... | <p>You have to turn your nodes into <strong>optional</strong> nodes.</p>
<p>See:
<a href="https://stackoverflow.com/questions/53104283/defining-nodes-that-do-not-have-to-be-visited">Defining nodes that do not have to be visited</a></p> | python|or-tools|vehicle-routing | 2 |
10,377 | 5,550,089 | How to create a nested list in reStructuredText? | <p>I am trying to create a properly nested list using the following code (following <a href="http://sphinx.pocoo.org/latest/rest.html#lists-and-quote-like-blocks" rel="noreferrer">Sphinx</a> and <a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html" rel="noreferrer">docutils</a> docs):</p>
<pre><... | <p>Make sure the nested list is indented to the same level as the text of the parent list (or three characters, whichever is greater), like this:</p>
<pre><code>1. X
a. U
b. V
c. W
2. Y
3. Z
</code></pre>
<p>Then you'll get the output you expected.</p> | markup|restructuredtext|python-sphinx | 125 |
10,378 | 61,894,712 | Unable to send POST request using Flask test client | <p>I'm following the <code>TestDriven.io</code> course, after setting up restful routes I encounter this error even after adding the route handler in <code>project/api/users.py</code>:</p>
<pre><code>test_app_is_development (test_config.TestDevelopmentConfig) ... ok
test_app_is_production (test_config.TestProductionCo... | <p>Judging by the error log, the problem is in the INSERT INTO statement. The <code>created_date</code> parameter is not a date but a function <code>sqlalchemy.sql.functions.now</code>. It looks like you forgot to call it.</p> | python|python-3.x|flask|sqlalchemy|testdriven.io | 1 |
10,379 | 67,553,058 | How to plot each axes above the other with a for-loop | <p>I am trying to get visualizations from titanic dataset:</p>
<pre class="lang-py prettyprint-override"><code>import seaborn as sns
fig, axs = plt.subplots(nrows=5, ncols=1)
X=['sex', 'cabin', 'port_of_embarkation', 'is_boy', 'is_married_female']
for ax, x in zip(axs, X):
sns.barplot(x, y='survived', data=main_d... | <p>You forgot to specify the axis for each plot, so it is plotting them all on the same axis.</p>
<pre><code>for ax, x in zip(axs, X):
sns.barplot(ax=ax, x=x, y='survived', data=main_df, estimator=lambda x: sum(x==1)*100.0/len(x))
</code></pre> | python|for-loop|seaborn | 1 |
10,380 | 67,243,165 | How do convert the output of a nested for loop into a list in Python? | <p>I am very new to Python so apologies for this basic question. I am trying to match columns of keywords with a list of text. If the keyword(s) can be found in the text, these should be appended to the spreadsheet which currently ends at the 'Engagement' column.</p>
<p>I currently get the following error message in th... | <p>I actually don't get why you want to have an empty string there, but maybe this helps you:</p>
<p><a href="https://i.stack.imgur.com/p8x1Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p8x1Y.png" alt="enter image description here" /></a></p> | python-3.x|nested-loops | 2 |
10,381 | 67,248,486 | Is it possible to convert integers to time intervals in a Pandas pivot table? | <p>This is my pivot DataFrame:</p>
<pre class="lang-py prettyprint-override"><code>Name Tutor Student
Date
2021-04-12 310 112
2021-04-13 394 210
2021-04-14 357 3
2021-04-15 359 0
2021-04-16 392 0
2021-04-17 307 ... | <p>Not very clear for the output you are looking for.</p>
<p>We can leverage pd.to_timedelta() method to convert seconds to timedelta.</p>
<p><strong>Solution</strong></p>
<pre><code>df.iloc[:].apply(pd.to_timedelta, unit='s')
</code></pre>
<p>(Considering you want all columns in df to be converted to time_delta, if ... | python|pandas|database|pivot-table | 2 |
10,382 | 67,277,227 | How do regex objects work in Python loops? | <p>I am constructing an if statement on Python that prints something when regex's match function founds a coincidence. I would like to know why the if statement works when my statement's condition is not a boolean (I think so).</p>
<pre><code>import re
coincidence = re.match(r'\w{3}', 'abc')
if coincidence:
print('... | <p>Python types have a "truthiness" value associated. You can try it out by executing <code>bool()</code> on different objects. The most obvious example would be integers:</p>
<pre><code>bool(1)
> True
bool(0)
> False
</code></pre>
<p>but it goes beyond. <code>bool("")</code> will be <code>... | python|python-3.x|regex|if-statement | 3 |
10,383 | 60,588,557 | Gensim row wise dataframe summary | <p>I am using 'Gensim' to generate summary of different rows I have. Here is what the original dataframe looks like:</p>
<pre><code>df.head()
Example Content
0 Not happy they have just reduced rates for Und...
1 One of the worst banks. I had a very bad exper...
2 Some one in l... | <p>You keep overwriting your list. Replace</p>
<pre><code>a = summarize(i, ratio=0.4, split = True)
</code></pre>
<p>with </p>
<pre><code>a.append(summarize(i, ratio=0.4, split = True))
</code></pre> | python|pandas|for-loop|gensim|summarization | 0 |
10,384 | 71,389,818 | Trying to use Python and Selenium to click on a drop-down menu on facebook ad library | <p>I'm trying to use Selenium and Python to automate searching for ads on the Facebook/Meta Ad Library.</p>
<p>I've tried two possible ways, being the first this code bellow, which I had no luck.</p>
<pre><code># open up the dropdown
dropdown = driver.find_element_by_css_selector("#content > div > div > d... | <p>Go for <strong>Relative xpath</strong> instead of <strong>Absolute xpath</strong>. The locators does not highlight any element in the DOM.</p>
<p>It is necessary to find unique locators for Automation.</p>
<p>Refer these links - <a href="https://stackoverflow.com/q/27183353/16452840">Link 1</a> ,<a href="https://aut... | python|selenium | 2 |
10,385 | 11,422,552 | pandas: bypassing numerical index | <p>Sometimes I am dealing with <code>DataFrame</code>s that have a numerical index, but I would like to bypass it to reference rows according to their order,</p>
<pre><code>In [49]: df = pandas.DataFrame(np.random.randn(3, 5))
In [50]: df
Out[50]:
0 1 2 3 4
0 -2.426211 0.67... | <p>You can use DataFrame.irow:</p>
<pre><code>In [18]: df2
Out[18]:
0 1 2
1 2.279885 -0.414938 -2.230296
2 -0.237980 -0.219556 1.231576
In [19]: df2.irow(0)
Out[19]:
0 2.279885
1 -0.414938
2 -2.230296
Name: 1
In [20]: df2.irow([0, 1])
Out[20]:
0 1 2
1 ... | python|pandas | 4 |
10,386 | 11,418,558 | How do you use numpy in google app engine (Python) | <p>numpy is supported as a library in google app engine according to the official documentation <a href="https://developers.google.com/appengine/docs/python/tools/libraries27" rel="noreferrer">here</a>. I was not able to import it after a few trials, can anyone share the code to use it?</p>
<p>I believe it should be c... | <p>If you want it to work locally you have to download and install it locally (I got mine from here <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy" rel="noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy</a>)</p>
<p>Besides that you have to make sure you are running python27, and that you're impor... | google-app-engine|numpy | 12 |
10,387 | 70,386,182 | How to read multiple cvs files to Google Colab at once | <p>I was doing something like this,
<a href="https://i.stack.imgur.com/Aoslf.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<p>Is there a way that I can read them all at once?</p> | <p>I would personally do a dict comprehension for this</p>
<pre class="lang-py prettyprint-override"><code>root = "drive/Mydrive/"
goodvariable = {f"subject{num}":
{'running': pd.read_csv(f'{root}data/subject_{num}/acc_running_chest.csv'),
'walking': pd.read_csv(f'{root}data/subject_{num}/acc_walk... | python|google-colaboratory | 0 |
10,388 | 63,422,692 | Python Discord OAuth2 - Guild.Join (Joining a Guild) | <p>Hi I'm trying to do a 'Authorize with Discord' that automatically joins the user to my guild.</p>
<p>I'm running a <code>Flask</code> application that handles all of these.</p>
<p>So far, here's my code:</p>
<pre><code>def add_to_guild(access_token, userID, guildID):
url = f"{Oauth.discord_api_url}/guil... | <p><strong>Update 3</strong> put() is the way to go
However, you're still missing the JSON payload which must include the user access token received from the token exchange from a code grant.</p>
<pre class="lang-json prettyprint-override"><code>data = {
"access_token" : access_token
}
</code></pr... | python|discord | 0 |
10,389 | 56,526,096 | Count how many consecutive TRUEs on each row in a dataframe | <p>I am trying to count how many consecutive TRUEs on each row and I solved that part myself but I need to find a solution for this part: If a row starts with FALSE then result must be 0. There is a sample dataset below. Can you recommend me your tips to how to solve this.</p>
<p>PS. my original question is at the lin... | <p>You can use <code>np.argmin</code>. You needn't prefilter your df, it will handle rows starting with <code>False</code> correctly.</p>
<pre><code>df.loc[:, 'M_1':'M_12'].values.argmin(1)
#array([0, 3, 1, 4, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 2, 0])
</code></pre>
<p>Note that this assumes there is at least one <code>... | python|arrays|pandas|numpy|dataframe | 3 |
10,390 | 60,991,417 | Save the Universal Sentence Encoder to Tflite or serve it to tensorflow api | <p>I have this code for finding sentence similarity using the pre-built universal sentence encoder. It takes a .txt file as input. Performs cosine similarity and then accepts an output from user to find the most similar sentence as per users input query. This is the code:</p>
<pre><code># tensroflow hub module for Uni... | <p>One option to proceed would be to save the model in <a href="https://www.tensorflow.org/guide/saved_model" rel="nofollow noreferrer">SavedModel format</a>, then convert the resulting model to tflite. Note that the ability to convert the model may depend on the ops that the model is using and some model architectures... | python|tensorflow|machine-learning|tensorflow-lite|tensorflow-hub | 1 |
10,391 | 66,010,622 | ValueError: Missing column provided to 'parse_dates': 'CRASH_DATE, CRASH_TIME' | <p>I made a streamlit app. It works fine when I run it locally.
But, after I push it to heroku, I got this value error on the parse_dates:</p>
<pre><code> ValueError: Missing column provided to 'parse_dates': 'CRASH_DATE, CRASH_TIME'
Traceback:
File "/app/.heroku/python/lib/python3.6/site-packages/streamlit/sc... | <p>When you reference a file on GitHub, you need to make sure you are accessing the "raw" version, not the version from the GitHub interface. Adding the <code>?raw=true</code> parameter to your url should work:</p>
<p><code>https://github.com/chairielazizi/streamlit-collision/blob/master/Motor_Vehicle_Collisi... | python|pandas | 0 |
10,392 | 69,265,804 | Read file name then call the convenable function (with one or two arguments) using python | <p>I want to read file name(A/B/C/D) and call the convenable function for each file in <strong>Files folder</strong> and then process the <em>next file</em> (pass automatically to the next file and function).</p>
<p>I have multiple files stored in <strong>Files folder:</strong></p>
<p>Here is the directory structure:</... | <p>You can check if a path is a directory with <code>os.path.isdir</code> and change the call arguments.</p>
<pre><code>base_path = 'Files/'
for name in os.listdir(base_path):
path = os.path.join(base_path, name)
if os.path.isdir(path):
files = [os.path.join(path, f) for f in os.listdir(path)]
i... | python|python-3.x|pandas|arguments|parameter-passing | 1 |
10,393 | 68,412,442 | making a contour plot using irregular x y z data | <p>I want to make a beautiful contour map using my data attached and want to write A B C D E F G H on the map itself.</p>
<pre><code>dt x y z
A 31.53 77.95 0.112
B 31.40 78.35 0.032
C 31.66 78.03 -0.001
D 31.48 77.75 -0.092
E 32.28 78.45 -0.113
F 31.99 76.42 -0.184
G 31.64 77.34 -0.... | <p>When you use the method: <code>np.loadtxt()</code>, you get an ndarray object which is different from pandas Dataframe because the first index are the <strong>rows</strong> and not the columns.</p>
<p><code>np.loadtxt()</code> documentation: <a href="https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.htm... | python|pandas|numpy|matplotlib|seaborn | 1 |
10,394 | 59,071,343 | Getting wrong number of rows after dropping row in Pandas Dataframe | <p>After I drop a specific row in a Pandas dataframe with:
<code>df = df.drop([rowNumber])</code> I no longer can get the correct number of rows with <code>len(df.index)</code>.
I have tried resetting the index with both <code>df = df.reset_index(drop=True)</code> and <code>df.index = range(len(df))</code>. When I go t... | <p>Maybe you forgot to use the <code>inplace</code> option, if set to true it apply changes to the dataframe itself else it will return a new dataframe.
I used it after using the dropna and it worked correctly
<code>df.reset_index(inplace=True, drop=True)</code></p>
<p><a href="https://note.nkmk.me/en/python-pandas-res... | python|pandas | 0 |
10,395 | 63,141,513 | django endpoint not returning all fields specified in serializer | <p>This is Source Def:</p>
<pre><code>class SourceDefinition(models.Model):
source = models.ForeignKey(Source, on_delete=models.DO_NOTHING)
special_id = models.IntegerField(default=0)
ad_group = models.CharField(max_length=50)
creator = models.CharField(max_length=100)
config = JSONField(default=dic... | <p>If you have a custom filed in you serializer, like source and source_id in your case, you must specify it explicitly in the fields list. Specify all fileds one by one, plus source and source_id too.</p>
<p>Example, in your case:</p>
<pre><code>class SourceDefinitionSerializer(serializers.ModelSerializer):
source... | python|django|django-rest-framework | 1 |
10,396 | 35,491,131 | how to execute a source command from php in a server | <p>I am unable to execute a source command in linux using php.All other commands are working except this one. I need to execute the following command.</p>
<pre><code> source /root/Envs/ate/bin/activate
</code></pre>
<p>This activates the ate-Automatic Test Equipment.Once I activate it then I need to run a python scri... | <p>I found out the error. Since I am doing it using php (for a web tool) the user is Apache. 'Apache' user is unable to access the script in root folder. Moving it to another directory, I am able to run the script fine.</p>
<p>Thanks all..</p> | php|python | 0 |
10,397 | 58,809,316 | Execution python script in terminal or pvpython in mac | <p>I installed ParaView 5.7 and record a python script with it.
In Windows 10, I'm able to open a pvpython shell and execute code but in my Mac I can't find this pvpython shell.</p>
<p>I have tried executing the script in the terminal <code>python my_script.py</code> and get the error</p>
<pre><code>from paraview.sim... | <p>On the Mac, <code>pvpython</code> is installed in <code>/Applications/ParaView-5.7.0.app/Contents/bin/pvpython</code></p> | python-2.7|paraview | 2 |
10,398 | 58,726,459 | MS Access data into Azure Blob | <p>Data is in MS Access and it's in one of the shared drive on the network. I need this data in azure blob storage as CSV files. Can anyone please suggest me how can this be possible? </p> | <p>You can move data to Azure Blob storage in several ways, You could use either Azcopy: located here: <a href="https://docs.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-v10" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-v10</a> , Or Storage Explorer(G... | python|ms-access|azure-data-factory|azure-blob-storage|azure-data-lake-gen2 | 1 |
10,399 | 58,672,542 | EOF when reading a line or idk | <p>I am just doing a program that does the following thing.</p>
<ol>
<li>You input "count" of something.</li>
<li>Then you input a value for every "count" separated by spaces</li>
<li>You get the output: How many of them are duplicated and which duplicated number is the highest again separated by space</li>
</ol>
<p>... | <pre><code>from collections import Counter
# Convert them all to an int
numbers = [int(i) for i in input("Numbers: ").split(" ")]
# Get number of input
count = len(numbers)
counter = Counter(numbers)
# Get the highest value of the most common values
max_dup, _ = max(counter.most_common(), key=lambda ele: ele[0])
#... | python|python-3.7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.