Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
7,700 | 72,882,060 | Find the number of occurrence of a string in a list of list | <p>I have a list in the following format.</p>
<pre><code>my_list=[['xyz','abc','Qwerty 1','Qwerty 2'],[],['1','2','Qwerty 1','Qwerty 2',1,4,'Qwerty 3',3],['1','QQQ','Quit','Qual','Qwerty 1']]
</code></pre>
<p>I'm trying to find the number of times the string 'Qwerty' appears in the list of list and return a list of li... | <pre><code>my_list = [
['xyz', 'abc', 'Qwerty 1', 'Qwerty 2'],
[],
['1', '2', 'Qwerty 1', 'Qwerty 2', 1, 4, 'Qwerty 3', 3],
['1', 'QQQ', 'Quit', 'Qual', 'Qwerty 1']
]
count_list = []
for list in my_list:
q_count = 0
for str_val in list:
if 'Qwerty' in str(str_val):
q_... | python|string|list | 1 |
7,701 | 55,926,173 | Compare elements in dataframe columns for each row - Python | <p>I have a really huge dataframe (thousends of rows), but let's assume it is like this:</p>
<pre><code> A B C D E F
0 2 5 2 2 2 2
1 5 2 5 5 5 5
2 5 2 5 2 5 5
3 2 2 2 2 2 2
4 5 5 5 5 5 5
</code></pre>
<p>I need to see which value appears most frequently in a group of columns for e... | <p>Here is one way using columns <code>groupby</code> </p>
<pre><code>mapperd={'A':'ABC','B':'ABC','C':'ABC','D':'DEF','E':'DEF','F':'DEF'}
df.groupby(mapperd,axis=1).agg(lambda x : x.mode()[0])
Out[826]:
ABC DEF
0 2 2
1 5 5
2 5 5
3 2 2
4 5 5
</code></pre> | python|pandas|dataframe | 8 |
7,702 | 55,952,826 | How to set fit function range to fit the function only between few data points in python | <p>I have a data point between 1-100 and I want to fit the Gaussian function only between data point 30 to 50. So how can I set the fit range 30 - 50 in the python.</p> | <p>you can use slice notation</p>
<pre><code>l_ = list(range(1, 100))
start = 30
stop = 50
print (l_[start-1:stop])
</code></pre>
<p><strong>Slicing Python Lists/Arrays</strong></p>
<pre><code>a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # ite... | python|matplotlib|scipy | 0 |
7,703 | 49,871,107 | Python - Global not working as expected | <p>I'm currently working on a tkinter project. The code is shown below:</p>
<pre><code>import tkinter as tk
from tkinter import font as tkfont
background_colour = "#F0F0F0"
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title("CCNA Comm... | <p>You simply need create it before MainPage in call stack.
Create it outside the IntroPage class, and initializing can stay where it is.</p> | python|python-3.x|class|tkinter|global | 0 |
7,704 | 50,091,981 | Images in Kivy app not displayed (show black box) after filling up memory, not released | <p>I've been using the Kivy sample Python code to try to make a slideshow on the official Raspberry Pi touchscreen. When I loop through a jpg photo directory, the images eventually refuse to show up, displaying a black box only. I get no error messages. I think it's a memory leak, though I'm not sure how to test this. ... | <p>A bit late, but try using <code>AsyncImage</code> instead of <code>Image</code></p>
<pre><code>from kivy.uix.image import AsyncImage
img = Image(source=name, nocache=False)
</code></pre>
<p>If this doesn't fix the issue, try setting <code>nocache=True</code>.
This significantly reduced the amount of times I enco... | python|image|touch|kivy|raspberry-pi3 | 1 |
7,705 | 64,070,050 | How to get a list of installed windows fonts using python? | <p>Stupid question, but how do I get a list of all the font names that are on my computer's system?</p> | <p>This is just a matter of listing the files in <code>Windows\fonts</code>:</p>
<pre><code>import os
print(os.listdir(r'C:\Windows\fonts'))
</code></pre> | python|operating-system|os.path|listdir | 7 |
7,706 | 10,267,124 | IronPython, C# and XML - break indentation? | <p>We're using IronPython on C#, and I get different results on the console and on our application.</p>
<p>This code runs fine on IronPython Console:</p>
<pre class="lang-python prettyprint-override"><code>str=[]
a = 1
b = 0
c = 1
if a==1:
str.append('One')
if b==1:
str.append('Two')
if c==1:
str.append('T... | <p>Nonsignificant whitespace in xml is not preserved</p>
<p><a href="http://www.w3.org/TR/1998/REC-xml-19980210#AVNormalize" rel="nofollow">http://www.w3.org/TR/1998/REC-xml-19980210#AVNormalize</a></p>
<blockquote>
<p>Before the value of an attribute is passed to the application or checked for validity, the XML pr... | python|xml|ironpython|indentation | 1 |
7,707 | 5,374,168 | Unable to select Checkbox inside TreeView | <p>I tried creating a treeview with checkboxes but I'm unable to select the checkboxes.</p>
<p>on the flag method I had mentioned it as ItemisuserCheckable but still could not get it working...</p>
<p>am I missing something here to enable the selection of checkboxes.</p>
<p>A snippet of the code is:</p>
<pre><code>... | <p>you need to hold somewhere current item state (checked\unchecked) and change it once setdata() method is called. Your items are always unchecked because you're always returning <code>QVariant(Qt.Unchecked)</code> for them in the data() method. </p>
<p>I've changed a bit your code, see it would work for you:</p>
<p... | python|qt|treeview|pyqt|pyqt4 | 3 |
7,708 | 5,214,910 | how could I pass a collection of the arguments that a function needed? | <p>For example, I have a function: </p>
<pre><code>def foo(a, b, c):
pass
</code></pre>
<p>Now I have a dict:<br>
<code>d = {'a': 1, 'b': 2, 'c': 3}</code><br>
I have to write something like:<br>
<code>foo(d['a'], d['b'], d['c'])</code><br>
I'd like to know, could I just pass a collection of the arguments(like ... | <p>Sure, you can pass a dict as <code>kwargs</code>:</p>
<pre><code>def foo(a, b, c):
print a, b, c
d = {'a': 1, 'b': 2, 'c': 3}
foo(**d)
</code></pre>
<p>Output:</p>
<pre><code>1 2 3
</code></pre> | python | 9 |
7,709 | 62,589,117 | Unable to populate array while using pandas_udf in PySpark | <p>I have a PySpark dataframe, which is like</p>
<pre><code>+---+------+------+
|key|value1|value2|
+---+------+------+
| a| 1| 0|
| a| 1| 42|
| b| 3| -1|
| b| 10| -2|
+---+------+------+
</code></pre>
<p>I have defined a pandas_udf like -</p>
<pre><code>schema = StructType([
StructF... | <p>I had to define a custom <a href="https://spark.apache.org/docs/2.1.2/api/python/_modules/pyspark/accumulators.html" rel="nofollow noreferrer">Accumulator</a> for a list and use it.</p>
<pre><code>from pyspark.accumulators import AccumulatorParam
class ListParam(AccumulatorParam):
def zero(self, val):
re... | pandas|apache-spark|pyspark|pandas-groupby|user-defined-functions | 1 |
7,710 | 62,858,095 | Does importing exit from sys run the in-built function or the one from the module? | <p>If I run this:</p>
<pre><code>from sys import exit
exit()
</code></pre>
<p>Does it run the inbuilt function exit, or sys.exit()?</p>
<p>I am using python 3.8.3</p> | <p>It runs <code>sys.exit</code>.</p>
<p>The import overwrites the existing <code>exit</code> variable with the <code>sys.exit</code> function.</p> | python|python-3.x|module | 1 |
7,711 | 62,751,801 | How to annotate that a function returns a union of input types? | <p>I have a function that can take a list of classes as an input argument, and will return an instance of one of these input classes, depending on other arguments. How can I annotate the function so that <code>mypy</code> will understand this?</p>
<p>I've tried using <a href="https://docs.python.org/3/library/typing.ht... | <p>You can just use <code>Union</code>:</p>
<pre><code>from typing import List, Type, Union
def multi_foo(t: List[Union[Type[int], Type[str]][) -> List[Union[int, str]]:
...
</code></pre> | python|mypy|python-typing | 0 |
7,712 | 60,559,095 | Failed building wheel for cryptography. Could not build wheels for cryptography which use PEP 517 and cannot be installed directly | <p>I couldn't install Scrapy on my system after I upgraded pip to 20.0.2.
And what file do I have to install manually in order to make it work?
Please help me out.</p> | <p>sudo apt-get install python3 python3-dev python3-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev</p> | python|git|scrapy | 1 |
7,713 | 60,536,289 | How to save HTML email as an outlook file using Python? | <p>Someone created a nice email template in outlook and sent it to me for automation. </p>
<p>I opened the email in HTML, and used that HTML to recreate the exact email images, formatting and all. </p>
<p>I can send this email out just fine, but I was then asked if I could save all the email files in a folder so tha... | <p><em>Work with <a href="https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa210279(v=office.11)" rel="nofollow noreferrer">SaveAs Method [MSDN]</a> with <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook.olsaveastype?view=outlook-pia" rel="nofollow nore... | python|email|outlook|win32com | 3 |
7,714 | 70,120,315 | Fastest way of list comprehension while calculating the distance with a fixed list | <p>I have a list,</p>
<pre><code> a = [1,2,3]
</code></pre>
<p>Now I have another list of lists(which is same size as above),</p>
<pre><code>x=[[1,2,3], [4,5,6], [7,8,9]]
</code></pre>
<p>Now I want to calculate the distance between each item in x with a them using cosine distance so I am using this,</p>
<pre><code>fro... | <p>With numpy, you can use broadcasting to do the same computation and take advantage of vectorized operations for more efficiency.</p>
<pre class="lang-py prettyprint-override"><code>def cosine_distance(a, x):
a = np.array(a)
x = np.array(x)
return 1 - x.dot(a) / (np.linalg.norm(a) * np.linalg.norm(x, axis... | python|list|iteration|list-comprehension|cosine-similarity | 2 |
7,715 | 11,066,850 | Error message "no theme named 'sphinx-theme-okfn'" when trying to build CKAN's docs | <p>I have CKAN installed in a virtualenv and the virtualenv activated, and I've installed the requirements in pip-requirements-docs.txt, but when I try to build the docs I get this error:</p>
<pre><code>> python setup.py build_sphinx
...
sphinx.errors.ThemeError: no theme named 'sphinx-theme-okfn' found (missing th... | <p>The problem is that the Sphinx theme that CKAN uses is not part of the CKAN git repository itself, it has its own git repo which is a <a href="http://git-scm.com/book/en/Git-Tools-Submodules" rel="noreferrer">submodule</a> of the CKAN git repo. So before you can build the docs, you need to checkout the submodule:</p... | python|git|python-sphinx|ckan | 5 |
7,716 | 11,026,205 | I'm using excel to build websites - Looking for an alternative | <p>I'm currently concatenating adjacent cells in excel to repeat common HTML elements and divs - it feels like I've gone down a strange excel path in developing my webpage, and I was wondering if an experienced web designer could let me know how I might accomplish my goals for the site with a more conventional method (... | <p>Wow, that sounds really painful.</p>
<p>If all you have is 40 images that you want to generate HTML for, and the rest of your site is static, it may be simplest just to have a single text file with each line containing an image file path. Then, use Python to look at each line, generate the appropriate HTML, and con... | python|mysql|html | 8 |
7,717 | 70,482,979 | Extract Information from Tkinter drawing | <p>I am currently trying to script something that allows me to "draw numercial Input".</p>
<p>The idea is to use tkinters <code>create_line</code> in combination with tkinters capability to <code>bind</code> methods to events in order to get some drawing that has then to be decoded into x and y values in orde... | <p>Thanks to Comments by users I can post an answer to my question here, but the real answer is the comments.</p>
<p>The hint to use post script was good but the website provided me with information which seems to give me what is closest to an answer to my question.</p>
<p>The canvas method <code>find_all</code> allows... | python|tkinter|draw | 2 |
7,718 | 63,433,686 | Create new column in python 3 (pandas) dataframe based on value in other column | <p>I have a pandas dataframe where I need to create new columns based on values from other columns in dataframe. Here is the dataframe</p>
<p>person city state country</p>
<p>A Chicago Illinois USA</p>
<p>B Phoenix Arizona USA</p>
<p>C San Diego California USA</p... | <p>For me working well, if no match conditions are created missing values:</p>
<pre><code>df.loc[df['state'] == 'Illinois', 'city-north'] = df['city']
df.loc[df['state'] != 'Illinois', 'city-south'] = df['city']
print (df)
person city state country city-north city-south
0 A Chicago Illinois ... | python-3.x|pandas|dataframe | 1 |
7,719 | 63,722,402 | Question on how to interpret this recursion sum function answer? def sum_numbers(n): return n + sum_numbers(n-1) if n else 0 | <p>Question asked to sum first n natural numbers.</p>
<p>My answer is:</p>
<pre class="lang-py prettyprint-override"><code>def sum_numbers(x):
if x == 1:
return x
else:
return sum_numbers(x-1) + x
</code></pre>
<p>However, there is a more succinct:</p>
<pre class="lang-py prettyprint-overri... | <h2>The ternary operator</h2>
<p>If you are familiar with other programming languages, python's <code>a if b else c</code> is expressed:</p>
<ul>
<li><p><code>b ? a : c</code> in C and Java;</p>
</li>
<li><p><code>if b then a else c</code> in OCaml and Haskell.</p>
</li>
</ul>
<p><code>?:</code> is often called "t... | python|recursion | 1 |
7,720 | 56,500,236 | How to generate every combination inside a list subject to constraints in python? | <p>I have a problem where I need to generate list of every combination possible based on given constraints and I am not sure of any approach that might help. I have a list with 12 slots available and I need to populate each slot x and y subject to constraints mentioned below.</p>
<pre><code>x >= 7, x <= 9
y >... | <p>Just following your description of the problem naively, one simple approach would be to loop over each of the pairs of lengths, as well as each possible starting index of each of the lists:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def find_all():
for x in range(7, 10):
for... | python|pandas|data-science | 1 |
7,721 | 56,786,751 | Calculate distance a dataframe with UTM coordinates in pandas | <p>I have a huge <code>dataframe</code>. The structure data looks like this:</p>
<pre><code>df
ID Annotation X Y
A Boarding 767513.9918 9425956.2571
A Alighting 767154.1396 9427584.0004
B Boarding 767450.5277 9432627.9543
B Alighting 767495.0101 9426797.1772
C Boarding 767648.9507 94... | <p>I would pivot the dataframe:</p>
<pre><code>result = df.pivot('ID', 'Annotation', ['X', 'Y'])
</code></pre>
<p>to get</p>
<pre><code> X Y
Annotation Alighting Boarding Alighting Boarding
ID ... | python|pandas|distance|utm | 2 |
7,722 | 65,915,769 | Jupyter notebook is giving error when using MinMaxScalar or StandardScalar? | <p>When performing StandardScalar or MinMaxScalar using PythonAdv kernel the jupyter notebook is printing error. However, when using Python 3 environment the same jupyter note book is working fine:</p>
<pre><code>from sklearn.preprocessing import MinMaxScaler
# Scale X values
X_scalar = MinMaxScaler().fit(X_train)
#pr... | <pre><code>from sklearn.preprocessing import MinMaxScaler
# Scale X values
X_scaler = MinMaxScaler().fit(X_train)
#print(X_scalar)
X_train_scaled = X_scaler.transform(X_train)
X_test_scaled = X_scaler.transform(X_test)
</code></pre>
<p>There is a small typo. you define X_scalar then use X_scaler.</p> | python|scikit-learn | 0 |
7,723 | 69,063,722 | Pandas: Aggregate mean ("totals") for each combination of dimensions | <p>I have a table like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>gender</th>
<th>city</th>
<th>age</th>
<th>time</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>male</td>
<td>newyork</td>
<td>10_20y</td>
<td>2010</td>
<td>10.5</td>
</tr>
<tr>
<td>female</td>
<td>newyork</td>... | <p>Using groupby on multiple columns will groupby with all combinations of these columns. So a simple <code>df.groupby(["city", "age"]).mean()</code> will achieve the mean for the "total", "city", "age" combination. The problem here is you want all combinations of all s... | pandas|pandas-groupby|aggregation | 1 |
7,724 | 68,884,942 | Using itertools.product with seed value in Python3 | <p>I am in almost the exact same situation as the OP of this question: <a href="https://stackoverflow.com/questions/9864809/using-itertools-product-and-want-to-seed-a-value">Using itertools.product and want to seed a value</a> and I am trying to use the code given in this <a href="https://stackoverflow.com/a/9865149/15... | <p>You can replace it with a single argument and then use tuple unpacking to create <code>n</code> and <code>l</code>:</p>
<pre class="lang-py prettyprint-override"><code>def fold(n_l, v):
(n, l) = n_l
(n, m) = divmod(n, len(v))
return (n, l + [v[m]])
</code></pre> | python|python-3.x|itertools|random-seed | 1 |
7,725 | 68,282,541 | Python script iterates over whole folder but skips files in the folder | <p>I tried running the following code. The code should read hdf5 files from a directory and create for every hdf5 file a png and a txt file with the same name (btw. I need it as input for the CNN YOLO).
The code does what I described but only for 20 images! I added print(i) to see if the for-loop is working proper... a... | <ol>
<li>Maybe it's because of the <code>name</code> variable? You remove 5 characters but you want to remove only 4: <code>name = str(i[0:-4])</code></li>
<li>Not related to your question, the last 3 lines are useless. you can remove them.</li>
</ol>
<pre><code> continue
else:
continue
<... | python|data-science | 1 |
7,726 | 59,412,732 | How to get a fully qualified class name from class alias | <p>File has an import:</p>
<pre class="lang-py prettyprint-override"><code>from lxml import etree
</code></pre>
<p>or with alias</p>
<pre class="lang-py prettyprint-override"><code>from lxml import etree as tree
</code></pre>
<p>How to get <code>lxml.etree</code> by using just <code>something(etree)</code> and <cod... | <p>Considering <code>etree</code> is a class, you can get the class name using this:</p>
<pre><code>from lxml import etree as tree
print(tree.__name__)
</code></pre> | python|python-3.x | 2 |
7,727 | 73,056,855 | python importing datetime module question | <p>I have noticed while reading up on python datetime module there are times when responses will show</p>
<pre><code>from datetime import datetime (or date or time)
</code></pre>
<p>and I'm not sure why I should or would do this. What is the rational behind this or could someone point me to some resources that might ex... | <p>The <code>datetime</code> module defines a bunch of different classes. If you just use</p>
<pre><code>import datetime
</code></pre>
<p>Then you have to write things like <code>datetime.datetime.strptime()</code> -- the first <code>datetime</code> is the module name, the second is the class name. By using the <code>f... | python|datetime|import | 2 |
7,728 | 63,092,776 | ImportError: cannot import name 'views' from 'learning_log' | <p>I am beginner in django and following a tutorial. got import error even after typing the exact code. here is the code</p>
<p>views.py:</p>
<pre><code>from django.shortcuts import render
def index(request):
return render(request, 'learning_logs/index.html')
</code></pre>
<p>urls.py:</p>
<pre><code>from django.con... | <p>Got it..it had worked perfectly in the current location but apparently i had created a template directory inside my current project which had shifted the path of views.py. I had to refactor views.py to the directory learning_log and it worked.</p> | python|django | 0 |
7,729 | 62,101,748 | Merging netCDF files in anaconda prompt using NCO? | <p>i am really at a loss about how to merge netcdf files of different times <strong>in windows 10</strong>, especially merging all nc files in folder. Usually in my ubuntu system i use CDO and the code <code>cdo mergetime *.nc output.nc</code> and that does the job. Unfortunately, in windows, that's a whole different c... | <p>First, if you are trying to concatentate along the time dimension, use <code>ncrcat</code> not <code>ncecat</code>. In any case, it appears you are attempting to provide the input list using shell wildcards (i.e. <code>*.nc</code>) that do not work in Windows DOS shells. Try instead explicitly specifying the input f... | python|merge|netcdf|nco|cdo-climate | 2 |
7,730 | 62,159,140 | Cython FIFO cache for function result | <p>I need some kind of cache to store the result of a function <code>f</code> in Cython for future reuse. A simple FIFO cache policy that discards the least recently computed result when the cache is full will do just fine. I need the cache to be reinitialised every time I call another function from Python which uses t... | <p>I think from the software engineering point of view, it is a good idea to have the function (which is a function-pointer/functor in C/cdef-Cython) and its memoization bundled together in an object/class.</p>
<p>My approach would be to write a cdef class (let's call it <code>FunWithMemoization</code>) which has a fu... | python|caching|cython | 2 |
7,731 | 35,611,554 | For loop, list append | <p>I have a simple code</p>
<pre><code>a_list=[1,2,3,4,5]
a2_list=[]
for x in a_list:
a2_list.append(x*2)
</code></pre>
<p>and I get <code>a2_list=[2,4,6,8,10]</code></p>
<p>If I write code like</p>
<pre><code>a_list=[1,2,3,4,5]
a2_list=[]
for x in a_list:
a2_list.append(x*2)
print a2_list
</code></pre>... | <p>That works</p>
<pre><code>a_list=[1,2,3,4,5]
a2_list=[]
b_list=[]
for x in a_list:
a2_list.append(x*2)
b = a2_list[:]
b_list.append(b)
</code></pre> | list|python-2.7|append | 2 |
7,732 | 58,985,090 | No trainable parameters when implementing Fourier convolution in Keras layer | <p>I'm attempting to implement a Fourier Convolutional Neural Network using tf.keras, where the input and kernel are transformed to the frequency domain, element-wise multiplication is performed, and then the output is inverse-transformed and cropped. The model summary shows there are no trainable parameters for the ke... | <p>The issue was in how I was renaming variables. I set <code>self.kernel</code> to be the transformed variable, so when I instead used a different variable <code>W</code> for all operations in the transform, the parameters were listed as expected.</p>
<p>For reference, the code listed below is a drop in replacement f... | tensorflow|keras|convolution | 0 |
7,733 | 58,764,192 | How to get value of last valid index of a different column for each row | <p>I have the following table in pandas.</p>
<ul>
<li><code>view_time</code>: time user viewed the ad</li>
<li><code>click_time</code>: time user clicked the ad (if it was clicked)</li>
<li><code>ad_id</code>: ad identifier</li>
</ul>
<pre><code>>>> df
view_time click_time username ad_id
250 07:00 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a>:</p>
<pre><code>df2 = (df[['click_time','username', 'ad_id']]
.dropna(subset=['click_time'])
.rename(columns={'ad_id':'last_clicked_ad', 'c... | python|pandas|dataframe | 1 |
7,734 | 58,828,238 | Python - Read terminal output and give input from the script itself | <p>I'm using a class from a module that on first usage asks me for some input in the terminal.</p>
<p>At every new instance the terminal asks for some inputs.</p>
<p>Example:</p>
<pre><code>instance = Class()
instance.run()
## asks for input in the terminal
</code></pre>
<p>I thought about the subprocess module but... | <p>Here's an example from <a href="https://codeburst.io/building-beautiful-command-line-interfaces-with-python-26c7e1bb54df" rel="nofollow noreferrer">a fun guide I found on google just now</a>. </p>
<p>I recommend you search for a few different articles on this topic to learn about the different approaches that might... | python|python-3.x|subprocess|stdout|stdin | 0 |
7,735 | 15,762,943 | Anaconda vs. EPD Enthought vs. manual installation of Python | <p>What are the relative merits / downsides of various Python bundles (EPD / Anaconda) vs. a manual install?</p>
<p>I have installed EPD academic, and I have no issues with it. It provides more packages that I think I will ever need, and it is very easy to update using enpkg enstaller. The EPD academic licence require... | <p><strong>Update 2015</strong>: Nowadays I always recommend Anaconda. It includes lots of Python packages for scientific computing, data science, web development, etc. It also provides a superior environment tool, <code>conda</code>, which allows to easily switch between environments, even between Python 2 and 3. It i... | python|epd-python|anaconda | 49 |
7,736 | 48,957,035 | Combine compiled Python regexes | <p>Is there any mechanism in Python for combining compiled regular expressions? </p>
<p>I know it's possible to compile a new expression by extracting the plain-old-string <code>.pattern</code> property from existing pattern objects. But this fails in several ways. For example:</p>
<pre><code>import re
first = re... | <p>Ken, this is an interesting problem. I agree with you that the Perl solution is very slick.
I came up with something, but it is not so elegant. Maybe it gives you some idea to further explore the solution using Python. The idea is to simulate the concatenation using Python re methods. </p>
<pre><code>first = re.co... | python|regex | 3 |
7,737 | 25,121,127 | How to extract URL from HTML anchor element using Python3? | <p>I want to extract URL from web page HTML source.<br>
Example:</p>
<pre><code>xyz.com source code:
<a rel="nofollow" href="example/hello/get/9f676bac2bb3.zip">Download XYZ</a>
</code></pre>
<p>I want to extract:</p>
<pre><code>example/hello/get/9f676bac2bb3.zip
</code></pre>
<p>How to extract this URL... | <p>You can use built-in <a href="https://docs.python.org/3/library/xml.etree.elementtree.html" rel="nofollow"><code>xml.etree.ElementTree</code></a> instead:</p>
<pre><code>>>> import xml.etree.ElementTree as ET
>>> url = '<a rel="nofollow" href="/example/hello/get/9f676bac2bb3.zip">XYZ</a&g... | python|regex|python-3.x|python-3.2 | 3 |
7,738 | 60,188,754 | Generating a Random String with only two specific characters | <p>I need to generate a fixed-length string with only 'y' and 'n' in a random order, and the number of 'n' in the string is determined by the variable Njk. The strings must be like 'yyyyynynynyyyyyy' or 'yynyyyynyyynyyyy', and I'll generate a huge amount of strings. Currently I'm doing like the code below. The problem ... | <p>If you know the size of the final string and the number of N, you can create a list that starts with <code>Njk</code> N and <code>length - Njk</code> Y. Then, shuffle the list and join it.</p>
<pre><code>from random import shuffle
final_size = 16
number_of_n = 3
# ['n', 'n', 'n', 'y', 'y', 'y', 'y', 'y', 'y', 'y',... | python | 1 |
7,739 | 2,743,716 | Programmatically check whether a drive letter is a shared/network drive | <p>Is there a way to check whether a drive letter stands for a shared drive/network drive or a local disc in python? I guess there is some windows api function that gives me that info, but I can't find it. Perhaps there is even a method already integrated in python?</p>
<p>What I am looking for is something with this ... | <p>The <code>GetDriveType</code> function in <code>win32file</code> module may help you - it's a wrapper for the <a href="http://msdn.microsoft.com/en-us/library/aa364939(VS.85).aspx" rel="noreferrer">GetDriveType</a> WINAPI function.</p>
<pre><code>import win32file
isNetworkDrive = win32file.GetDriveType("Z:\\") == w... | python|winapi|network-drive|drive-letter | 13 |
7,740 | 6,311,705 | Python/Django Patching/Mocking a functions current decorator | <p>I saw you posting around decorators. I am having a hard time finding out how to Mock a decorator. Most searches show me how to write a decorate to help tes, but to be clear, I already have decorators and when I am unittesting a function that HAS a decorator I would like to mock it so its response is not part of the ... | <p>You can't mock a decorator. A decorator replaces your function at compile time with the decorated function. If a function is decorated, you cannot test that function without the decorator without pulling the guts of the function out into another (non-decorated) function.</p> | python|unit-testing|testing|mocking|decorator | 0 |
7,741 | 30,548,155 | Send email flask google app engine - Invalid sender format | <p>I'm trying to make a simple flask contact form on google app engine. I'm new to both.</p>
<p>There are two links which I have used to help me:
<a href="https://cloud.google.com/appengine/docs/python/mail/sendingmail" rel="nofollow">https://cloud.google.com/appengine/docs/python/mail/sendingmail</a>
<a href="http://... | <p>Are you following the rules they have for who is allowed to be in the from field of the emails?</p>
<blockquote>
<p>The email address of the sender, the From address. The sender address must be one of the following types:</p>
<ul>
<li><p>The address of a registered administrator for the application. You can add admi... | python|google-app-engine|flask|google-app-engine-python | 1 |
7,742 | 67,105,928 | how to iterate over list of dataframes? | <p>Basically, I have 5 pd.dataframes, named= <code>df0, df1, df2, df3, df4</code>. What I would like to do is use a for loop to add data to these 5 dataframes. Something the likes of:</p>
<blockquote>
<pre><code>for i, dataset in enumerate([df0,df1,df2,df3,df4]):
dataset = pd.concat([dataset, NEW_DATA])
</code></pr... | <p>You can re-assign the new <code>df</code> into your list:</p>
<pre class="lang-py prettyprint-override"><code># setup example
df0 = pd.DataFrame(np.random.randint(0, 10, (3, 2)))
df1 = pd.DataFrame(np.random.randint(0, 10, (3, 2)))
df2 = pd.DataFrame(np.random.randint(0, 10, (3, 2)))
# then
lst = [df0, df1, df2]
fo... | python|pandas|list|dataframe|for-loop | 0 |
7,743 | 42,590,512 | How to convert from infix to postfix/prefix using AST python module? | <p>I'm trying to convert python math expressions to postfix notation using the AST python module. Here's what I got so far:</p>
<pre><code>import parser
import ast
from math import sin, cos, tan
formulas = [
"1+2",
"1+2*3",
"1/2",
"(1+2)*3",
"sin(x)*x**2",
"cos(x)",
"True and False",
"... | <p>You can use <a href="https://docs.python.org/3/library/ast.html#ast.dump" rel="nofollow noreferrer"><code>ast.dump</code></a> to get more information about the the nodes and AST structure:</p>
<pre><code>>>> import ast
>>> node = ast.parse("sin(x)*x**2")
>>> ast.dump(node)
"Module(body=[E... | python|python-3.x|abstract-syntax-tree|postfix-notation|infix-notation | 6 |
7,744 | 42,650,289 | Split an array dependent on the array values in Python | <p>I have an array of coordinates like this:</p>
<pre><code>array = [[1,6],[2,6],[3,8],[4,10],[5,6],[5,7],[18,6],[19,5],[17,9],[10,5]]
</code></pre>
<p>I want to split the array between <code>6</code>. and <code>7</code>. coordinate <code>([5,7],[18,6])</code> because there is a gap in the <code>X</code> value there.... | <p>This might be what you are looking for</p>
<pre><code>array = [[1,6],[2,6],[3,8],[4,10],[5,6],[5,7],[18,6],[19,5],[17,9],[10,5]]
# Declare two array variables
arr1 = None
arr2 = None
n = len(array)
for i in range(n-1):
if abs(array[i][0] - array[i+1][0]) >= 10:
arr1 = array[:i+1]
arr2 = array[... | python|arrays|split | 2 |
7,745 | 72,209,584 | What is stopping win32.Dispatch() from opening Microsoft Office programs? | <p>I am attempting to open Outlook using the following Python code:</p>
<pre><code>import os
import win32com.client as win32
outlook = win32.Dispatch('Outlook.Application')
</code></pre>
<p>This does not work, but it doesn't throw an error either, which it does when I replace Outlook with a random word. I can't open a... | <p>It would be great to specify exactly what you get from the following call:</p>
<pre><code>outlook = win32.Dispatch('Outlook.Application')
</code></pre>
<p>If Outlook can't be instantiated this way then its windows registry keys were corrupted. I'd recommend repairing MS Office or Outlook to get all the keys restored... | python|outlook|com|ms-office | 0 |
7,746 | 65,597,453 | How to store private and public key into pem file generated by rsa module of python | <p>I am using below module in python for <code>rsa</code> encryption.
<a href="https://github.com/sybrenstuvel/python-rsa" rel="nofollow noreferrer">https://github.com/sybrenstuvel/python-rsa</a>
it can be installed by pip as follows <code>pip3 install rsa</code></p>
<p>I have read of using this module here: <a href="h... | <p>The Github site of <a href="https://github.com/sybrenstuvel/python-rsa" rel="noreferrer">Python RSA</a> refers via its <a href="https://stuvel.eu/software/rsa/" rel="noreferrer">homepage</a> to this <a href="https://stuvel.eu/python-rsa-doc/" rel="noreferrer">documentation</a>, according to which the library has ded... | python|encryption|rsa | 7 |
7,747 | 65,772,879 | Scraping table data transformed by dropdown selection (but same URL) | <p>I want to scrape all the data in the first table (Regular Season) on this <a href="https://www.pro-football-reference.com/players/B/BreeDr00/gamelog/" rel="nofollow noreferrer">page</a>. I could do it via the HTML tags, but the webpage has a handy drop-down feature for converting the table to CSV format which is exa... | <p>Create the dataframe with beautifulsoup, then use pandas to write as csv file.</p>
<p>Or just use pandas to parse the table (then do a little clean up). Pandas uses beutifulsoup under the hood:</p>
<pre><code>import pandas as pd
url = 'https://www.pro-football-reference.com/players/B/BreeDr00/gamelog/'
df = pd.read... | python|web-scraping|beautifulsoup | 0 |
7,748 | 50,444,297 | Getting count of rows from breakpoints of different column | <p>Consider there are two columns A and B in a dataframe. How can I decile column A and use those breakpoints of column A deciles to calculate the count of rows in column B??</p>
<pre><code>import pandas as pd
import numpy as np
df=pd.read_excel("E:\Sai\Development\UCG\qcut.xlsx")
df['Range']=pd.qcut(df['a'],10)
df... | <p>I hope this would help:</p>
<pre><code>df['Range'] = pd.qcut(df['a'], 10)
df2 = df.groupby(['Range'])['a'].count().reset_index().rename(columns = {'a':'count_A'})
for item in df2['Range'].values:
df2.loc[df2['Range'] == item, 'count_B'] = df['b'].apply(lambda x: x in item).sum()
df2 = df2.sort_values('Range',... | pandas|numpy|breakpoints | 2 |
7,749 | 34,931,486 | Python code freezes up my computer - Project Euler 58 | <p>I am trying to learn python by solving problems from Project Euler. I am stuck on problem 58. The problem states thus:</p>
<pre><code>Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 ... | <p>Even though you are using xrange, you are still generating a list of of size 10**9 when making your primesieve. That use a large amount of memory, and is likely your problem.</p>
<p>Instead, you might consider writing a function that checks if a number, N, is prime or not, by checking of any number between (2,N**.5... | python|performance|processing-efficiency | 0 |
7,750 | 26,484,674 | Programming LCD over Serial using Python, Linux | <p>I've been sent the below code for controlling the backlight on my LCD device</p>
<pre><code>Sample for set the brightness of iIO backlight.
Brightness : 00H (dark)
0AH (bright)
brightness = 0xA;// fully light
write(/dev/ttyS0,0x95,1);// send 95H command function.
write(/dev/ttyS0,brightness,1);// send the brightnes... | <p>You need to calculate the checksum as a 7 bit integer value. ie:</p>
<pre><code>checksum = (0x95 + value) & 0x7f
</code></pre>
<p>then write the binary values to the serial port.</p>
<pre><code>import struct
value = 0
checksum = (0x95 + value) & 0x7f
cmd = struct.pack("<BBB", 0x95, value, checksum)
ser... | python|linux|serial-port|lcd | 0 |
7,751 | 56,796,264 | Boost python not seeing memory is owned by smart pointer | <p>I am getting a seg fault trigger when the destructor below destroys it's vector elements. Originally it was a <code>vector<Parent></code> but I changed this to <code>vector<unique_ptr<Parent>></code> and since then the crash occurs every time:</p>
<pre><code>class Owner
{
Owner() = default;
... | <p>Based on the code you are giving and with the assumption <code>boost::python</code> has not a bug here I would guess your usage of moving semantics might be the cause:</p>
<pre><code>void assignVec(std::vector<std::unique_ptr<Parent>>& vec)
{
_vec = std::move(vec);
}
</code></pre>
<... | c++|move|smart-pointers|unique-ptr|boost-python | 0 |
7,752 | 61,410,320 | Send GET request over socket Python | <p>I am trying to send a GET request to a server with Python 3.8.2. When I execute the command <code>print(sock.recv(1024))</code>, however, it just returns the instructions that were given to me: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippe... | <p>Answering my question, replacing the line <code>sock.send(b"GET / HTTP/1.1\r\nHost:127.0.0.1\r\n\r\n")</code> with just <code>sock.send(b"GET")</code> did the trick.</p> | get|serversocket|python-3.8 | -1 |
7,753 | 61,503,827 | python create file and read, doesn't output anything | <pre><code># create two new files
a = open("file.txt","w+")
b = open("file2.txt", "w+")
#write to file
a.write("text in english")
b.write("text in english2")
#read the file & print the text to console
teksts1 = a.read()
teksts2 = b.read()
print(teksts1)
print(teksts2)
#close both files, so we don't run into ... | <p>You could try this which uses <code>with open</code> as opposed to <code>open</code> which is a safer way of opening files:</p>
<pre><code>file_list = ['file.txt', 'file2.txt']
for file in file_list:
with open(file, 'w+') as f:
f.write('text in english')
f.seek(0)
print(f.read())
</code>... | python | 2 |
7,754 | 57,963,599 | Merging diff tables between 2 Databases sqlite | <p>Ok, so I have a program that I wrote (some user control automation), it has a Database - it's running just now on one of my Server, and it's version is 1.0.</p>
<p>In the last time I added some upgrades to the tool (so it's version is 1.5).</p>
<p>what is my problem -
In version 1, the tool's Database looks like ... | <p>If you just need to add missing tables - without migrating rows and columns for already existing tables, you can achieve it this way.</p>
<ol>
<li><p>Make a backup before running any stackoverflow tips through your production database. ;-)</p></li>
<li><p>Dump your new database into the sql file.</p></li>
</ol>
<p... | python|database|sqlite | 1 |
7,755 | 56,204,282 | How to vectorize code in Python for a heat dispersion problem? | <p>I am trying to vectorize the following code below, but I do not know how to get started. The problem is the writing a piece of code given a numpy array. The 2D array contains elements which represent the temperature of steel on the front side profile. The outer ring of elements represents the temperature if a hot cl... | <p>Youre close, to change an element of a numpy array <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html" rel="nofollow noreferrer">numpy indexing</a> for assignment instead. This alone should fix your solution. (use <code>arr[i, j] =</code> instead of <code>arr[i][j] =</code>)
Another comment I... | python|numpy|for-loop|vectorization | 0 |
7,756 | 56,353,032 | Python, I want to convert a specific column type after importing a csv file | <pre><code>import numpy as np
data_arr = np.loadtxt("asset.csv", delimiter = ",", dtype = 'str')
data_arr
</code></pre>
<p><strong>Result:</strong></p>
<pre><code>array([['G1', '1', '100', '5', '0'],
['G1', '1', '21', '538', '0'],
['G1', '1', '22', '6000', '0'],
...,
['G2', '8', '61', '241908', '8800'],
['G2', ... | <p>Give the proper types of columns:</p>
<pre><code>np.loadtxt('asset.csv', delimiter=",", dtype='S20,int64,int64,int64,int64')
</code></pre>
<p>EDIT: list the maximum string length alongside. E.g. this should now work assuming your first column doesn't exceed 20 characters.</p> | python|csv|types|casting | 1 |
7,757 | 56,041,466 | for loop and in operator in python | <p>I am trying to understand existing code, written in python. I am currently learning python. Can someone help me understand this piece of code?</p>
<pre><code>bits_list = split_string_into_chunks(coding, n)
# take first bit as the sign, and the remaining bits as integers
signs_nums = [(-1 if bits[0] == '0' else 1, i... | <p>bits_list = split_string_into_chunks(coding, n)</p>
<p>This line of code calls a function split_string_into_chunks, taking 2 parameters, what they are you don't show. bits_list is the return value which looks like a dataframe list or dictionary object</p>
<p>signs_nums = [(-1 if bits[0] == '0' else 1, int(bits[1:]... | python-3.x | 1 |
7,758 | 56,153,298 | Trouble connecting to Azure-Datalakes-gen2 using requests module in python | <p>I am currently trying to connect to azure datalakes-gen2 using python to grab information from json files stored inside. Hearing that the azure-datalakes module for python does not work for gen 2 (and having troubles myself), I moved on to connecting via rest-api and the requests package found in python. However, re... | <p>If you want to read file content, you should use <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/read" rel="nofollow noreferrer">Read api</a>.</p>
<p>The code below works at my side:</p>
<pre><code>import requests
import datetime
import hmac
import hashlib
import base64
... | python|rest|azure-data-lake | 1 |
7,759 | 18,293,885 | PyQt - Widget in QtGui.QtMainWindow | <p>I have a window(QtGui.QMainWindow) that I'm trying to add text, but I know you can't add text to a window in pyqt so im adding a widget into the window but the widget isnt showing up only the dialog </p>
<p>here is the window code:</p>
<pre><code>class MyWindow(QtGui.QMainWindow):
def __init__(self, parent=Non... | <p>You have to set the widget to be the the central widget of your <code>MyWindow</code> MainWindow. QMainWindow should have a central widget set.</p>
<pre><code>class MyWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.setWindowFlags(QtCore.Qt.... | python|pyqt | 3 |
7,760 | 69,638,882 | Comparing pairs of unique column values in pandas | <p>I have the following dataframe:</p>
<pre><code>name group feedback question
a g1 False abc
a g1 True abc
a g1 True xyz
b g1 True xyz
b g1 True abc
c g1 False def
d g2 False xyz
d g2 Tru... | <p>Here's an attempt. First, find the set of questions answered for each group:</p>
<pre><code>>>> g = df.groupby('group')['question'].apply(set)
>>> g
group
g1 {xyz, abc, def}
g2 {xyz}
g3 {xyz, abc, www}
g4 {qqq, xyz, www}
Name: question, dtype: object
</code></pre>
<p>Then, us... | python|pandas|dataframe|group-by | 1 |
7,761 | 55,201,108 | Printing Nested JSON Data | <p>I am new to programming. I am working with some data that I got using the requests library. I saved the response to a separate file. The response has a lot of company information that I don't want to print. I only want certain types of company data.</p>
<p>The problem I am having is with a nested key/value. I c... | <p>you can use <code>enumerate</code> to access to the <code>index</code> and <code>value</code> of your list element at the same time:</p>
<pre><code>for index, key in enumerate(company_data['result'][0]['info']):
print('Company Name: ' + key.get('company_name'))
print('Country Name: ' + key.get('country_name... | python|json | 0 |
7,762 | 55,237,190 | how does the result of num2=[0,100,20] get? | <p>I've met a question about list comprehension.</p>
<pre><code>num1 = [5,10,15]
num2 = [i**2 if i == 10 else i-5 if i < 7 else i+5 for i in num1]
</code></pre>
<p>why <code>num2</code> is <code>num2 = [0,100,20]</code>?
How does the result get?</p> | <p>Read it as:</p>
<pre><code>num2 = [i**2 if i == 10
else i-5 if i < 7
else i+5
for i in num1]
</code></pre>
<ul>
<li>5 is not equal to 10, but it is less than 7, so it yields 5 - 5 (i.e. 0)</li>
<li>10 is equal to 10, so it yields 10 ** 2 (i.e. 100)</li>
<li>15 is not equal to 10, not eq... | python|list-comprehension | 1 |
7,763 | 55,485,949 | "str = str.replace("something", "something_else")" not working in Python 3.6.5 | <p>When I enter the following:</p>
<pre><code>str = str.replace("something", "something_else")
</code></pre>
<p>It returns with:</p>
<pre><code>AttributeError: 'tuple' object has no attribute 'replace'
</code></pre>
<p>I am on Python 3.6.5. Any help would be appreciated.</p> | <p>Check the content of <code>str</code>. It contains a tuple, not a string. Is it the output from a <code>.split()</code> operation or suchlike?</p>
<p>For example:</p>
<pre><code>>>> str = ( 'a', 'b', 'banana' )
>>> str.replace("something", "something_else")
Traceback (most recent call last):
Fi... | python | -2 |
7,764 | 57,651,760 | shutil.copyfileobj but without headers or skip first line | <p>I have about 8000 <code>text</code> files which contain csv data like</p>
<pre><code>CustomerID,Gender,Day,SaleAmount
18,Male,Monday,71.55
24,Female,Monday,219.66
112,Male,Friday,150.44
</code></pre>
<p>My code is looping through all the files and then appending it to <code>final.txt</code>-</p>
<pre><code>with o... | <p>Use this method</p>
<pre><code>def copy_csv(fname):
allFiles = glob.glob(fname)
allFiles.sort() # glob lacks reliable ordering, so impose your own if output order matters
with open(fname+'.csv', 'wb') as outfile:
for i, fname in enumerate(allFiles):
with open(fname, 'rb') as infile:
... | python-3.x|pandas|shutil | 2 |
7,765 | 54,059,524 | Tensorflow freezes when trying to create a session in docker container | <p>I'm trying to deploy a web site for the demo using CNN.
To serve this purpose, I built a docker image with dependencies (in my case tensorflow, keras and any other miscellanies). </p>
<p>I managed to built the docker image. However It fails when I tested on some sample images. I found out that the problem is tensor... | <p>Ran into a similar issue when I was using Docker. Can't find the link to the blog post but it basically recommends to set a global variable for the GRAPH.</p>
<pre><code>GRAPH = tf.Graph()
# and then where you need it
with GRAPH.as_default():
sess = tf.Session()
</code></pre>
<p>Here is a <a href="https://www.... | python|docker|tensorflow | 0 |
7,766 | 54,031,644 | Custom Keras loss function that conditionally creates a zero gradient | <p>My problem is I don't want the weights to be adjusted if <code>y_true</code> takes certain values. I do not want to simply remove those examples from training data because of the nature of the RNN I am trying to use.</p>
<p>Is there a way to write a conditional loss function in Keras with this behavior?</p>
<p>For... | <p>You can define a custom loss function and simply use <code>K.switch</code> to conditionally get zero loss:</p>
<pre><code>from keras import backend as K
from keras import losses
def custom_loss(y_true, y_pred):
loss = losses.mean_squared_error(y_true, y_pred)
return K.switch(K.flatten(K.equal(y_true, 0.)),... | python|tensorflow|machine-learning|keras|loss-function | 2 |
7,767 | 53,981,338 | What is causing this JSONDecodeError? | <p>I am trying to setup the itunes Media Player in HASSio. I have the REST API running on my mac, and I am able to pull it up in my browser and see that it is running. From within HA, I am able to adjust the volume and change to the next song, however it will not tell me what is currently playing. the below code is... | <p>Mac OS Sierra only came installed with a Python 2.XX. Upgrading to Python 3.6X seems to have it working. </p> | python|json|python-3.x|itunes|simplejson | -1 |
7,768 | 28,716,139 | How to use linecache with unicode? | <p>I open my file thus:</p>
<pre><code>with open(sourceFileName, 'r', encoding='ISO-8859-1') as sourceFile:
</code></pre>
<p>but, when I </p>
<pre><code>previousLine = linecache.getline(sourceFileName, i - 1)
</code></pre>
<p>I get an exception</p>
<pre><code>"UnicodeDecodeError: 'utf-8' codec can't decode byte 0x... | <p><code>linecache</code> takes a filename, not a file object, as your usage shows. It has no provision for an encoding. Also from the <a href="https://docs.python.org/3.3/library/linecache.html" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>This is used by the traceback module to retrieve source lines for... | python|python-3.x|unicode|linecache | 4 |
7,769 | 28,863,033 | Killing multiple httpservers running on different ports | <p>I start multiple servers using the following:</p>
<pre><code>from threading import Thread
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Cont... | <p>To stop one of these servers, you can use its <a href="https://docs.python.org/2/library/socketserver.html#SocketServer.BaseServer.shutdown" rel="nofollow"><code>shutdown()</code></a> method. This means you will need a reference to the server from the code that catches the <code>KeyboardInterrupt</code>. For example... | python|multithreading|python-multithreading|socketserver | 1 |
7,770 | 25,510,407 | Cause a test to use the multiprocessing capabilities of my server | <p>I have a Python server application that can prefork gevent Streamserver into multiple processes to exploit multiple CPU cores. </p>
<p>The common gevent server test-case works. However, I don't know how to launch tests that I know will definitely <strong>exercise the multiprocessing capabilities of my server</stron... | <p>The <a href="http://pypi.python.org/pypi/testtools" rel="nofollow noreferrer">testtools</a> package is an extension of unittest which supports running tests concurrently. It can be used with your old test classes that inherit <code>unittest.TestCase</code>.</p>
<p>For example:</p>
<pre><code>import unittest
import... | python|unit-testing|gevent | 1 |
7,771 | 25,432,654 | How to create matplotlib colormap that treats one value specially? | <p>How can I create a matplotlib colormap that maps <code>0</code> (and <em>only</em> <code>0</code>) to white, and any other value <code>0 < v <= 1</code> to a smooth gradient such as <code>rainbow</code>?</p>
<p>It seems neither <code>LinearSegmentedColormap</code> nor <code>ListedColormap</code> can do this.<... | <p>There are a few ways of doing it. From your description of your values range, you just want to use <code>cmap.set_under('white')</code> and then set the <code>vmin</code> to <code>0 + eps</code>.</p>
<p>For example:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
cmap = plt.get_cmap('rainbow')
... | python|matplotlib | 19 |
7,772 | 44,644,004 | How do i insert multiple tables into a table using TinyDB? | <p>I have been trying to create multiple tables in a table using TinyDB. Here is a website to help you understand what TinyDb is (<a href="https://media.readthedocs.org/pdf/tinydb/latest/tinydb.pdf" rel="nofollow noreferrer">TinyDB PDF</a>). The PDF file did not show how to insert multiple tables into one, one multiple... | <p>It doesn't make sense to insert tables into another table ?</p>
<pre><code>from tinydb import TinyDB
db = TinyDB('db.json')
table1 = db.table('TABLE 1')
table1.insert({'Name' : 'Alice' , 'Age' : 19})
table2 = db.table('TABLE 2')
table2.insert({'Name' : 'john' , 'Age' : 12})
</code></pre>
<p>Gives <strong>db.jso... | python|json|python-3.x|tinydb | 2 |
7,773 | 44,473,023 | Getting TypeError based on whether I use a function or not | <p>I keep getting this error in my tic-tac-toe game: <code>TypeError: unsupported operand type(s)</code> for <code>%</code>: <br/>
'<code>list'</code> and <code>'int'</code>".</p>
<p>I have a "turns" variable to count the number of turns that have passed, and have a list of strings that act as the board.</p>
<p>Given... | <pre><code>def place_char(i, brd, xo):
"""Change the value of an item in the board list from an 'e' to an 'X' or
'O'."""
brd[int(i) - 1] = '{}'.format(xo)
</code></pre>
<p>can you try replacing your <code>place_char</code> method with this one.</p>
<p>Errors in your method:</p>
<ul>
<li>in your method si... | python|typeerror | 0 |
7,774 | 44,449,125 | identify the key in a dictionary that appears the maximum number of times, along with the number of times it appears | <p>Hoping someone can help:
I created a dictionary named stat_pair, and am trying to return the key with the maximum number of occurrences, along with the number of times the key appears.
I'm new to Python & tried several approaches, but haven't been successful.
Any assistance would be appreciated.</p> | <p>Assuming that tied keys all count as the winner:</p>
<pre><code>keys_tied_for_most_occurences = [k for k in my_dict.keys()]
num_of_occurences = 1
</code></pre> | python|dictionary | -2 |
7,775 | 23,687,213 | Extracting a substring from a string and also including 10 characters before and after | <p>I have a string:</p>
<pre><code>str = "alskdfj asldfj 1234_important_what_i_need_123 sdlfja faslkdjfsdkf 234234_important_what_i_need_12312 alsdfj asdfj"
</code></pre>
<p>I want to extract each occurrence of the <code>"%important_what_i_need%"</code> bit from the string, including <code>10</code> or so characters ... | <p>Starting with "aaafoobbb" and looking for "foo" and the surrounding two characters on either side, you could do:</p>
<pre><code>>>> start_string = "aaafoobbb"
>>> search_string = "foo"
>>> index = start_string.index(search_string)
>>> s[(index - 2) : (index + len(search_string) +... | python|regex | 1 |
7,776 | 24,126,883 | pandas DataFrame.to_sql() function if_exists parameter not working | <p>When I try to pass the <code>if_exists='replace'</code> parameter to <code>to_sql</code> I get a programming error telling me the table already exists:</p>
<pre><code>>>> foobar.to_sql('foobar', engine, if_exists=u'replace')
...
ProgrammingError: (ProgrammingError) ('42S01', "[42S01] [Microsoft][ODBC SQL S... | <p>This issue seem to have been fixed in 0.14.1 <a href="https://github.com/pydata/pandas/issues/7815" rel="nofollow noreferrer">reference</a></p>
<h3>Solution</h3>
<p>Update your pandas</p> | python|sql|pandas | 2 |
7,777 | 20,405,664 | Pygame TypeError: __init__ takes exactly 4 arguments (1 given) | <p>Hello I am getting an error when attempting to run my game (TypeError) I don't have a clue why and so brought me to stack overflow here is the code:</p>
<pre><code>import pygame
import random
import pygame.mixer
import Funk
from player import *
from zombie import *
from level import *
from bullet import *
class Ga... | <p>Game class expects 3 arguments - <code>x</code>, <code>y</code>, <code>direction</code> (+ <code>self</code>)</p>
<pre><code>class Game():
def __init__(self, x, y, direction):
</code></pre>
<p>but you create object without arguments</p>
<pre><code>Game().run()
</code></pre>
<p>It seems you don't need thi... | python|pygame|typeerror | 2 |
7,778 | 46,395,397 | Add pair in a tuple to each item in a list | <p>With just basic Python and no other libraries, how can I add a value <code>(1, 0)</code>
to each item of a list containing items: </p>
<pre><code>[(0, 0)]
[(0, 1)]
[(0, 2)]
[(0, 3)]
</code></pre>
<p>Such that if the initial row, starting with <code>[(0, 0)]</code>, a new list of items is created having the element... | <pre><code>my_list = [[(0, 0)],[(0, 1)],[(0, 2)],[(0, 3)]]
item_to_add = [(1,0)]
#way 1 use for loop
for item in my_list:
item.append(item_to_add)
print my_list
my_list = [[(0, 0)],[(0, 1)],[(0, 2)],[(0, 3)]]
# way 2 use list comprehension
[item.append(item_to_add) for item in my_list]
print my_list
</code></pre> | python | -1 |
7,779 | 46,270,513 | Verifying the integrity of PyPI Python packages | <p>Recently there came some news about some <strong>Malicious Libraries</strong> that were uploaded into Python Package Index (PyPI), see:</p>
<ol>
<li><a href="https://www.bleepingcomputer.com/news/security/ten-malicious-libraries-found-on-pypi-python-package-index/" rel="noreferrer">Malicious libraries on PyPI</a></... | <p>First, your concern of obtaining malicious files when downloading from <code>PyPI</code> using <code>pip</code> is valid. In fact as of 2020, <a href="https://security.stackexchange.com/a/234098/213165"><code>pip</code> has no way to cryptographically validate the authenticity and integrity</a> of the software it do... | python|python-2.7|python-3.x|security|pypi | 2 |
7,780 | 49,430,040 | How to avoid overlapping when there's hundreds of nodes in networkx? | <p>I've got 2000+ nodes and 900+ edges, but when I was trying to make graphics in networkx, I found all the nodes crowded together. I tried changing attribute values, such as scale, k. I found them no use since there were hundreds of nodes with labels below which means I could not choose the small size of nodes. I'm wo... | <p>You can use interactive graphs by <strong>ploty</strong> to plot such large number of nodes and edges. You can change every attribute like canvas size etc and visualize it more easily by zooming other actions.<br>
Example:</p>
<p>Import ploty</p>
<pre><code>import plotly.graph_objects as go
import networkx as nx
</... | python|matplotlib|networkx | 1 |
7,781 | 21,277,385 | Python Invalid syntax in elif | <p>The code below shows in invlid syntax in the first elif statement. I have checked and rechecked my code several times, but cant figure out how to solve the error.</p>
<pre><code>fileHandle = open ( 'gra1.txt' )
count=0
count1=0
fileList = fileHandle.readlines()
for fileLine in fileList:
line=fileLine.split()
... | <p>Your <code>elif</code> is not indented properly...it should be indented the same way <code>if</code> is indented. Seeing the <code>else</code> block, it seems that you have by mistake indented the first <code>if</code>. Remember that <code>elif/else</code> should be preceded by an <code>if</code> always.</p>
<p><st... | python|if-statement|syntax-error | 10 |
7,782 | 53,715,893 | Iterate through list and print 'true' if list element is of a certain type | <p>I was wondering if there were a way in python to loop through a list and check if a list element was of a certain type. Something like this in incorrect pseudo code. </p>
<pre><code>listt = ['3109', datetime.timedelta(0, 240), datetime.timedelta(0, 60), '2411',
datetime.timedelta(0, 2160), '3109']
for i in listt:
... | <p>You can do this using <a href="https://docs.python.org/3/library/functions.html#isinstance" rel="nofollow noreferrer"><code>isinstance</code></a>:</p>
<pre><code>for i in listt:
if isinstance(i,str):
print('success')
</code></pre>
<p>Output:</p>
<pre><code>success
success
success
</code></pre>
<p>Not... | python | 4 |
7,783 | 45,985,682 | Tensorflow Shape of a vector is (col,) | <p>I have been working through Andrew Ng's course lately, and I figured I might as well try to implement what I've learnt in other languages (which so happens to be Python for me), but I've run into a wall.
Here's my code:</p>
<pre><code>train_x = [[1,2,3,4], [5,6,7,8]]
train_y = [24, 1680]
train_x = np.asarray(train... | <p>You need to reshape input <code>x</code> to <code>(some_number, 4)</code> . Also fix the <code>y</code> placeholder</p>
<pre><code>train_x = [[1, 2, 3, 4], [5, 6, 7, 8]]
train_y = [24, 1680]
train_x = np.asarray(train_x)
train_y = np.asarray(train_y)
m = train_x.shape[0]
n = train_x.shape[1]
X = tf.placeholder(t... | python|machine-learning|tensorflow|python-3.5|linear-regression | 1 |
7,784 | 54,912,487 | Get timestamp for 27/02/2019 00:00 US/Eastern in python using pytz and datetime | <p>I have the following string:</p>
<pre><code>27/02/2019
</code></pre>
<p>As it is known in the program that those dates correspond to NY time zone, I would like to get the timestamp corresponding to:</p>
<pre><code>27/02/2019 00:00 US/Eastern
</code></pre>
<p>I have tried:</p>
<pre class="lang-py prettyprint-ove... | <p>Just in case it helps others, I found the error was located here:</p>
<pre><code>_period1_ts = int((_period1_localized - datetime.datetime(1970, 1, 1, tzinfo=exchange_tz)).total_seconds())
</code></pre>
<p>It shall use UTC timezone for the EPOCH time:</p>
<pre><code>_period1_ts = int((_period1_localized - datetim... | python|python-2.7|datetime|timestamp|pytz | 1 |
7,785 | 21,823,229 | Finding next occurring tag and its enclosed text with Beautiful Soup | <p>I'm trying to parse text between the tag <code><blockquote></code>. When I type <code>soup.blockquote.get_text()</code>. </p>
<p>I get the result I want for the first occurring blockquote in the HTML file. How do I find the next and sequential <code><blockquote></code> tag in the file? Maybe I'm just... | <p>Use <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-next-siblings-and-find-next-sibling"><code>find_next_sibling</code></a> (If it not a sibling, use <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all-next-and-find-next"><code>find_next</code></a> instead)</p>
<pre><code>>... | python|html|python-2.7|beautifulsoup | 25 |
7,786 | 41,047,598 | Can you use {} and .format to put values into a dictionary | <p>I am writing a script to query an ArcGIS rest service and return records. I want to use {} and .format to allow a dictionary item to be changed a time. How do I write this:</p>
<pre><code>time = '2016-10-06 19:18:00'
URL = 'http://XXXXXXXXX.gov/arcgis/rest/services/AGO_Street/StreetMaint_ServReqs/FeatureServer/10/q... | <p><code>str.format</code> is a <strong>string method</strong>, not a method on a dictionary. Just apply the method to that one string value:</p>
<pre><code>params = {
'f': 'pjson',
'where': "CLOSE_DATE > '{}'".format(time),
'outfields' : 'OBJECTID, REPORTED_DATE, SUMMARY, ADDRESS1, REQUEST_STATUS, CLO... | python|json | 3 |
7,787 | 38,487,334 | Pandas/Python memory spike while reading 3.2 GB file | <p>So I have been trying to read a 3.2GB file in memory using pandas <code>read_csv</code> function but I kept on running into some sort of memory leak, my memory usage would spike <code>90%+</code>.</p>
<p>So as alternatives </p>
<ol>
<li><p>I tried defining <code>dtype</code> to avoid keeping the data in memory as ... | <p>A file stored in memory as text is not as compact as a compressed binary format, however it is relatively compact data-wise. If it's a simple ascii file, aside from any file header information, each character is only 1 byte. Python strings have a similar relation, where there's some overhead for internal python stuf... | python|csv|pandas|memory | 1 |
7,788 | 31,204,332 | Access another child class from parent | <p>I have the code:</p>
<pre><code>class Class1(object):
class Class2:
var1 = value1
class Class3:
var1 = Class2.var1 + value2
</code></pre>
<p>How can I access in Class3 the value I want from Class2?</p> | <p>You can use <code>@classmethod</code>'s to access <code>class</code> variables without instantiating the class</p>
<pre><code>In [17]: class Class1(object):
class Class2:
@classmethod
def setvar(cls,value):
cls.var1 = value
class Class3:
@classmethod
def setvar(cl... | python|python-2.7 | 2 |
7,789 | 40,293,959 | EOFError: EOF when reading a line only when execute it via curl | <p>I have a python code that construct a CURL command base on URL and data from user inputs</p>
<hr />
<p>I have</p>
<pre><code>import os
print ("______________\n")
print " 1.GET "
print " 2.POST "
print " 3.PUT "
print " 4.DELETE "
... | <p>Since you're piping the <code>curl</code> command to <code>python</code>, stdin is connected to the pipe, not the user's terminal.</p>
<p>You can use bash <a href="https://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html" rel="nofollow noreferrer">process substitution</a> to make the curl comman... | python|curl | 3 |
7,790 | 29,200,594 | How do I split a long list in python 3? And print them individually indented? | <p>I would like to know how to print things from a list individually and indented. For example:</p>
<pre><code>l = ['- cat', '- dog', '- mouse', '- frog', '- hamster']
lsplit = l.split
for i in range(len(l)):
print(lsplit)
</code></pre>
<p>I get this error: </p>
<pre><code>AttributeError: 'list' object has no attrib... | <p>There is no need for a <code>for</code> loop nor for the use of <code>split</code>. I would advise simply using <code>.join</code> and <code>\n</code> (newline character) to place each element on a separate line, like this:</p>
<pre><code>my_list = ['- cat', '- dog', '- mouse', '- frog', '- hamster']
print ("\n".jo... | python-3.x | 0 |
7,791 | 29,212,006 | Random freezing / hanging in Python ZeroMQ | <p>I am writing a broker-less, balanced, client-worker service written in python with <strong><code>ZeroMQ</code></strong>.</p>
<p>The clients acquire a worker's address, establish a connection ( <code>zmq.REQ / zmq.REP</code> ), send single request, receive a single response and then disconnect. </p>
<p>I have chose... | <p>The <code>REP</code> socket is synchronous by definition. So your server can only serve one request at a time, rest of them will just fill up the buffer and get lost at some point.</p>
<p>To fix the root cause, you need to use the <code>ROUTER</code> socket instead.</p>
<pre><code>class Server:
def __init__(se... | python|zeromq|pyzmq | 0 |
7,792 | 58,917,184 | fill values from cell above in a given column | <p>For the column labelled "Category", I want to fill the cells with white spaces with the value from above, see df number 2 in image below. </p>
<p>Here is what I tried but it didn't work:</p>
<pre><code>df[df['Category']==" "] = np.NaN
df = df['Category'].fillna(method='ffill')
col = ['Category']
df.loc[:,col] = df... | <p>We can transform to NaN using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html" rel="nofollow noreferrer"><code>Series.mask</code></a> and then drop duplicated:</p>
<pre><code>df['Category']=df['Category'].mask(df['Category'].eq('')|df['Category'].isnull()).ffill()
</code>... | python|pandas | 1 |
7,793 | 52,287,855 | file.read() in Python | <pre><code>def main():
f = open('yahoo.txt', 'w')
f.write('yahoo\n')
f.write('google\n')
f.write('bing\n')
f.write('duckduck\n')
f.write('aol\n')
f.close()
f = open('yahoo.txt', 'r')
print('f.read ', f.read() )
print('f.read(5)', f.read(5)) # just 'f.read(4)' being printed
main... | <p>Once you call f.read(), it reads the whole file, moving the <code>cursor</code> to the end of the file. If you want to start reading from the beginning again, you can use the <code>seek</code> function.</p>
<pre><code>def main():
f = open('yahoo.txt', 'w')
f.write('yahoo\n')
f.write('google\n')
f.wr... | python|python-3.x | 2 |
7,794 | 51,736,043 | Is there any python IDE that supports "highlight and run"? | <p>I used to be a heavy R programmer and really used to the Rstudio's "highlight and run" feature. I just wonder if there any python IDE that has similar feature that allows you to select part of the code in a script and run and show the results in a console?</p> | <p>In <a href="https://pythonhosted.org/spyder/installation.html" rel="nofollow noreferrer">Spyder</a> you can highlight and run by pressing F9. I also heard a rumour that RStudio is going to be able to run python soon but I'm not sure if it's true</p> | python|r|ide|rstudio | 1 |
7,795 | 59,664,883 | Finding subset List of Python List based on an input integer | <p>I want a subset list from input List based on input integer value.</p>
<p>For Example:</p>
<pre><code>Input List: [3,7,9,11,12]
Input Value: 2
Output List: [1,7,9,11,12]
# 2 is subtracted from first element of list
Input List: [3,7,9,11,12]
Input Value: 5
Output List: [5,9,11,12]
#5 is subtracted from list in seq... | <p>Use <code>numpy.cumsum()</code> if modules are allowed:</p>
<pre><code>import numpy as np
input_list = np.asarray([3, 7, 9, 11, 12])
input_integer = 5
output_list = input_list[input_list.cumsum() > input_integer]
output_list[0] -= input_integer - input_list[input_list.cumsum() <= input_integer].sum()
print(ou... | python-3.x|list | 2 |
7,796 | 59,838,948 | Scraping javascript table with a scroll using selenium | <p>I am trying to scrape a table which is being generated through javascript but I am struggling. My code so far is:</p>
<pre><code>driver = webdriver.Chrome();
driver.get("https://af.ktnlandscapes.com/")
# get table -- first wait for table to fully load
WebDriverWait(driver, 10).until(EC.presence_of_all_elements_lo... | <p>Try to use below code:</p>
<pre><code>driver = webdriver.Chrome()
driver.get("https://af.ktnlandscapes.com/")
# get table -- first wait for table to fully load
WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//*[@id='list-view']/tbody/tr")))
table = driver.find_element_by_xpath("//*... | python|selenium | 5 |
7,797 | 62,214,708 | Python, pandas and NLP: creating a corpus by dividing text based on value in other column | <p>I'm quite new to "coding" in general, and Python in particular, so bear with me! </p>
<p>I have a CSV file that has feedback gathered from a feedback form on a web site (a "Was this page useful" feedback form. The CSV has one row per feedback received. There are several columns, but the ones that I'M interested in ... | <p>Not sure if its the fastest way but you could do something like:</p>
<pre class="lang-py prettyprint-override"><code>topic_dict = {}
for topic, topic_df in data_cropped.groupby('Topic'):
topic_dict[topic] = ' '.join(topic_df['Details'].tolist())
</code></pre> | python|pandas|nlp | 0 |
7,798 | 63,364,588 | UnboundLocalError: local variable 'batch_outputs' referenced before assignment | <p>I am writing machine learning code using Keras to grade the severity of prostate cancer. After running it the following error appears:</p>
<pre><code>---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-inp... | <p>This error is usually thrown when you pass an empty array to Keras. Check the array you are passing.</p> | python|machine-learning|keras | 18 |
7,799 | 63,438,808 | Is there a faster method to use a 2d numpy array of booleans to select elements from a 2d array, but with a 2d output? | <p>If I have an array like this</p>
<pre><code>arr=np.array([['a','b','c'],
['d','e','f']])
</code></pre>
<p>and an array of booleans of the same shape, like this:</p>
<pre><code>boolarr=np.array([[False,True,False],
[True,True,True]])
</code></pre>
<p>I want to be able to only select th... | <p>Thanks for the comments. I misunderstood how an array works. For those curious this is my solution (I'm actually working with numbers):</p>
<pre><code>arr[boolarr]=np.nan
</code></pre>
<p>And then I just changed how the rest of the function handles nan values</p> | python|arrays|numpy|indexing | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.