Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
9,300 | 38,154,247 | Efficiency of checking for string in querystring parameters in python | <p>I am running a query that needs to exclude all previously seen items and return a certain number of items (10 in this case). The list of items is sent in a querystring parameter and are uuid4 strings separated by '&'. </p>
<p>With a possible very large database, I don't think it makes sense to add the exclude s... | <p>Whatever you are doing will be much faster if you use Python's built in <code>set</code> data structure. Checking for inclusion then is very fast, if you have some memory available, but 1k items is nothing. see <a href="https://docs.python.org/2/library/stdtypes.html#set" rel="nofollow">https://docs.python.org/2/l... | python|string|list | 1 |
9,301 | 38,276,495 | Window-Leveling in python | <p>I would like to change the window-level of my dicom images from lung window to chest window. I know the values need for the window-leveling. But how to implement it in python? Or else anyone can provide me with an detailed description of this process would be highly appreciated. </p> | <p>I have already implemented this in Python. Take a look at the function GetImage in <a href="https://github.com/dicompyler/dicompyler-core/blob/master/dicompylercore/dicomparser.py" rel="nofollow">dicomparser</a> module in the <a href="https://github.com/dicompyler/dicompyler-core" rel="nofollow">dicompyler-core</a> ... | python|image|dicom | 2 |
9,302 | 40,246,277 | How to change the ticks in a confusion matrix? | <p>I am working with a confusion matrix (Figure A)</p>
<p>How can I make my <code>ticks</code> to start from 1 to 3 instead of 0 to 2?</p>
<p>I tried adding a +1 in <code>tick_marks</code>. But it does not work (Figure B)</p>
<p>Check my code:</p>
<pre><code>import itertools
cm = confusion_matrix(y_test, y_pred)
n... | <p>You should get the <code>axis</code> of the <code>plt</code> and change the <code>xtick_labels</code> (if that's what you intend to do):</p>
<pre><code>import itertools
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
from skl... | python-3.x|numpy|matplotlib|scikit-learn|confusion-matrix | 4 |
9,303 | 29,111,197 | Require character anywhere in a match | <p>I'm working on a regex to match <code>F. Supp.</code> or <code>F.3d</code> but not <code>On June</code> or <code>foobar</code>.</p>
<p>So far, I have <code>[A-Z][ ]?[A-Z|a-z|\.| ][A-Z|a-z|\.| |0-9]+</code>. It's almost there, but it still matches <code>On June</code>. I want to require a <code>.</code> (period char... | <p>If you just want your string contain <code>.</code> you can use <code>in</code> operand :</p>
<pre><code>if '.' in word
</code></pre>
<p>And with regex you can use a positive look-around to ensure that you have a dot <code>.</code> in your string :</p>
<pre><code>([\w ]+)?(?=\.).([\w ]+)?
</code></pre>
<p><img s... | python|regex|string | 1 |
9,304 | 8,915,020 | Validating a form in a get request, how? | <p>in my way of perfectionism, I'm here to ask more questions about the not-so-well-documented class-based views.</p>
<p>I spend like 5 hours learning about class-based views, lurking into the code and I got a question.</p>
<p>Maybe what I'm trying to do is stupid, and if so, just say that.</p>
<p>I will put a simpl... | <p>Your problem is that <code>super(SearchFormView, self).get(request, *args, **kwargs)</code> renders its own form and own context. It's only a 3 line view function, so you should really be overriding what you need to change its behavior.</p>
<pre><code> def get(self, request, *args, **kwargs):
form = Searc... | python|django|django-class-based-views | 3 |
9,305 | 8,529,258 | Generate a Sound file with a 15Khz tone | <p>I'm playing around with high-pitched sounds. I'd like to generate an MP3 file with a 1 second 15Khz burst. Is there a simple way to do this from C or Python? I don't want to use MATLAB.</p> | <p>You could use Python's <a href="http://docs.python.org/library/wave"><code>wave</code></a> module to create a wave file which you could then compress to MP3. To create a one second 15khz sine wave:</p>
<pre><code>import math
import wave
import struct
nchannels = 1
sampwidth = 2
framerate = 44100
nframes = 44100
co... | python|c|audio|mp3 | 14 |
9,306 | 58,837,083 | JSON.loads is converting double quotes to single quotes | <p>I am beginner to Python. Here I am trying use JSON.load to parse the JSON string. When using json.dumps, I receive the following output:</p>
<pre><code>{
"events": [
{
"sourceip": "10.10.10.1",
"destinationip": "127.0.0.1"
},
{
"sourceip": "10.10.10.2",
"destinationip": "127.0.... | <p>Once you load JSON with <code>.load</code> or <code>.loads</code>, there are no longer any quotes whatsoever. Instead, it's converted into a data structure consisting of Python objects: the root <code>dict</code>, containing other <code>dict</code>s or <code>list</code>s an so on.</p>
<p>What you see in your second ... | python|json | 2 |
9,307 | 52,418,213 | How to make the rotation (by the center) of this pygame sprite work? | <p>I'm having a great difficulty to create a single sprite rotation using pygame. </p>
<p>I'm following this code (<a href="https://stackoverflow.com/a/47688650/5074998">https://stackoverflow.com/a/47688650/5074998</a>) to obtain a center rotation of a sprite. And here is my current code:</p>
<pre><code>import pygame... | <p>That happens because you're blitting the <code>self.image</code> at the position <code>[100, 100]</code> instead of the <code>self.rect</code> (that means at the <code>self.rect.topleft</code> coordinates). The size of the image is different after each rotation and if you just blit it at the same top left coordinate... | python|python-3.x|rotation|pygame | 2 |
9,308 | 52,436,368 | Testing for new line in Python stdout | <p>I have a script in which I'm having difficulty testing for a new line character coming from stdout of a remote command.</p>
<pre><code> OUT = stdout.readlines()
print OUT
if ['\n'] in OUT:
print "/disk/var/log/app directory deleted"
else:
for line in OUT:
print line.strip()
</code></pre>
<p>... | <p>Right now you are checking if the list <code>['\n']</code> (i.e. the list containing only one element, <code>'\n'</code>) is contained in <code>OUT</code></p>
<p><a href="https://docs.python.org/3/library/io.html#io.IOBase.readlines" rel="nofollow noreferrer">readlines()</a> returns a list of strings. It will never... | python|stdout | 1 |
9,309 | 52,250,577 | Python coding trouble | <p>For homework, I am supposed to code a recipe that takes the input of the deserts and spit out how much of the ingredients would be required. I'm still new and keep getting this error code, but could possibly be wrong altogether? </p>
<pre><code>print("Welcome to Carmack's Bakery")
cookies = int(input('How many do... | <p>It looks like you're on the right track here.</p>
<p>The problem is in your second to the last line:</p>
<p><code>
cookies_dozen = float('cookie_eggs' + 'cookie_butter' + 'cookie_sugar' +
'cookie_flour' * 'cookies')
</code></p>
<p>Since <code>cookie_eggs</code>, <code>cookie_butter</code> etc are all variable... | python|string|recipe | 1 |
9,310 | 51,647,828 | how to send authorization details in pact Json Generation or to pact verfier in PACT PYTHON | <p>how to send authorization details in MOCK service or to pact verfier in PACT PYTHON</p>
<p>when i call API thorugh soapUI it is working fine but when i run it mock Json through Pact verfier , it is faling since i am not senidng Authorization details in request header or not adding in pact verfier.
can u please help... | <p>Please read <a href="https://docs.pact.io/faq#how-do-i-test-oauth-or-other-security-headers" rel="nofollow noreferrer">https://docs.pact.io/faq#how-do-i-test-oauth-or-other-security-headers</a> as a starting point.</p>
<p>On the consumer side, what you have done is fine (although you might want a matcher if you are... | python-requests|pact | 0 |
9,311 | 68,924,974 | ' '.join(context.args) recieves only strings how can i make it recieve int? | <p>See my code first:</p>
<pre><code>def data(update: Update, context: CallbackContext):
user_says = ' '.join(context.args)
</code></pre>
<p>so the problem here is that user_says only accepts string even if the user wrote 1 it takes it as '1' how can I make it take 1 or any int as itself?</p> | <p>You can always parse the <code>int</code> to <code>string</code> and the use <code>.join</code> like this</p>
<pre><code>user_says = ' '.join(str(context.args))
</code></pre>
<p>Hope this is the answer you're looking for, if not please specify :)</p> | python|telegram|telegram-bot|python-telegram-bot | 2 |
9,312 | 63,571,746 | A generator for multivariate normal variates in Python | <p>I want to generate samples from a multivariate normal distribution with given mean and covariance, which, of course, is possible with <code>numpy.random.multivariate_normal</code>. But I want to generate a (philosophically) infinite stream of such things, and so I want to define a multivariate normal generator <code... | <p>Just to establish some ground truth, this is how one might implement it:</p>
<pre><code>from collections.abc import Generator
import numpy as np
class multinorm(Generator):
def __init__(self, themean, themat):
self.eigs, self.cmat = np.linalg.eigh(themat)
self.meanvec = themean
self.thed... | python|numpy|scipy|generator | 0 |
9,313 | 19,775,036 | issues rotation in pygame and python | <p>I have the following program: what it does is it reads in a file of xyz coordinates and stores them in a list:</p>
<pre><code>J
-2000 379 -1817 # 21
J
-1112 379 -1791 # 16
-1112 379 -1817 # 22
J
-589 379 -1896 # 7
-79 379 -1896 # 23
-79 405 -1870 # 25
-589 405 -1870 # 8
J
</code></pre>
<p>I then take this ... | <p>You can multiply a tuple with a float like this:</p>
<pre><code>new_tuple = tuple(multiplier*x for x in previous_tuple)
</code></pre>
<p>In your case that would be:</p>
<pre><code>rot_Z = tuple(cosa*x for x in Ys) + tuple(-sina*x for x in Xs)
</code></pre> | python|list|rotation|pygame|typeerror | 0 |
9,314 | 13,574,606 | How to add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x | <p>I'm stuck on how to formulate this problem properly and the following is:</p>
<p>What if we had the following values:</p>
<pre><code>{('A','B','C','D'):3,
('A','C','B','D'):2,
('B','D','C','A'):4,
('D','C','B','A'):3,
('C','B','A','D'):1,
('C','D','A','B'):1}
</code></pre>
<p>When we sum up the first place value... | <p>The following should work:</p>
<pre><code>def popular(letter):
'''(dict of {tuple of (str, str, str, str): int}) -> dict of {str:int}
'''
my_dictionary = {}
for alphabet, picks in letter.items():
if alphabet[0] in my_dictionary:
my_dictionary[alphabet[0]] += picks
else... | python|key|tuples|dictionary | 0 |
9,315 | 13,651,531 | Python regex speed - Greedy vs. non-greedy | <p>I am making several regex substitutions in Python along the lines of </p>
<pre><code> \w\s+\w
</code></pre>
<p>over many large documents. Obviously if I make the regex non-greedy (with a <code>?</code>) it won't change what it matches (as <code>\w</code> != <code>\s</code>) but will it make the code run any fa... | <p>Is this the pattern you implied?</p>
<pre><code>In [15]: s = 'some text with \tspaces between'
In [16]: timeit re.sub(r'(\w)(\s+)(\w)', '\\1 \\3', s)
10000 loops, best of 3: 30.5 us per loop
In [17]: timeit re.sub(r'(\w)(\s+?)(\w)', '\\1 \\3', s)
10000 loops, best of 3: 24.9 us per loop
</code></pre>
<p>Seems... | python|regex|performance|non-greedy | 2 |
9,316 | 22,321,423 | Python Tabulate | <p>How can I merge multiple tables in python using tabulate package?</p>
<p><code>append</code> is not working when concatenating the two tables in python.The tables are implemented using tabulate package in python.</p>
<pre><code>table_1 = [["Value_1",1,2],["Value_2",2,4],["Value_3",2,3]]
table_2 = [["Value_1",1,2],... | <p>For " concatenating the two tables" you probably want <a href="http://docs.python.org/2/tutorial/datastructures.html" rel="nofollow">list.extend</a>, not append. Append will insert the second list as a single item to the first one. Also note that <code>extend</code> will modify the source list in-place and return <... | python|python-2.7|python-3.x | 3 |
9,317 | 57,788,654 | Why is column-wise computation faster than computation on whole DataFrame in Pandas when computing Euclidean distance | <p>I have a pandas Series which contains <em>x</em> and <em>y</em> coordinate of a point <em>p</em> and a DataFrame which contains several points <em>q<sub>1</sub></em> to <em>q<sub>n</sub></em> (also <em>x</em> and <em>y</em>). I then compute the pairwise Euclidean distances between <em>p</em> and each of the <em>qs</... | <p>The reason for the poorer performance of <code>d2</code> is the addional overhead of organizing the data frame operations (index checking an alignment etc.) Although I'm not able to explain every detail you'll get the basic idea from the profile charts for <a href="https://i.stack.imgur.com/AqzBc.png" rel="nofollow... | python|pandas|performance|dataframe | 1 |
9,318 | 54,340,400 | Angular in node communication to python backend inside docker failed | <p>I have an angular application hosted using Node and also have a python flask backend for other python operation. As these are 2 separate modules, I had created separate docker images for node+angular and python flask. In order for isolation, I also used a docker network for these containers. </p>
<p>I have built th... | <p>If you plan on running your Python containers on multiple servers at once for scaling then your best option is ALB. </p>
<p>If you plan to have only one instance of the container running per single EC2 instance then you can use both ALB and CLB. But if you plan to run multiple instances of those containers on a sin... | python|angular|amazon-web-services|docker | 2 |
9,319 | 71,177,701 | i cant seem to break out of this while loop | <p>i took a comp class in my college and its in the real early stages. i was asked to make this little program which plays madlibs and now i cant seem to complete it.</p>
<pre><code>import random
verb=input("Enter a verb: ")
celebrity= input("Enter name of a celebrity: ")
age=input("Enter a... | <p><code>input()</code> function always return a string. It won't be dynamically casted,
you can use <code>isdecimal()</code> str method.</p>
<p>If you want to use age as a number don't forget to cast it.</p>
<p>You can replace this part:</p>
<pre class="lang-py prettyprint-override"><code>while not age==int():
age... | python|while-loop | 1 |
9,320 | 71,326,676 | Regex to detect string including special characters | <p>I have these inputs:</p>
<pre><code>s1 = 'I am using c++ programming'.
s2 = = 'I am usingc++ programming'.
</code></pre>
<p>I want to check if s1 or s2 contains the exact word <code>c++</code>.</p>
<p>running this regex on both s1 and s2, it does not give any output:</p>
<pre><code>x=s1 #x=s2
if re.search(r'\bc\... | <p>You may use this regex for this using different flavors of word boundaries:</p>
<pre class="lang-py prettyprint-override"><code>\bc\+\+\B
</code></pre>
<p><a href="https://regex101.com/r/c3rE6s/2" rel="nofollow noreferrer">RegEx Demo</a></p>
<p><strong>RegEx Details:</strong></p>
<ul>
<li><code>\b</code>: Word bound... | python|regex|string | 3 |
9,321 | 9,403,275 | Python: How to get multiple elements inside square brackets | <p>I have a string/pattern like this:</p>
<pre><code>[xy][abc]
</code></pre>
<p>I try to get the values contained inside the square brackets:</p>
<ul>
<li>xy</li>
<li>abc</li>
</ul>
<p>There are never brackets inside brackets. Invalid: <code>[[abc][def]]</code></p>
<p>So far I've got this:</p>
<pre><code>import r... | <p><code>re.findall</code> is your friend here:</p>
<pre><code>>>> import re
>>> sample = "[xy][abc]"
>>> re.findall(r'\[([^]]*)\]',sample)
['xy', 'abc']
</code></pre> | python|regex|pattern-matching|match|python-2.7 | 20 |
9,322 | 39,142,876 | Check if a polygon is a multipolygon in Shapely | <p>How can I check if a polygon entity is actually a multipolygon?
I've tried: </p>
<pre><code>if len(polygon) > 1:
</code></pre>
<p>but then get the error:</p>
<pre><code>TypeError: object of type 'Polygon' has no len()
</code></pre>
<p>I've tried <code>Nill</code>, <code>None</code> and others, nothing worked.... | <p>Use the <code>object.geom_type</code> string (see <a href="https://shapely.readthedocs.io/en/stable/manual.html#general-attributes-and-methods" rel="noreferrer">general attributes and methods</a>).</p>
<p>For example:</p>
<pre><code>if poly.geom_type == 'MultiPolygon':
# do multipolygon things.
elif poly.geom_ty... | python|shapely | 44 |
9,323 | 55,276,501 | Checking length of password vault | <p>The updated code for the errors, it now can succesfully check for enters and maximum and minimum valuesThe updated code for the errors, it now can succesfully check for enters and maximum and minimum valuesThe updated code for the errors, it now can succesfully check for enters and maximum and minimum values</p>
<p... | <p>Add and <code>elif</code> with a condition and modify the <code>if</code> condition a little:</p>
<pre><code>username = input('''Welcome, {} {}
what would you like your username to be, it should be something
memorable and no longer than ten characters long
'''.format(first_name, sur_name))
while True:
use... | python|python-3.x | 0 |
9,324 | 52,841,242 | How to catch error code from one shell script into another shell script | <p>The thing is :
I have one python file <br>
I am executing it using a shell script named <code>run.sh</code><br>
<strong>content of run.sh</strong></p>
<pre><code>python test.py
</code></pre>
<p>and in python file I am testing for something and if it is not matching i am exiting using sys.exit(1). I am able to cat... | <p>You can do the same thing you did for <code>run.sh</code>, catch the <code>return_code</code></p>
<p>in master.sh</p>
<pre><code>sh run.sh
if [ $? == 0 ]
then sh test.sh
else
exit 1
fi
</code></pre> | python|bash|shell|unix|sh | 1 |
9,325 | 52,465,317 | Can I run multiprocessing Python programs on a single core machine? | <p>So this is more or less a theoretical question. I have a single core machine which is supposedly powerful but nevertheless only one core. Now I have two choices to make :</p>
<ol>
<li><p>Multithreading: As far as my knowledge is concerned I cannot make use of multiple cores in my machines even if I had them because... | <p>This is a big topic but here are some pointers.</p>
<ul>
<li>Think of threads as processes that share the same address space and can access the same memory. Communication is done by shared variables. Multiple threads can run within the same process.</li>
<li>Processes (in this context, and roughly speaking) have th... | python|multiprocessing|python-multiprocessing | 12 |
9,326 | 47,548,430 | Upload file using form-data body | <p>I need to upload a PNG file using an API which says:</p>
<blockquote>
<p>The request body accepts multipart/form-data with the key as uploadedFile.</p>
</blockquote>
<p>Using Chrome postman plugin, I am able to upload the file using API, this is what I did:</p>
<pre><code>Header: none
Body
type: form-data
k... | <p>You need to upload the file under the <code>uploadedFile</code> name. Do not use that name with a path, <em>name the file itself that</em>:</p>
<pre><code>upload_url = "Some_Value"
file_path = '/root/sample.png'
file = {'uploadedFile': ('pngfile', open(file_path, 'rb'), 'image/png')}
post_file = requests.post(uplo... | python|python-requests | 1 |
9,327 | 37,245,347 | How does this Lambda Expression work? | <p>I'm familiar with simple lambda expressions. However I have this lambda expression in a book.</p>
<pre><code>dd_pair = defaultdict(lambda: [0,0])
dd_pair[2][1] = 1 #now dd_pair contains {2: [0,1]}
</code></pre>
<p>I didn't declare any input variables, which is not how I learned Lambdas.</p>
<p>The previous exa... | <p><code>lambda: [0, 0]</code> is exactly the same as:</p>
<pre><code>def zero_pair():
return [0, 0]
</code></pre>
<p>that is, it is a function that takes no arguments and returns a <code>len</code> 2 array with the two entries set to 0. <code>defaultdict</code> takes a callable that takes no arguments and retur... | python|dictionary | 2 |
9,328 | 7,692,771 | Django Admin TabularInline Complaining About Missing Field | <p>I have the following model and TabularInline subclasses:</p>
<pre><code>class SomeModel(models.Model):
name = models.CharField(max_length=50)
class SomeModelInline(admin.TabularInline):
model = SomeModel
class SomeOtherModelAdmin(admin.ModelAdmin):
inlines = [SomeModelInline]
</code></pre>
<p>Without... | <p>Ids are non-editable, by default inline shows the editable fields, but you can show the non-editable fields as well</p>
<p>From <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields" rel="nofollow">django docs</a> </p>
<blockquote>
<p>fields can contain values d... | python|django|django-admin | 4 |
9,329 | 7,110,118 | SQLAlchemy - don't enforce foreign key constraint on a relationship | <p>I have a <code>Test</code> model/table and a <code>TestAuditLog</code> model/table, using SQLAlchemy and SQL Server 2008. The relationship between the two is <code>Test.id == TestAuditLog.entityId</code>, with one test having many audit logs. <code>TestAuditLog</code> is intended to keep a history of changes to ro... | <p>You can solve this by:</p>
<ul>
<li><strong>POINT-1:</strong> not having a <code>ForeignKey</code> neither on the <code>RDBMS</code> level nor on the SA level</li>
<li><strong>POINT-2:</strong> explicitly specify join conditions for the relationship </li>
<li><strong>POINT-3:</strong> mark relationship cascades to ... | python|sql-server|join|foreign-keys|sqlalchemy | 16 |
9,330 | 72,632,654 | Return Excel file from Azure Function via HTTP using Python | <h2>Use Case</h2>
<p>Within a Logic App, I create some data using an Azure Function with a Pandas DataFrame. After employing the Azure Function, I want to further process the data in .xlsx format within the Logic App. Therefore I need the Azure Function to return an .xlsx file.</p>
<h2>Problem</h2>
<p>I am unable to fo... | <p>The approach could be to write the output to a buffer and return the buffer's content within the <code>HTTPResponse</code></p>
<pre class="lang-py prettyprint-override"><code>def main(req: func.HttpRequest) -> func.HttpResponse:
df = pd.DataFrame(np.random.randint(0, 100, size=(2, 4)), columns=list('ABCD'... | python-3.x|excel|http|azure-functions|azure-logic-apps | 0 |
9,331 | 16,231,904 | interaction between python script and user in text mode | <p>I am seeking for a good example or manual describing standards of text-based dialogs in a linux console using standard I/O commands and utilizing formatted text output. For example: how to inquire input of parameters proposing some default values and alternatives, how to do a progress bar in the text mode, and other... | <p>"text-based dialogs in a linux console" --> have a look at <a href="http://docs.python.org/2/library/curses.html" rel="nofollow"><code>curses</code></a></p> | python | 2 |
9,332 | 38,817,525 | Dependencies error in Matplotlib and numpy | <p>These versions of softwares are installed :</p>
<ol>
<li>python-2.5</li>
<li>numpy-1.0.1.win32-py2.5</li>
<li>scipy-0.5.2.win32-py2.5</li>
<li>matplotlib-0.87.7.win32-py2.5</li>
</ol>
<p>[installed in same order]</p>
<p>While running my program, I am getting this error message :</p>
<pre class="lang-none prettyp... | <p>The issue was resolved by downloading 2 dll files and copying in system32 and syswow64</p>
<p>Got this answer from another similar stackoverflow question </p>
<p><a href="https://stackoverflow.com/questions/20201868/importerror-dll-load-failed-the-specified-module-could-not-be-found">ImportError: DLL load failed: ... | python|numpy|matplotlib | 0 |
9,333 | 40,656,925 | Steps for creating an optimizer on TensorFlow | <p>I'm trying to implement a new optimizer that consist in a big part of the Gradient Descent method (which means I want to perform a few Gradient Descent steps, then do different operations on the output and then again). Unfortunately, I found 2 pieces of information; </p>
<ol>
<li>You can't perform a given amount of... | <ol>
<li><p>I am not 100% sure about that, but I think you are right. But I don't see the benefits of adding such option to TensorFlow. The optimizers based on GD I know usually work like this:</p>
<pre><code>for i in num_of_epochs:
g = gradient_of_loss()
some_storage = f(previous_storage, func(g))
params ... | c++|python-2.7|optimization|tensorflow|gradient-descent | 1 |
9,334 | 40,769,018 | Pyinstaller and import issue with wx.lib.pubsub | <p>My Python GUI app, works perfectly but when I try to create an executable I tried with pyinstaller (3.3.dev0+483c819) command:</p>
<pre><code>pyinstaller gui_app.py
</code></pre>
<p>I get the follow issue:</p>
<pre><code>7699 INFO: Loading module hook "hook-wx.lib.pubsub.py"...
Traceback (most recent call last):
... | <pre><code>8006 WARNING: Hidden import "wx.lib.pubsub.core.publisher" not found!
8008 WARNING: Hidden import "wx.lib.pubsub.core.listenerimpl" not found!
8009 WARNING: Hidden import "wx.lib.pubsub.core.publishermixin" not found!
8009 WARNING: Hidden import "wx.lib.pubsub.core.datamsg" not found!
8009 WARNING: Hidden im... | python|wxpython|wxwidgets|pyinstaller|pypubsub | 2 |
9,335 | 25,985,069 | User data through Google APIs without authorization flow | <p>I'm writing a web application that reads my personal calendar data, crunches stats, and then spits them out for the world to see. I don't need an authorization flow. Is it possible to leverage the Google APIs without going through a user sign-in flow? In other words, <strong>I want my personal Google account permane... | <p>An alternative approach is using a service account while sharing your calendar with that service account. See <a href="https://developers.google.com/accounts/docs/OAuth2ServiceAccount" rel="nofollow">https://developers.google.com/accounts/docs/OAuth2ServiceAccount</a></p> | heroku|google-api|google-calendar-api|google-authentication|google-api-python-client | 1 |
9,336 | 26,132,600 | command prompt appears than immediately disappears | <p>I encountered this problem after following a python tutorial on Youtube about creating text files. The instructor had us type in the following code to start:</p>
<pre><code>def createFile(dest):
print dest
if__name__ == '__main__':
createFile('ham')
raw_input('done!')
</code></pre>
<p>We had created a fo... | <p>You can open command prompt then navigate to python interpreter
directory and run your program by typing python /diretory/to/your/program.py for
example if you have a program named test.py in the directory c:/python and you want to
run it and you have python interpreter installed in C:/python2.x/ directory
then y... | python-2.7|command-prompt | 0 |
9,337 | 60,146,030 | Replacing certain parts of Array in different folders via Pythion | <h1>My code does the replacement for the entire file. Whereas I want only certain replacements.</h1>
<h1>Below is the file I'm trying to replace. I just want to change some words in "sheetname" : "Main"</h1>
<pre><code> [
{
"sheetname": "Main",
"emp_details": ... | <p>Naming you data from file as <code>data</code>:</p>
<pre><code> data = [
{
"sheetname": "Main",
"emp_details": [
[
"スバム",
"ksing.shubh@gmail.com",
"marble",
"intern"
],
[
"Gaurav",
"gaurav.singh@cobol.in",
... | python|arrays|json|python-3.x|python-2.7 | 0 |
9,338 | 1,858,447 | What is a library that provides a very simple, universal usage of Naives Bayes classifier? | <p>I know that NLTK has this. But...is that only for NLP?
Is there a library that specializes in classification?</p> | <p><a href="http://code.google.com/p/pybayes/" rel="nofollow noreferrer">http://code.google.com/p/pybayes/</a></p> | python | 2 |
9,339 | 63,191,385 | Numpy element-wise comparison using a different array for values | <p>This might be a simple problem but I am stuck with this one and the solution I found is not efficient (I think).</p>
<p>Let's say I have two numpy arrays, one containing indices for each position and the second one the valid indices:</p>
<pre><code>import numpy as np
x = np.array([0, 1, 2, 1, 3, 2])
indices = np.a... | <p>It seems that you want to index <code>indices</code> with the indices in <code>x</code>. Try with:</p>
<pre><code>indices[x]
</code></pre> | python|numpy | 2 |
9,340 | 32,545,260 | while loop not executing in Python 3.4.3 | <p>I am writing a function that takes a string, and determines if it is an integer or not.</p>
<p>for the most part it is working well. The only problem I have is when I use a + or - in front of the number. I thought I had taken this into account with my while loop, but it seems to not be executing. Here is my code... | <p>The check after the while loop is causing the value to return False because you are checking for the whole sentence.</p>
<pre><code>if sentence.isdigit() == True:
</code></pre>
<p>Use this instead?</p>
<pre><code>if sentence[count].isdigit() == True:
</code></pre> | python | 0 |
9,341 | 28,057,338 | Understanding execute async script in Selenium | <p>I've been using <code>selenium</code> (with <a href="http://selenium-python.readthedocs.org/" rel="noreferrer">python bindings</a> and through <a href="http://angular.github.io/protractor/#/" rel="noreferrer"><code>protractor</code></a> mostly) for a rather long time and every time I needed to execute a javascript c... | <blockquote>
<p>When should I use <code>execute_async_script()</code> instead of the regular <code>execute_script()</code>?</p>
</blockquote>
<p>When it comes to checking conditions on the browser side, <strong>all checks you can perform with <code>execute_async_script</code> can be performed with <code>execute_scri... | javascript|python|selenium|selenium-webdriver|protractor | 35 |
9,342 | 44,314,963 | Transpose and expand data | <p>I have the following dataframe:</p>
<pre><code>id begcost endcost
100 1 3
200 10 12
</code></pre>
<p>I want:</p>
<pre><code>id newcost
100 1
100 2
100 3
200 10
200 11
200 12
</code></pre>
<p>Basically I need to create a new row for each value contain... | <pre><code>pd.DataFrame(
[(i, j) for i, b, e in df.itertuples(index=False) for j in range(b, e + 1)],
columns=['id', 'newcost']
)
id newcost
0 100 1
1 100 2
2 100 3
3 200 10
4 200 11
5 200 12
</code></pre>
<hr>
<p><strong>Timing</strong> </p>
<pre><code>%%t... | python|pandas | 5 |
9,343 | 34,618,393 | Python Script; Logging into site | <p>I am trying to log into a site,
<a href="https://www.telenor.no/privat/minesider/logginnfelles.cms?skin=telenor" rel="nofollow">https://www.telenor.no/privat/minesider/logginnfelles.cms?skin=telenor</a>, with my user credentials. That site then redirects to <a href="https://www.telenor.no/privat/minesider/minside/m... | <p>Not sure how your attempting to log into the website, but here's an article that shows how it's done in python. Maybe post your code on here so we can get an idea of what's going on.</p>
<p><a href="https://stackoverflow.com/questions/2910221/how-can-i-login-to-a-website-with-python">How can I login to a website wi... | python | 0 |
9,344 | 27,068,827 | having trouble opening and closing windows in tkinter | <p>I'm really new to python just managing to get my head round it, here is what I have so far.</p>
<p>Basically I'm struggling to switch between I think (mind my coding terminology I'm new to this) i've created a parent window "root=Tk()" and I'm trying to switch to a new area of the program (open up a new window "Cla... | <p>Frames have a zero width by default because there is no reason to show an empty container, so put something in them. Also you import Tkinter twice. Choose one or the other.</p>
<pre><code>import Tkinter as tk
class WelcomeWindow():
def __init__(self,master):
self.master = master
##self.frame... | python|python-2.7|user-interface|tkinter|tk | 1 |
9,345 | 23,041,342 | Filtering out only true values from Pandas DataFrame, return tuples of (Row,Col) | <p>Given a frame like this:</p>
<pre><code> a b c
1 True False False
2 True True False
3 False True True
</code></pre>
<p>I want to get a list like this:</p>
<pre><code>[(1,a), (2,a), (2,b), (3,b), (3,c)]
</code></pre>
<p>That is filtering out all the values that are true and retrieving tuples (rowName, col... | <p>Another approach is to use <code>stack</code>:</p>
<pre><code>>>> s = df.stack()
>>> s[s].index.tolist()
[(0L, 'a'), (1L, 'a'), (1L, 'b'), (2L, 'b'), (2L, 'c')]
</code></pre>
<p>which works because <code>stack</code> here returns the flattened version:</p>
<pre><code>>>> df.stack()
0 a... | python|pandas | 5 |
9,346 | 8,335,779 | Aptana vs. Eclipse - pygame working only on Aptana? | <p>Have used Eclipse with PyDev for a while...without any problems. Recently I wanted to try out PyGame but the problem is that Eclipse gives errors when trying to do that:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Artur\workspace\miniprojekt\src\pygame.py", line 1, in <module>
import pyga... | <p>You are right in that Aptana Studio 3 uses the same PyDev you installed, so, it should be exactly the same thing... do the following:</p>
<ol>
<li><p>Update PyDev to the latest nightly build -- this is just to be sure you have the proper version.</p></li>
<li><p>Rename your own module from pygame.py to something el... | python|eclipse|python-3.x|aptana|pydev | 1 |
9,347 | 41,795,111 | How can I remove the Python Shell window while using Tkinter? | <p>Hello to the Stack Overflow Community! I am an amateur coder & student and am developing a UI for my superiors at my 'school.' I have been bothered by the Python Shell window opening as well and was wondering if there was a way to remove that window without having my Tkinter program shut down.</p>
<p>Thanks!</p... | <p>Rename you main script to have the extension <code>.pyw</code>. This file type, when executed, is by default run by pythonw.exe instead of python.exe, and it doesn't show the console.</p>
<p>You will need some means to report debug errors, though. Just an advice.</p> | python|macos|python-3.x|tkinter | 1 |
9,348 | 47,187,446 | Python BigQuery API - get table schema/header | <p>Given a query example like</p>
<pre><code>import uuid
from google.cloud import bigquery
def query_shakespeare():
client = bigquery.Client()
query_job = client.run_async_query(str(uuid.uuid4()), """
#standardSQL
SELECT corpus AS title, COUNT(*) AS unique_words
FROM `publicdata.samp... | <p>If you need the schema of the table you just queried, you can get it from the <code>result</code> method from the <code>QueryJob</code>:</p>
<pre><code>client = bq.Client()
query = """
#standardSQL
SELECT corpus AS title, COUNT(*) AS unique_words
FROM `publicdata.samples.shakespeare`
... | python|google-bigquery|google-cloud-python | 4 |
9,349 | 47,215,704 | Unable to login to a site with requests | <p>For fun, I'm trying to use Python requests to log on to my school's student portal. This is what I've come up with so far. I'm trying to be very explicit on the headers, because I'm getting a 200 status code (the code you also get when failing to login) instead of a 302 (successful login).</p>
<pre><code>import sys... | <p>What response do you expect? You are using a wrong way to analyze your response.</p>
<pre><code>with requests.Session() as s:
p = s.post(url, data=values)
if p.status_code == 302:
print(p.text)
print('Authentication error', p.status_code)
r = s.get('(link)guardian/home.html')
print(r.te... | python|post|get|python-requests | 0 |
9,350 | 47,224,719 | How to write data from a genetic evolutionary algorithm to an external file in python | <p>I wrote a genetic algorithm in order to find the best fiber layout in a carbon fiber reinforced polymer composite brake booster. Both finite element model and the optimization algorithm were written in Python.
I am trying to print every information regarding the optimization, but I did not find a way so far.
Could ... | <p>As it was not clear from your question what data where you taking about, is it the results or some fine tuned parameters as in neural networks?</p>
<p>So a more Generic answer is :
You can always dump all the parameters and data form genetic algorithm to a pickle file.</p>
<pre><code>import cPickle as pickle
with ... | python | 0 |
9,351 | 57,727,171 | how to do deletion of an element from array in python without using builtin functions | <p>How to delete element in an array without using python builtin functions</p>
<p>I have tried this program with builtin functions, but I do not know how to do it without them</p>
<pre><code>c = [6,7,8,9]
c.remove(c[0])
print(c)
</code></pre>
<p>I am getting expected result but I want it without using the built-in ... | <p>This should do it, but this method creates a new array</p>
<pre><code>c=[6,7,8,9]
d=[]
a=0
for x in c:
if x!=c[a]: #or you write c[0] and remove the a=0
d.append(x)
print(d)
</code></pre> | python | 1 |
9,352 | 71,005,040 | How to replace a character in the string only giving its index? | <p>Im making hangman and i want to put the blank and if he give the correct letters i want to put the correct letter to its correct index blanks this is my code</p>
<pre><code>guess = "code"
howmuch = len(guess)
times = "_" * howmuch
blank = times
print(blank)
answer = input("what letter: "... | <p>One way to do this might be converting it to list and then joining the list. This can be done by:</p>
<pre><code>a = 'Hello'
lst1 = []
for i in a: lst1.append(i) # or use lst1 = list(a) as suggested by @buran
# Code to replace here, use replace function
a = ''.join(lst1)
</code></pre>
<p>This is just a sample</p>
<p... | python|string | 0 |
9,353 | 33,670,308 | Convert time from command line argument | <p>I am trying to look in current directory for all files that changed in <code>x</code> amount of minutes. <code>x</code> will be a command line argument given by user when running the script.</p>
<p>I am having issues converting the command line argument into the appropriate number of seconds:</p>
<p>Here is what I... | <p>Regarding the <code>I don't understand how time works</code>, please refer to the documentation:</p>
<ul>
<li><a href="https://docs.python.org/2/library/time.html#time.time" rel="nofollow"><code>time.time()</code></a>: Return the time in seconds since the epoch as a floating point number.</li>
<li><a href="https://... | python | 1 |
9,354 | 33,894,197 | Add list of files into a dictionary using python | <p>I wrote this script that will show all files within a specific directory and will let the user input which file he wants to edit.</p>
<pre><code>import os
path = "/home/luai/Desktop/python/test"
dirs = os.listdir( path )
print "Here is a list of all files: "
for files in dirs:
print files
filename = raw_inp... | <p>I would just loop over the <code>listdir</code> output with an index:</p>
<pre><code>import os
path = "/home/luai/Desktop/python/test"
dirs = os.listdir( path )
print "Here is a list of all files: "
for filenumber in range(len(dirs)):
print filenumber, dirs[filenumber]
filenumber = raw_input ("Number of fil... | python | 1 |
9,355 | 46,867,718 | Function of batch in TensorFlow? | <p>I am new to TensorFlow and Machine Learning and found the concept of batch. </p>
<p>What is the purpose of splitting the DataSets into batches and how does the TensorFlow perform an optimization task on variables, using different sub-sets?</p> | <p>You are confusing a few things, as far as I understand.</p>
<p>First, you need to split the dataset into two (or more) distinct sets. The one is a set that you train your system on, and the second one is used to test your model.</p>
<p>This are basics of ML and you should easily find more in the internet. Look for... | machine-learning|tensorflow|mathematical-optimization | 0 |
9,356 | 46,636,125 | Execute Python script in terminal fullscreen | <p>how do I write/execute a Python script full screen at the terminal.
I want to write a small Programm which shoud be shown like "vim", "sl", or "nano".</p> | <p>As fas as I can understand from your question, you can make the terminal to be fullscreen by pressing <code>F11</code> (at least in Ubuntu)</p> | python|terminal | 0 |
9,357 | 46,921,392 | Compiling TensorFlow 1.4.0 GPU on Windows 10 x64 | <p>There doesn't seem to be any detailed documentation for how to compile TensorFlow 1.4.0 GPU on Windows 10 x64.</p>
<p>I need to recompile TF to add missing functionality for a Windows 7 x64 production system.</p>
<p>The official Google link at <a href="https://www.tensorflow.org/install/install_sources" rel="nofol... | <p>Got the <a href="https://github.com/tensorflow/tensorflow/issues/13962" rel="nofollow noreferrer">answer</a> from Adriano Carmezim over at github. The complete instructions for building TensorFlow on Windows, including making Windows Python wheels are at: <a href="https://github.com/tensorflow/tensorflow/blob/master... | windows|tensorflow | 1 |
9,358 | 37,925,160 | SQLite from API Call | <p>i am trying to insert a few thousands rows from the quandl site by making an API call and storing into an object call "data"
The structure of the data is simply date and price</p>
<pre><code>import quandl as q
import sqlite3 as sq
token = "asdaasdewqrdfc"
data = quandl.get("WGC/GOLD_DAILY_USD", authtoken=token)
... | <p>The return from <code>quandl.get</code> is a Pandas dataframe. Use the Pandas utility function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow"><code>.to_sql()</code></a> to insert your data:</p>
<pre><code>import quandl as q
import sqlite3 as sq
token = "... | python|sqlite|api | 0 |
9,359 | 65,850,929 | In Python, is it possible to assign an if-then statement to a variable? | <p>I've defined a few variables below and I want to use them to define a variable.</p>
<pre><code>today = datetime.today()
datem = str(datetime(today.year, today.month, 1))
curr_month = datem[5:7]
curr_year = datem[2:4]
list_early_fy = ['04', '05', '06', '07', '08', '09', '10', '11', '12']
</code></pre>
<p>I then want ... | <p>The first piece of code is invalid because you're trying to assign a value while doing boolean. For the second, you forgot the () that would go after test_year to define the paramters. It should be <code>def test_year(curr_month):</code>. To use the function in your code, call it using <code>test_year(current_month_... | python | 0 |
9,360 | 37,006,863 | python mqtt script on raspberry pi to send and receive messages | <p>MQTT question:</p>
<p>Hi, I’m trying to set up a MQTT network between multiple Raspberry Pis (starting with two).
I have one raspberry pi (RPi-A), MQTT client, with a thermistor sensor attached and one raspberry (RPi-B), MQTT broker/client, acting as a hub for my network.
Through python scripting I’d like the tempe... | <p>The simplest way is to start the network loop on a separate thread using the <code>client.loop_start()</code> function, then use the normal <code>client.publish</code> method</p>
<pre><code>from sense_hat import SenseHat
import time
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
sense = SenseHa... | python|raspberry-pi|mqtt|paho | 10 |
9,361 | 48,662,281 | Make border of Label, bbox or axes.text flush with spines of Graph in python matplotlib | <p>for a certain manuscript i need to position my label of the Graph exactly in the right or left top corner. The label needs a border with the same thickness as the spines of the graph. Currently i do it like this:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
my_dpi=96
xposr_box=0.975
ypos_box=0... | <p>The problem is that the position of a <code>text</code> element is relative to the text's extent, not to its surrounding box. While it would in principle be possible to calculate the border padding and position the text such that it sits at coordinates <code>(1,1)-borderpadding</code>, this is rather cumbersome sinc... | python|matplotlib|text|label | 4 |
9,362 | 48,756,304 | Python Tkinter widgets added to root window instead of Toplevel window | <p>Using Python 2.7 here. I am trying to add a basic settings window, but when I open a Toplevel window and try to add widgets to it, the widgets get added to the main window instead. Here is an example:</p>
<pre><code>import Tkinter as tk
class MainWindow (tk.Frame):
def __init__ (self, root):
tk.Frame._... | <p>its because your packing on the same line, check out the answer to this question, he explains it in detail: <a href="https://stackoverflow.com/questions/14328346/python-tkinter-widgets-created-inside-a-class-inherited-from-toplevel-appe">Python - Tkinter - Widgets created inside a class inherited from Toplevel() app... | python|python-2.7|tkinter | 1 |
9,363 | 20,172,727 | python: Packages in user-site not overriding dist-packages on ubuntu | <p>I use ubuntu 13.04. When developing in python, I sometimes wish to use newer versions of some packages than those shipped with ubuntu. In these cases, the method I'm used to is to install the package only to my user account, for example like this (for the package <code>six</code>):</p>
<pre><code>$ pip install --us... | <p>Having dist packages before users packages actually makes sense IMHO. But anyway, you have two options here, the bad one and the right one. </p>
<p>The bad one is to redefine your PYTHONPATH environment variable to put your local package's dir before site-wide packages. It's as simple as this, but don't complain wh... | python|ubuntu|path|installation|package | 1 |
9,364 | 4,372,346 | Uses of combining **kwargs and key word arguments in a method signature | <p>Is there a use for combining **kwargs and keyword arguments in a method signature?</p>
<pre><code>>>> def f(arg, kw=[123], *args, **kwargs):
... print arg
... print kw
... print args
... print kwargs
...
>>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def')
Traceback (most recent call last):
File... | <p>In Python 3 you can have keyword-only arguments (<a href="http://www.python.org/dev/peps/pep-3102/">PEP 3102</a>). With these, your function would look like this:</p>
<pre><code>>>> def f(arg, *args, kw=[123], **kwargs):
... print(arg)
... print(kw)
... print(args)
... print(kwargs)
>>> f(5,... | python | 14 |
9,365 | 4,442,286 | Python code generation with pyside-uic | <p>How can I generate python code from a QtDesigner file ?
I found pyside-uic but I can't find an example for the syntax.
I run win7 and pythonxy with spyder.</p> | <p>pyside-uic is more or less identical to pyuic4, as such the man page specifies:</p>
<pre><code>Usage:
pyside-uic [options] <ui-file>
Options:
--version
show program's version number and exit
-h,--help
show this help message and exit
-oFILE,--output=FILE
write gen... | python|pyside | 38 |
9,366 | 48,053,470 | Why don't these two table join in Python? | <p>I'm using the below code to import <a href="https://www.kaggle.com/secareanualin/football-events" rel="nofollow noreferrer">these sample Kaggle data sets</a> for Python pratice):</p>
<pre><code># importing everything
import pandas as pd
df_events = pd.DataFrame()
df_ginf = pd.DataFrame()
df_events = pd.read_csv('.... | <p>The columns have different names, thus you can't use <code>on</code>. It should be specified which dataset contains given column:</p>
<pre><code>pd.merge(df_eventsPlayer, eventsMatchTable, how = 'left',
left_on = 'shot_outcome', right_on='eventKey')
</code></pre>
<p>Parameter <code>on</code> is used when ... | python|python-3.x|pandas | 2 |
9,367 | 48,169,209 | ValueError: No axis named 'inp' for object type <class 'pandas.core.frame.DataFrame'> | <p>I have a dataframe,df</p>
<pre><code> Date inp name
0 2017-08-07 2.3.6 ABC
1 2017-08-07 2.3.6 ABC
2 2017-08-08 2.3.6 TAC
3 2017-08-22 2.5.9 TTT
4 2017-09-23 0.8.0 TAC
5 2017-10-09 2.3.6 ABC
6 2017-10-09 2.3... | <p>I think you can use faster solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>floor</code></a> instead <code>df['Date'].dt.date</code> first with <code>[]</code> for list in <code>groupby</code>:</p>
<pre><code>df2 = (df.groupby(... | pandas|pandas-groupby | 1 |
9,368 | 17,490,921 | no module named rpm - when i call yum on shell | <p>I installed python 2.7.5 and mod_wsgi on centos machine linux os. And this happened:</p>
<pre><code># yum
Error processing line 1 of /usr/local/lib/python2.7/site-packages/abrt.pth:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site.py", line 152, in addpackage
exec line
File "&... | <p>I had similar problem, what I did is to manually download the old version python and reinstall it with rpm: </p>
<pre><code>$ rpm -qa | grep python- | grep 2.6
$ sudo rpm -ivh --force ftp://mirror.switch.ch/pool/4/mirror/scientificlinux/6.5/x86_64/updates/fastbugs/python-2.6.6-52.el6.x86_64.rpm
</code></pre>
<p>Af... | python|apache|mod-wsgi|rpm|yum | 1 |
9,369 | 70,636,298 | unable to source user defined python gdb command | <p>I've been following <a href="https://undo.io/resources/gdb-watchpoint/how-write-user-defined-gdb-commands-python/" rel="nofollow noreferrer">this</a> amazing (video) tutorial to create custom user defined GDB command using python</p>
<p>here is my code</p>
<pre><code>import os
import gdb
class BugReport (gdb.Comman... | <blockquote>
<p>what I'm doing wrong?</p>
</blockquote>
<p>Python is indentation-sensitive. You want:</p>
<pre><code>class BugReport (gdb.Command):
"""Collect required info for a bug report"""
def __init__(self):
super(BugReport, self).__init__("bugreport", gdb.COMMAND_U... | python|gdb | 1 |
9,370 | 69,770,196 | Pandas - moving data between columns in a dataframe | <pre><code>df1
Reference_Code Last_Price Price_Now
B0002EH2X2 NaN 9.99
B0075DRIAK NaN 19.99
B0083F2XDQ NaN 29.99
B009AS5VW0 NaN 39.99
df2
Reference_Code Price_Now
B0002EH2X2 49.99
B0075DRIAK 19.99
B0083F2XDQ 29.99
B009AS5VW0 9.99... | <p>Do a map:</p>
<pre><code>s = df1['Reference_Code'].map(df2.set_index('Reference_Code')['Price_Now'])
mask = (s!=df1['Price_Now'])
df1['Last_Price'] = df1['Price_Now'].where(mask)
df1['Price_Now'] = s.where(mask, df['Price_Now']
</code></pre>
<p>Output:</p>
<pre><code> Reference_Code Last_Price Price_Now
0 B0... | pandas|dataframe | 0 |
9,371 | 73,024,612 | cx_oracle connection without DSN | <p>I am maintaining some code where i came about a curious connection string of following type to an oracle database (from redhat linux):</p>
<pre><code>import cx_Oracle
cx_Oracle.Connection("username/password")
</code></pre>
<p>Notably no DSN is specified; User name and password are enough (the connection is... | <p>As Devyl mentioned, if you have ORACLE_SID or TWO_TASK environment variables set, they maybe used to make a connection.</p>
<p>E.g. see this answer <a href="https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:89412348059" rel="nofollow noreferrer">https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11... | python|database|oracle|cx-oracle | 2 |
9,372 | 55,814,515 | I am doing transfer learning and I have gotten an " np.expand_dims" error | <p>I am using VGG16 model, I have frozen al Convolutional layers, removed the last dense layer ( predictions one) and changed it for my own (3 outputs). </p>
<p>if it is of any help: train = 200images, valid = 8, test = 10</p>
<p><strong>This is my code.</strong></p>
<pre><code>train_path = 'animals/train'
valid_pat... | <p>You cannot use <code>model.fit</code> with a generator, for that you have to use <code>model.fit_generator</code>.</p> | python|keras|deep-learning|prediction | -1 |
9,373 | 55,579,749 | How to have a Form from another Model inside a DetailView in Django? | <p>I'm working with Django and what I want to do is to have a DetailView of Posts, and inside that detail view I want a comments section with a form for posts comments. When I load the detail view it doesn't show me the form of Comments I'm using Class Based Views for the Detail of the form.
My models.py looks like thi... | <p>That's because <code>DetailView</code> does not handle the <code>form_class</code>. You have a few options here:</p>
<ul>
<li>provide the form via <code>get_context_data</code></li>
<li>apply the <code>FormMixin</code> on the <code>DetailView</code>. (Can be found under <code>django.view.generic.edit</code>)</li>
<... | python|django|django-forms|django-class-based-views | 1 |
9,374 | 50,063,135 | .loc[ ] and pd.Series.nunique function | <pre><code>df_all = pd.DataFrame.from_records(features_all)
df_all = df_all.loc[:,df_all.apply(pd.Series.nunique) != 1]
df_benign = df_all.loc[df_all['Y'] == 1]
df_Malw = df_all.loc[df_all['Y'] == 0]
</code></pre>
<p>I was going through a code and came across these statements.
I am not able to understand what .loc an... | <p>pd.Series.nunique will return unique values within the series.
.loc can be used to slice the dataframe on the basis of index in the dataframe.</p> | python|pandas|dataframe | 0 |
9,375 | 50,142,269 | Why does scipy bessel root finding not return roots at zero? | <p>I am trying to use code which uses Bessel function zeros for other calculations. I noticed the following piece of code produces results that I consider unexpected.</p>
<pre><code> import scipy
from scipy import special
scipy.special.jn_zeros(1,2)
</code></pre>
<p>I would expect the result from this cal... | <p>It appears to be convention to not count the zero at zero, see for example <a href="http://mathworld.wolfram.com/BesselFunctionZeros.html" rel="nofollow noreferrer">ħere</a>. Maybe it is considered redundant?</p> | python|scipy|bessel-functions | 2 |
9,376 | 64,783,782 | Choosing combinations from Pandas Dataframes | <p>A Dataframe contains stock data (the data in the dataframe is irrelevant and omitted):</p>
<pre><code> open high low close
MSFT
APPL
IBM
GM
XP
INTC
</code></pre>
<p>The problem: select combinations of 3 stocks such that</p>
<ol>
<li>order is not important: if MSFT/APPL/IBM has been calculated then IBM/MSF... | <p>You can use <code>itertools.combination</code>. It's quite useful, fast, and it attends both of your requirements.</p>
<pre><code>from itertools import combinations
stocks = ['MSFT','APPL','IBM','GM','XP','INTC']
list(combinations(iterable=stocks, r=2))
</code></pre>
<p>then modify the <code>r</code> parameter as i... | python|pandas|dataframe|dataset|data-science | 1 |
9,377 | 64,677,525 | Regex for matching various forms of strings | <p>Let's say the input string is</p>
<pre><code>s_in = 'auto encoder'
</code></pre>
<p>and the list of strings is</p>
<pre><code>l_s = ['autoencoder', 'auto-encoder', 'auto', 'one']
</code></pre>
<p>My goal is to match s_in with its possible forms in l_s so that in return ill get all matched strings from the list.</p>
... | <p>You can compare the strings after removing all special characters, say, with <code>[\W_]+</code> pattern:</p>
<pre class="lang-py prettyprint-override"><code>import re
s_in = 'auto encoder'
l_s = ['autoencoder', 'auto-encoder', 'auto', 'one']
rx = re.compile(r'[\W_]+') # Define the regex for non-alnum chars
s_chec... | python|regex | 2 |
9,378 | 64,644,029 | Join / merge two Python SimpleNamespace | <p>Simple question: How do I merge Python's SimpleNamespace?</p>
<p>It looks like there is no way to do this in a simple command like <code>a.update(b)</code> or <code>a | b</code>. In fact, I haven't even found a way to systematically access all attributes of a SimpleNamespace.</p>
<p>Any leads?</p> | <p>Each <code>SimpleNamespace</code> has a <code>__dict__</code> slot, which gives access to its actual attributes. Unpacking the <code>__dict__</code> from multiple <code>SimpleNamespace</code>s into a new <code>SimpleNamespace</code> effectively merges them.</p>
<pre class="lang-py prettyprint-override"><code>>>... | python|types | 4 |
9,379 | 64,146,994 | How to create an new column on a DF2 using two DF1 columns as requisite | <p>I have two dataframes with different data and I need to add a new column on DF2 based on information obtained in two columns of DF1. In the example below, I need to check all entries that have the same city AND DOB value in both DF and add a new column in DF1 saying YES or NO.</p>
<pre><code>DF1:
City DOB ... | <p>Not sure how large the data is, or limitations around that and a solution using something like the following:</p>
<pre class="lang-py prettyprint-override"><code>df3 = (
df2.set_index(["City", "DOB"])
.join(
df1.set_index(["City", "DOB"])
.drop("Ge... | pandas|dataframe|compare|filtering | 0 |
9,380 | 53,342,155 | pandas series string path replace | <p>I have a pandas dataframe with multiple columns. The entries corresponding to one column are strings that represent paths to pictures stored on my machine e.g.</p>
<pre><code>df["image_files"][df.index[0]]
df["image_files"][df.index[1]]
.
.
.
</code></pre>
<p>will print </p>
<pre><code>'/home/user_name/Desktop/fo... | <p>Try this, replace the string in series column.</p>
<pre><code>df["image_files"] = df["image_files"].str.replace("/home/user_name/Desktop/folder_name_1/folder_name_2/","./new_folder_name_1/new_folder_name_2/")
</code></pre> | pandas | 0 |
9,381 | 53,266,491 | Input numerical arrays instead of images into Keras/TF CNN | <p>I have been building some variations of CNN's off of Keras/Tensorflow examples that use the MNIST data images (ubyte files) for feature extraction. My eventual goal is to do a similar thing but with a collection (~10000) 2D FFT arrays of signal data that I have made (n x m ~ 1000 x 50)(32 bite float data)</p>
<p>I ... | <p>Yes, you can use CNN for data other than images like sequential/time-series data(1D convolution but you can use 2D convolution as well).</p>
<p>CNN does its job pretty good for these types of data.</p>
<p>You should provide your input as an image matrix i.e a window on which CNN can perform convolution on.</p>
<p... | python|tensorflow|keras|conv-neural-network|mnist | 1 |
9,382 | 65,143,862 | If a specific string is found, set as variable | <p>I'm trying to assign a variable to a specific member of a list if it's found, but need to assign it to the human readable string first.</p>
<p>The original list is not human readable but can be interpreted using an API's GetName() function.</p>
<p>So to get my original list:</p>
<pre><code>subFolders = rootFolder.Ge... | <p>assuming the function GetName returns a string:<br />
replace the line of code:<br />
<code>if Mmedia.GetName == '02_media':</code></p>
<p>with:<br />
<code>if Mmedia.GetName().find('02_media') >= 0:</code></p> | python-3.x|for-loop|if-statement | 1 |
9,383 | 71,921,651 | Django get distinct based on rows fields group | <p>I have a model which stores mail logs.
I want to send one primary email and two reminder emails.
I have separated the email logs based on the type. (first_email, first_reminder_email, second_reminder_email)
What is wanted is the records to which we have sent all three emails.</p>
<p>My model</p>
<pre><code>class Mai... | <p>You can use <a href="https://docs.djangoproject.com/en/4.0/ref/models/querysets/#count" rel="nofollow noreferrer">Count</a> with <a href="https://docs.djangoproject.com/en/dev/ref/models/database-functions/#concat" rel="nofollow noreferrer">Concat</a>.</p>
<p>Assuming the <code>user_id</code>, <code>mail_type</code>... | python|django|database|postgresql | 1 |
9,384 | 68,465,875 | Saving an image of an expression displayed with Sympy? | <p>I'm relatively new to Sympy and had a lot of trouble with the information that I was able to scavenge on this site. My main goal is basically to take a string, representing some mathematical expression, and then save an image of that expression but in a cleaner form.</p>
<p>So for example, if this is the expression ... | <p>The program in your question does not convert the expression from
string format to the <code>sympy</code> internal format. See below for examples.</p>
<p>Also, <code>sympy</code> has capabilities to detect what works best in your
environment. Running the following program in Spyder 5.0 with an
iPython 7.22 terminal,... | python|matplotlib|sympy | 0 |
9,385 | 71,728,233 | How do I get the coordinates of a specific turtle in turtlesim (by python script)? | <p>I am fairly new to this and I am trying to get the coordinates of a turtle to calculate Euclidean distances in python.
I have a python code which moves around 2 turtles. one named "turtle1" and the other named "turtle2". I am solely confused on how I would only get the coordinates of either turtl... | <p>You can do this by subscribing to the odometry of the robot. The following code shows how this could look like:</p>
<pre><code>#! /usr/bin/env python
import rospy
from nav_msgs.msg import Odometry
def callback(msg):
print(msg.pose.pose)
rospy.init_node('get_odometry')
odom_sub = rospy.Subscriber('/odom', Odo... | python|coordinates|ros|turtle-graphics|python-turtle | 1 |
9,386 | 62,689,293 | In VS code I tried solving a problem using python,selenium, behave but I'm not getting the correct output. Can you tell me where the problem is? | <p>my folders are</p>
<blockquote>
<p>features/features_files_folder</p>
<p>features/steps</p>
</blockquote>
<p>In features_files_folder</p>
<blockquote>
<p>omniwyse.feature</p>
</blockquote>
<p>code:</p>
<p>Feature: Omniwyse</p>
<pre><code>@tagcurrent
Scenario Outline: COMPANY
Given I load the website "https... | <p>In omniwyse.feature</p>
<p>Replace scenario outline with scenario</p> | python-behave | 0 |
9,387 | 67,202,711 | How to get multiple lines exported to wandb | <p>I am using the library weights and biases. My model outputs a curve (a time series). I'd like to see how this curve changes throughout training. So, I'd need some kind of slider where I can select epoch and it shows me the curve for that epoch. It could be something very similar to what it's done with histograms (i... | <p>You can use <code>wandb.log()</code> with matplotlib. Create your plot using matplotlib:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 50)
for i in range(1, 4):
fig, ax = plt.subplots()
y = x ** i
ax.plot(x, y)
wandb.log({'chart': ax})
</code></pre>
<p>Then when... | python|pytorch|wandb | 3 |
9,388 | 60,738,234 | Closing popup window by clicking close button in selenium | <p>I want to close the popup window that appears when I hit a particular url. Here is the "inspect element" window of that page:</p>
<p><a href="https://i.stack.imgur.com/5S6IX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5S6IX.png" alt="enter image description here"></a></p>
<p>Here is what I h... | <p>The popup appears after some time, so you need wait to solve this. And you have invalid selector : <code>i[@class='popupCloseIcon']</code>, please use <code>i[class*='largeBannerCloser']</code></p>
<p><a href="https://i.stack.imgur.com/9BIoK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9BIoK.p... | python|selenium|selenium-webdriver | 2 |
9,389 | 63,530,146 | How to map values from multiple columns using fillna() to fill 'nan' values after merging two tables together in pandas? | <p>I have two dataframes regarding building property assessments. One dataframe has multiple columns on financial information while the other has columns containing location information for these buildings. Both of these dataframes do NOT have the same row and column length (the financial dataframe has over 60,000 rows... | <p>Please try Use outer instead. A full outer join returns all the rows from the left dataframe, all the rows from the right dataframe</p>
<pre><code>result = pd.merge(fin_df, loc_df, how='outer', on='BldgID')
BldgID Assmnt Phase Funding Amt State City
0 1 Phase 1 $$$$$$$$ CO Denver
1 2 ... | python|pandas|merge | 0 |
9,390 | 61,053,583 | how do i include a string or an 'and' inside a list? | <p>So in my code i want to do this structure</p>
<p>Mix the , , , and together.</p>
<p>I have this code</p>
<pre><code>import random
ingredient = ['flour', 'baking powder', 'butter', 'milk', 'eggs', 'vanilla', 'sugar']
def create_recipe(main_ingredient, baking, measure, ingredient):
"""Create a random recipe... | <p>Put all your ingredients into a list and slice it according to your choosen string formatting:</p>
<pre><code>things = ['flour', 'baking powder', 'butter', 'milk', 'eggs', 'vanilla', 'sugar']
# join all but the last element using ", " as seperator, then print the last element
# after the "and"
print(f"You need... | python-3.x|list|function | 0 |
9,391 | 60,979,298 | Problem with the date layout when importing a .csv file into a MySQL database | <p>as I life in Germany the several hundred dates in my .csv file have another layout than the US-American dates as mine is 'DD-MM-YYYY' and I need to convert every single of them to 'YYYY-MM-DD'. Now to my question. How can I convert it? Right now I'm getting the following error: </p>
<blockquote>
<p>TypeError: not... | <p>Before your call to <code>cursor.execute()</code>, you can convert the date value in <code>row</code> using the <code>datetime.strptime()</code>:</p>
<blockquote>
<p># Using datetime.strptime()</p>
<p>dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")</p>
</blockquote>
<p>This will set dt... | python|mysql|csv | 0 |
9,392 | 59,406,350 | Operate on stretches of elements by shifting a window along a list of elements | <p>I am trying to operate on the sum of stretches of elements by moving by N along the list. For example, if I have <code>['A', 'B', 'C', 'D', 'E', 'F']</code>, and I move by N=2, I would like to have <code>['A+B', 'B+C', 'C+D', 'D+E', 'E+F']</code>. Could you suggest a suitable way in Python?</p> | <p>of course this can be implemented using just standard library tools, but you may want to have look at the nice <a href="https://pypi.org/project/more-itertools/" rel="nofollow noreferrer">more-itertools package</a>
there is <a href="https://more-itertools.readthedocs.io/en/stable/api.html#windowing" rel="nofollow no... | python|string|list|sum | 3 |
9,393 | 63,189,696 | Django order_by price field with linked currency field | <p>I have real estate model. There are two fields <strong>price</strong> and <strong>currency</strong>. People can enter real estate's price in two currency only. However as price field is just numbers and prices are linked to currency, I can not order prices with different currency. Only ordering with the same currenc... | <p>Use case expression for converting the prices to a common currency value. For example</p>
<pre class="lang-py prettyprint-override"><code>from django.db.models import Case, When
#...
conversion_rate = 1 / 10_000 # This value can be from an exchange board
qs = Property.objects.annotate(
price_usd=Case(
... | python|django | 2 |
9,394 | 35,367,889 | python store function result to file | <p>I got a function (see below) that gets data from Google analytics to my computer.
I would like to store the result in a csv file but I dont know how. please help me out.
I can print the result on screen, but can't save it</p>
<pre><code>def print_top_pages(service, site, start_date, end_date, max_results=10000):
... | <p>replace the return with this.</p>
<pre><code>with open("output.txt", "w") as out:
out.write(print_data_table(query))
</code></pre>
<p>you should get the same printed output in a file named output.txt</p> | python|file|save|store | 0 |
9,395 | 49,131,300 | get some list element index based on another list elements | <p>I have two list :</p>
<pre><code>a=['book','car','car','have']
b=['car','have']
</code></pre>
<p>I want this output:</p>
<pre><code>a_basedon_b_indexes=[1,2,3]# 'car' and 'have' indexes in list a
</code></pre>
<p>i want a one line expression for this output.(i know how to do it with for loop).is this possible in... | <p>You can use <code>enumerate</code> in a list comprehension for this</p>
<pre><code>>>> [i for i,j in enumerate(a) if j in b]
[1, 2, 3]
</code></pre>
<p>If <code>b</code> is large, I'd recommend using a <code>set</code> as the <code>in</code> operation will be faster</p>
<pre><code>>>> b = {'car'... | python|list|lambda | 4 |
9,396 | 49,076,378 | Pytest Generate Tests Based on Arguments | <p>New to pytest...</p>
<p>I have the following in conftest.py to collect a team argument from the command line, and read in a yaml config file:</p>
<pre><code>import pytest
import yaml
def pytest_addoption(parser):
parser.addoption(
'--team',
action='store',
)
@pytest.fixture
def team... | <p>The problem with your setup is that you want to parameterize on <code>conf[team]</code>, but <code>conf</code> needs to be defined at <em>import</em> time, because that's when the decorator executes. </p>
<p>So, you'll have to go about this parameterization differently, using pytest's <a href="https://docs.pytest.... | python|pytest | 12 |
9,397 | 66,799,306 | How to save multiple stocks data frame into different separate csv files? | <p>Sample code:</p>
<pre><code>tickers = ["FB", "AMZN", "AAPL", "NFLX", "GOOG", "^GSPC",...]
multpl_stocks = web.get_data_yahoo(tickers,
start = "2013-01-01",
end = "2014-03-01"())
</code></pre>
<p>I would like to save all tickers at the sa... | <p>You could do something like this:</p>
<pre><code>import pandas as pd
from pandas_datareader import data as web #I assume this is what you have
from datetime import datetime
tickers = ["FB", "AMZN", "AAPL", "NFLX", "GOOG"] #and everything else
for stock in tickers:
... | python-3.x|export-to-csv|yahoo-finance | 0 |
9,398 | 67,054,311 | Retrieve tag of every post in a hashtag instagram | <p>I need a very simple Instagram API to retrieve every username that posted something on a specific hashtag, i tried with Instaloader and BeautifulSoup but I didn't realise anything.</p> | <p>Instagram provides a Hashtag API for this usecase</p>
<p><a href="https://developers.facebook.com/docs/instagram-api/guides/hashtag-search/" rel="nofollow noreferrer">https://developers.facebook.com/docs/instagram-api/guides/hashtag-search/</a></p> | python|instagram|instagram-api | 0 |
9,399 | 66,828,008 | Speed per process getting slower with more processes | <p>I am trying to improve the speed of some code with multiprocess. And I noticed the speed does not increase as expected. I know there are overheads for the spawn of child processes and there are overheads for data transfer between the parent process and child processes. However, even after I minimized the overheads, ... | <p>Have you figured out the problem? I had the same issue with multiprocessing. I found that if you add a certain delay (not too small) between different processes, the time consumption of each process will reduce down to same value as that of one parallel process. However, we end up gaining nothing from multiprocessin... | python|multiprocess | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.