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 |
|---|---|---|---|---|---|---|
1,400 | 9,077,126 | How to use fcntl reading status of lock file? | <p>I have a simple example:</p>
<pre><code>#!/usr/bin/python
import time
import fcntl
file = open("e", "w")
fcntl.lockf(file.fileno(),fcntl.LOCK_EX)
file.write("foo")
file.close()
</code></pre>
<p>How to know locked file or not ? ( Not waiting until file is unlocked )</p> | <p>That's what <code>fcntl.LOCK_NB</code> is for. For example:</p>
<pre><code>import warnings
try:
fcntl.flock(myfile, fcntl.LOCK_EX|fcntl.LOCK_NB)
except IOError:
warnings.warn("can't immediately write-lock the file ($!), blocking ...")
fcntl.flock(myfile, fcntl.LOCK_EX)
</code></pre>
<p>From <a href="ht... | python | 5 |
1,401 | 39,013,061 | Trouble with Python3 imports | <p>This question was asked a lots of times but none of the solutions seem to help in my case.</p>
<p>I have a directory structure like this</p>
<pre><code>my_project/
main.py
bootstrap/
__init__.py
boot.py
consumer/
__init__.py
main.py
</code></pre>
<p>Being at the topleve... | <p>You are getting this error because module search path only includes the current directory, and not its parents; and since your other module is not in the <code>PYTHONPATH</code> it isn't available to import.</p>
<p>You can find this out yourself by printing <code>sys.path</code> in your script.</p>
<p>I created a ... | python|python-3.x|import | 4 |
1,402 | 55,409,921 | facing date error while extraction weeks in pandas | <p>I all i write the below code for getting weekdays values from calendar date in pandas dataframe. but i am getting some error</p>
<pre><code>codetest['DATE'] = pd.to_datetime(codetest['DATE'], format = '%m/%d/%y')
codetest['day_of_week'] = codetest['DATE'].dt.dt.day_name()
</code></pre>
<p>ValueError: unconverted d... | <p>Assuming that you have DATE: String variable, YYYY-MM-DD HH:MM:SS</p>
<p><strong>Step 1:</strong> Convert your "DATE" column to datetime</p>
<p><code>codetest['DATE'] = pd.to_datetime(codetest['DATE'])</code></p>
<p><strong>Step 2:</strong> Extract all required field in new column using below code </p>
<p><code>... | pandas|date|dt | 0 |
1,403 | 55,553,660 | How to emit custom Events to the Event Loop in PyQt | <p>I am trying to emit custom events in PyQt. One widget would emit and another would listen to events, but the two widgets would not need to be related.</p>
<p>In JavaScript, I would achieve this by doing</p>
<pre><code>// Component 1
document.addEventListener('Hello', () => console.log('Got it'))
// Component 2... | <p>In PyQt the following instruction:</p>
<pre class="lang-js prettyprint-override"><code>document.addEventListener('Hello', () => console.log('Got it'))
</code></pre>
<p>is equivalent</p>
<pre class="lang-py prettyprint-override"><code>document.hello_signal.connect(lambda: print('Got it'))
</code></pre>
<p>In a... | python|pyqt|pyqt5 | 5 |
1,404 | 52,527,232 | how can does one declare a sub-class object inside of a base class without leading to recursion errors? | <p>I am trying to structure a Python 3 program as follows:</p>
<p><strong>Base Class</strong>: Body</p>
<p><strong>Sub-Class</strong>: Head</p>
<p>A super-simple code representation is as follows:</p>
<pre><code>class Body:
def __init__(self):
self.head_obj = Head()
# ...Set-up body...
def ... | <p>A head is not a <em>kind</em> of body, it's a <em>part</em> of the body AFAIK.</p>
<p>So you should be using <em>composition</em> instead of <em>inheritance</em>:</p>
<pre><code>class Head:
def __init__(self):
# ...Set-up head...
def head_actions():
print('Head does something')
class Body... | python|python-3.x|oop | 2 |
1,405 | 52,878,027 | Keras regression prediction is not same dimension as output dimension | <p>Hello I'm trying to do Energy Disaggregation (predict the energy use of appliances while given the total energy consumption of a certain household.)</p>
<p>Now I have an input dimension of 2 because of 2 main energy measurements.
The output dimension of the Keras Sequential model should be 18 because I have 18 appl... | <p>Well you are reshaping the predictions and flattening them here:</p>
<pre><code>pred = model.predict(X_test).reshape(-1)
</code></pre>
<p>The <code>reshape(-1)</code> effectively makes the array one-dimensional. Just take the predictions directly:</p>
<pre><code>pred = model.predict(X_test)
</code></pre> | python|tensorflow|neural-network|keras|regression | 3 |
1,406 | 52,744,334 | Creating a function to perform grouping and sorting based on columns in Pandas dataframe and Labeling | <pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame([
[100, 'm1', 1, 4],
[200, 'm2', 7, 5],
[120, 'm1', 4, 4],
[240, 'm2', 8, 5],
[300, 'm3', 5, 4],
[330, 'm3', 2, 4],
[350, 'm3', 11, 4],
[200, 'm4', 9, 4]],
columns=['Col1', 'Col2', 'Col3', 'Col4'])... | <p>You can create a higher level function (let's call it <code>my_function()</code>) that is called by <code>transform()</code>, which then calls a lower level function (let's call it <code>deeper_logic()</code>) that applies the previous logic outlined in your question, like so:</p>
<pre><code>def my_function(group):... | python|pandas|dataframe | 1 |
1,407 | 37,198,602 | List inside a List using python and Database | <p>I wish to create a document like --</p>
<pre><code>{
"name" : "John" ,
"DOB" : "21-Jun-1999" ,
"Sex" : "M" ,
"Skill" : ["C","PYTHON","COBOL"],
"Location" : { "lat":12.3 , "Long" : "14.6" }
}
</code></pre>
<p>I am using <code>cx_oracle</code> to pull data out of my database .
Here is a small... | <p>I don't have cx_oracle installed, so this isn't tested but...</p>
<p>From your desired output, it looks like you want the value of your <code>Location</code> field to be a dict, not a list. Given this, and assuming index 4 and 5 of <code>row</code> will always represent your <code>lat</code> and <code>long</code> c... | python|json|list|document | 0 |
1,408 | 37,515,659 | Returning a list of x and y coordinate tuples | <p>I am trying to return a list of x and y co-ordinate tuples after reading a text file with numbers in it for example:</p>
<pre><code>68,125
113,69
65,86
108,149
152,53
</code></pre>
<p>I have got to the point where i return a list of numbers but not as pairs in a tuple.</p>
<p>here is my code:</p>
<pre><code>def ... | <p>You can read each line, then split each line by comma and convert each piece of that split to an int using map. Finally convert it into tuple</p>
<pre><code>coords = [tuple(map(int, line.split(","))) for line in lines]
</code></pre>
<p>This gives the output:</p>
<pre><code>[(68, 125), (113, 69), (65, 86), (108, 1... | python-3.x|tuples | 0 |
1,409 | 37,323,256 | Python script not executing under lighttpd | <p>I'm under Debian,
Installed python and lighttpd using "apt-get install"</p>
<p>Here is my lighttpd conf file:</p>
<pre><code>server.modules = (
"mod_access",
"mod_alias",
"mod_compress",
"mod_redirect",
"mod_rewrite",
"mod_cgi"
)
server.document-root = "/var/... | <p>From the docs here:</p>
<p><a href="https://wiki.archlinux.org/index.php/lighttpd#CGI" rel="nofollow">https://wiki.archlinux.org/index.php/lighttpd#CGI</a></p>
<p>it appears you need also need to set <code>cgi.assign</code>, e.g.:</p>
<pre><code>cgi.assign = ( ".pl" => "/usr/bin/perl",
... | python|lighttpd | 2 |
1,410 | 37,195,901 | How can I make a PyQt widget resizable by dragging? | <p>I have a QScrollArea containing a widget with a QVBoxLayout. Inside this layout are several other widgets. I want the user to be able to drag the lower borders of those widgets to resize them in the vertical direction. When they are resized, I don't want them to "steal" size from the other widgets in the scrollin... | <pre><code>class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setWindowTitle("MainWindow")
MainWindow.resize(500, 500)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
... | python|qt|resize|pyqt|qscrollarea | 2 |
1,411 | 37,229,543 | Represent a function by a mathematical function | <p>Is it possible to output a mathematical function directly from the function implementation ? </p>
<pre><code>class MyFunction:
def __init__(self, func):
self.func = func
def math_representation(self):
# returns a string representation of self.func
f = lambda x: 3*x**2
myFunc = MyFunction(f)... | <p>As I said, you can use <a href="http://docs.sympy.org/latest/modules/functions/index.html" rel="noreferrer">SymPy</a> if you want this to be more complex, but for simple functions (and trusted inputs), you could do something like this:</p>
<pre><code>class MathFunction(object):
def __init__(self, code):
... | python|math | 5 |
1,412 | 39,576,673 | python lxml - simply get/check class of HTML element | <p>I use <code>tree.xpath</code> to iterate over all interesting HTML elements but I need to be able to tell whether the current element is part of a certain CSS class or not.</p>
<pre><code>from lxml import html
mypage = """
<div class="otherclass exampleclass">some</div>
<div class="otherclass">th... | <p>There is no need for <em>iter</em>, <code>if "exampleclass" in item.classes:</code> does the exact same thing, only more efficiently. </p>
<pre><code>from lxml import html
mypage = """
<div class="otherclass exampleclass">some</div>
<div class="otherclass">things</div>
<div class="exam... | python|class|python-3.x|lxml | 7 |
1,413 | 39,851,879 | xlwings (0.10.0) Automation error while importing UDF | <p>i am using xlwings for the first time, i created a file using the "xlwings quickstart" command and added the following function in the python file</p>
<pre><code> @xlw.func
def add(x,y):
return 2 * (x+y)
</code></pre>
<p>when i try to import this udf into the excel file, i get a Runtime <code>error 440 ... | <p>I solved same problem with:<br>
- under Excel, go to File/Options/Trust Center/Trust Center Settings<br>
- in Macro Settings make sure "Trust access to the VBA porject object model" is checked</p> | python-3.x|xlwings | 1 |
1,414 | 39,759,503 | How to document multiple return values using reStructuredText in Python 2? | <p>The <a href="https://docs.python.org/devguide/documenting.html" rel="noreferrer">Python docs</a> say that "the markup used for the Python documentation is <a href="http://docutils.sf.net/rst.html" rel="noreferrer">reStructuredText</a>". My question is: How is a block comment supposed to be written to show multiple r... | <p>There is a compromised solution: just write in normal Markdown texts.
e.g.</p>
<pre class="lang-py prettyprint-override"><code>def func(a, b):
"""
:param int a: first input
:param int a: second input
:returns:
- x - first output
- y - second output
"""
return x, y
</code><... | python|python-2.7|documentation|restructuredtext | 12 |
1,415 | 16,495,753 | python - possible encoding and decoding values | <p>I'm trying to decode chatacters which have been encoded in the following way:<br>
&#number;<br>
I tried:</p>
<pre><code> s.decode("utf8")
</code></pre>
<p>and:</p>
<pre><code> s.decode("unicode-escape")
</code></pre>
<p>but both not seems to work.</p>
<p>What is the encoding I should use to decode this kind... | <p>Python <strong>2</strong>:</p>
<pre><code>import HTMLParser
h = HTMLParser.HTMLParser()
print h.unescape('&pound;682m')
£682m
</code></pre>
<p>Python <strong>3</strong>:</p>
<pre><code>import html.parser
h = html.parser.HTMLParser()
print(h.unescape('&pound;682m'))
£682m
</code></pre>
<p>.encode and .dec... | python|unicode | 5 |
1,416 | 32,015,909 | printing child nodes along with their xml tags in python | <p>I have a file called m.xml which has the following content:</p>
<pre><code><volume name="sp" type="span" operation="create">
<driver>HDD1</driver>
<driver>HDD2</driver>
<driver>HDD3</driver>
<driver>HDD4</driver>
</volume>
</code></pre>
<p... | <p>Use <a href="https://medium.com/code-zen/beautifulsoup-first-dip-2c275db7653f" rel="nofollow">BeautifulSoup</a> to parse XML. It's very simple: </p>
<pre><code>from bs4 import BeautifulSoup as Soup
with open("sample.xml", "r") as f:
target_xml = f.read()
# create a `Soup` object
soup = Soup(target_xml, "xm... | python|xml|elementtree | 1 |
1,417 | 38,672,018 | Pandas: slicing a dataframe into multiple sheets of the same spreadsheet | <p>Say I have 3 dictionaries of the same length, which I combine into a unique <code>pandas</code> dataframe. Then I dump said dataframe into an Excel file. Example:</p>
<pre><code>import pandas as pd
from itertools import izip_longest
d1={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
d2={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
... | <p>First prep your dataframe for writing like this:</p>
<pre><code>prepdf = mydf.groupby(mydf.index // 2).apply(lambda df: df.reset_index(drop=True))
prepdf
</code></pre>
<p><a href="https://i.stack.imgur.com/eGDyZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eGDyZ.png" alt="enter image descript... | python|excel|pandas|dataframe|slice | 4 |
1,418 | 38,632,753 | XlsxWriter: add color to cells | <p>I try to write dataframe to xlsx and give color to that.
I use</p>
<pre><code>worksheet.conditional_format('A1:C1', {'type': '3_color_scale'})
</code></pre>
<p>But it's not give color to cell. And I want to one color to this cells.
I saw <code>cell_format.set_font_color('#FF0000')</code>
but there is don't specify... | <p>The problem is that <code>worksheet.write('A1:C1', 'Ray', format)</code> is used only to write a single cell.
A possible solution to write more cells in a row, is use <code>write_row()</code>.</p>
<pre><code>worksheet.write_row("A1:C1", ['Ray','Ray2','Ray3'], format)
</code></pre>
<p>Remember that <strong>write_r... | python|pandas|xlsxwriter | 3 |
1,419 | 38,643,450 | Python: Can an exception class identify the object that raised it? | <p>When a Python program raises an exception, is there a way the exception handler can identify the object in which the exception was raised?</p>
<p>If not, I believe I can find out by defining the exception class like this...</p>
<pre><code>class FoobarException(Exception) :
def __init__(self,message,context) :
... | <p>It quickly gets messy if you want the exception itself to figure out where in the stack it is. You can do something like this:</p>
<pre><code>import inspect
frameinfo = inspect.getframeinfo(inspect.stack()[1][0])
caller_name = frameinfo[2]
file_name = frameinfo[0]
</code></pre>
<p>This, however, will only really w... | python|class|exception-handling | 0 |
1,420 | 38,771,317 | Creating a 2D array from Nested Dictionaries | <p>I am a student working with python dictionaries for the first time and I'm getting stuck on resorting them in to matrix arrays.</p>
<p>I have a nested ordered dictionary describing the temperature and humidity week by week.</p>
<pre><code>weather = OrderedDict([(92, OrderedDict([('Mon', 79), ('Tues', 85),
... | <p>You need to loop through the nested dictionaries appending values to a list. You also should store the day number so as to have something to plot temperature against. The colour for humidity should also be stored for each day. You then need to define the axis label to display the days as strings. The code to do this... | python|arrays|dictionary|multidimensional-array|matplotlib | 2 |
1,421 | 10,107,971 | Using struct timeval in Python | <p>I have a C program containing a structure</p>
<pre><code>struct S{
int x;
struct timeval t;
};
</code></pre>
<p>and a function</p>
<pre><code>int func(struct S s1, struct S s2)
</code></pre>
<p>I need to call this function from my python program.
I am using ctypes.The parallel structure on... | <p>Find the definition of <code>struct timeval</code> in your platform's C include files (the Internet suggests <code>sys/time.h</code>), then transcode that into a ctypes structure.</p>
<p>On my platform a <code>struct timeval</code> is</p>
<pre><code>struct timeval {
long tv_sec;
long tv_usec;
};
</code></pre>
... | python|ctypes|timeval | 6 |
1,422 | 68,109,761 | Transform list of strings of commit-details to structured dictionary applying grouping by name and date | <p>From the data I have, I want to show in such form where a commit key will have an array
of commits that are done on the particular date. This is what I am expecting my output to be</p>
<pre><code>{
"Dan Ab": [
{
"2014-05-2": {
"commit_count": &quo... | <p>You can parse and restructure your data like so:</p>
<pre><code>merged_result = [
"43f4cc160;Dan Ab;2021-06-17; 1 file changed, 10 insertions(+), 19 deletions(-)",
"6cbf2a8b3;Dan Ab;2021-06-15; 1 file changed, 14303 insertions(+)",
"c0a77029c;Dan Ab;2021-06-15; 1 file changed, 1 ... | python|json|regex|grouping | 2 |
1,423 | 68,301,487 | How to convert integer months to year in python | <p>I have inputs start date and end date. I want output like <strong>2 years 7 months</strong></p>
<pre><code>from dateutil.relativedelta import relativedelta
rdelta = relativedelta(now, birthdate)
print 'years - ', rdelta.years
print 'months - ', rdelta.months
</code></pre>
<p>in this method, I got output like</p>
<pr... | <p>This worked for me.</p>
<pre><code>def format_date_range(start: datetime.date, end: datetime.date):
rdelta = relativedelta(end, start)
return f"{rdelta.years} years, {rdelta.months} months"
</code></pre>
<p>What's the start and end dates here?</p> | python|django|python-datetime | 1 |
1,424 | 26,050,454 | Running Django Rest Framework inside Apache | <p>I have a web server running Apache, and I need to implement a RESTful API on the same domain, and I'd like to use Django Restful Framework to serve the REST calls.</p>
<p>For example: going to <a href="http://myawesomedomain.com/" rel="nofollow">http://myawesomedomain.com/</a> in a browser serves a good old fashion... | <p>I did some more digging and found the answer myself.</p>
<p>You use mod_wsgi.</p>
<p>Here is a perfect tutorial to get started: <a href="https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/modwsgi/" rel="nofollow">https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/modwsgi/</a></p> | python|apache|rest|django-rest-framework | 1 |
1,425 | 63,029,747 | How to read a tab delimited file into Python with rows of unequal length? | <p>I have a text file which is the results of measurements. When the object is not in the correct place to be measured it cannot take the full suite of measurements, which gives rows of unequal length in the text file.</p>
<p>How can this be read in Python? Do I have to fill in the spaces in the text file with blanks?<... | <p>The error message indicates that you are trying to import the header row. Use the <code>skiprows</code> parameter to <code>loadtxt</code> to skip this row:</p>
<pre><code>lines = loadtxt(file_to_read, comments="#", delimiter="\t", skiprows=1, unpack=False)
</code></pre>
<p>You can read more about... | python|numpy|text-files|csv | 2 |
1,426 | 62,986,319 | Vercel: Cannot import other functions with Python Serverless API | <p>I am trying to import helper functions into my Serverless Flask Api but am unable to do so with Vercel using the <code>vercel dev</code> command.</p>
<p>My folder structure is:</p>
<pre><code>api
_utils/
common.py
app.py
</code></pre>
<p>However, when I try to import my helper function into my app.py file I ... | <p>I moved my _utils file to the root of my project and now in my api/index.py I import as follows</p>
<p><code>from _utils.common import helper_function</code></p>
<p>My vercel.json file looks like:</p>
<pre><code>{
"routes": [
{
"src": "/api/(.*)",
"dest": &qu... | python|next.js|vercel | -1 |
1,427 | 44,338,564 | Keras merge/concatenate models outputs as a new layers | <p>I want to use pretrained models' convolutionnal feature maps as input features for a master model. </p>
<pre><code>inputs = layers.Input(shape=(100, 100, 12))
sub_models = get_model_ensemble(inputs)
sub_models_outputs = [m.layers[-1] for m in sub_models]
inputs_augmented = layers.concatenate([inputs] + sub_models_o... | <p>The thing works if we do: </p>
<pre><code>sub_models_outputs = [m(inputs) for m in sub_models]
</code></pre>
<p>rather than:</p>
<pre><code>sub_models_outputs = [m.layers[-1] for m in sub_models]
</code></pre>
<p>TLDR: models needs to be called as a layer. </p> | python|machine-learning|keras|keras-layer|keras-2 | 0 |
1,428 | 32,981,350 | Several functions without global variable | <p>I want to know how I can make this code without global variables.</p>
<p>I have tried myself but it seems like it involves return, but then It won't go back to the "menu" (main_list). The point of this code is to always return to the menu except when pressing "3" (exit program).</p>
<p>Sorry for the big (and bad) ... | <p>As Xeno said, you need a <code>while</code> loop to continually loop over the input. For your case, I would suggest a <code>do-while</code> loop, but Python does not have a built-in <code>do-while</code>, so you will need to emulate one, possibly something like this:</p>
<pre><code>while True:
# do stuff
i... | python|list|variables|global | 1 |
1,429 | 8,307,242 | How to extend SQLite with Python functions in Django? | <p>It's possible to <a href="http://docs.python.org/library/sqlite3.html#sqlite3.Connection.create_function">define new SQL functions for SQLite in Python</a>. How can I do this in Django so that the functions are available everywhere?</p>
<p>An example use case is a query which uses the <a href="http://www.postgresql... | <p>Here's a Django code example that extends SQLite with GREATEST() and LEAST() methods by calling Python's built-in max() and min():</p>
<pre><code>from django.db.backends.signals import connection_created
from django.dispatch import receiver
@receiver(connection_created)
def extend_sqlite(connection=None, **kwargs)... | python|django|sqlite | 11 |
1,430 | 7,728,694 | Python/Regex - How to extract date from filename using regular expression? | <p>I need to use python to extract the date from filenames. The date is in the following format:</p>
<pre><code>month-day-year.somefileextension
</code></pre>
<p>Examples:</p>
<pre><code>10-12-2011.zip
somedatabase-10-04-2011.sql.tar.gz
</code></pre>
<p>The best way to extract this would be using regular expression... | <p>Assuming the date is always in the format: [MM]-[DD]-[YYYY].</p>
<pre><code>re.search("([0-9]{2}\-[0-9]{2}\-[0-9]{4})", fileName)
</code></pre> | python|regex | 26 |
1,431 | 41,968,378 | Increasing the counter in a list every two elements | <p>I have a list of elements:</p>
<pre><code>list = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5']
</code></pre>
<p>which I use in pairs in this way:</p>
<pre><code>for x in range(0, len(list)-1):
print(list[x], list[x+1])
</code></pre>
<p>This works and returns:</p>
<pre><code>('elem1', 'elem2')
('elem2', 'ele... | <p>First of all don't use list as a variable name, that can cause some serious problems.</p>
<p>Second, the simple way is just initial a counter and increment it inside the loop.</p>
<pre><code>li = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5']
cnt = 0
for index in range(0, len(li)-1):
cnt += 1
print(li[inde... | python | 3 |
1,432 | 47,427,843 | SyntaxError: invalid syntax [in python code] | <p>code is:</p>
<pre><code>cat_list = [k for k, v in cat_counter.()[:50]]
</code></pre>
<p>Error is as follows:</p>
<blockquote>
<p>File "", line 1
cat_list = [k for k, v in cat_counter.()[:50]]</p>
<p>SyntaxError: invalid syntax</p>
</blockquote> | <p>The <code>cat_counter</code> function would be defined like this:</p>
<pre><code>def cat_counter():
# Make function
</code></pre>
<p>Thus, simply <strong>remove the dot</strong> to properly call the function:</p>
<pre><code>cat_list = [k for k, v in cat_counter()[:50]]
</code></pre> | ipython | 1 |
1,433 | 71,087,746 | Find a substring in cells across multiple columns in a Pandas dataframe | <p>I have a large DataFrame with 50+ columns which I'm simplifying here below:</p>
<pre><code>students = [('Samurai', 34, '777.0', 'usa--->jp', 'usd--->yen') ,
('Jack', 31, '555.5','usa','usd') ,
('Mojo', 16,'488.1','n/a','n/a') ,
('Jojo', 32,'119.11','uk--->usa','pound---&g... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html#pandas-dataframe-applymap" rel="nofollow noreferrer"><code>.applymap()</code></a> to test each individual value in a dataframe.</p>
<pre><code>>>> df
Name Age Balance Country Currenc... | python|python-3.x|pandas|dataframe | 2 |
1,434 | 11,730,984 | hadoop-streaming: reducer doesn't seem to be running when mapred.reduce.tasks=1 | <p>I am running a basic <code>Map Reduce</code> program via <code>hadoop-streaming</code></p>
<p>The <code>Map</code> looks like </p>
<pre><code>import sys
index = int(sys.argv[1])
max = 0
for line in sys.stdin:
fields = line.strip().split(",")
if fields[index].isdigit():
val = int(fields[index])
... | <p>do you get the expected output when you set <code>mapred.reduce.tasks=0</code>? What if you specify <code>-reducer 'cat'</code> with <code>mapred.reduce.tasks=1</code>? One of the neat things about streaming is that you can test it pretty effectively from the command-line using pipes:</p>
<pre><code>cat input | pyt... | python|hadoop|mapreduce|hadoop-streaming | 1 |
1,435 | 58,311,149 | I want to get product of 2 list without using for loop. As with for loop it is taking a lot of time | <p>I want to get product of 2 list without using for loop. As with for loop it is taking a lot of time.</p>
<pre><code>from itertools import product
from string import ascii_lowercase,ascii_uppercase
keywords = [a+b+c for a,b,c in product(ascii_lowercase, repeat=3)]
keywords1 = [a+b for a,b in product(ascii_uppercase,... | <p>If you are looking for the product of the two lists:</p>
<pre><code>from itertools import product
from string import ascii_lowercase,ascii_uppercase
keywords = [a+b+c for a,b,c in product(ascii_lowercase, repeat=3)]
keywords1 = [a+b for a,b in product(ascii_uppercase, repeat=2)]
def fast_list():
return [a+b fo... | python|python-3.x | 2 |
1,436 | 33,813,429 | How do you multiply each digit by different numbers in python? | <p>I want to multiply my 1st digit by 3 then my 2nd digit by 1 then my 3rd digit by 3 then my 4th digit by 1 then my 5th digit by 3 then my 6th digit by 1 then my 7th digit by 1. Im stuck on how to do this</p> | <p>If I understand your question correctly, you want to do something like this:</p>
<pre><code>number = 7568934
multiplier = [3, 1, 3, 1, 3, 1, 1]
for idx, digit in enumerate(str(number)):
print('Res: ' + str(int(digit) * multiplier[idx]))
</code></pre> | python|int | 1 |
1,437 | 37,871,095 | object has no attributes. New to classes in python | <pre><code>import praw
import time
class getPms():
r = praw.Reddit(user_agent="Test Bot By /u/TheC4T")
r.login(username='*************', password='***************')
cache = []
inboxMessage = []
file = 'cache.txt'
def __init__(self):
cache = self.cacheRead(self, self.file)
sel... | <p>Your <code>cacheRead</code> function (as well as <code>bot_run</code> and <code>cacheSave</code>) is indented too far, so it's defined in the body of your other function <code>getPms</code>. Thus it is only accessible inside of <code>getPms</code>. But you're trying to call it from <code>__init__</code>.</p>
<p>I'm... | python|class | 3 |
1,438 | 37,743,656 | key error when no dictionary is required | <p>I have a function which sets the shutter on a camera and takes a float as input:</p>
<pre><code>def changeShutter(value):
global camera, shutter
shutter['abs_value']+=value
try:
camera.set_property(**shutter)
except:
print "could not set shutter"
</code></pre>
<p>where <code>shutter... | <p>As mentioned in the comments above, this was a stupid error where I had 2 different functions of the same name.</p> | python|dictionary | 0 |
1,439 | 37,831,905 | Fast sorting of large nested lists | <p>I am looking to find out the likelihood of parameter combinations using Monte Carlo Simulation.
I've got 4 parameters and each can have about 250 values.
I have randomly generated 250,000 scenarios for each of those parameters using some probability distribution function.
I now want to find out which parameter combi... | <p>You can take out the sorting part, as the final result is a dictionary which will be unordered in any case, then use a dict comprehension:</p>
<pre><code>>>> a = [[1,2],[1,2],[3,4,5],[3,4,5], [3,4,5]]
>>> a_tupled = [tuple(i) for i in a]
>>> b_set = set(a_tupled)
>>> {repr(i): a_... | python|performance|list|python-2.7|count | 1 |
1,440 | 27,804,710 | Python Urllib2 SSL error | <p>Python 2.7.9 is now much more strict about SSL certificate verification. Awesome!</p>
<p>I'm not surprised that programs that were working before are now getting CERTIFICATE_VERIFY_FAILED errors. But I can't seem to get them working (without disabling certificate verification entirely).</p>
<p>One program was us... | <p>To summarize the comments about the cause of the problem and explain the real problem in more detail:</p>
<p>If you check the trust chain for the OpenSSL client you get the following:</p>
<pre><code> [0] 54:7D:B3:AC:BF:... /CN=*.s3.amazonaws.com
[1] 5D:EB:8F:33:9E:... /CN=VeriSign Class 3 Secure Server CA - G3
... | python|ssl|urllib2 | 41 |
1,441 | 43,402,140 | Removing the .0's off data when Python reads data from a csv file | <p>I have successfully gotten the volumes to add up correctly, but it is returning the volume as a decimal. All volumes in the CSV file are whole numbers. I would like to have them without the decimal part.</p>
<p>Code is below.</p>
<pre><code>import pandas as pd
datagrid = pd.read_csv("Daily Receipts.csv")
daily_vo... | <p>When you <code>sum</code> with <code>pandas</code> it converted the results to float.</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow noreferrer"><strong><code>astype(int)</code></strong></a> <--- Link to Docs</p>
<pre><code>import pandas as pd
... | python-3.x|pandas | 1 |
1,442 | 43,214,003 | Python Argparse: Use an empty flag | <p>I'm trying to write a python script using <code>argparse</code> which sets a value to <code>True</code> if <code>-d</code> has been set. </p>
<p>Here is what I'm trying:</p>
<pre><code>parser.add_argument("-d", "--dynamic", required=False)
dynamic = False
if args.dynamic is not None:
dynamic = True
</code></pre... | <p>Use the <em>action</em>:</p>
<pre><code>parser.add_argument("-d", "--dynamic", action='store_true')
</code></pre>
<p>You may drop the "required" kwarg. </p> | python|command-line|args | 10 |
1,443 | 43,289,688 | Creating python scrabble function | <p>I'm trying to create a scrabble function that takes a string of letters and returns the score based on the letters.
This is my code so far: </p>
<pre><code>def scrabble_score(rack):
count = 0
for letter in rack:
if letter == "EAIONRTLSU":
count += 1
return count
... | <p>The code has two issues:</p>
<ul>
<li>The <code>return</code> statement should be called only one time, <strong>after</strong> the <code>for</code> iteration ends, so it can sum all the letter values</li>
<li>each <code>if</code> statement should check if the letter is <strong>in</strong> the string, not if it is e... | python | 0 |
1,444 | 37,003,073 | Facebook messenger bot not sending messages (Python/Django) | <p>I've followed <a href="https://abhaykashyap.com/blog/post/tutorial-how-build-facebook-messenger-bot-using-django-ngrok" rel="nofollow">this tutorial</a> to implement a Facebook Messenger bot that simply echoes what you type. It hooks up ok with Facebook, but I can't make it work beyond that and I can't find the prob... | <p>Try placing the entire function</p>
<pre><code>def post_facebook_message(fbid, recevied_message):
....
</code></pre>
<p>outside of the BotsView class. If you keep it within the class, it must take in "self" as its first parameter and they must be accessed within the class as </p>
<pre><code>self.post_facebook_... | python|django|facebook|facebook-graph-api | 1 |
1,445 | 36,936,688 | How do I make an infinite for loop in Python (without using a while loop)? | <p>Is there way to write an infinite for loop in Python?</p>
<pre><code>for t in range(0,10):
if(t == 9): t= 0 # will this set t to 0 and launch infinite loop? No!
print(t)
</code></pre>
<p>Generally speaking, is there way to write infinite pythonic for loop like in java without using a while loop?</p> | <p>The itertools.repeat function will return an object endlessly, so you could loop over that:</p>
<pre><code>import itertools
for x in itertools.repeat(1):
pass
</code></pre> | python|for-loop | 8 |
1,446 | 48,509,902 | update ListProperty variable after for loop kivy | <p>I am using a for loop to cycle the months of the year and then append them to a list rather than manually type out each month. </p>
<p>The variable <code>self.mylist</code> updates <code>mylist</code> perfectly fine.<br>
When <code>for i in range(1,13):</code> is run it updates <code>self.mylist</code> perfectly f... | <p>So I solved the issue with List comprehensions.<br>
Instead of using a loop outside the variable i want to manupilate list comprehension cut down on length of the code and made updating my variables a non issue.<br>
<a href="https://docs.python.org/3.6/tutorial/datastructures.html#list-comprehensions" rel="nofollow ... | python|python-3.x|kivy|kivy-language | 0 |
1,447 | 48,887,896 | numpy: finding all pairs of numbers in a matrix that suffice on neighboring condition | <p>Suppose you have a matrix: </p>
<pre><code>import numpy as np
mat = np.array([[0, 0, 1], [2, 0, 1], [1, 0, 3]])
</code></pre>
<p>and you want to retrieve all pairs of numbers in this matrix that are neighboring each other, not equal and ignoring zero. In this case this would be 3 & 1 and 2 & 1, but I want ... | <p>This should do the trick, though admittedly, it's not the most elegant; I tested it on a 1000x1000 matrix of random integers, and it was pretty fast (just over a second). I'm not sure how you are thinking about the output, so I put it into a list called res.</p>
<pre><code>import numpy as np
# To test on larger arr... | python|numpy | 1 |
1,448 | 19,983,632 | Python CIM_DataFile search for file by full path | <p>So, I am trying to write a script that will be able to connect to remote systems and query the CIM_DataFile among other things.</p>
<p>For the sake of testing, I wrote the following code to test on my local machine. I have two files (ns.txt and dns.txt) in the root of my C: drive, however, the queries are not worki... | <p>The reason for the <strong>file:wmi.py</strong> inside the <strong>path:Python27\Lib\site-packages</strong>.</p>
<p>I changed this file.</p>
<p>My problem has been resolved.</p>
<p>In fact, the problem is with a library that is installed.</p> | python|wmi | -1 |
1,449 | 19,957,791 | python, replace if/elif with dictionary | <p>Folks,
How would you rewrite the if/elif in the 'checkme' function with a dictionary?</p>
<pre><code>def dosomething(queue):
...
def checkme(queue):
""" Consume Message """
if queue == 'foo':
username = 'foo'
password = 'vlTTdhML'
elif queue == 'bar':
username = 'bar'
password = 'xneoYb... | <p>You could do something like this:</p>
<pre><code>CHECK_ME = {'foo': 'vlTTdhML', 'bar': 'xneoYb2c', 'baz': 'wnkyVsBI'}
def checkme(queue):
username, password = queue, CHECK_ME.get(queue)
#May be some more check here, like
if not password:
print 'password is none'
#Or do something more re... | python | 5 |
1,450 | 48,277,696 | Get current server ip or domain in Django | <p>I have a util method in Python Django project:</p>
<pre><code>def getUserInfo(request):
user = request.user
user_dict = model_to_dict(user)
user_dict.pop("password")
user_dict.pop("is_superuser")
user_dict["head_img"] = user.head_img.url # there is `/media/images/users/head_img/blob_NOawLs1`
</... | <p>You can get the hostname from the request like this (<a href="https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.get_host" rel="noreferrer">docs</a>):</p>
<pre><code>request.get_host()
</code></pre>
<p>and the remote IP of the client like this (<a href="https://docs.djangoproject.... | python|django | 12 |
1,451 | 51,412,369 | Extracting data from specific columns of numpy array for each row | <p>I am trying to obtain the value corresponding to column b[i] for each row i in A</p>
<p>Can I do this without using the for loop?</p>
<pre><code>A = np.array([[35, 2, 23, 22], [44, 21, 15, 4], [44, 21, 15, 4], [37, 4, 17, 41], [33, 4, 4, 18], [35, 2, 23, 22]])
b = np.array([0,1,1,2,3,0])
C = zeros(len(b),1)
for i ... | <p>Since you want to sequentially index the rows of <code>A</code>, you can index with <strong><code>np.arange(len(A))</code></strong> in addition to <code>b</code> to get your desired output:</p>
<pre><code>A[np.arange(len(A)), b]
# array([35, 21, 21, 17, 18, 35])
</code></pre>
<p>Showing how this works:</p>
<pre>... | python|numpy | 1 |
1,452 | 51,413,998 | How to find all occurrence of a key in nested dict, but also keep track of the outer dict key value? | <p>I've searched over stackoverflow and found the following code that allow me to search for a key values in nested dict recursively. However, I also want to keep track of the outer dict's key value. How should I do that?</p>
<p>from Alfe's answer in the below link, I can use the code below get all the values of the k... | <p>functions returns the path as well as value as a list of tuple. </p>
<pre><code>def dict_key_lookup(_dict, key, path=[]):
results = []
if isinstance(_dict, dict):
if key in _dict:
results.append((path+[key], _dict[key]))
else:
for k, v in _dict.items():
... | python|dictionary|nested | 2 |
1,453 | 51,143,854 | Python project: Create a program that keeps track of the items that a wizard can carry | <p><code>show</code> doesn't work and it won't show any of my items</p>
<p>In the first file of my code I have the following content:</p>
<p>items.py:</p>
<pre><code>list(inventory_list):
inventory = ["a wooden staff", "a wizard hat", "a cloak of invisibility",
"some elven bread", "an unknown potion", "a scroll of ... | <p>I think this is more along the lines of what you're looking for. Also, I will help you out because I can see from your code a few places you are struggling, but please review the rules regarding posting questions to SO, because as mentioned this does not fit the profile. And also examine what I'm doing differently a... | python | 0 |
1,454 | 51,140,063 | Distribute executable with python pip | <p>I am trying to distribute a CLI tool for public use. My code contains a executable (written in golang) and a helper python script (used by the executable).</p>
<p>My initial approach was to call the executable from python using this, where main is the entrypoint of the cli command.</p>
<pre><code>import os
import ... | <p>Not a pythonic solution, but for anyone struggling having the same problem, npm allows a <code>bin</code> param in the <code>package.json</code> file, where you can directly link up your executable. </p>
<pre><code>{
"name": "myclipkg",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": ... | python|pip|command-line-interface|setuptools | 0 |
1,455 | 51,469,627 | Should a python file always include a class? | <p>I have been coding in python for a couple months now, and something has always been on my mind. I know you can have classes in your .py file, but you don't have to. My question is, is it good practice to always have your code in a class, or is it not necessary? </p>
<p>FYI: I have been coding in Java for a few year... | <p>It depends on what your file is. In theory everything (saying this with some hesitation) can be written as a class. But it is a bit overkill to do that just for the sake of being "correct" and will probably make your code look strange rather than clear. In general i would make the following distinctions between case... | java|python|class|compilationunit | 1 |
1,456 | 51,148,933 | Simple batch request for Graph API returning Unsupported Post Request error | <p>I'm trying to get public engagement metrics via the Graph API for a list of links. Since there are a lot of them, a batch request is necessary to avoid hitting the rate limits. Using the <a href="https://developers.facebook.com/docs/graph-api/reference/v3.0/url" rel="nofollow noreferrer">engagement endpoint for link... | <p>You need to pass the batch requests using the <code>batch</code> parameter like so:</p>
<p><code>payload = {'batch': json.dumps(batch)}</code></p> | python|facebook|facebook-graph-api|python-requests|facebook-batch-request | 0 |
1,457 | 64,406,845 | extract inner values of a nested dictionary | <p>I have a nested dictionary A and trying to collect all inner values which are basically the float numbers.</p>
<pre><code>A={0:{1:2.3, 2:4.3, 6:2.1}, 1:{3:2.6, 4:4.1, 6:8.1}, 3:{0:2.2, 2:9.3, 4:3.1},5:{1:2.8, 2:5.3, 6:2.1}}
</code></pre>
<p>I am using</p>
<pre><code>col=[A[key][values] for values in A[key]]
</code><... | <p>Try this:</p>
<pre><code>[x for y in A.values() for x in y.values() ]
</code></pre>
<p>Output:</p>
<pre><code>[2.3, 4.3, 2.1, 2.6, 4.1, 8.1, 2.2, 9.3, 3.1, 2.8, 5.3, 2.1]
</code></pre> | python|dictionary|nested|key|extract | 3 |
1,458 | 70,730,475 | how to get "if suite" along with my "else suite" | <p>I have written these simple lines of code to get the current day name, and then using if/else statement wanted to check if it is the current day which is Sunday,and I should receive my <em>if suite</em> , because today is exactly Sunday, but the terminal gives me the <em>else suite</em>. I was wonder what is wrong w... | <p>You are testing if <code>now</code> (a datetime object) is in <code>weeks</code> (string objects). <code>now</code> is not in <code>weeks</code>. No datetime object is in <code>weeks</code></p>
<p>The formatted day name (<code>now.strftime("%A")</code>) might be, but you're not testing that.</p>
<pre><code... | python|list|if-statement | 3 |
1,459 | 69,986,654 | How to send file from Nodejs to Flask Python? | <p>Hope you are doing well.
I'm trying to send pdfs file from <strong>Nodejs</strong> to <strong>Flask</strong> using Axios.
I read files from a directory (in the form of buffer array) and add them into formData (an npm package) and send an Axios request.</p>
<pre><code> const existingFile = fs.readFileSync(path) ... | <p>I solved this issue by updating my <strong>Nodejs</strong> code.
We need to convert formData file into <strong>octet/stream</strong> format.</p>
<p>so I did minor change in my formData code :</p>
<p>before: <code>formData.append("file", existingFile)</code></p>
<p>after: <code>formData.append("file&qu... | python|node.js|flask | 1 |
1,460 | 55,845,002 | How to shuffle data at each epoch using tf.data API in TensorFlow 2.0? | <p>I am getting my hands dirty using TensorFlow 2.0 to train my model. The new iteration feature in <code>tf.data</code> API is pretty awesome. However, when I was executing the following codes, I found that, unlike the iteration features in <code>torch.utils.data.DataLoader</code>, it did not shuffle data automaticall... | <p>The batch needs to be reshuffled:</p>
<pre><code>train_dset = tf.data.Dataset.from_tensor_slices(data_train).\
repeat(1).batch(BATCH_SIZE)
train_dset = train_dset.shuffle(buffer_size=buffer_size)
</code></pre> | python-3.x|tensorflow2.0 | 1 |
1,461 | 66,720,710 | Does "df['var'].map(df2)" and "df.var.map(df2)" always produce the same result? | <p>I have a dataframe <code>df</code> with a column <code>var</code>, and another dataframe <code>df2</code> with columns <code>var</code> and <code>var2</code>. Both columns <code>var</code> in 2 dataframes are exactly the same.</p>
<p>In my example, <code>df['var'].map(df2)</code> and <code>df.var.map(df2)</code> yie... | <p>Yes (as long as the column exists in your data). It's syntactic sugar called <em>attribute access</em>. See the pandas documentation <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#attribute-access" rel="nofollow noreferrer">here</a>.</p> | python|pandas|dataframe | 2 |
1,462 | 71,661,619 | How to adapt tensorflow recommender system tutorial to own data? Issues with Dataset and MapDataset | <p>I am working on a recommender system in tensorflow. What I am trying to do is something similar to <a href="https://www.tensorflow.org/recommenders/examples/quickstart" rel="nofollow noreferrer">tensorflow's quickstart example</a>. However I cannot seem to understand how to replace the Dataset structure(s) with my o... | <p>This reply is a little late, but if you take a look at the value of rating
after the line of code</p>
<pre><code>rating = tf.data.Dataset.from_tensor_slices(df[['song_id', 'user_id']].values)
</code></pre>
<p>You will notice there are no keys in the result, see in the example below how the struture has changed.</p>
... | python-3.x|tensorflow|recommendation-system | 0 |
1,463 | 61,959,682 | Pyspark String to Decimal Conversion along with precision and format like Java decimal formatter | <p>I am trying to convert String to decimal.<br>
I may receive decimal data as below sometimes <br>
<strong>1234.6789-</strong> (- at the end) <br>
In java i can specify format like below to parse above ,<br>
<strong>DecimalFormat dfmt = new DecimalFormat("0000.0000;0000.0000-")</strong> so that i get decimal value as... | <p>You could <code>regexp_reaplace</code> first to move the <code>-</code> sign in front and then <code>cast</code> to <code>DecimalType</code>. Like that you avoid having to use a UDF. Something like this should work:</p>
<pre><code>from pyspark.sql.functions import regexp_replace
...
dframe = dframe.withColumn(
... | python|pyspark|decimal|user-defined-functions | 2 |
1,464 | 66,106,910 | Should a custom keras true positive metric always return an integer? | <p>I'm working with a non-standard dataset, where my <code>y_true</code> is (batch x 5 x 1), and <code>y_pred</code> is (batch x 5 x 1). A batch sample <code>i</code> is "true" if any value of <code>y_true[i] > 0.</code>, and it is predicted "true" if an <code>y_pred[i] >= b</code> where <code... | <p>A two part answer: Yes, the metrics are averaged over the batches. You will see the same behavior with the built-in metrics, eg <code>tensorflow.keras.metrics.TruePositive</code>, but at the end of each epoch it will be an integer.</p>
<p>However, you are not persisting state for your metric, so TensorFlow just take... | tensorflow|keras|metrics|training-data|tf.keras | 1 |
1,465 | 59,419,950 | Unpacking SequenceMatcher loop results | <p>What is the best way to unpack <code>SequenceMatcher</code> loop results in Python so that values can be easily accessed and processed? </p>
<pre><code>from difflib import *
orig = "1234567890"
commented = "123435456353453578901343154"
diff = SequenceMatcher(None, orig, commented)
match_id = []
for block in dif... | <h1>1. Unpacking <code>SequenceMatcher</code> results to yield a sequence</h1>
<p>You can unzip <code>match_id</code> and then use a list comprehension with your expression.</p>
<pre class="lang-py prettyprint-override"><code>a, b, size = zip(*match_id)
# a = (0, 4, 6, 10)
# b = (0, 7, 16, 27)
# size = (4, 2, ... | python|iterable-unpacking | 1 |
1,466 | 59,110,069 | Predicting the Trajectories of Planets Using Polyfit | <p>I'm simulating the three body problem and graphed the trajectories in 3D. I'm trying to figure out how I can predict the trajectories of these planets by extending the plot lines using np.polyfit. I have experience in doing this with dataframes and on 2D plots, but not in 3D and without using any sort of dataframe. ... | <p><code>np.polyfit</code> returns an array of coefficients:</p>
<pre class="lang-py prettyprint-override"><code>>>> np.polyfit(np.arange(4), np.arange(4), 1)
array([1.00000000e+00, 1.12255857e-16])
</code></pre>
<p>To turn this into a callable polynomial, use <code>np.poly1d</code> on the result:</p>
<pre ... | python|numpy|matplotlib | 1 |
1,467 | 62,960,941 | Merge 2 dataframes using the first column as the index | <pre><code>df 1:
Condition Currency Total Hours
0 Used USD 100
1 Used USD 75
2 Used USD 13
3 Used USD NaN
df 2:
Condition Currency Total Hours
1 Used USD 99
3 New USD 1000
Desired ... | <p>Try <code>update</code>:</p>
<pre><code>df.update(df2)
print(df)
</code></pre>
<p>Output:</p>
<pre><code> Condition Currency Total Hours
0 Used USD 100.0
1 Used USD 99.0
2 Used USD 13.0
3 New USD 1000.0
</code></pre> | python-3.x|pandas|dataframe | 1 |
1,468 | 35,714,452 | problems with using string.join() operator | <p>I tested out the <code>string.join()</code> method on a few lines of code:</p>
<pre><code>a = 1
b = 1
c = 0
superpower = []
if a == 1:
superpower.append("flying")
if b == 1:
superpower.append("soaring")
if c == 1:
superpower.append("high")
", ".join(superpower)
print superpower
</code></... | <p><code>", ".join(superpower)</code> <em>returns</em> a string, it doesn't convert the input iterable into a string. You aren't doing anything with that return value:</p>
<pre><code>superpower_str = ', '.join(superpower)
print(superpower_str)
</code></pre>
<p>is probably what you want.</p> | python | 5 |
1,469 | 60,070,016 | Sampled softmax loss eval code works but function call results in ValueError | <p>I am implementing the skip-gram model in a federated learning setup. I get the inputs and label in the following way:</p>
<pre><code>train_inputs_embed = tf.nn.embedding_lookup(variables.weights, batch['target_id'])
train_labels = tf.reshape(batch['context_id'], [-1, 1])
</code></pre>
<p>When I define the loss a... | <p>Reshaping the train_inputs_embed resolved the error</p>
<pre><code>train_inputs_embed = tf.reshape(tf.nn.embedding_lookup(variables.weights, batch['target_id']), [-1, embedding_size])
</code></pre> | tensorflow|tensorflow-federated | 0 |
1,470 | 72,228,867 | Django model default value in response | <p>I want to have a default value in my django model response value</p>
<p>Sample model query</p>
<pre><code>myModel.objects.filter().values("username", "user_gender")
</code></pre>
<p>I want to have a default value in response</p>
<p>It must be like</p>
<pre><code>Select username, user_gender, 'del... | <p>You can add additional value to queryset using <a href="https://docs.djangoproject.com/en/4.0/ref/models/expressions/#value-expressions" rel="nofollow noreferrer"><code>Value</code></a> expression:</p>
<pre><code>from django.db.models import CharField, Value
myModel.objects.filter().values("username", &qu... | python-3.x|django|django-models|django-rest-framework|django-views | 1 |
1,471 | 72,455,032 | Group strings in a pandas dataframe column which share a common parent three or more times | <p>I'm trying to find and group strings in a dataframe column which share a common parent three or more times.</p>
<p>I have two columns taken from a google search. One containing the keyword used in the search, and another containing the domain returned.</p>
<p>If a keyword shares the same domain four times with anoth... | <p>Here is a solution that works for you example. Count the number of occurrences of each url/keyword, keep counts of 3+ and then keep only url which have at least 2 keywords meeting that criteria.</p>
<p>We can then turn each url into a number using <code>cat.codes</code></p>
<pre><code>import pandas as pd
d= {
... | python | 0 |
1,472 | 65,761,463 | Python to fit a linear-plateau curve | <p>I have curve that initially Y increases linearly with X, then reach a plateau at point C.
In other words, the curve can be defined as:</p>
<pre><code>if X < C:
Y = k * X + b
else:
Y = k * C + b
</code></pre>
<p>The training data is a list of X ~ Y values. I need to determine k, b and C through a machine... | <p>WLOG you can say the second equation is</p>
<pre><code>Y = C
</code></pre>
<p>looks like you have a linear regression to fit the line and then a detection point to find the constant.</p>
<p>You know that in the high values of <code>X</code>, as in <code>X > C</code> you are already at the constant. So just check... | pandas|machine-learning|scikit-learn|scipy | 0 |
1,473 | 50,953,413 | How do I ignore blank space in a spreadsheet while making a DataFrame? | <p>I have an Excel file that looks like this-</p>
<p><a href="https://i.stack.imgur.com/LFFYj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LFFYj.png" alt="enter image description here"></a></p>
<p>I want to ignore all blank rows INCLUDING the BSE_IDA.INTV_R (Temporary Table) part and use the col... | <p>the pandas read_excel function has a skiprows parameter, it helps you to specify the row to skip when reading your file.</p>
<p>From <a href="http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.read_excel.html" rel="nofollow noreferrer">the doc</a>s it's said :</p>
<blockquote>
<p>skiprows : list-... | python|python-2.7|pandas|dataframe | 3 |
1,474 | 57,814,017 | How to loop with Python sockets? | <p>I was planning to do a Hostname to Ip script using socket.gethostbyname() but it seems like it's not functioning </p>
<p>I've tried to input the host's list from a .txt file and loop through it, it worked only when there is no more than one host in the list which that makes it trash. I tried combining the hosts int... | <p>The result of <code>readlines()</code> include the newline characters (<code>\n</code> or <code>\r\n</code>) of every line in the file, so you are actually passing <code>'youtube.com\n'</code> to <code>gethostbyname()</code>.</p>
<p>Using <code>strip()</code> on the parameter will remove any trailing whitespace:</p... | python|sockets|proxy | 0 |
1,475 | 42,548,392 | How to debug skflow code (tensorflow) gmm_ops.py? | <p>Hi I am new to tensorflow. I want to debug Tensorflow (skflow) gmm_ops.py (Gaussian Mixture Model). I am getting ERROR:tensorflow:Model diverged with loss = NaN.
How should I do it ? Is there any example?</p>
<pre><code> raise NanLossDuringTrainingError
tensorflow.python.training.basic_session_run_hooks.NanLossD... | <p>Usually a NanLoss means something overflowed or underflowed during training. Things such as normalizing the examples or processing a subset of the data tend to help debugging what could have caused this.</p> | python-3.x|tensorflow|skflow | 0 |
1,476 | 58,526,001 | List all S3 keys between start date(inclusive) and end date(exclusive) | <p>Is there a way to list all s3 files between specified dates. The start date can be passed as a prefix. I have a confusion as to how to pass the end date. Please can any help.</p>
<pre><code>import boto3
def get_matching_s3_objects(bucket, prefix=''):
"""
Generate objects in an S3 bucket.
:param bucke... | <p>AFAIK there is no direct way to filter by date using boto3, the only <a href="https://boto3.amazonaws.com/v1/documentation/api/1.9.42/reference/services/s3.html#object" rel="nofollow noreferrer">filter available</a> are <code>Bucket</code>, <code>Delimiter</code>, <code>EncodingType</code>, <code>Marker</code>, <cod... | python|amazon-s3|boto3|prefix | 1 |
1,477 | 57,128,900 | Trying to load a page and cycle through proxies each time | <p>I'm currently trying to learn Python by doing small little silly projects to try and get my head around certain bits but I have hit a bit of a brick wall. I'm wanting to make something that will visit a page using a proxy list I have in a .txt file. I want it to load up the web page with the first proxy in the file,... | <p>You need to pass proxies as a dict</p>
<pre><code>import requests
proxyList = 'proxies.txt'
file = open(proxyList, "r")
url = input('Website: ')
for line in file:
print(line, end="")
proxies = {'http': line.strip(), 'https': line.strip()}
r = requests.get(url, proxies=proxies)
print('Finished.')
inp... | python|python-requests | 2 |
1,478 | 43,640,238 | six: cannot import name python_2_unicode_compatible | <p>With <code>six 1.10.0</code> installed under Python and pip 2.6, an old Django 1.0.4 app is not able to import <code>python_2_unicode_compatible</code> even though it finds <code>six</code> 1.10.0 just fine:</p>
<pre><code>>>> import six
>>> six.__version__
'1.10.0'
>>> from six import py... | <p>The <code>python_2_unicode_compatible</code> method was originally in Django, then added to <code>six</code> in 1.9.</p>
<p>One of your installed packages may be trying to import <code>python_2_unicode_compatible</code> from <code>django.utils.encoding</code>, rather than from the <code>six</code> package.</p> | python|django|six | 3 |
1,479 | 54,341,810 | How to print loss value which was set in keras backend function | <p>I am new to keras.
The below code snippet is for policy gradient loss function.
I tried to print the loss value to see if the loss value could be negative for policy gradient. but I couldn't.
Is there any way to print it?</p>
<p>I found some ways, but it uses keras history and seems like you can get history from mo... | <p>you may use for loop for train like epochs:</p>
<pre><code>for epoch in epochs:
train=K.function(..)
K.print_tensor(loss, message='{} Epochs Training Loss = '.format(epoch))
</code></pre> | python|tensorflow|keras | 0 |
1,480 | 27,177,999 | getting socket id of a client in flask socket.io | <p>Is there a way to get socket id of current client? I have seen it is possible to get socket id in node.js. But it seems flask's socket.io extension is a little bit different than node's socketio.</p> | <p>From <a href="https://flask-socketio.readthedocs.io/en/latest/" rel="noreferrer">Flask-SocketIO documentation</a>:</p>
<blockquote>
<p>The request object defines <code>request.namespace</code> as the name of the namespace being handled, and adds <code>request.sid</code>, defined as the unique session ID for the c... | python|flask|socket.io | 14 |
1,481 | 46,588,494 | Python Logical Error in Loop while reading Dictionary | <p>I am new to python and OOPS.I am expecting my module add_book to increment if book is already present in dictionary. Please help me .Not sure why for loop is not working as expected.</p>
<p><a href="https://github.com/amitsuneja/Bookstore/commit/4aefb378171ac326aacb35f355051bc0b057d3be" rel="nofollow noreferrer">ht... | <p>You should not append to the list while you are still iterating it. Also, your code will append the new item for <em>each</em> item already in the list that has a different name. Instead, you should use a <code>for/else</code> loop. Here, the <code>else</code> case will only be triggered if you do not <code>break</c... | python|oop | 1 |
1,482 | 60,884,078 | Use a list in prepared statement | <p>I want to use a Python <code>list</code> (or a <code>set</code> actually) in my <code>execute</code>, but I don't quite get it.</p>
<pre><code>BRANDS = {
'toyota',
'ford',
'dodge',
'spyker'
}
cur = connection.cursor()
cur.execute("SELECT model FROM cars WHERE brand IN (%s)", (list(BRANDS),)
</code></pre>
... | <p>psycopg2 converts lists to <em>arrays</em>, and <code>(%s)</code> means a single value inside a tuple, so that's obviously not correct.</p>
<p>What you want to do is either:</p>
<ul>
<li>let postgres convert a tuple to a tuple
<pre class="lang-py prettyprint-override"><code>cur.execute("SELECT model FROM cars WHE... | python|list|set|prepared-statement|psycopg2 | 1 |
1,483 | 49,355,010 | How do i watch python source code files and restart when i save? | <p>When I save a python source code file, I want to re-run the script. Is there a command that works like this (sort of like nodemon for node)?</p> | <p>While there are probably ways to do this within the python ecosystem such as watchdog/watchmedo ( <a href="https://github.com/gorakhargosh/watchdog" rel="noreferrer">https://github.com/gorakhargosh/watchdog</a> ), and maybe even linux scripting options with inotifywait ( <a href="https://linux.die.net/man/1/inotifyw... | python|nodemon | 122 |
1,484 | 20,966,389 | how to update the new module in openerp 7 in ubuntu 12.0? | <p>Done,all the possible ways for updating the new module in openerp 7 in ubuntu 12.0.</p>
<p>Is there any other way to update the new module in openerp 7 in ubuntu 12.0 ?</p>
<pre><code> can anyone help me..
</code></pre> | <ul>
<li>Put your module under <strong>addons/</strong> directory </li>
<li>restart your server</li>
<li>Go to <strong>OpenERP Menu</strong> Setting -> Modules -> Update Modules List and Update than</li>
<li>Go to <strong>OpenERP Menu</strong> Setting -> Modules -> Installed Modules and search your module name</li>
</u... | python-2.7|openerp|postgresql-9.1 | 1 |
1,485 | 21,109,521 | Pandas: plot multiple columns to same x value | <p>Followup to a <a href="https://stackoverflow.com/questions/21089154/pandas-selecting-multiple-columns-from-one-row">previous question</a> regarding data analysis with pandas. I now want to plot my data, which looks like this:</p>
<pre><code>PrEST ID Gene Sequence Ratio1 Ratio2 Ratio3
HPRR12 ATF1... | <p>Skipping some of the finer points of plotting, to get:</p>
<ul>
<li>Each row (3 ratios) should be plotted against the row's ID, as points</li>
<li>All rows with the same ID should be plotted to the same x value / ID, but with another colour</li>
<li>The x ticks should be the IDs, and (if possible) the corresponding... | python|matplotlib|plot|pandas | 6 |
1,486 | 21,368,815 | Is random.randint() in Python truly random? | <p>So I was using the random module in Python with some loops and was printing out a batch of numbers to check what they looked like. I noticed that when I input: </p>
<pre><code>random.randint(0,100000)
</code></pre>
<p>most of the numbers would be six figure numbers with a few at five figures and fewer at 4. There ... | <p>Between 0 and 100000, 90% of the numbers have 5 figures! Only 0.01% have 1 figure. So the behavior is what I'd expect.
EDIT: And note what ignacio says. The numbers are definitely not "truly" random as that would require some sort of quantum event. They are "pseudo" random numbers.</p> | python|random | 5 |
1,487 | 62,736,870 | Django: How to sort Query set based on another function outside of class | <p>I am trying to sort my Post objects based on a function that gets the score of every object. My score function is:</p>
<pre><code>def score(up, down):
return up - down
z = log(max(abs(score), 1), 10)
</code></pre>
<p>And I was trying to get the QuerySet by using:</p>
<pre><code>Post.objects.all().annotate(scor... | <p>considering your <code>up</code> and <code>down</code> is two different integer field meaning two separate columns in your table you can do this with <code>F Objects</code></p>
<pre class="lang-py prettyprint-override"><code>from django.db.models import F
scores = Post.objects.annotate(score=(F("up") - F(... | python|django|django-models|django-views | 0 |
1,488 | 53,543,654 | How to remove elements from a list under some conditions? | <p>I want to implement Binary Search algorithm in python considering the following list:</p>
<pre><code>Fibonacci_Seq = [1,1,2,3,5,8,13,21,34,55,89]
</code></pre>
<p>So, I wrote a function to do the calculation but when I came down to this block of code, I didn't know what to do:</p>
<pre><code>min = Fibonacci_Seq[0... | <p>Do a modified Binary Search to find the index of that first element which is greater than or equal to 22 and then just slice the existing list. </p>
<p>In your case the index is <code>8</code> such that <code>Fibonacci_Seq[8]=34</code> and then just slice your list as <code>Fibonacci_Seq=Fibonacci_Seq[8:]</code>.</... | python|binary-search | 1 |
1,489 | 33,439,966 | Pandas drop rare entries | <p>I'm new to Pandas.
To simplify, I have a data frame with two columns: product_id and rating. Each entry is a new review for the given product.
Now I want to get a new data frame in which lines corresponding to the product which received less then 20 reviews (ie. appears less then 20 times in the original data frame... | <p>You want to <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration" rel="nofollow"><code>filter</code></a>:</p>
<pre><code>a = data.groupby('product_id').filter(lambda x: len(x) > 20)
</code></pre> | python|pandas|group-by | 3 |
1,490 | 33,239,211 | Django ORM for select max(field1) from table group by (field2); | <p>I have the following model:</p>
<pre><code>class Transition(models.Models):
id = models.AutoField(primary_key=True)
transition_type = models.IntegerField(dbcolumn='transition_typeid')
instance = models.IntegerField(dbcolumn='instanceid')
ts = models.DateTimeField()
class Meta:
managed=False
db_tab... | <p>This query should work for you </p>
<pre><code>Transition.objects.values('instance').annotate(Max('id'))
</code></pre>
<p>docs : <a href="http://docs%20aggregation" rel="nofollow">https://docs.djangoproject.com/en/1.8/topics/db/aggregation/</a></p> | python|mysql|django|django-orm | 1 |
1,491 | 73,594,284 | How to add extra sign to already existing x-ticks label matplotlib? | <p>Currently, my histogram plot's x-tick labels are [200. 400. 600. 800. 1000. 1200. 1400.]. It represents the rate in dollars. I want to add $ in prefix of these ticks like [$200 $400 $600 $800 $1000 $1200 $1400].</p>
<p>I tried this <code>axs.xaxis.get_majorticklocs()</code> to fetch x-tick labels and <code>axs... | <p>You can use automatic <code>StrMethodFormatter</code> like this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))
# Use automatic StrMethodFormatter
ax.xaxis.set_major_formatter('${x:1.2f}')
plt.show()
</code></pre>
<p><a href="https://i.st... | python|matplotlib | 3 |
1,492 | 21,771,966 | Connect to raspberry pi from a web server | <p>I have a Raspberry pi on my home network. This is set up on my router, so it has a 192.168.x.x IP address. I have a python server running on my pi that is listening for incoming connections on a fixed port (48000).</p>
<p>I would like to connect to this raspberry pi from a machine that is on my work network (IP add... | <p>You should register with a free DNS service, such as no-ip (<a href="https://www.noip.com/managed-dns" rel="nofollow">https://www.noip.com/managed-dns</a>) and configure dynamic dns with your router (given it is able to do so). Then your router is always available at a given hostname. A potential domain for you coul... | python|linux|networking|raspberry-pi | 2 |
1,493 | 24,613,618 | Python regex insert | <p>I have a String s</p>
<pre><code>s = "x01777"
</code></pre>
<p>Now I want to insert a <code>-</code> into s at this position:</p>
<pre><code>s = "x01-777"
</code></pre>
<p>I tried to do this with <code>re.sub()</code> but I can't figure out how to insert the <code>-</code> without deleting my regex (I need this ... | <p>Capture the first three characters into a group and then the next three to another group. In the replacement part just add <code>-</code> after the first captured group followed by the second captured group.</p>
<pre><code>>>> import re
>>> s = "x01777"
>>> m = re.sub(r'(\w\d\d)(\d\d\d)'... | python|regex | 24 |
1,494 | 40,833,744 | CSV Load Error with Pandas | <p>Can someone help me figure out what this error is telling me? I don't understand why this csv won't load.</p>
<p>Code:</p>
<pre><code>import pandas as pd
import numpy as np
energy = pd.read_csv('Energy Indicators.csv')
GDP = pd.read_csv('world_bank_new.csv')
ScimEn = pd.read_csv('scimagojr-3.csv')
</code></pre>
<... | <p>The <code>read_csv</code> function takes an <code>encoding</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">option</a>. You're going to need to tell Pandas what the file encoding is. Try <code>encoding = "ISO-8859-1"</code>.</p> | python|csv|pandas | 2 |
1,495 | 40,823,302 | GridLayout Not Scrolling in Kivy | <p>Please tell me why this doesn't work, the whole program works fine, it uses a function inside the main program to get it's text, but it won't scroll so the user won't be able to view the entire output.</p>
<pre><code><AnswerScreen@Screen>:
input_textb: input_textb
ScrollView:
size_hint: (1, No... | <p>I believe the label's size is not set, which i agree can be confusing at first, Label has a widget size (<code>size</code> as all widgets) and a <code>texture_size</code>, which is set to the actual size of the displayed text, kivy doesn't relate these two in any particular way at first, and it's up to you to decide... | python|scrollview|kivy | 1 |
1,496 | 38,391,125 | Stream Analytics deserialising JSON from Python via Event Hub | <p>I have set up an Azure Event Hub and I am sending AMQP messages in JSON format from a Python script, and am attempting to stream those messages to Power BI using Stream Analytics.
The messages a very simple device activity from and IoT device</p>
<p>The Python snippet is</p>
<pre><code>msg = json.dumps({ "Hub": MA... | <p>This is caused by client API incompatibility. Python uses Proton to send the JSON string in the body of an AMQP Value message. The body is encoded as an AMQP string (AMQP type encoding bytes + utf8 encoded bytes of string). Stream Analytics uses Service Bus .Net SDK which exposes AMQP message as EventData and its bo... | python|json|azure|amqp|asa | 3 |
1,497 | 40,231,957 | Python - appending to multiple arrays | <p>If I wanted to perform something like Levene's test of equal variances via scipy stats, which produces two outputs (the test statistic and p-value) for all the data in a dictionary, how would I append the outputs for each test to two different lists? I tried the code below:</p>
<pre><code>test_stat[]
p_value[]
for ... | <p>Not everything needs to be in a single line... This should work fine:</p>
<pre><code>test_stats = []
p_values = []
for i in range(0, n_data):
for j in range(1, n_name):
test_stat, p_value = scipy.stats.levene(data[i][name[j-1]],
data[i][name[j]],
... | python|arrays|scipy|append | 1 |
1,498 | 40,110,207 | Anaconda OpenCV Arch Linux libselinux.so error | <p>I have installed Anaconda 64 bit on a relatively fresh install of Arch.</p>
<p>I followed the instructions <a href="https://rivercitylabs.org/up-and-running-with-opencv3-and-python-3-anaconda-edition/" rel="nofollow">here</a> to set up a virtual environment for opencv:</p>
<pre><code>conda create -n opencv numpy s... | <p>Fixed with installing the libselinux package in the AUR:</p>
<pre><code>yaourt -S libselinux
</code></pre>
<p>I now have <strong>another</strong> problem:</p>
<pre><code>ImportError: /usr/lib/libpangoft2-1.0.so.0: undefined symbol: FcWeightToOpenType
</code></pre>
<p>Solved as in issue <a href="https://github.co... | python|linux|opencv|anaconda | 2 |
1,499 | 40,273,329 | How to go back to a line of code in python if a condition is met? | <p>Basically, I am trying to create a game. It's going well so far! However, I am trying to figure out how to make code go back. I am a beginner at python, so I think its something to do with <code>def start():</code> and <code>start():</code> - or something along those lines - but I'm not sure.</p>
<p>If you do not kn... | <p>You want to use a while loop</p>
<pre><code>while <condition>:
(1) if (variable == whatever):
(2) print ("Cool you win")
(4) #nothing needed here
(5) else:
(6) print ("You loose!")
(7) #nothing needed here
</code></pre>
<p>If you don't have a particular condition, you can just loop forever with <code... | python|loops | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.