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
5,100
7,119,452
Git commit from python
<p>I want to write a module in python (This is the learning project) to enhance my git experience. Is there a python module for various git commands? At least the basic ones (commit/diff/log/add)?</p> <p>I saw <a href="https://github.com/gitpython-developers/GitPython">GitPython</a> but I couldn't find the support for...
<p>In GitPython you <a href="http://gitpython.readthedocs.org/en/stable/tutorial.html#the-index-object" rel="noreferrer">create a commit from an index object</a>.</p> <p>In libgit2 you <a href="http://www.pygit2.org/objects.html#pygit2.Repository.create_commit" rel="noreferrer">create a commit from a repository object...
python|git
15
5,101
39,870,942
Parsing XML in Python with multiple tags
<p>I'm trying to parse an XML file.<br> I succeeded at parsing tags at the upper layer, but now I have a tag within a tag and I'm not getting the correct output.</p> <p><strong>XML FILE:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Stations&gt; &lt;Station&gt; &lt;Code&gt;HT&lt...
<p>something like this (note: I have used <code>.fromstring()</code> in this example, but you can modify this for your own use with files)</p> <pre><code>import xml.etree.ElementTree xmlstring = "&lt;root&gt;&lt;synoniemen&gt;&lt;synoniem&gt;A&lt;/synoniem&gt;&lt;synoniem&gt;B&lt;/synoniem&gt;&lt;/synoniemen&gt;&lt;/r...
python|python-3.x
2
5,102
39,551,886
How to make loop repeat until the sum is a single digit?
<p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p> <p>T...
<p>This should work, no division involved.</p> <pre><code>n = int(input("Input an integer:")) while n &gt; 9: n = sum(map(int, str(n))) print(n) </code></pre> <p>It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9....
python
6
5,103
16,305,478
Python raw input and system.split in a fab file
<p>Python newbie here. Lets say I have this:</p> <pre><code>def test_servers(): env.user = getpass.getuser() env.hosts = [] </code></pre> <p><br> And I want to do something like this:</p> <pre><code>def test_servers(): env.user = getpass.getuser() system = raw_input("Enter FQD...
<pre><code>&gt;&gt;&gt; system = raw_input("Enter FQDN to show (seperated by commas for multiple entries) &gt; ") Enter FQDN to show (seperated by commas for multiple entries)&gt; apple,oranges,lim es,lemons &gt;&gt;&gt; system 'apple,oranges,limes,lemons' &gt;&gt;&gt; splitted = system .split(',') &gt;&gt;&gt; split...
python|string-formatting|fabric
1
5,104
16,495,682
boost exposing classes LNK2019 / module does not define init function
<p>I know those errors in the headline are nothing new, but in this constellation I have here it's rather strange and I don't find a solution that is helping. So let me explain.</p> <p>I'm working with boost.python, Visual Studio 2012 and the tutorial from the developers site. So as i finally fixed all linker problems...
<p>You are missing the name of class:</p> <pre><code>void World::greet(){ printf("hello"); } </code></pre>
c++|python|boost|lnk2019
0
5,105
16,544,796
Proper Python packaging with external package dependencies
<p>Let's suppose I have a project that depends on packages that should only be installed via the systems package manager (e.g. bindings to C libraries), so that <code>install_requires</code> is not working.</p> <p>Currently, I try to import said packages in <code>setup.py</code> and call <code>sys.exit()</code> with a...
<p>You can create native system packages (<code>deb</code>, <code>rpm</code>, etc.) and describe the dependencies in it (which are the C libraries in your case). You can check the <a href="http://www.debian.org/doc/manuals/maint-guide/build.en.html" rel="nofollow">Debian packages packing manual</a> (or packages for som...
python|packaging|setup.py
0
5,106
31,789,149
Python Multiprocessing: AttributeError: 'Test' object has no attribute 'get_type'
<p><strong>short short version:</strong> </p> <p>I am having trouble parallelizing code which uses instance methods.</p> <p><strong>Longer version:</strong></p> <p>This python code produces the error:</p> <pre><code>Error Traceback (most recent call last): File "/Users/gilzellner/dev/git/3.2.1-build/cloudify-syst...
<p>You're using multiprocessing <code>map</code> method incorrectly.<br> According to <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map" rel="nofollow">python docs</a>:</p> <blockquote> <p>A parallel equivalent of the map() built-in function (it supports on...
python|multiprocessing|pickle|dill|pathos
1
5,107
40,432,366
What's the difference between non-pure and pure functions?
<p>Can pure functions take an argument? For example,</p> <p>def convert(n):</p> <p>Thank you in advance</p>
<p>Of course they can have arguments. The only difference is whether they have side effects beyond the input and output parameters. Without input arguments to use as "inspiration", it's difficult for a pure function to do something useful.</p>
python|python-3.x
2
5,108
68,390,241
Add method dynamically to class _without_ exposing method in python
<p>I have a library that for various reasons I want to build up in pieces (mainly so I can document them, work on them and test them independently in a notebook).</p> <p>Suppose I have an owner class <code>Parse</code> - and I want to add a bunch of static methods to it.</p> <p>This code works:</p> <pre class="lang-py ...
<p>So my first somewhat crude answer would be to define the helper function, set it as an attribute of Parse and then delete the original reference.</p> <pre><code>class Test: def __init__(self): pass def my_func(): print('yay') Test.my_method = my_func del my_func Test.my_method() try:...
python
1
5,109
60,240,054
Spaces replaced by =20 after extracting text from email
<p>I tried to get the text of a received gmail, using the email and imaplib modules in python. After decoding with utf-8 and after getting the payload of the message, all the spaces are still replaced by =20. Can I use another decoding step in order to fix this? </p> <p>The code is the following: (I got it from a yout...
<p>Try to <code>import quopri</code>, and then when you get the content of the email body (or whatever text that has the <code>=20s</code> inside), you can use <code>quopri.decodestring()</code></p> <p>I do it like this</p> <p><code>quopri.decodestring(part.get_payload())</code></p> <p>But do keep in mind that this is ...
python|python-3.x|email|imap|imaplib
2
5,110
44,229,149
Executing a PowerShell script OUTSIDE of Python
<p>I am trying to run a sort of application that utilises both Python and powershell scripts. I already wrote the Python script and powershell script, which are meant to work simultaneously but separate from each other. What I want to do is create a Python program that launches them both, is there a way? Thanks! What ...
<p>I think you don't want <code>"-ExecutionPolicy","Unrestricted"</code> as script arguments but instead want to set powershells execution policy to allow the execution of your script. Therefore you should pass those parameters before the actual Script.</p> <p>Second: It's not enough, to pass the script as argument to...
python|powershell|subprocess
2
5,111
54,462,987
Traceback little prob
<p>I got that error when i use "swtichbot bonuschanger on game" </p> <p>Traceback (most recent call last):</p> <p>File "ui.py", line 1506, in OnToggleDown</p> <p>File "switchbot.py", line 115, in Activate</p> <p>AttributeError 'int' object has no attribute 'gameWindow'</p> <p>ui.py </p> <pre><code>def OnToggleDow...
<p>i changed this line </p> <pre><code>if self.parentWindow.parentWindow.gameWindow != None: #--line 115 </code></pre> <p>with this one </p> <pre><code>if self.sub_parent.parentWindow.parentWindow.gameWindow != None: </code></pre> <p>thanks a lot for your time , you the best !!!</p>
python
0
5,112
12,098,462
Python MultiProcessing and Directory Creation
<p>I am using Python Multiprocessing module to scrape a website. Now this website has over 100,000 pages. What I am trying to do is to put every 500 pages I retrieve into a separate folder. The problem is that though I successfully create a new folder, my script only populates the previous folder. Here is the code:</p>...
<p>It is best for the worker function to <em>only</em> rely on the single argument it gets for determining what to do. Because that is the only information it gets from the parent process every time it is called. This argument can be almost any Python object (including a tuple, dict, list) so you're not really limited ...
python|file|directory|multiprocessing
1
5,113
12,456,308
Python, from matrix to array
<p>I have a 3d matrix <code>grid_z0</code>, whose dimension are (let's say) 50x25x36. Each point of this matrix represents a cell. I would like to convert this matrix into a 1D array of size 50x25x36. I would also like to create 3 array of the same size showing the coordinate of the cell center. The array <code>cx</co...
<p>You should consider using <a href="http://docs.scipy.org" rel="nofollow">NumPy</a>.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.random.rand(50,25,36) # Create a fake array &gt;&gt;&gt; print a.shape (50, 25, 36) &gt;&gt;&gt; a.shape = -1 # Flatten the array in place &gt;&gt;&gt; print a.shape...
python
3
5,114
12,577,279
Convert string 5'8'' to 5.677 in Python?
<p>I am trying to calculate BMI(Body Mass Index) using Python where user inputs their height and weight. The user inputs the height as 5'8" or 6" or 6'1" which should be converted into feet like 5'8" should be converted to 5.667. Here's my code so far.</p> <pre><code>#!/usr/bin/python3.2 W = input("Enter weight:") H...
<p>I think you have misunderstood your homework, you need to convert feet and inches into inches. 5'8" should go to 68 in your formula. Here's what you want to do (doesn't do any format checking though, assumes xx'yy"):</p> <pre><code>H_feet = H.split("'")[0] H_inch = H.split("'")[1].split("\"")[0] H_inches = int(H_f...
python
3
5,115
7,795,457
Elegant way of grouping attributes
<p>I want to group attributes of instances of a class, so that it would be easy to iterate through all the attributes belonging to a group. The obvious answer would be to put all these into a list or dict, but then I wouldn't be able to access them as attributes of my object, and I would prefer that.</p> <p>Some code ...
<p>How about make <code>rotatable</code> an attribute of a <code>Vector</code> class:</p> <pre><code>class Vector(object): def __init__(self,v,rotatable=False): self.value = v self.rotatable = rotatable </code></pre> <p>And then use <code>properties</code> to access the values easily:</p> <pre><c...
python
3
5,116
79,850
How do you design data models for Bigtable/Datastore (GAE)?
<p>Since the Google App Engine Datastore is based on <a href="http://research.google.com/archive/bigtable.html" rel="noreferrer">Bigtable</a> and we know that's not a relational database, how do you design a <strong><em>database schema</em>/<em>data model</em></strong> for applications that use this type of database sy...
<p>Designing a bigtable schema is an open process, and basically requires you to think about:</p> <ul> <li>The access patterns you will be using and how often each will be used</li> <li>The relationships between your types</li> <li>What indices you are going to need</li> <li>The write patterns you will be using (in or...
python|database|google-app-engine|bigtable
19
5,117
990,169
How do convert unicode escape sequences to unicode characters in a python string
<p>When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?</p>
<p>Assuming Python sees the name as a normal string, you'll first have to decode it to unicode:</p> <pre><code>&gt;&gt;&gt; name 'Christensen Sk\xf6ld' &gt;&gt;&gt; unicode(name, 'latin-1') u'Christensen Sk\xf6ld' </code></pre> <p>Another way of achieving this:</p> <pre><code>&gt;&gt;&gt; name.decode('latin-1') u'Ch...
python|unicode|python-2.x
31
5,118
33,957,742
Installing psycopg2 in an Azure Web App
<p>I use Heroku to host a Django web app with a postgres back-end. I'm now looking to migrate this web app to Azure, taking advantage of a great deal Azure recently offered me.</p> <p>I've made an Azure Web App, and hosted the postgres DB on a separate Azure VM.</p> <p>When I try to set up Contiguous Integration in t...
<p>There are two key points as your missing.</p> <p>First, Azure Webapps normally run on the 32-bit system platform. If you have to use the 64-bit package, you need to update the Basic or Standard mode for your apps and switch the 64-bit platform, see below in the tab <code>Configure</code> of Azure WebApps.</p> <p><...
python|django|postgresql|azure|heroku
1
5,119
57,151,829
CTCI 6TH EDITION 1.9
<p>Question : Check if s2 is a rotation of s1.</p> <pre class="lang-py prettyprint-override"><code> def check(s1, s2): s1 += s1 return (s1.find(s2) != -1) s1 = 'abcd' s2 = 'dabc' print(check(s1, s2)) METHOD 2 def check(s1, s2): s1 = list(s1) s2 = list(s2) for _ in range (len(s2)): if s1 != s2: ...
<pre><code>In [15]: s1 = 'abcd' ...: s2 = 'dabc' In [16]: set(s1).difference(set(s2)) ...
python|python-3.x|string
0
5,120
27,781,881
how to get a video file's orientation in Python
<p>I would like to load a video file's frames into a numpy array. I want the frames to be properly upright, which means I need to read the orientation metadata in the video file, and rotate the loaded frames accordingly.</p> <p>I have a means of loading the frames (opencv's python bindings), so all I need is a way to ...
<p>use qtrotate. It's just one file, and it works on .Mov files </p> <p><a href="https://github.com/danielgtaylor/qtrotate" rel="nofollow">https://github.com/danielgtaylor/qtrotate</a></p>
python|video|orientation|metadata|exif
1
5,121
43,227,470
how to set the font size of chart title which is drawn using openpyxl module
<p>I'm using <code>openpyxl</code> module to plot the graphs for available analytical data. I'm able to plot the graphs, but I'm unable to find the option to change the font size of chart title. By default it's giving '18' as font size. In <code>openpyxl</code> there was <code>openpyxl.Styles</code> module which has 'F...
<p>Try the following snippet with applying <code>CharacterProperties</code> with integer <code>sz</code> (size) value:</p> <pre><code>from openpyxl.drawing.text import CharacterProperties chart.x_axis.title.tx.rich.p[0].r.rPr = CharacterProperties(sz=3500) </code></pre>
python-3.x|openpyxl
3
5,122
37,115,369
Extract non- empty values from columns of a dataframe in python
<p>This is a follow up of this question: <a href="https://stackoverflow.com/questions/37099920/extract-non-empty-values-from-the-regex-array-output-in-python">Extract non- empty values from the regex array output in python</a></p> <p>I have a DF with columns "col" and "col1" of type 'numpy.ndarray' and looks like :</p...
<p>Try the following:</p> <pre><code>import pandas as pd def parse_nested_max(xss): return max( (max((int(x) for x in xs if x), default=0) for xs in xss), default=0 ) df['col'] = df.col.apply(parse_nested_max) df['col1'] = df.col1.apply(lambda s: ','.join(s) or 'NOT FOUND') </code></pre> <...
python|regex|numpy|pandas
0
5,123
36,712,898
Find all csv files in the directory and add found file to the proper list by its name
<p>I have declared dictionary. I want to find all csv files in the directory and if it has a key from dictionary in its name it should be added to <code>KeyFile</code> variable. If it has a string under key in its name, it should be added to a list <code>FoundedFiles</code>.</p> <p>My code:</p> <pre><code>ScriptDirec...
<p>Wellcome to python world! :)</p> <p>First of all if you have deep nested conditions or loops, you should use functions for a simple tasks like found something in filename.</p> <p>Second - i recommend you to read pep8 <a href="https://www.python.org/dev/peps/pep-0008" rel="nofollow">https://www.python.org/dev/peps/...
python|python-2.7
2
5,124
48,886,748
List VM sizes in Microsoft Azure Compute based on Type or Category
<p>We are trying to list all available sizes for particular location using the API "GET <a href="https://management.azure.com/subscriptions/" rel="nofollow noreferrer">https://management.azure.com/subscriptions/</a>{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/...
<p>I used the sample posted by Laurent (link below) and it returned all available VM sizes' names, cores, disks, memory, etc. in the region (use parm location=region). If you put some code around it you should be able to do example 2.</p> <p><a href="https://stackoverflow.com/questions/52061293/get-virtual-machine-siz...
python-2.7|azure|adal|azure-resource-manager|azure-resource-group
2
5,125
48,161,312
How can I set the created instance's property in Django-Rest-Framework CreateAPIView?
<p>How can I set the created instance's property in Django-Rest-Framework? </p> <pre><code>class ServerTaskCreateAPIView(CreateAPIView): serializer_class = PhysicalServerTaskCreateSerializer permission_classes = [] queryset = ServerTask.objects.all() def perform_create(self, serializer): # I w...
<p>You can use this: <a href="http://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations" rel="nofollow noreferrer">http://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations</a></p> <pre><code>def create(self, valida...
python|django|django-rest-framework
0
5,126
51,260,936
Convert .txt file (data feed) to .csv file
<p>Basically the original data has no headers but only value (but i have header list). The delimiter is '|'. Now what i try to do is to convert txt file to csv file by using. The csv file contains headers i have and corresponding values. </p> <p>For example: </p> <p><strong>txt file looks like:</strong> </p> <blockq...
<p>Stitching up from parts in stackoverflow yields the following solution</p> <pre><code>import pandas as pd mycolnames = ['col1','col2','col3','col4','col5'] # Use the sep argument to change your delimiter accordingly df = pd.read_csv("foo.txt", sep="|") # Set your column names to the data frame df.columns = mycol...
python|text-parsing
0
5,127
73,724,994
Can we do predictions for sub-classes i.e. class within class?
<p>I need to classify an object into multiple classes. Normally we are familiar with multi-class classification with a single hierarchy, but in my case I have two levels of hierarchy. See the below images to get a clear picture of what I am talking about. so that if I want to classify an image, it should give me all th...
<p>If you know your hierarchy tree, wouldn't it be ok for you to do multi-class classification on the leaves (the final classes), then check what are the parent classes in the tree, for a given prediction ?</p>
tensorflow|machine-learning|pytorch|conv-neural-network|image-classification
0
5,128
17,461,600
Semi-transparent 2d VTK text background
<p>Simple question, but I've tried a few things and nothing seems to work.</p> <p>I want to overlay some statistics onto a 3d VTK scene, using 2D <code>vtkTextActor</code>s. This works fine, but the text is at times difficult to see, depending on what appears behind it in the 3D scene.</p> <p>For this reason, I'd lik...
<p>I've found a way to do this with <code>vtkPolyMapper2D</code> which seems to work okay. It seems to be a very stupid way to do this. If there is something more elegant, I'm all ears.</p> <pre><code>import vtk extents = [[0,0],[620,0],[620,220],[0,220]] polyPoints = vtk.vtkPoints() for x, y in extents: polyPoi...
python|vtk
1
5,129
17,377,113
Using python to batch run other python scripts
<p>I have a number of python scripts I want to pipe back to back about 1000 times, changing the input file for each</p> <p>I was previously doing this with a bash shell script, but I need it to work on a windows machine now. </p> <p>Here is the python, with the line in question commented out</p> <pre><code>namecount...
<p>subprocess.call should be fine. The basic is,</p> <pre><code>call(["args" in comma separated]) </code></pre> <p>Here is the link <a href="http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module" rel="nofollow">http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module</a>.</p...
python|command-line-interface
1
5,130
72,964,352
The b-button is not displayed in the b-table VueJs
<p>I'm starting at Vue Js, my problem is that my b-button is not shown in my table and I don't understand why.</p> <p>Here is my HTML code:</p> <pre><code>&lt;div id=&quot;listlocales&quot;&gt; &lt;div class=&quot;overflow-auto&quot;&gt; &lt;b-button size =&quot;sm&quot; href=&quot;{% url 'n...
<p>The v-slot directive, that Boostrap is using, was introduced in Vue version 2.6.0. To fix your issue you have to upgrade your Vue version</p> <pre><code>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue@2.6.0/dist/vue.js&quot;&gt;&lt;/script&gt; </code></pre>
javascript|python|html|django|vue.js
0
5,131
73,033,021
Pytorch fine tuned CNN model giving always the same prediction in training and validation data
<p>I decided to move from TensorFlow to Pytorch and I am with some issues in understanding how it works. I tried to follow <a href="https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html" rel="nofollow noreferrer">This Tutorial</a> which has a very simple example of Feature Extraction from I...
<p>Be careful, <code>img_to_test</code> is in the <code>HWC</code> format. You are reshaping the image when you should be transposing its axes from <code>HWC</code> to <code>CHW</code>. You may want to replace the following:</p> <pre><code>&gt;&gt;&gt; test_x = img_to_test.reshape(1, 3, 224, 224) </code></pre> <p>With ...
python|machine-learning|pytorch|conv-neural-network|imagenet
1
5,132
64,777,868
pandas barchart color the bar to matching column data
<p>I have a graph where values are the number of colors ( 4 red, 5 blue, 1 white) etc. How do I color the bars to match the data, when I try my code the reds are green , the whites are black for example.</p> <pre><code>def this_family(): data = pd.read_sql('SELECT * FROM toys WHERE Date &gt;= ? ', conn, params=(...
<p>This was solved by ordering the initial database query.</p>
pandas|plot
0
5,133
53,285,499
asyncio + aiohttp: overlapping IO with sleeping
<p>When all coroutines are waiting, asyncio listens for events to wake them up again. A common example would be <code>asyncio.sleep()</code>, which registers a timed event. In practice an event is usually an IO socket ready for receiving or sending new data.</p> <p>To get a better understanding of this behaviour, I se...
<p>The problem is that one second happens in server is performed in <code>async with session.get("http://127.0.0.1:5000/") as response:</code>.</p> <p>The http request finishes before you get this <code>response</code> object.</p> <p>You can test it by:</p> <pre><code>... async def main(): async with aiohttp.Cli...
python|async-await|python-asyncio|aiohttp
2
5,134
53,346,803
pyinstaller executable doesn't run in Ubuntu 18.04.1
<p>I looked through other posts and they didn't seem to address the specific issue where <em>nothing</em> happens when I try to execute a compiled program.</p> <p>Not sure if this is an Ubuntu issue or a python issue... Either way I'm very new to both so I'm sure there's some simple answer to this.</p> <p>I wrote a s...
<p>Try running it like this: <code>./mytest</code></p> <p>Bash only looks is the current directory if you specify the relative path to the file.</p>
python|python-3.x|ubuntu|pyinstaller
0
5,135
53,137,109
Why would you need to turn a python file into an executable?
<p>I know that it is possible to turn python files into .exe files but why would you need to do that? What are the benefits?</p>
<p>A lot of the time, it has to do with bundling.</p> <p>Consider that when you go to distribute a standalone Python program, you often have to assume that whomever the program is intended for already has, at the very least, a Python interpreter of a compatible version installed. Similarly, if your program uses packag...
python-3.x
0
5,136
68,471,495
Not able to read Sharepoint list items which has blanks in its headers
<p>I am using Sharepoint online to fetch the data from the list. For that I have written below code:</p> <pre><code>from office365.runtime.auth.authentication_context import AuthenticationContext from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.user_credential import UserCredent...
<p>Hi i got the answer for it. If you have space or underscore in headers just write without space in header for example:-</p> <pre><code>for item in l_items: print(item.properties['ProjectID'], item.properties['ProcessOwner']) </code></pre> <p>This worked for me.</p>
python|sharepoint|office365|sharepoint-online|sharepoint-list
0
5,137
68,868,317
value_counts unstack with additional categories
<p>I have this DataFrame:</p> <pre><code>data = [{'name':'John', 'date':20210801, 'work':False}, {'name':'John', 'date':20210802, 'work':True}, {'name':'Lucy', 'date':20210801, 'work':False}] df = pd.DataFrame(data) df.groupby(['name'])['work'].value_counts(normalize=True).unstack(fill_value=0).stack().reset_index() </...
<p>We can use normalized <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> to ensure that there are bo...
python|pandas|dataframe
2
5,138
10,766,009
flip order of ndarray in cython for opencv - OpenCV Error
<p>Apologies for the length of the post...</p> <p>I am using cython to wrap some cpp code for image processing. </p> <p>On return of my processed image which is in 32-bit ARGB mode - i.e. a 32-bit uint where <code>r = (buff[0] &gt;&gt; 16) &amp; 0xFF; g = (buff[0] &gt;&gt; 8) &amp; 0xFF; g = buff[0] &amp; 0xFF</code...
<p>It fails because of bug in OpenCV: <a href="http://code.opencv.org/issues/1393" rel="nofollow">http://code.opencv.org/issues/1393</a></p> <p>You should be able to workaround this issue by multiplying flipped matrix by 1:</p> <pre><code>original = original * 1 </code></pre>
python|opencv|numpy|cython
1
5,139
4,985,347
KeyError when adding a constraint in python-constraint
<p>I am making a function that takes in a list of drivers and passengers with their locations, and returns a list of allocations of passengers to drivers that maximise the number of passengers assigned to a driver, subject to the following constraints:</p> <ol> <li><p>A passenger can only be in one car</p></li> <li><p...
<p>Your variables have the form <code>(driver, passenger)</code>:</p> <pre><code>p = [(driver, passenger) for driver in drivers for passenger in passengers] self.problem.addVariables(p, [0,1]) </code></pre> <p>The variables you give to <code>addConstraint()</code>, however, have the form <code>(passenger, driver)</co...
python|constraint-programming
4
5,140
61,933,851
Installation of Opencv4 on Ubuntu
<p>how are you ? I am currently a tutorial on the installation of opencv4 with ubuntu 18.04 LTS on <a href="https://i.stack.imgur.com/AgPAt.jpg" rel="nofollow noreferrer">pyimagesearch</a>. But in step 4 I have some error.</p> <p>1.) The python3 section is actually missing so the Interpeter does not point to the Pytho...
<p>You have to remove spaces on every side of <code>/</code> :</p> <pre><code>cmake -D CMAKE_BUILD_TYPE = RELEASE \ -D CMAKE_INSTALL_PREFIX =/usr/local \ -D INSTALL_PYTHON_EXAMPLES = ON \ -D INSTALL_C_EXAMPLES = OFF \ -D OPENCV_ENABLE_NONFREE = ON \ -D OPENCV_EXTRA_MODULES_PATH = ~/opencv_contrib/modules \ -D PYTHON_E...
python|opencv
0
5,141
61,683,084
Python: cerberus check_with function
<p>I would like to validate a <code>dict</code>, where the values adhere to the following rules:</p> <ul> <li>value must be either a single <code>float</code> or <code>List(float)</code></li> <li>if it is a single <code>float</code>, the value must be 1</li> <li>if it's a <code>List(float)</code>, each float must be p...
<p>What if you try to catch the error and only continue your function, if the error was occurred? For example like in this manner:</p> <pre><code>class MyValidator(Validator): def _check_with_sum_eq_one(self, field, value): &quot;&quot;&quot; Checks whether value is a list and its sum equals 1.0. &quot;&quot;&quot...
python|python-3.x|validation|cerberus
1
5,142
60,601,171
Can not render objects while embedding ipython with qtConsole in win10
<p>I've embedded <code>QTConsole</code> with <code>Ipython</code>. Everything works fine when I try to render objects through <code>IPython</code> in Linux/Ubuntu but in Win10, it can not be rendered. </p> <p>although I can render any other objects in a separated window on win10.</p> <p>Here's my code snippet : </p>...
<p>Finally, I resolved my problem by using Kernel Manager to handle my processes</p>
python|opengl|pyqt|ipython|vtk
0
5,143
61,065,243
Indexing array from second element for all elements
<p>I think it must be easy, but I cannot google it. Suppose I have array of numbers 1, 2, 3, 4.</p> <pre><code>import numpy as np a = np.array([1,2,3,4]) </code></pre> <p>How to index array if I want sequence 2, 3, 4, 1?? I know that for sequence 2, 3, 4 I can choose e.g.:</p> <pre><code>print(a[1::1]) </code></pr...
<p>If you want to rotate the list, you can use a <a href="https://docs.python.org/3.8/library/collections.html#deque-objects" rel="nofollow noreferrer">deque</a> instead of a numpy array. This data structure is designed for this kind of operation and directly provides a rotate function.</p> <pre class="lang-py prettyp...
python|numpy|slice
1
5,144
60,889,926
Altair: Crop Log10 axis to desired interval (domain)
<p>Using the Altair in Python, is it possible to crop Log10 axis at the designated value? I would like to show only between 5 - 50 on the log scale.</p> <p>Below is my code and the image I get:</p> <pre><code>import altair as alt import pandas as pd from vega_datasets import data cars = data.cars() nice = pd.DataFr...
<p>The domain argument does work with log scales, but domains must start and end on integer powers of the base, and other values will be rounded to the next integer power.</p> <p>For example, here is a default base-10 domain:</p> <pre><code>import altair as alt import pandas as pd data = pd.DataFrame({'x': [1, 10, 1...
python|altair
2
5,145
66,273,129
How to add a column in a CSV file while converting Image folder to CSV file in Python
<p>I have lots of Images of digits in a folder which I have converted in a CSV file, but like in MNIST data set when we converted a digit in a CSV file it has a label column attached to it but when I converted my image folder into CSV , my CSV file does not consist of Label column.</p> <p>Please help me how can I add a...
<p>Assuming that you are having sub-directories inside a directory where each sub-directory denotes a class.</p> <p>I have also faced a similar albeit not exact issue in the past, here's how I handled it.</p> <ol> <li>Make a dictionary object with your class name as keys and their ordinal encoded value as the value of ...
python|machine-learning|deep-learning|mnist
0
5,146
59,048,712
How to make borders align with sub headers?
<p>I am trying to create a table like structure in <code>tkinter</code> using <code>grid</code> method. In my code i have 3 headers and 3 sub-headers, and each header must have three sub-headers under them. To achieve this i have used <code>columnspan</code> in <code>grid</code>. I am almost getting the required output...
<p>I believe you are looking for <code>sticky</code> parameter:</p> <pre><code>... for i in headers: label = Label(root, text = i, width = 15, relief = "groove") label.grid(row = 0, column = c, columnspan = 3, sticky="ew") c += 3 </code></pre>
python-3.x|tkinter
0
5,147
62,316,630
How do I use Try Except to catch a FileNotFoundError when a file is passed to a function?
<p>I have a function that takes a filename as an argument and performs some operations on the data inside the file. I need to implement a Try Except clause that catches a FileNotFoundError (if the filename passed to the function is invalid) and returns the value 1.</p> <p>Here is the function:</p> <pre><code>def crea...
<pre class="lang-py prettyprint-override"><code>def createdict(x): try: with open (x, "r") as file: lines = file.readlines() for i in range(len(lines)): lines[i] = lines[i].rstrip() except FileNotFoundError: return 1 else: return 0 </code></pre...
python-3.x
1
5,148
62,099,031
confusion_matrix() library is giving ValueError
<p>When trying to get confusion matrix for a ConvNet constantly getting the same error. </p> <pre><code>from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras impo...
<p>I am able to recreate your error using <code>Dogs_Vs_Cats</code> dataset. Where i have 2000 samples in train directory and 400 samples in validation directory.</p> <p>Please change <code>model.predict_generator</code> from </p> <pre><code>Y_pred = model.predict_generator(validation_generator, nb_validation_samples...
python|tensorflow|keras
1
5,149
31,528,375
"Trailing" One-Hot Encode
<p>I am trying to do something similar to One-Hot-Encoding but instead of the selected class being 1 and the rest zero, I want all the classes up to (and including the selected class) to be 1. Say I have a training batch with labels (5 possible class labels; 0, 1, 2, 3, 4)</p> <pre><code>y = np.array([0,2,1,3,4,1]) <...
<p>You could achieve this by using a lower-triangular matrix instead of an identity matrix in your function definition:</p> <pre><code>def many_hot_encode(arr, num_classes): return np.tril(np.ones(num_classes))[arr] many_hot_encode(y,5) array([[ 1., 0., 0., 0., 0.], [ 1., 1., 1., 0., 0.], [ ...
python|numpy
2
5,150
59,573,743
How to format a string using variables instead of numbers within curly braces?
<p>I'm using Python 3.7 and I have stored a value inside a variable. This variable holds the value of padding which I want to use within curly braces for string formatting. The code explains what I am trying to do.</p> <pre><code>def print_formatted(number): for i in range(1, number + 1): binum = bin(i).re...
<p>You can use f-strings and also format specifiers to avoid use of the <code>hex</code>, <code>oct</code> and <code>bin</code> builtins and then string slicing and use <code>int.bit_length()</code> instead of taking the length of the binary string, eg:</p> <pre><code>def print_formatted(number): # get number of b...
python|python-3.x|string-formatting
3
5,151
59,968,314
Find Href based on specific text in the name attribute of the a tag
<pre><code>&lt;a class="cscore_link" name="&amp;lpos=house:schedule:final" href="https://www.url.com-2019-20"&gt; </code></pre> <p>There are multiple classes of <code>cscore_link</code> in the <code>html</code>, but the value of <code>name</code> attribute differs. I need to get the href value of all the <code>cscore...
<p>Use Regex. </p> <p><strong>Ex:</strong></p> <pre><code>import re from bs4 import BeautifulSoup html = """&lt;a class="cscore_link" name="&amp;lpos=house:schedule:final" href="https://www.url.com-2019-20"&gt;&lt;/a&gt; &lt;a class="cscore_link" name="&amp;lpos=house:schedule" href="https://www.url.com-2019-20"&g...
python|beautifulsoup
1
5,152
67,823,058
Why is my x0 set to 110.0, but the x coordinate in the resulting image still starts from 0?
<p>Why is my x0 set to 110.0, but the x coordinate in the resulting image still starts from 0?</p> <pre><code>print(x0, y0) now = datetime.now() forecast = datetime(now.year, now.month, now.day) datestr = forecast.strftime(&quot;%Y%m%d&quot;) hour = now.hour dfs_filename = f&quot;dfs_{datestr}_{hour}.dfs2&quot; coordi...
<p>DFS2 is a raster file format, and a DFS2-file is always displayed with the coordinates of the raster cells measured from the bottom left, starting at 0,0 and then counting the rows and colums in the raster. The &quot;world coordinates&quot; of the cells are not displayed.</p>
python|mikeio
0
5,153
42,878,576
Putting two legend labels in different location in one plot
<p>I have three plots merged with one another in one figure that contain a lot of notable information. I recently was able to color code the legend labels instead of having them be labeled with their associated lines.</p> <p><a href="https://i.stack.imgur.com/m6FGU.png" rel="nofollow noreferrer"><img src="https://i.st...
<p>As can be seen in the chapter <a href="http://matplotlib.org/users/legend_guide.html#multiple-legends-on-the-same-axes" rel="nofollow noreferrer">Multiple legends on the same axes</a> of the matplotlib legend guide, you need to add the first legend as an artist to the axes before creating the second one</p> <pre><c...
python|matplotlib|label
1
5,154
51,054,361
make python utilize any symbol's input
<p>I'm making a code that can translate numbers to piano keys,</p> <p>***Sorry for the confusion, I meant the ideal output for <code>"3.14159ABC265"</code> is <code>"E1 _ C1 F1 C1 G1 D2 _ _ _ D1 A2 G1"</code>, however python will give an error when the input has #, \, or something</p> <p>the codes:</p> <pre><code>nu...
<p>You can use <code>ord</code> to turn any characters into numbers (based on <a href="https://www.asciitable.com/" rel="nofollow noreferrer">ASCII values</a>), then use division and remainder to map the numbers into piano key numbers and scales, and then use <code>chr</code> to turn key numbers into alphabets. Here's ...
python|python-3.x|input|symbols
0
5,155
45,053,886
How to get a Python Dataframe from ElasticSearch helpers.scan result
<p>Suppose I have a helper functions like:</p> <pre><code>result_helper = helpers.scan(es, scroll='2m', query={"query": {"match_all": {}}} ,index="test", size=1000, _source=('logtime','host_name', 'kv', 'value') ) </code></pre> <p>How I can get this data into a python dataframe?</p> <p>With this approach:</p> <pre>...
<p>After a few considerations and tests I have developed the following solution:</p> <p>With</p> <pre><code>result_helper_list = list(helpers.scan(es, scroll='2m', query={"query": {"match_all": {}}} ,index="check_mk_wnp_csh", size=1000, _source=('logtime','host_name', 'kv', 'value') )) </code></pre> <p>and</p> <pre...
python|elasticsearch|dataframe
0
5,156
56,256,941
Which initializers are affected by tf.variable_scope("Model", reuse=None, initializer=initializer)?
<pre><code>initializer = tf.random_uniform_initializer(-0.1, 0.1) with tf.name_scope("Train"): with tf.variable_scope("Model", reuse=None, initializer=initializer): model = network.Model(iterator, is_training=True) </code></pre> <p>My question is which varia...
<p>Short answer is no. And you can check it with </p> <pre class="lang-py prettyprint-override"><code>initializer = tf.random_uniform_initializer(-0.1, 0.1) with tf.variable_scope("Model", reuse=None, initializer=initializer): model = tf.layers.Conv2D(filters=3, kernel_size=1) print(model.get_config()) </code></p...
python|tensorflow
0
5,157
44,376,358
Filtering Dataframe Using Headers From Other Dataframes in Python
<p>I am trying to filter a dataframe based on the columns I have previously obtained from filtering the dataframe below. </p> <pre><code>AA BB CC DD EE FF GG 0 1 1 0 1 0 0 </code></pre> <p>The dataframe is coming from a file where the data in each row is either a 0 or a 1 and will change based on the file tha...
<p>Here's one way you can do this:</p> <pre><code>headers = InterestingFactors.columns.append(pd.Index(['ID','Postion_X','Position_Y'])) PivotTable = InfoTable.loc[:, headers] </code></pre> <p>This combines the columns you're looking for from <code>InterestingFactors</code> with the 3 columns you mention above. This ...
python|pandas|dataframe
1
5,158
23,944,242
How do numpy and GMPY2 compare with GMP in terms of speed?
<p>I understand that GMPY2 supports the GMP library and numpy has fast numerical libraries. I want to know how the speed compares to actually writing C (or C++) code with GMP. Since Python is a scripting language, I don't think it will ever be as fast as a compiled language, however I have been wrong about these genera...
<p>numpy and GMPY2 have different purposes.</p> <p>numpy has fast numerical libraries but to achieve high performance, numpy is effectively restricted to working with vectors or arrays of low-level types - 16, 32, or 64 bit integers, or 32 or 64 bit floating point values. For example, numpy access highly optimized rou...
python|c|numpy|gmp|gmpy
8
5,159
29,295,628
Django: remotely access a PythonAnywhere MySQL database
<p>I have a Django app (Python 3.4, Django 1.7) on PythonAnywhere, along with a MySQL database. <strong>The database is working fine on the deployed app.</strong></p> <p>However, I cannot get to connect it to the app on my local machine.</p> <p>The following error is thrown when I run <code>python manage.py runserver...
<p>I think It's not possible to connect directly to your mysqlserver instance from remote, for security reason, the port 3306 is blocked. They suggest to connect through SSH Tunnel, follow this <a href="https://www.pythonanywhere.com/wiki/SSHTunnelling" rel="nofollow">link</a>.<br/>I don't know If you can do an ssh tun...
python|mysql|django|pythonanywhere
4
5,160
52,023,464
Optimizing parameter in odeint with the output of a neural network in TensorFlow
<p>I would like to optimize the coefficients of an ODE using tensorflow. </p> <pre><code>def odeModel(state, t): x, y, z = tf.unstack(state) dx = y # Here I want to define dy and dz as follows: # [dy, dz] = tf.nn.relu(tf.matmul([y, z], W) + b) return tf.stack([dx, dy, dz]) </code></pre> <p>Basical...
<p>This can be done in exactly the way your describe:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np RS = np.random.RandomState(42) # Defining model parameters as TF variables W1 = tf.Variable(RS.randn(2, 1)) b1 = tf.Variable(RS.randn(1,)) W2 = tf.Variable(RS.randn(2...
python|tensorflow
0
5,161
51,941,227
How can I parse JSON data from the college scorecard API onto an HTML file?
<p>I was able to pull data from the college scorecard API into JSON objects using this template repeated a few times over:</p> <pre><code>def data_public_net_price(): url = 'https://api.data.gov/ed/collegescorecard/v1/schools.json' payload = { 'api_key': "api_key_string", '_fields': ','.join([ ...
<p>I would recommend using a template engine like <a href="http://jinja.pocoo.org/docs/2.10/" rel="nofollow noreferrer">Jinja2</a>.</p> <p>And for your html structure it depends on how you want to show the data. You could show inside a <code>&lt;ul&gt;</code> with <code>&lt;li&gt;</code>, or some <code>&lt;div&gt;</co...
python|html|json|api
0
5,162
43,737,948
How do I determine the memory usage of a python type?
<p>Working with large datasets means worrying about memory usage. Is there a bulit-in function, neat hack or widely available package to determine the memory usage of a given type?</p> <p>In the current case I am wondering how many bytes of memory a single <code>pandas.timedelta</code> Object requires, in order to det...
<pre><code>this can be done by using python memory profiler &gt;&gt;&gt; from guppy import hpy; h=hpy() &gt;&gt;&gt; h.heap() Partition of a set of 48477 objects. Total size = 3265516 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 25773 53 1612820 49 1612820 49 str 1...
python|memory
1
5,163
54,660,531
UDP sockets with Python
<p>I am trying to make a server capable of receiving and sending data using udp, I have reviewed some codes but they send or receive data, but not both, I am trying to send the data through one port and receive it by another, however I could not.</p> <p>Had I thought about using the accept () function as in TCP, is th...
<p>If you're a UDP listener, you <code>bind</code> a port to the socket. If you are sender, you don't need to bind a port:</p> <p><strong>echo server</strong></p> <pre><code>from socket import * s = socket(type=SOCK_DGRAM) s.bind(('localhost',5000)) while True: data,addr = s.recvfrom(1024) print(data,addr)...
python|sockets|udp
2
5,164
54,357,005
How to append a dataframe row to another within a for loop using .loc?
<p>Let's say I have the following dataframes:</p> <pre><code>df_t1 = pd.DataFrame([["AAA", 1 ,2],["BBB", 0, 3],["CCC", 1, 2],["DDD", 0, 0],["EEE", 0, 3]], columns=list('ABC')) A B C 0 AAA 1 2 1 BBB 0 3 2 CCC 1 2 3 DDD 0 0 4 EEE 0 3 </code></pre> <p>and</p> <pre><code>df_t2 = pd.DataFrame...
<p>From the docs, the append method: "Appends rows of other to the end of this frame, returning a <em>new</em> object". You have to use assign <code>df_t2</code> in your loop:</p> <pre><code>value_check = [2,3] for i in value_check: df_t2 = df_t2.append(df_t1.loc[(df_t1['B'] &lt;= i) &amp; (df_t1['C'] &gt; i)]) <...
python|python-3.x|pandas|dataframe
1
5,165
52,711,790
DataFrame column compare
<p>I'm a beginner to python and am having a hard time finding documentation on how to fix a problem I've come across.</p> <p>I need to know if the values in df1['id'] are in df2['id_list'] but hit a snag when I saw how the values were stored in df2</p> <p>when I export the values which creates my "id_list" series, it...
<p>For this kind of string problem, often list comprehensions are faster than built-in <code>pandas</code> string methods. You can do something like this:</p> <pre><code>desired_df = df1.join(df2) desired_df['located'] = [i1 if i1 in i2 else False for i1, i2 in zip(df1['id'], df2['id_list']) ] &gt;&gt;&gt; desired_d...
python|regex|pandas|merge
2
5,166
28,240,464
Python HTTP server send JSON response
<h1>What im doing</h1> <p>Im trying to get my hands dirty with python and im making a very simple http server so i can send commands to my arduino via serial. Im validating the commands as i sgould and everything works as it ahould be.</p> <h1>The concept</h1> <p>Im using the HTTP server in order to recieve <code>PO...
<p>The <code>json</code> module of Python's standard library offers exactly the functionality you're asking for. <code>import json</code> at the top of your module and <code>json.dumps(whatever)</code> to get the <code>json</code> string to send in the response.</p> <p>As a side note, failing authorization is most de...
python|json|http|http-headers
9
5,167
42,005,613
Can't find Flask template specified by relative path
<p>I am trying to render the <code>index.html</code> template in my Flask app's templates folder. However, I get a <code>TemplateNotFound</code> error. The template exists. How do I render it?</p> <pre><code>@app.route('/') def index(): return render_template('../../templates/index.html') </code></pre> <pre><co...
<p><a href="http://flask.pocoo.org/docs/api/#flask.render_template" rel="nofollow noreferrer"><code>render_template</code></a> takes the name to be looked up by the Jinja env, which has the <code>templates</code> folder it its lookup path. Only specify the path <em>after</em> that.</p> <pre><code># index.html is in th...
python|flask|jinja2
1
5,168
37,898,144
pydbus: How to publish an object?
<p>I want to publish a python object on a session bus, using <strong>pydbus</strong> and <strong>python 2.7</strong>. I'm new to pydbus, so I stick to the example and did the tutorial. However, I did not manage to launch a simply test server with pydbus. </p> <p>I wrote a simple class, with only one method, which retu...
<p>As described in Readme: "Since 0.5, it supports publishing objects on the bus - however this requires GLib 2.46 or newer."</p> <p>Unfortunately there is no way to publish objects with older GLib.</p>
python|python-2.7|dbus
3
5,169
37,094,344
Python: Repeating a function until a keypress is initiated
<p>My function 'hello()' simply displays a stimulus on screen for 2 seconds, during which time a key can be pressed. If a key isn't pressed, it waits 1 second and then runs the function again, over and over if no keys are pressed. When a key is pressed it exits the while loop and prints yes. For some reason, if I let t...
<p>You have called the function <code>hello</code> in <code>hello</code>. It's <strong>recursion</strong>. By the 5.th time, you press a key. It will print your <em><code>thing</code></em> and end the 5.th call of <code>hello</code>. Your program returns to the 4.th <code>hello</code> and catches the pressed key. The 4...
python|psychopy
0
5,170
64,617,290
How to import module in pydroid
<p>I'm having problem in importing my created module in pydroid 3. The process seems very simple in desktop version of python 3 but I tried doing it in Mobile in pydroid 3 application, but it does not work. The output was no module named ‘mymodule’ found When I created my module using Def and saved with mymodule.py</p>...
<p>I was having the same problem too , then i moved the module to ru.iiec.pydroid3 . Try it and see if it works .</p>
python|python-3.x|module|pydroid
0
5,171
64,525,337
Regex for finding chains of >=1 words starting with capital letters and connected with "-" or " "
<p>I want to obtain all the letter-only &quot;chains&quot; of at least 1 word starting with uppercase letters and followed by lowercase letters, connected with either space (&quot; &quot;) <strong>or</strong> &quot;-&quot; (a &quot;chain&quot; cannot be connected with &quot;-&quot; and with &quot; &quot;)</p> <p>For ex...
<p>You can use</p> <pre><code>\b[A-Z][a-z]+(?=([-\s]?))(?:\1[A-Z][a-z]+)*\b(?!-[A-Z]) </code></pre> <p>See the <a href="https://regex101.com/r/3hqUSL/3" rel="nofollow noreferrer">regex demo</a>. <strong>Details</strong>:</p> <ul> <li><code>\b</code> - word boundary</li> <li><code>[A-Z][a-z]+</code> - an uppercase ASCII...
python|regex|python-re
1
5,172
55,625,684
Can a non-blocking socket raise BlockingIOError from a reader/writer?
<p>Can a <code>sock.recvfrom</code> ever raise a <code>BlockingIOError</code> from a reader? Such as below</p> <pre class="lang-py prettyprint-override"><code>sock.setblocking(False) def reader() try: (data, addr) = sock.recvfrom(512) except BlockingIOError: # Can this ever be raised? loop.ad...
<blockquote> <p>Can [<code>BlockingIOError</code> in an asyncio reader] never actually happen, logically? If if it can happen, under what circumstances?</p> </blockquote> <p>The answer to this question will almost certainly be system-dependent. Python itself doesn't provide any guarantees on the matter: functions li...
python|linux|python-3.x|sockets|python-asyncio
3
5,173
73,272,778
Create bins with 1 percentage increments?
<p>I have a dataframe with column activity_percentage of a customer. This range is from 0-100%. Now, I want to create bin for each percentage but my current approach will require me to manually create 100 bins which is probably not the best way. How can I achieve this in a more programmatic way?</p> <pre><code>def cond...
<p>This will allow you to choose the increments that you want to look at. First, find the remainder of your <code>value</code> * 100 divided by the <code>increment</code>, then multiply that number by the <code>increment</code> to get the bottom range of your increments. If the bottom range is less than 100, print the ...
python|pandas
0
5,174
66,488,407
Darts how to build Timeseries - ValueError: cannot reindex from a duplicate axis
<p>I'm using DARTS to run forecasting model</p> <p>I have two columns:</p> <pre><code>TIME, QUANTITY </code></pre> <p>value is allocated quarterly with missing value.</p> <pre><code>2006-01-01 13.0 2006-04-01 2.0 2007-0-01 3.0 2007-10-01 11.0 </code></pre> <p>I want to build Timeseries</p> <pre><code>_df.index = ...
<p>Solved using pandas interpolation</p> <pre><code>_df.index = _df[c_time] #_df = _df[c_quantity] _df = _df.resample('Q').sum().interpolate(method='time') </code></pre>
python|pandas|time-series|u8darts
0
5,175
65,028,853
Set IPython terminal as default in vscode?
<p>I've installed most popular Python extensions in vscode. So I can do <code>shift+enter</code> to execute some selected code into a <em>python terminal</em>.</p> <p>This uses <code>/usr/bin/python3</code> as default. I would like to use IPython3 instead. However, I don't find such settings in <code>settings.json</cod...
<p>1.The reason for &quot;I can do shift+enter to execute some selected code into a python terminal.&quot; is that &quot;<code>shift</code>+<code>enter</code>&quot; is the default shortcut key of VSCode, and the command it executes is &quot;<code>python.execSelectionInTerminal</code>&quot;:</p> <pre><code>{ &quot;key&q...
python|visual-studio-code
1
5,176
64,155,169
Mock a decorator function to bypass decorator logic
<p>I'm trying write some unittests for my code which in turn uses a decorator</p> <pre><code>import unittest from unittest.mock import patch from functools import wraps def decorator(f): @wraps(f) def decorated(x): return f(x+1) return decorated @decorator def get_value(x): return x class...
<p>Since the decorator runs immediately after you define <code>get_value</code>, it's too late to mock the decorator. What you can do, though, (since you used <code>functools.wraps</code>) is mock <code>get_value</code> itself and use <code>get_value.__wrapped__</code> (the original function) in some way. Something lik...
python|python-unittest
3
5,177
65,256,284
Counting Word Frequency in a list of lists
<p>I have a list of lists:</p> <pre><code>list1 = [['This','could','be','heaven'] ,['This','could','be','hell'],['heaven','or','hell','i','like','it']] </code></pre> <p>I want to produce an ordered dictionary of word frequency where the word is the key and the value is the number of times it occurred in the entire lis...
<p>If you want a one liner:</p> <pre><code>from collections import Counter counts = Counter(x for sublist in list1 for x in sublist) </code></pre> <p>or a multi-liner without any imports:</p> <pre><code>counts = {} for sublist in list1: for x in sublist: if x in counts: counts[x] += 1 el...
python|python-3.x|dictionary|set
3
5,178
65,360,692
Python patching __new__ method
<p>I am trying to patch <code>__new__</code> method of a class, and it is not working as I expect.</p> <pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager class A: def __init__(self, arg): print('A init', arg) @contextmanager def patch_a(): new = A.__new__ def fa...
<p>You've run into a complicated part of Python object instantiation - in which the language opted for a design that would allow one to create a custom <code>__init__</code> method with parameters, without having to touch <code>__new__</code>.</p> <p>However, the in the base of class hierarchy, <code>object</code>, bot...
python|python-3.x|class
2
5,179
68,457,800
How to click a link on a web page using Python Selenium?
<p>I am trying to click a link on a web page with Python Selenium but I am getting this exception:</p> <blockquote> <p>no such element: Unable to locate element:</p> </blockquote> <p>I have already tried using <code>find_element_by_xpath</code>, <code>find_element_by_partial_link_text</code> and <code>find_element_by_l...
<p>You can try with <code>explicit waits</code> and with the <code>customized css</code> :</p> <p><strong>CSS_SELECTOR :</strong></p> <pre><code>a[href*='../../websys/webArch/getStatus.cgi'] </code></pre> <p><strong>Sample code :</strong></p> <pre><code>wait = WebDriverWait(driver, 10) wait.until(EC.element_to_be_clic...
python|selenium
0
5,180
62,496,275
Sklearn Decision Tree Classifier - Animal Guessing game
<p>I'm trying to make an Animal Guessing game with sklearn's Decision tree classifier. In this, with the users input, it will say whether the animal is a spider or a fish. When I enter the number of legs and where it stays, it says animal is a fish and vice versa. This is the code, any ideas?</p> <pre><code>from sklear...
<p>You inverted the <code>outcomes</code>, like this works for me:</p> <pre><code>from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier() features=[[6,0], [6,0], #0 is spider and 1 is fish [0,1], #6 = 4 legs and 8=stays in land ( this is a spider) ...
python|scikit-learn
1
5,181
67,493,137
Django file object always 0 bytes when uploaded from python requests
<p>I have been trying to upload a file to django REST using python requests.</p> <p>I put the file, and some other data, to the server.</p> <pre><code>r = self.session.put( f&quot;{hello_url}/shadow_pbem/savefile_api/&quot;, files=test_files, data={&quot;hash&quot;: test_file_hash, 'leader': 78}, heade...
<p>If you do</p> <pre><code>testfile.seek(0, os.SEEK_END) filesize = testfile.tell() </code></pre> <p>as you say, you'll need to also rewind back to the start – otherwise there is indeed zero bytes for Requests to read anymore.</p> <pre><code>testfile.seek(0) </code></pre>
python-3.x|django|django-rest-framework|python-requests
2
5,182
60,420,006
Python Selenium - Cannot find submit button
<p>Link: <a href="https://mail.protonmail.com/create/new?language=en" rel="nofollow noreferrer">https://mail.protonmail.com/create/new?language=en</a></p> <p>Problem</p> <p><code>chrome.find_element_by_xpath("//input[@type='submit']").click()</code></p> <p>Python cannot find the submit button id, name, or class in t...
<p>First you need to switch to <code>iframe</code> witch contains submit button. The you can find it and submit.</p> <pre><code>from selenium import webdriver import os import time browser = webdriver.Chrome(executable_path =os.path.abspath(os.getcwd()) + "/chromedriver") browser.get("https://mail.protonmail.com/crea...
python|selenium|selenium-webdriver
2
5,183
71,416,542
Python3 cant detect<class 'NoneType'>
<p>I am running some python3 code which will occasionally get a list, dict, and None.</p> <pre><code> fieldType = type(raw_data[root_key].get(&quot;oslc_cm:ChangeRequest&quot;)) print('fieldType=') print(fieldType) if fieldType is None: print('its none') else: ...
<p><code>fieldType</code> is <code>&lt;class 'NoneType'&gt;</code>, which is different from <code>None</code>. It can never be <code>None</code>, because <code>type</code> always returns some type.</p> <p>Looks like you want</p> <pre><code>raw_data[root_key].get(&quot;oslc_cm:ChangeRequest&quot;) is None </code></pre> ...
python-3.x|nonetype
1
5,184
64,266,229
Fast way to find length and start index of repeated elements in array
<p>I have an array A:</p> <pre><code>import numpy as np A = np.array( [0, 0, 1, 1, 1, 0, 1, 1, 0 ,0, 1, 0] ) </code></pre> <p>The length of consecutive '1s' would be:</p> <pre><code>output: [3, 2, 1] </code></pre> <p>with the corresponding starting indices:</p> <pre><code>idx = [2, 6, 10] </code></pre> <p>The original ...
<p>Let's try <code>unique</code>:</p> <pre><code>_, idx, counts = np.unique(np.cumsum(1-A)*A, return_index=True, return_counts=True) # your expected output: idx, counts </code></pre> <p>Output:</p> <pre><code>(array([ 2, 6, 10]), array([3, 2, 1])) </code></pre>
python|numpy
5
5,185
64,464,301
Absolute positions in mpld3 graphs
<p>I'm trying to define a custom plugin for <a href="https://mpld3.github.io/" rel="nofollow noreferrer"><code>mpld3</code></a>, and I'm struggling with positions. More particularly, by default, SVG generated by <code>mpld3</code> come with <code>Move</code> and <code>Zoom</code> buttons, which change the view of the g...
<p>I've managed to make it work. It turns out that downgrading <code>mpld3</code> to version <code>0.3</code> does what I want. I'm sure there is a better solution (because I can't take advantage of the latest version) but it gets the job done.</p>
python|matplotlib|data-visualization|mpld3
0
5,186
70,124,000
Trying to create a new dictionary through for and if loops
<p>I'm trying to write a loop that will iterate through a list of four-letter words, take the last two letters of the word, and assign the word to a dictionary key based on the last two letters. This is what I've got so far:</p> <pre><code>dictionary = {} for z in four_letters: #For each element of the four_letters li...
<p>The problem is in the line:</p> <pre><code>dictionary[last_letters] = z </code></pre> <p>It should have been:</p> <pre><code>dictionary[last_letters] = [z] </code></pre> <p>But here is a better (performant and some what cleaner) solution you should consider.</p> <pre><code>dictionary = {} four_letters = [ &quot...
python|loops|dictionary
0
5,187
11,385,521
Metaclass and syntax in Python
<p>I try to make something like that :</p> <pre class="lang-py prettyprint-override"><code>class oObject(object): def __init__(self, x = 0, y = 0, z = 0): self.x = x self.y = y self.z = z def asString (self, value): return str(value) vector = oObject(5,5,5) # So i can do asString(vec...
<p>You could either write a custom method for your <code>oObject</code> class that returns the string of the given <code>key</code>, or maybe you could write a custom <code>Variant</code> class and wrap your values:</p> <pre><code>class oObject(object): def __init__(self, x = 0, y = 0, z = 0): self.x = Var...
python|class|syntax
3
5,188
55,760,768
How can I fix "SystemError: null argument to internal routine" error when python callback in called from C
<h1>Intro</h1> <p>I'm writing a python application which uses a library written in C. When some event occurred at C level a Python callback is used to be called.</p> <p>Here is a part of my python callback definition:</p> <pre><code>def callback(str1, str2, cdata, flag): print("PYTHON HANDLER") ... print("&gt;...
<p>You should pass <code>cfunction_pointer</code> rather than <code>py_callback_ptr = cfunction_pointer.value</code> to your library.</p> <p>Minimal working example:</p> <p>cside.h:</p> <pre><code>#pragma once #ifdef __cplusplus extern "C" { #endif typedef struct DataStructure { int a; } DataStructure; typedef ...
python|c|gdb|swig
0
5,189
56,520,227
How to Identify Each Components from Audio Signal?
<p>I have some audio files recorded from wind turbines, and I'm trying to do anomaly detection. The general idea is if a blade has a fault (e.g. cracking), the sound of this blade will differ with other two blades, so we can basically find a way to extract each blade's sound signal and compare the similarity / distance...
<p>Well...</p> <p>If your shaft is rotating at, say 1200 RPM or 20 Hz, then all the significant sound produced by that rotation should be at harmonics of 20Hz.</p> <p>If the turbine has 3 perfect blades, however, then it will be in exactly the same configuration 3 times for every rotation, so all of the sound produce...
python|machine-learning|signal-processing
1
5,190
56,510,019
What is the best way to combine 2 string columns in pandas into a new column based on a specific condition?
<p>I have a pandas dataframe with string values in each column. I would like to combine column 1 and column 2 into a new column, let's say column 4. However, if words in columns 1 and 2 are the same, I would like to combine columns 1 and 3 into the new column instead.</p> <p>I have tried to put pairs in a list first, ...
<p>you could use the <code>where</code> method for pandas dataframes , </p> <pre class="lang-py prettyprint-override"><code>df['first_distinct_pair'] = (df['interest1'] + df['interest2']).where(df['interest1'] != df['interest2'], df['interest1'] + df['interest3']) </code></pre> <p>if you want to include spaces , you...
python|string|pandas
1
5,191
56,744,067
Faster way to execute multiple queries to postgresql in python
<p>I'm writing a script in python where I will need to access a postgresql database multiple times and execute multiple select queries and insert queries. I am trying to reduce the time it takes for this script to run. </p> <p>Currently I have written a secondary function which I pass a qry string, a boolean indicatin...
<p>A few things you can do. First, don't reestablish the connection with each query. This can be used over multiple queries so you will not need to recreate it with each query. If you still want to have the flexibility of having a function to execute the query, create a class where the <code>__init__</code> method open...
python|postgresql
1
5,192
17,748,551
Non-callable subclass of a callable class
<p>I have a class <code>A</code> that is callable. I also have a subclass of <code>A</code> called <code>B</code> that I want to make not callable. It should raise the normal "not callable" <code>TypeError</code> when I try to call it.</p> <pre><code>class A(): def __call__(self): print "I did it" class B...
<p>You can override type creation with Python metaclasses. Here after object creation, I replace parent's <code>__call__</code> method with another one throwing an exception:</p> <pre><code>&gt;&gt;&gt; class A(object): def __call__(self): print 'Called !' &gt;&gt;&gt; class MetaNotCallable(type): @s...
python|inheritance|callable
1
5,193
17,790,268
Successive Squares in Python
<p>I am writing a program in python that involves raising a number to an extremely high exponent. To do this, I am trying to implement the successive squares method to lower calculation time and remove the risk of overflow error.</p> <p>Successive squares is meant to do the same thing as <code>base**exponent % modulo<...
<p>You are doing <code>pow(7, 93, 13)</code> => <code>8</code> but what you want is <code>pow(7, 13, 93)</code> => <code>19</code></p> <p>Swap your function's second and third argument.</p> <pre><code>&gt;&gt;&gt; def ssp(b, n, m): ... ssp = 1 ... while n&gt;0: ... if n % 2 == 1: ... ssp =...
python|math
4
5,194
61,036,430
What is a compact way to create a multi-dimensional array with default values?
<p>I need to create a 4-D array, each of size 3, where each final element is a default. I thought I was clever with this.</p> <pre><code>&gt;&gt;&gt; arr = '-' &gt;&gt;&gt; for _ in range(4): ... arr = [arr] * 3 ... </code></pre> <p>It looks like I want the default to look, but more experienced Python devs probab...
<p>try </p> <pre><code>arr = [[[['-' for x in range(3)] for y in range(3)] for z in range(3)] for w in range(3)] </code></pre>
python
4
5,195
69,059,121
How to draw a normal curve on seaborn displot
<p>distplot was deprecated in favour of displot.</p> <p>The previous function had the option to draw a normal curve.</p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt from scipy import stats ax = sns.distplot(df.extracted, bins=40, kde=False, fit=stats.norm) </code></pre> <p>the <code>fit=stats.norm...
<p>If you want to replicate the same plot as your <code>distplot</code>, I suggest using <a href="https://seaborn.pydata.org/generated/seaborn.histplot.html" rel="nofollow noreferrer"><code>histplot</code></a>. Fitting our data to a normal is one line of code.</p> <pre><code>import numpy as np from scipy import stats i...
python|seaborn|histogram|distribution|displot
2
5,196
59,193,678
transform a 3D numpy array into a list of 3 indices
<p>So I have large 3D data matrix, say <em>10000X10000X1000</em>, now what I need to do is to go over every element of the 3D data matrix and write to a file the indices and the values of 2 different matrix with the same size, an example of a line:</p> <pre><code>i j k val1 val2 </code></pre> <p>What I currently do i...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html" rel="nofollow noreferrer"><code>np.mgrid</code></a> for generating the indices and in case you don't mind saving everything as the same data type you can just stack the arrays together and save the result via <code>np.save</c...
arrays|python-3.x|numpy
2
5,197
59,152,975
How I do circular shifting (rotation) of int in Python?
<p>In Java right rotation is done using:</p> <pre><code> (bits &gt;&gt;&gt; k) | (bits &lt;&lt; (Integer.SIZE - k)) </code></pre> <p>But how to do similar thing in Python?</p> <p>I tried to do (as described <a href="https://www.geeksforgeeks.org/rotate-bits-of-an-integer/" rel="nofollow noreferrer">here</a>):</p> <...
<p>It is my mistake, if you want to change <code>INT_BITS</code> to 4 you also need to change <code>0xFFFFFFFF</code> to <code>0xF</code> (one hex equals 4-bits):</p> <pre><code>n = 13 d = 2 INT_BITS = 4 print(bin(n)) print(bin((n &gt;&gt; d)|(n &lt;&lt; (INT_BITS - d)) &amp; 0xF)) </code></pre> <p>will output:</p> ...
python|rotation|bit-shift|bitmask
0
5,198
59,395,975
keras custom sigmoid adding bias
<p>There is a need to add bias to my custom sigmod function and apply this as a last activation layer in NN. But my recall goes rightly into 1. That shows me that something is wrong with the formula. </p> <p><strong>Custom sigmoid function</strong> </p> <p><a href="https://i.stack.imgur.com/6EOri.png" rel="nofollow ...
<p>Your formula has no apparent problem, but it's likely to cause arithmetic overflow for <code>-20*x - 0.5</code>, can you check the range of <code>x</code>. For example, if x is in <code>[-100, 100]</code>, the original sigmoid won't overflow while your customized sigmoid will. You can do a simple experiment in numpy...
python|python-3.x|keras
2
5,199
72,986,952
using regex to find a ether address
<p>I'm trying to use a regex expression to find a ether address. im pretty new to regex so id apparated a bit of help explaining why my code is returning a null value. its probably something to do with the expression its self. <code>row</code> has two ether address in it.</p> <pre><code>row = 'afdsf1 asdfasdf0xc7d688cb...
<p>You need to update the regex and remove <code>^</code>. re.findall() will return list of strings with this pattern <code>'0x[a-fA-F0-9]{40}$'</code>.</p> <pre class="lang-py prettyprint-override"><code>row = 'afdsf1 asdfasdf0xc7d688cb053c19ad5ee4f48c348958880537835fdsgdsfg 0xc7d688cb053c19ad5ee4f48c3z48958880537835f...
python|regex
-1