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 |
|---|---|---|---|---|---|---|
4,600 | 2,200,027 | which is more efficient for buffer manipulations: python strings or array() | <p>I am building a routine that processes disk buffers for forensic purposes. Am I better off using python strings or the array() type? My first thought was to use strings, but I'm trying to void unicode problems, so perhaps array('c') is better?</p> | <p>Write the code using what is most natural (strings), find out if it's too slow and then improve it. </p>
<p>Arrays can be used as drop-in replacements for <code>str</code> in most cases, as long as you restrict yourself to index and slice access. Both are fixed-length. Both should have about the same memory require... | python|arrays|performance | 9 |
4,601 | 63,241,770 | How to get a file name inside a particular folder and pass that file name into a for loop index? | <p>I have a folder named <strong>test</strong> ,which contains <strong>11.txt,12.txt,13.txt</strong></p>
<p>I need to read the content of the <strong>test</strong> folder , find the largest text file name and pass it into for loop starting index :</p>
<pre><code>def find_largest_index(file_path):
txt_files = glob.glo... | <pre><code>import os
filenames = [int(filename[:-4]) for filename in os.listdir(file_path) if ( filename.endswith('.txt') and not filename.startswith('running') )]
i = max(filenames)
</code></pre> | python|python-3.x|glob | 1 |
4,602 | 55,005,554 | join new columns to redshift/sql table from another table | <p>I'm new to sql/redshift and am looking for the best way to merge to tables.</p>
<p>I have a large(ish) table in redshift (Around 2k cols by 50k rows). The table has a datetime sortkey. I'm pulling the sortkey and 1 other column iteratively into in a python/pandas dataframe performing some (fairly complicated) opera... | <p>You can that "the original table is not updated" with this command:</p>
<pre><code>SELECT * FROM table1
FULL OUTER JOIN pandasdf ON (table1.datetime = pandasdf.datetime)
</code></pre>
<p>A <code>SELECT</code> command in SQL <em>returns</em> data. It does <em>not</em> update data.</p>
<p>If you wish to create a ne... | python|sql|pandas|amazon-web-services|amazon-redshift | 1 |
4,603 | 28,337,298 | configuring web.py in nginx.. confusion | <p>Hi I am new with nginx server, and I have uploaded my <code>index.py</code> file at <code>/var/www/pyth/index.py</code> ...</p>
<p>I am a little bit confused because in my local I can run freely
<code>python index.py</code> and access <code>http://127.0.0.1:8080</code></p>
<p>I was wondering how can I do that in ... | <p>You should set up either a <a href="https://uwsgi-docs.readthedocs.org/en/latest/" rel="nofollow">uwsgi</a> (or similar), or a <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass" rel="nofollow"><code>proxy_pass</code></a> in nginx.
The option with UWSGI is better because it'll use the proto... | python|nginx|web.py | 2 |
4,604 | 28,105,718 | Is there a way to inhibit rounding in python? | <p>is there a way to inhibit python rounding, e.g.:</p>
<pre><code>>>> getcontext().prec = 11; print (Decimal(1.1237836550999999999)*10**10)
11237836551
</code></pre>
<p>I need to show the first 10 decimal places of the decimal number, so actually I need <code>11237836550</code> as output and I do not need t... | <p>You problem is not <code>Decimal</code>. It's <code>float</code>. Namely:</p>
<pre><code>>>> 1.1237836550999999999
1.1237836551
</code></pre>
<p>But if you do:</p>
<pre><code>>>> int(Decimal("1.1237836550999999999")*10**10)
11237836550
</code></pre>
<p>You are good to go. Use strings when... | python|decimal|rounding | 7 |
4,605 | 44,220,692 | Python IDLE less or more? | <p>Getting a list of <code>__builtins__</code> in IDLE how do I pause it after a certain number or bottom of the screen? </p>
<p>This gives me one at a time..</p>
<pre><code>>>> for i in dir(__builtins__):
... print i
... raw_input("Press Enter...")
</code></pre>
<p>and I could slice it like ... <... | <p>Try something like:</p>
<pre><code>print_every = 5
for i, f in enumerate(dir(__builtins__)):
print f
if i % print_every == 0 and i != 0:
raw_input("Press Enter...")
</code></pre>
<ul>
<li><code>enumerate</code> pairs each entry in the list with its index in the list </li>
<li><code>if i % print_e... | python | 0 |
4,606 | 14,081,450 | How do you invoke a function on a bunch of lines selected via Ctrl-v? | <p>I am selecting some text via Ctrl-v (visual mode). Then I type
\s to align those lines and sort them like so:</p>
<pre><code>"Strip trailing space
:map <Leader>S :1,$ s/\s\+$//g<CR>
:imap <Leader>S :1,$ s/\s\+$//g<CR>
</code></pre>
<p>How do I pass all the selected lines to Sort(). I thoug... | <p>When you want a mapping to work on the visual selection, you need to use <code>:vnoremap</code>. An Ex command (like <code>:call</code>) will then automatically have the visual range <code>'<,'></code> prepended. An ordinary function would then be invoked once per line, but you can define a special kind of fun... | python|vim | 2 |
4,607 | 27,086,341 | How to login to ASP website using python | <p>I am trying to login to a ASP website using python. Here is what the login page looks like.</p>
<pre><code> <div class="menuitem">
<form id="login" action="public.asp?sid=new" method="post">
<ol>
<li>
<label for="username">Username:</... | <p>I would simply use the <a href="https://pypi.python.org/pypi/requests" rel="nofollow">request</a> module. It is really simple in comparison with urllibs...</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
session = requests.session()
payload = {'username': username, 'password': password}... | python|authentication|asp-classic|urllib | 0 |
4,608 | 12,091,353 | Hindi or Farsi numbers in django templating engine | <p>I want to print {{forloop.counter}} with persian or Hindi encoding means to have "۱ ۲ ۳ ۴ .." instead of "1 2 3 4 ...". I searched a lot but I couldn't find any related functions. Would you mind helping me?</p>
<p>Regards</p> | <p>You could use a <a href="https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters">custom template filter</a>. I'm not familiar enough with Django's l10n library to know if they do this for you.</p>
<pre><code>def devanagari_int(arabic_int):
""" Converts an arabic numera... | python|django|django-templates|persian|hindi | 6 |
4,609 | 23,233,935 | using while loop to check errors with inputs in a list | <p>i've been making a program on python...</p>
<pre><code>selected_pizzas=[] #creates an empty list
for n in range(pizza_number):
selected_pizzas = selected_pizzas + [int(input("Choose a pizza: "))]
</code></pre>
<p>that will let the user input up to 5 numbers and store them in an empty list (selected_pizzas) t... | <p>You could do:</p>
<pre><code>selected_pizzas=[] #creates an empty list
while len(selected_pizzas) < pizza_number:
try:
pizza_selection = int(input("Choose a pizza: "))
except ValueError:
print("Not a number, Try again")
else:
if 1 <= pizza_selection <= 11:
s... | python|list|while-loop | 1 |
4,610 | 7,756,619 | Python __repr__ and None | <p>I'm quite new to Python and currently I need to have a <code>__repr__</code> for a SqlAlchemy class.
I have an integer column that can accept <code>Null</code> value and SqlAlchemy converts it to <code>None</code>.
For example:</p>
<pre><code>class Stats(Base):
__tablename__ = "stats"
description = Column(Str... | <p>The <code>__repr__</code> should return a string that describes the object. If possible, it should be a valid Python expression that evaluates to an equal object. This is true for built-in types like <code>int</code> or <code>str</code>:</p>
<pre><code>>>> x = 'foo'
>>> eval(repr(x)) == x
True
</c... | python|sqlalchemy|repr | 12 |
4,611 | 244,438 | Map two lists into one single list of dictionaries | <p>Imagine I have these python lists:</p>
<pre><code>keys = ['name', 'age']
values = ['Monty', 42, 'Matt', 28, 'Frank', 33]
</code></pre>
<p>Is there a direct or at least a simple way to produce the following list of dictionaries ?</p>
<pre><code>[
{'name': 'Monty', 'age': 42},
{'name': 'Matt', 'age': 28},
... | <p>Here is the zip way</p>
<pre><code>def mapper(keys, values):
n = len(keys)
return [dict(zip(keys, values[i:i + n]))
for i in range(0, len(values), n)]
</code></pre> | python|dictionary|list | 14 |
4,612 | 42,102,228 | Analysis of algorithm run time iterative for loops | <p>If i have the following code</p>
<pre><code>def func(A,n):
for i in A-1:
for k in A-1:
for l in A-1
if A[i]+A[k]+A[l] = 0:
return True
else:
return False
</code></pre>
<p>How can i analyze the run time for this algorith... | <p>As the comments said, the code as is now is O(1) since it will exit out of <code>func</code> after a single pass every time.</p>
<p>If you did change the returns to something else, like setting a variable, then it would become O(n^3). </p>
<p>To explain how you get to that value, I'm going to reduce the problem t... | python|arrays|algorithm|array-algorithms | 1 |
4,613 | 47,514,329 | Specifying input/output nodes to run inference in TensorFlow 1.0+ on a model loaded with the C++ API | <p>I'm loading a V2 checkpoint with the TensorFlow 1.4 C++ API, which is fairly straightforward following this answer: <a href="https://stackoverflow.com/a/43639305/9015277">https://stackoverflow.com/a/43639305/9015277</a> . However, this answer does not specify the how the inputs can be fed to the loaded network.</p>
... | <p>Well, I was not getting any useful answers, so finally I ended up just using the old C++ API instead (which BTW still works in r1.4). I'm still looking for an answer how this should be done with the new API.</p>
<p>In the old TF API Session::Run is as follows:</p>
<pre><code>virtual Status Run(
const std::vector... | c++|machine-learning|tensorflow | 2 |
4,614 | 70,857,918 | Insert 2d Array into Table without importing sqlalchemy Table Column etc objects? | <p>I'm writing an app in Python and part of it includes an api that needs to interact with a MySQL database. Coming from sqlite3 to sqlalchemy, there are parts of the workflow that seem a bit too verbose for my taste and wasn't sure if there was a way to simplify the process.</p>
<h4>Sqlite3 Workflow</h4>
<p>If I wante... | <p>I didn't know SQLite allowed weakly typed columns as your demonstrated in your example. As far as I know most other databases, mysql and postgresql, will require strongly typed columns. Usually the table metadata is either reflected or pre-defined and used. Sort of like type definitions in a statically typed lang... | python|mysql|sqlalchemy | 1 |
4,615 | 70,879,918 | Alternative to irregular nested np.where clauses | <p>I'm struggling to simplify my irregular nested np.where clauses. Is there a way to make the code more readable?</p>
<pre><code> df["COL"] = np.where(
(df["A1"] == df["B1"]) & (df["A1"].notna()),
np.where(
(df["A1"] == df["C"]),
... | <p>Using <code>np.select</code> as suggested by @sammywemmy:</p>
<pre><code># Create boolean masks
m1 = (df["A1"] == df["B1"]) & (df["A1"].notna())
m11 = (df["A1"] == df["C"])
m12 = (df["A"] == df["B"]) & (df["A"].notna())
m111 = (d... | python|pandas|numpy | 3 |
4,616 | 71,032,312 | Code Question - Encrypt the elements in a list by using lambda and map functions in Python | <p>Encrypt the Elements in a List
Description
A company stores the names of its employees in a list. It wants to encrypt the names so that no one can read them and the data remains safe. One of the steps in this encryption is to reverse each name on the list and convert it to uppercase. Your task is to write Python cod... | <pre><code>names = ['Ronaldo', 'Cristiano', 'Rakesh', 'Ronak']
output = list(map(lambda x: x[::-1].upper(), names))
</code></pre> | python | 1 |
4,617 | 46,754,592 | How to shuffle the contents of a text file in groups of n lines in Python | <p>Let's say the text file is this:</p>
<pre><code>1
2
3
4
5
6
...
</code></pre>
<p>What I want is to randomely order the contents in groups of N lines, without shuffling the lines in each group, like this:</p>
<pre><code>#In this case, N = 2.
5
6
1
2
7
8
...
</code></pre>
<p>My file isn't huge, it will be less th... | <p>You tried to join a list of lists; flatten them first:</p>
<pre><code>with open("data.txt", "w") as file:
file.write("\n".join(['\n'.join(g) for g in groups]))
</code></pre>
<p>You could use any of the <a href="https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-c... | python|file | 3 |
4,618 | 37,925,802 | Order of response in Google Adwords API | <p>Are there any guarantees the Google Adwords API can make about the order of the entries in the response when creating objects calling <code>mutate()</code>?</p>
<p>For example if the request was sent something like:</p>
<pre><code>operations = [add_adgroup_1, add_adgroup_2, add_adgroup_3]
response = client.mutate(... | <p>Yes they are according to the AdWords API Team: <a href="https://groups.google.com/forum/#!topic/adwords-api/6Jpcc6dnr-M" rel="nofollow">https://groups.google.com/forum/#!topic/adwords-api/6Jpcc6dnr-M</a></p> | python|google-ads-api | 0 |
4,619 | 27,487,070 | Handle 1 to n elements | <p>I'm using xmltodict to parse an XML config. The XML has structures where an element can occur in 1 to n instances, where both are valid:</p>
<pre><code><items>
<item-ref>abc</item-ref>
</items>
</code></pre>
<p>and </p>
<pre><code><items>
<item-ref>abc</item-ref>
... | <p>I am not sure of a super elegant way to do this. Python doesn't have any built-in methods or functions that will help you do this in a single line of code. Nevertheless, in the interest of consolidating code, you will want to do something. As matsjoyce mentioned in a comment, you may simply want to create a function... | python|xml|xmltodict | 4 |
4,620 | 43,146,298 | Http request from Chrome hangs python webserver | <p>I have a very basic python (2.7.12) web server (I've stripped it down as much as possible), code given below</p>
<pre><code>import time
import ssl
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class Management(SimpleHTTPRequestHandler):
def do_GET(self):
se... | <p>Just finished wrestling around with this for 2 days :(</p>
<p>Turns out user Ami Bar was exactly right in his/her answer. Google Chrome holds open the connection and causes the multiplexing in the selector library to register the connection as readable. Essentially it forces multiplexing to fail and thus you have ... | python-2.7|python-3.x|google-chrome|pyopenssl | 8 |
4,621 | 48,449,606 | Shovel cannot import 'task' | <p>Here is my <code>shovel.py</code></p>
<pre><code>from shovel import task
@task
def hello():
println "Hello World!"
</code></pre>
<p>However when I run it I get this:</p>
<pre><code>$ shovel hello
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "shovel.py", line 1, ... | <p>For some reason your Python is looking for <code>task</code> from within your own <code>shovel.py</code> rather than the global <code>shovel</code> module. Fix this by moving <code>shovel.py</code> to a <code>shovel</code> directory.</p>
<pre><code>mkdir shovel
mv shovel.py shovel
shovel hello
</code></pre> | python | 0 |
4,622 | 48,593,694 | Python multiprocessing returning AttributeError when following documentation code | <p>I decided to try and get into the multiprocessor module to help speed up my program. To figure it out, I tried using some of the code examples on the official python documentation on multiprocessing.</p>
<h1>First attempt: <a href="https://docs.python.org/3/library/multiprocessing.html#introduction" rel="noreferrer... | <p>You're in interactive mode. That basically doesn't work with <code>multiprocessing</code>, because the workers have to import <code>__main__</code> and get something that mostly resembles the main process's <code>__main__</code>. This is one of the many ways in which the <code>multiprocessing</code> API is horribly ... | python|python-3.x|multiprocessing|python-3.6 | 8 |
4,623 | 48,454,296 | Can't get all comments from Youtube Data API V3 [Python] | <p>I have a python function, which allows you to get all comments from a youtube video. Therefore I use the youtube API v3 comments.list method.</p>
<pre><code>key = 'My Key'
textFormat = 'plainText'
part = 'snippet'
maxResult = '100'
order = 'relevance'
nextToken = ''
videoId = 'Ix9NXVIbm2A'
while(True):
res... | <p>This error come because your api limits is exhausted. Youtube change the limit of api time to time.</p>
<p>And sometimes network problem is also occur. You have to write code for multiple attempt when once request is fail.</p>
<p>You can read full documentation here - [<a href="https://developers.google.com/youtub... | python|api|youtube|youtube-api|youtube-data-api | 0 |
4,624 | 48,820,601 | Obtaining summary from logistic regression(Python) | <pre><code>model = LogisticRegression(random_state=0)
model.fit(X2, Y2)
Y2_prob=model.predict_proba(X2)[:,1]
</code></pre>
<p>I've built a logistic regression model on my training dataset X2 and Y2. Now is it possible for me to obtain the coefficients and p values from here?
Because:</p>
<pre><code>model.summary()
</... | <p>No. Its not possible to get the p-values from here. You can get the coefficients however by using <code>model.coef_</code>. If you need the p-values you'll have to use the <code>statsmodels</code> package. See <a href="https://stackoverflow.com/questions/27928275/find-p-value-significance-in-scikit-learn-linearregre... | python|scikit-learn|logistic-regression | 5 |
4,625 | 48,599,100 | Linux Python server wont terminate properly | <p>I made a echo server run on port 5555 and it receives and returns data perfectly but it will not close correctly. When i enter the exit command, it just keeps printing blank output. Can someone please help, thanks.</p>
<p><a href="https://i.stack.imgur.com/bi3Rm.png" rel="nofollow noreferrer">Echo working correctly... | <p>As you are breaking out of the while loop on the client side (in the case of the quit input) prior to sending the message, the server never receives the command to shut down. This means the client will close down while leaving the server up. </p>
<p>One option to fix this issue is to switch the order in which the m... | python|linux | 1 |
4,626 | 48,882,088 | import tensorflow with python 2.7.6 | <p>Python terminal getting abort with following msg:</p>
<p>/grid/common//pkgs/python/v2.7.6/bin/python
Python 2.7.6 (default, Jan 17 2014, 04:05:53)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.</p>
<blockquote>
<blockquote>
<blockquote... | <p>You need to compile <code>TensorFlow</code> on the same computer.</p> | python|tensorflow | 0 |
4,627 | 19,928,618 | Too many values to unpack. Error during python programming | <p>I am trying to make a huffman tree program such that it converts a given hash into a huffman tree. I want to return a list of tuples with each tuple having the child element, its frequency, parent element and an assigned value 0 0r 1.</p>
<p>But when I run the code, it shows too many values to unpack. Can you verif... | <p>You most certainly do something like this</p>
<pre><code>def myFunction()
return (1,1,1)
a,b = myFunction() #raises an 'Too many values to unpack' Error
a,b,c = myFunction() #this works
a = myFunction() # this works too, a is now a tuple
</code></pre>
<p>Check all return values of your functions and see i... | python | 4 |
4,628 | 4,647,524 | What is the Pythonic way of reordering a list consisting of dicts? | <p>I have the the following list: </p>
<pre><code>list = [{'nr' : 2, 'name': 'streamname'}, {'nr' : 3,'name': 'streamname'}, {'nr' : 1, 'name': 'streamname'}]
</code></pre>
<p>So how would I reorder it to become like this in an efficient way in python?</p>
<pre><code>list = [{'nr' : 1, 'name': 'streamname'}, {'nr' :... | <p>No, using <code>cmp=</code> is not efficient. Use <code>key=</code> instead. Like so:</p>
<pre><code>sorted(list, key=lambda x: x['nr'])
</code></pre>
<p>The reason is simple: <code>cmp</code> compares two objects. If your list is long, there are many combinations of two objects you can have to compare, so a list ... | sorting|python|lambda | 12 |
4,629 | 69,570,573 | Only read a variable if it exists | <p>I'm using the requests module to collect some data from a website. This application runs once every day. The amount of rows of data I get changes every time, per request I can get a maximum 250 rows of data. If there is more then 250 rows of data the API gives me a follow uplink which can be used to get the rows 251... | <p>You only want to enter the <code>while</code> loop when <code>q_1</code> has the key <code>'@odata.nextLink'</code> Inside the <code>while</code> loop, this is already accomplished in the line <code>next_link_1 = new_data_1.get('@odata.nextLink', None)</code> You could use the same approach -- setting <code>next_lin... | python|python-requests | 1 |
4,630 | 69,425,612 | CreateCompatibleDC() or DeleteDC() fail in continues loop in Python - possible memory leak? | <p>I am feeding an opencv window in a loop with this specific window screen capture routine below.</p>
<p><strong>PROBLEM: after hundreds of cycles in the loop, it suddenly fail at either one of the two FAIL POINTS marked below in the code.</strong></p>
<p>I am suspecting possible memory leak, but if I am not mistaken,... | <p>I tried the above code with <code>ctypes.windll.user32.PrintWindow</code> and there were no GDI leaks. <code>PrintWindow</code>'s third argument should be <code>PW_CLIENTONLY</code> (1), or there is the undocumented <code>PW_RENDERFULLCONTENT</code> (2) option. Undocumented code is not reliable. I don't know what th... | python|memory-leaks|pywin32|win32gui|win32-process | 1 |
4,631 | 48,056,574 | When writing current url to csv TypeError: can only concatenate list (not "tuple") to list | <p>TypeError: can only concatenate list (not "tuple") to list adding current url to new column</p>
<p>I'm running a script that gets current url and writing it to a csv file but I get:</p>
<pre><code> writer.writerow(row + (url1,))
TypeError: can only concatenate list (not "tuple") to list
</code></pre>
<p>becaus... | <p>You have <code>data.append([bp1, ba1, bp3, url1])</code> which means when you do</p>
<pre><code> for row in data:
writer.writerow(row + (url1,))
</code></pre>
<p>the <code>row</code> already contains the <code>url1</code>. You want the 4 data elements to appear in your csv, so change your code to:</p>
... | python|list|csv|selenium|tuples | 1 |
4,632 | 51,369,320 | Using my Python Web Crawler in my site | <p>I created a Web Crawler in Python 3.7 that pulls different info and stores them into 4 different arrays. I have now come across an issue that I am not sure how to fix. I want to use the data from those four arrays in my site and place them into a table made from JS and HTML/CSS. How do I go about accessing the info ... | <p>Ok, this will be somewhat long but I'm going to try breaking it down into simple steps. The goal of this answer is to:</p>
<ol>
<li>Have you get a basic webpage being generated and served from python.</li>
<li>Insert the results of your script as javascript into the page.</li>
<li>Do some basic rendering with the d... | javascript|python|html|python-3.x | 0 |
4,633 | 73,598,622 | How to iterate through a list and compare each character with each other | <p>Basically, I wish to compare every character of a string inside the list and how many times it repeats.
My approach to this was to use a for or while loop but the first problem with that is the index gets out of bound if I compare <code>i == i+1</code> and the 2nd issue is that even if this miraculously works then i... | <p>One approach to your problem would be:</p>
<ol>
<li>get the unique characters in your string</li>
<li>count the occurrences of each character in the string</li>
</ol>
<p>given the string:</p>
<pre><code>my_str = "this is my string"
</code></pre>
<p>first get the unique characters:</p>
<pre><code>my_list_of... | python|python-3.x|string|list|character | 1 |
4,634 | 17,242,414 | Appending to the dictionary dynamically | <p>I am reading from a text file which has the format below: </p>
<pre><code>0.000 ff:dd ff:ff 4 126 48000
0.001 sd:fg er:sd 5 125 67000
0.002 qw:er ff:dd 5 127 90000
0.003 xc:sd ff:dd 5 127 90000
0.004 io:uy gh:ij 4 126 56000
</code></pre>
<p>In the fourth column, 4 indicates request and 5 indicates respo... | <p>Let's make sure first that we are clear about what a dictionary is and what it can be used for (and hope I don't put my foot in my mouth - I am fairly new to Python myself).</p>
<h2>About Dictionaries</h2>
<p>In Python, a <code>dict</code> maps <em>single keys</em> to <em>single values</em>. You can <a href="http:... | python | 0 |
4,635 | 69,961,076 | Find capitalized words in a text | <p>How to specify words that start with a capital letter and the number of that word in a text? If no word with this attribute is found in the text, print it in the None output. The words at the beginning of the sentence should not be considered. Numbers should not be considered and if the semicolon is at the end of th... | <p>Here's the code. You can add any other character to strip and it should remove it from the end of the word. You can also change the last print to anything you want.</p>
<pre><code>import numpy as np
s1="The University of Edinburgh is a public research university in Edinburgh, Scotland. The University of Texas ... | python|word|capitalize | 0 |
4,636 | 50,077,553 | Click: Use another function in chained commands with context object | <p>I recently have been using the <a href="http://click.pocoo.org" rel="nofollow noreferrer">click package</a> to build command line interfaces which has worked perfectly, so far.</p>
<p>Now I got into some trouble when using chained commands in combination with the context object. The problem is that I somehow get an... | <p>If you can edit your click command functions, you can organize them like this:</p>
<pre><code>@cli.command()
@click.argument('some_argument', type=str)
@click.pass_context
def say_something(ctx, some_argument):
return _say_something(ctx, some_argument):
def _say_something(ctx, some_argument):
print(some_ar... | python|python-click | 7 |
4,637 | 53,237,338 | Instagram Bot: Click Button in Firefox with Selenium Python | <p>I'm making an Instagram Bot (from a YT tutorial) and I can't get past the "Turn On Notifications" pop-up that appears after login.</p>
<p><a href="https://i.stack.imgur.com/APxCV.png" rel="nofollow noreferrer">I want to click "Turn On"</a></p>
<p>How do I click the button? Here's the xpath and what I see after ins... | <p>Solution!</p>
<p>Instead of using this...</p>
<pre><code>notify_button = browser.find_element_by_xpath('//button[text()="Turn On"]')
notify_button.click()
time.sleep(2)
</code></pre>
<p>Use this!</p>
<pre><code>notify_element = driver.find_element_by_css_selector("COPY PASTE CSS SELECTOR HERE")
notify_element.se... | python|macos|selenium|firefox|instagram | 0 |
4,638 | 53,284,138 | One hot encoding huge 3D array | <p>As the title my data looks like this:
<code>["test", "bob", "romeo"]</code> - etc just random words
I have converted them into numbers based on position in alphabet for each letter in the word so now it would be:</p>
<pre><code>[[19, 4, 18, 19], [1, 14, 1], [17, 14, 12, 4, 14]]
</code></pre>
<p>and now I'd want to... | <p>You basically run out of memory. Two approaches which could help are using less features (e.g count the words and just keep the top 10000 or so and a "unknown toekn" for therest) to make the onehot size smaller. Or you could use an embedding layer in your network and feed the integers directly. </p> | python|tensorflow|one-hot-encoding | 2 |
4,639 | 65,320,115 | extracting upper and lower row if a condition is met | <p>Regards.
I have the following coordinate dataframe, divided by blocks. Each block starts at seq0_leftend, seq0_rightend, seq1_leftend, seq1_rightend, seq2_leftend, seq2_rightend, seq3_leftend, seq3_rightend, and so on. I would like that, for each block given the condition if, coordinates are negative, extract the up... | <p>I assume that you have a <strong>list</strong> of DataFrames, let's call it <em>src</em>.</p>
<p>To convert a <strong>single</strong> DataFrame, define the following function:</p>
<pre><code>def findRows(df):
col = df.iloc[:, 0]
if col.lt(0).any():
return df[col.lt(0) | col.shift(1).lt(0) | col.shift... | python|pandas|dataframe|numpy | 0 |
4,640 | 71,918,073 | Issue with presenting understandable predictions on a Python Keras CNN model | <p>Apologies if this is in the wrong place or formatting is incorrect in advance.</p>
<p>Having an issue that I'm having trouble finding an answer to as I may have it worded incorrectly during my search. I have a model created and working correctly- achieving 91.5% accuracy across 6 classes. Anyways to summarize my iss... | <p>The model's predictions, i.e. these floating point numbers, are the probabilities for the respective classes (e.g. a value of 6.734e-1 = 6.734 * 10 ** (-1) indicating a probability of 67.34%). Your prediction is then the element in your array of classes at the index of the maximum value in your array of probabilitie... | python|tensorflow|keras|deep-learning|densenet | 0 |
4,641 | 67,521,763 | Hierarchical Indexing in a Pandas dataframe | <p>Say I'm working with data with hierarchical indices:</p>
<p><a href="https://i.stack.imgur.com/qccPD.png" rel="nofollow noreferrer">Public CDC Data</a></p>
<p>The goal is to have those hierarchical indices represented in a pandas dataframe and grouped.</p>
<p>This is as close as I've gotten</p>
<pre><code>import pan... | <p>To have a clean indexed dataframe:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.read_excel(url, skiprows=3, skipfooter=5,
index_col=[0, 1], header=[0, 1])
df = df.rename_axis(columns=["Year", "Variable"],
index=["Nation/State", "... | python|pandas | 0 |
4,642 | 70,176,163 | Function within a function unknown number of times | <p>How do I use the output of one function as the argument of another. There is an unknown (X) number of functions and each function is different. The argument to the first function is known (lets call it n).</p>
<p>I have tried to create a list of the functions and use the results of one for another, I can't really ge... | <p>It's way easier than you made it:</p>
<pre><code>funcs = [function1, function2, function3, function4, function5.....functionX]
def nestedfunction(funcs, n):
for f in funcs:
n = f(n)
return n
</code></pre> | python|function | 4 |
4,643 | 56,779,846 | Saving Bokeh widgets dynamic values | <p>I am new to java script so please forgive my ignorance.</p>
<p>I am using the example code from documentation.</p>
<pre><code>from bokeh.io import output_file, show
from bokeh.models.widgets import Slider
output_file("slider.html")
slider = Slider(start=0, end=10, value=1, step=.1, title="Stuff")
show(slider)
<... | <p>"Storing in Python" implies that there is actually a Python process running, for the value to be stored in. But when you run a script like the one above, that is not the case. The sequence of events is:</p>
<ul>
<li>Python interpreter starts runs your script</li>
<li>Static HTML/JS/CSS output is saved with the slid... | javascript|python|bokeh | 1 |
4,644 | 69,289,657 | Need Help Running .execute method in python (SQLite3 library) | <p>I am attempting to take an Excel spreadsheet, turn it into a dataframe, and from there create a database table in SQLite3. Here is my code:</p>
<hr />
<pre><code>import numpy as np
import pandas as pd
import sqlite3 as sqlite3
qb = pd.read_excel('d:/2021_College_QB_Week_3.xlsx', sheet_name = '2021_College_QB_W... | <p>The <code>/</code> character is a reserved character to SQLite. If you want to use it in a column name, you'll need to <a href="https://www.sqlite.org/lang_keywords.html" rel="nofollow noreferrer">escape it</a>:</p>
<pre class="lang-python prettyprint-override"><code>c.execute("""
CREATE TABLE qb... | python|database|dataframe|sqlite | 0 |
4,645 | 35,610,801 | Apache + Python : Serving binairy files | <p>I have an Apache server with python cgi (Python3). A client start a get request to get a virtual file, and I need to give him back the good one regarding his user-agent. I was able to do it with text files but when I try to serve back binairies files like images (.jpg) or .zip, the downloaded file seems corrupted. <... | <p>Ok, I have found that print() insert '\n' character and other stuff. So, for binairies file, I recommend to use sys.stdout.</p>
<pre><code> file = open(filePath, "rb")
content = file.read()
length = len(content)
file.close()
print("Content-type:application/x-download")
print("Content-length:... | python|apache | 0 |
4,646 | 58,981,109 | when to call compile while training a tensorflow (2.0) model in incremental fashion? | <p>I am writing a neural network to train incrementally (not online). Here is a snippet of the code</p>
<pre class="lang-py prettyprint-override"><code>
output = create_model()
model = Model(inputs=values, outputs=output)
if start_epoch > 1:
weights_list = load_model_from_pickle()
model.set_weights(weights_... | <p>You need to compile the model ones and after training when you reload the model, you dont' require to compile it again. Read more <a href="https://www.tensorflow.org/tutorials/distribute/save_and_load#the_keras_apis" rel="nofollow noreferrer">here</a>.
Compile function defines the optimizer, loss functions and metr... | python|tensorflow|neural-network|tensorflow2.0 | 0 |
4,647 | 66,784,928 | Rasa ask for new entity but keeping previous intent | <p>I have an intent rent example:<br />
Me: I want to rent a house in Madrid with 2 bedrooms<br />
Bot: Which type? House, duplex...<br />
Me: Duplex<br />
Bot: You want a house in Madrid with 2 bedrooms, there are some examples<br />
Me: And with 3 bedrooms?
Bot: You want a house in Madrid with 3 bedrooms, there are s... | <p>The solution I found is using rasa interactive and add them manually. With the intent inform</p> | python|android-intent|entity|rasa | 0 |
4,648 | 42,912,345 | pytest fixture is not getting called in class | <p>I recently started working on a python project. In that project, I am writing test cases using <a href="http://doc.pytest.org/en/latest/" rel="nofollow noreferrer">pytest</a>. In that, I tried using <a href="http://doc.pytest.org/en/latest/fixture.html" rel="nofollow noreferrer">pytest-fixtures</a> and understood th... | <p><code>flask.ext.testing.TestCase</code> is a subclass of <code>unittest.TestCase</code>.</p>
<p>If you want to be able to use pytest fixtures with unittest, please read this:</p>
<p><a href="http://doc.pytest.org/en/latest/unittest.html" rel="nofollow noreferrer">Mixing pytest fixtures into unittest</a></p> | python|unit-testing|pytest|fixtures | 2 |
4,649 | 50,955,451 | Python Timed Rotating Logs | <p>Asking for some clarification on this article in the section labeled "TimedRotatingLogs": <a href="https://www.blog.pythonlibrary.org/2014/02/11/python-how-to-create-rotating-logs/" rel="nofollow noreferrer">https://www.blog.pythonlibrary.org/2014/02/11/python-how-to-create-rotating-logs/</a></p>
<pre><code> han... | <p>According to the article on <a href="https://kite.com/docs/python;logging.handlers.TimedRotatingFileHandler" rel="nofollow noreferrer">Kite Docs</a>. It states that </p>
<blockquote>
<p>When using weekday-based rotation, specify ‘W0’ for Monday, ‘W1’ for
Tuesday, and so on up to ‘W6’ for Sunday. In this case, t... | python|python-3.x|logging | 1 |
4,650 | 61,200,709 | What is causing this unusual cull and how can I fix it? | <p>I am an extreme novice to OpenGL, just trying to hack something together for a personal project. When I enabled GL_CULL_FACE I mostly got what I wanted, except a big triangle chunk is now missing from my cube!</p>
<p><a href="https://i.stack.imgur.com/NAhKw.png" rel="nofollow noreferrer"><img src="https://i.stack.... | <p>Each polygon has a "front" and "back" side, and when culling is on you only see polygons whose "front" is toward you (the ones for which the normal is pointing toward the camera). </p>
<p>The fact that this face is getting culled from this angle suggests that its normal points inside the cube instead of outside; t... | python|opengl | 0 |
4,651 | 45,628,078 | python date string object to datetime object | <p>I get following response from an API:</p>
<pre><code>/Date(1503964800000+0000)/
</code></pre>
<p>It is a string object. How do I convert it in to something like</p>
<pre><code>2017-08-11T00:00:00
</code></pre> | <p>You can use datetime.datetime.fromtimestamp]<a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.fromtimestamp" rel="nofollow noreferrer">1</a> in combination with <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow noreferrer">strftime</a>:</p>
<... | python-2.7|datetime | 0 |
4,652 | 28,792,777 | Create a line from an oval to another by dragging | <p>I'm working on a project to represent a friendship network. I'm using ovals to represent the friends, and lines to represent their friendship.</p>
<p>I've looked up how to bind an event, and so far I understood how to bind the event as so :</p>
<pre><code>def line(self, event):
x1, y1 = (event.x - 1), (event.y... | <p>On a <code><B1></code>event, remember the x/y coordinate. On <code><B1-Motion></code>, draw a line from the remembered coordinate to the coordinate of the event. At any point in time you can check whether a coordinate is over or near an oval with the <code>find_*</code> functions of the canvas. </p> | python-3.x|tkinter | 1 |
4,653 | 28,748,936 | Obtaining an array of values for coupled nonlinear equations by iterating over input arrays | <p>I am attempting to solve a coupled system of nonlinear equations:</p>
<p>x(x+2y)/(1-x-y) = A</p>
<p>y(x+2y)/x = B</p>
<p>where A and B are elements in two different arrays of identical size.</p>
<p>I have 10,000 values for A in an array, and 10,000 values for B in another array. </p>
<p>I need to determine x[i]... | <p>The line <code>for i in A and B:</code> doesn't make much sense. <code>A and B</code> is a binary logical operation on the arrays <code>A</code> and <code>B</code>, which is neither valid nor the operation you need.</p>
<p>What you want to do is probably something like <code>for a, b in zip(A, B):</code>. This yiel... | python|arrays|iteration | 2 |
4,654 | 20,715,704 | Applying arange for simultaneous computation of multiple ranges | <p>I am having some difficulty computing multiple ranges over a list of lists.
Here is what I have attempted:</p>
<pre><code>import numpy as np
k=[[0.0234,0.131,0.475,0.393,0.620],[0.0234,0.131,0.475,0.393,0.620]]
tak=[]
def thresh(a,b):
for x in k:
m=[val for val in x if a<=val<=b]
tak.appen... | <p>Your order of loop evaluation is not correct. You need to ensure what you are iterating upon and in what order, because it would finally impact your output structure.</p>
<p>Here is a possible implementation after correction of order</p>
<pre><code>k=[[0.0234,0.131,0.475,0.393,0.620],[0.0234,0.131,0.475,0.393,0.62... | python|numpy|range | 2 |
4,655 | 49,546,436 | update only selected model fields | <p>i have a list of tasks each task has a button edit for updating it ,
in my update view</p>
<pre><code>class TaskUpdate(UpdateView):
model = Task
fields = ['titre', 'objectif', 'date', 'theme']
</code></pre>
<h1>urls.py</h1>
<pre><code>url(r'^edit_task/(?P<pk>\d+)/$', views.TaskUpdate.as_view(), n... | <p>I think the default for an update view is to call a model (in this case a Task's) form.</p>
<p>Thus when you call TaskUpdate it searches for the nonexistent form. You might have to make a non-custom form. </p>
<p>"A view that displays a form for editing an existing object, redisplaying the form with validation err... | python|django | 0 |
4,656 | 49,519,370 | Print permutation tree python3 | <p>I have list of numbers and I need to create tree and print all permutations, e.g. for <code>[1, 2, 3]</code> it should print <br/>
<code>123
132
213
231
312
321</code>
<br /> Currently my code prints first element only once: <br />
<code>123
32
213
31
312
21</code>
<br /> How do I fix it? <br /></p>
... | <p>This is pretty good example showing why <a href="https://softwareengineering.stackexchange.com/questions/40297/what-is-a-side-effect">side effects</a> should be done in as few places as possible.</p>
<h1>Side effects everywhere</h1>
<p>Your approach is like this: "<em>I will print one digit every time it is nee... | python-3.x|permutation | 1 |
4,657 | 45,831,391 | How to import modules from another folders at different locations [Python]? | <p>I have a folder structure like this.</p>
<pre><code>Main_Folder
A
A1
A2
__init__.py
file1.py
B
B1
B2
__init__.py
file2.py
</code></pre>
<p>I would like to import file2 in file1.py , ... | <p>you need <code>__init__.py</code> on each directory. like <code>B</code> , <code>B1,</code> <code>B2</code> if you defined <code>__init__.py</code> then only python will understand its package folder... </p>
<pre><code>Main_Folder
A
__init__.py
A1
A2
__in... | python-2.7|operating-system|sys|sys.path | 2 |
4,658 | 51,942,837 | User-defined function to print line when ID is entered | <pre><code>df= pd.read_csv('portfolios.csv')
df1 = df.set_index('id');df
df1
</code></pre>
<p>Hi guys, I'm not sure how to start. I have attached a picture here. Can I ask how do I define a user function, whereby I input the id, I will get the entire row? </p>
<p>Thanks for your help guys. The question:</p>
<p><a h... | <p>Use for one row <code>DataFrame</code> use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a> with double <code>[]</code> and for <code>Series</code> only one <code>[]</code>:</p>
<pre><code>df = pd.DataFrame({'id':[1,2,3,4,5,6],
... | python|pandas|portfolio | 2 |
4,659 | 52,582,458 | How can I include the relative path to a module in a Python logging statement? | <p>My project has a subpackage nested under the root package like so:</p>
<ul>
<li><code>mypackage/</code>
<ul>
<li><code>__init__.py</code></li>
<li><code>topmodule.py</code></li>
<li><code>subpackage/</code>
<ul>
<li><code>__init__.py</code></li>
<li><code>nested.py</code></li>
</ul></li>
</ul></li>
</ul>
<p>My g... | <p>You'd have to do additional processing to get the path that you want here.</p>
<p>You can do such processing and add additional information to log records, including the 'local' path for your own package, by creating a <a href="https://docs.python.org/3/library/logging.html#filter-objects" rel="noreferrer">custom f... | python|logging | 8 |
4,660 | 39,505,658 | Merge list concating unique values as comma seperated retaining original order from csv | <p>Here is my data:</p>
<p>data.csv</p>
<pre><code>id,fname,lname,education,gradyear,attributes
1,john,smith,mit,2003,qa
1,john,smith,harvard,207,admin
1,john,smith,ft,212,master
2,john,doe,htw,2000,dev
</code></pre>
<p>Here is the code:</p>
<pre><code>from itertools import groupby
import csv
import pprint
t = cs... | <p>The problem is sorting, which is not required. Change as:</p>
<pre><code>groupby(t, lambda x:x[0])
</code></pre> | python | 0 |
4,661 | 47,380,749 | python3 - Named semaphores only within a given process? | <p>I know that there are python modules that allow the use of IPC and System V named semaphores. However, these resources exist at the system level. For my particular multithreaded python3 application, I need named semaphores in order to protect certain totally unrelated sections of code, but these semaphores should on... | <p>Why not use <code>threading.Semaphore</code>?</p>
<p>You only need a <em>name</em> if a semaphore is to be accessed by another <em>process</em>.</p>
<p>Threads by definition share an address space, so they can have access to basically everything in the right scope.</p>
<p><strong>Edit:</strong>
Note that <code>Se... | python-3.x|semaphore|named | 1 |
4,662 | 46,770,018 | boolean index did not match indexed array along dimension | <p>This code is in my book</p>
<pre><code>rlr.get_support()
print(u'有效特征为:%s' % ','.join(data.columns[rlr.get_support()]))
</code></pre>
<p>I got the error</p>
<pre><code>IndexError: boolean index did not match indexed array along dimension 0;dimension is 9 but corresponding boolean dimension is 8
the rlr.get_suppor... | <p>you can use the following code:</p>
<pre><code>r1.get_support(indices=True)
print(u'有效特征为:%s' % ','.join(data.columns[rlr.get_support()]))
</code></pre>
<p>I think the reason for the Indexerror is the version of numpy.you can look at the docs。
[<a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.... | python|python-3.x | 2 |
4,663 | 37,939,843 | Shifting origin in plots using pandas python | <p>I have a data frame in pandas and I am plotting a scatter plot between two columns of the data frame,Now I want to transform the origin from (0,0) to say (1300,50) in this scatter plot.I am using Jupyter IPython notebook on ubuntu</p> | <p>You can use <code>xlim</code> and <code>ylim</code>, and provide either a <code>tuple</code> as <code>(lower, upper)</code> or an <code>int</code> as lower limit only:</p>
<pre><code>import pandas as pd
import numpy as np
plt.style.use('ggplot')
df = pd.DataFrame(data={'X': np.random.random(100) * 50 + 100, 'Y': np... | python|pandas|data-visualization|jupyter-notebook | 1 |
4,664 | 43,132,300 | How can I normalize colormap in matplotlib scatter plot? | <p>The <a href="http://matplotlib.org/users/colormapnorms.html" rel="noreferrer">matplotlib documentation</a> explain in detail how to normalize colormaps for a pcolormesh, but how can I correctly do it for a scatter plot?</p>
<pre><code>normalize = mcolors.Normalize(vmin=-1, vmax=1)
plt.scatter(x,y,z,cmap=colormap(no... | <p>The syntax you're using is completely different to the one in the linked documentation. There is essentially no difference between normalizing a scatter or a pcolor(mesh) or just any other scalar mappable object.</p>
<p>It's always </p>
<pre><code>colormap = plt.cm.bwr #or any other colormap
normalize = matplotlib... | python|matplotlib|colormap | 22 |
4,665 | 51,501,224 | Wheel generated inconsistently compared to installation | <p>I have the following files:</p>
<pre><code>setup.py
problems/
__init__.py
sometimes_included/
file.txt
</code></pre>
<p><code>__init__.py</code> simply contains:</p>
<pre><code>import os
with open(os.path.join(os.path.join(os.path.dirname(__file__), "sometimes_included"), "file.txt")) as f:
pr... | <p>Create a file <code>MANIFEST.in</code> with <code>include problems/sometimes_included/file.txt</code></p> | python|python-3.x|pip|setuptools | 0 |
4,666 | 64,387,974 | I'm returning a defaultdict(list), but randomly choosing between the two, why does it return nothing sometimes? | <pre><code>output = ""
numberList = [0, 1]
print(random.choice(numberList))
if(random.choice(numberList) == 0):
if len(slots) > 0:
output = templates[state][0].replace("<num_classes>", str(slots[0][1]))
else:
output = templates[state][0]
elif(random.choice(number... | <p>With</p>
<pre><code>elif(random.choice(numberList) == 1)
</code></pre>
<p>you will <em>again</em> choose a <em>brand new</em> random number. And if that isn't <code>1</code> then there's no <code>else</code> that will set <code>output</code>.</p>
<p>Instead of <code>elif</code> you should have a plain <code>else</co... | python | 1 |
4,667 | 70,447,546 | Delete specific data from JSON file | <p><strong>The idea:</strong>
<br>A JSON file should be loaded and the object <code>2-uID</code> with its sub-items should be deleted. The edited content should be saved in the same JSON file.</p>
<p><strong>The problem:</strong>
<br>I have already tried several approaches, like <a href="https://stackoverflow.com/quest... | <p>EDIT:</p>
<p>This is your problem:</p>
<pre class="lang-py prettyprint-override"><code>for element in data:
if '2-uID' in element:
del element['2-uID']
</code></pre>
<p><code>data</code> is the top-level element, so it only has one key: "uID". Try printing out "element" :)</p>
<hr />
... | python|json|python-3.x|file | 1 |
4,668 | 70,724,156 | Import osmnx to python | <p>I'm trying to use the osmnx package in Python. I followed the steps given in <a href="https://osmnx.readthedocs.io/en/stable/" rel="nofollow noreferrer">https://osmnx.readthedocs.io/en/stable/</a> and I now have an enviorment in anconda with the given package.</p>
<p>But, when I try to import this package to python ... | <p><strong>edit</strong> - another solution:</p>
<p>try
<code>conda install osmnx</code> and then <code>conda install gdal=2.4.4</code></p>
<hr />
<p>try creating a new full env for OSMnx:</p>
<pre><code>conda config --prepend channels conda-forge
conda create -n ox --strict-channel-priority osmnx
</code></pre>
<p>then... | python|osmnx | 0 |
4,669 | 73,074,823 | 'from extension import utils' giving error in AWS Glue Jupyter Notebook | <p>In AWS Glue Jupyter Notebook, When I run the command <code>from extension import utils</code> i get error <code>ModuleNotFoundError: No module named 'extension'</code></p>
<p>Below is the complete list of things that I have to import, Only the last one I am getting error.</p>
<pre><code>import time
import boto3
impo... | <p>First of all, in order to add additional libraries you can use <code>%additional_python_modules</code> option in notebook. You can give pypi packages or s3 location of packages.</p>
<p>Second, I dont see utils class in any of extension/extensions/pyextension packages. Can you double check the package.? If its inte... | python|pyspark|jupyter-notebook|boto3|aws-glue | 1 |
4,670 | 72,946,450 | Why does the kv file return different value of the py file? | <p>In my kv file a button size receives its texture size, when I print the size with the kv file it returns the real size but when I print with the py file it returns a different value. Why?</p>
<p>It's my kv file code, it prints [87, 25]:</p>
<pre><code><Base_P_Brick>:
background_color: 0, 0, 0, 0
markup... | <p>In an <code>__init__()</code> method, the <code>size</code> of a widget has not yet been assigned, so your <code>print</code> is just printing the default initial size of any widget (which is probably <code>(100,100)</code>).</p>
<p>You can add a method to your <code>Base_P_Brick</code> class that will report the <c... | python|python-3.x|kivy|kivy-language | 0 |
4,671 | 73,340,331 | Selenium Scrape not reading all elements | <p>I am trying to scrape data from the following site. I was able to click on load more yet the code doesn't catch most of the elements and I do not really know what to do.</p>
<pre><code>url = 'https://www.carrefouregypt.com/mafegy/en/c/FEGY1701230'
products = []
options = Options()
driver = webdriver.Chrome(options ... | <p>The following code will click that button until it cannot locate it, and exit gracefully:</p>
<pre><code>from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.keys import Key... | python|selenium|web|web-scraping | 0 |
4,672 | 64,045,319 | Using pandas to get max value per row and column header | <p>I have a data frame and I am looking to get the max value for each row and the column header for the column where the max value is located and return a new dataframe. In reality my data frame has over 50 columns and over 30,000 rows:</p>
<p>df1:</p>
<pre><code>ID Tis RNA DNA Prot Node Exv
AB 1.4 ... | <p>Use if <code>ID</code> is index <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer"><code>DataFrame.agg</code></a> with replace <code>0</code> rows by missing values:</p>
<pre><code>df = df1.agg(['idxmax','max'], axis=1).mask(lambda x: x['max'].eq(0... | python|pandas | 2 |
4,673 | 63,985,526 | Getting warning when filtering data in a DataFrame | <p>I want to open a file, filter its data, and show it to the user.</p>
<p>Here is the code:</p>
<pre><code>import pandas as pd
df = pd.read_csv(<file path>)
data = df["Unique Number"] == UID # Unique Number is a column and UID is a Variable
print(data)
</code></pre>
<p>And I get a warning (maybe an err... | <p>The reason of problem is that I think your <code>UID</code> is string. And in csv some or all of uids are numbers (ints). So to compare later strings and ints they both should be of same common type (type of UID which is string). Specify type string for "Unique Number" field on reading.</p>
<pre><code>df =... | python|pandas | 1 |
4,674 | 53,008,631 | Django integration with Bootstrap template | <p>I downloaded Bootstrap theme and integrated it with django, the frontend is perfectly fine but i need help in writing code for its backend integration.</p>
<p>index.html as per dwonloaded template:</p>
<pre><code> <div class="col-lg-5 col-md-8">
<div class="form">
<div id="sendmessage">... | <p>The models.py file should be see like this</p>
<pre><code># -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class Contact(models.Model):
# if the field is required
name = models.CharField(max_length=200)
# if the fields can... | django|python-3.x|django-models|django-forms|bootstrap-4 | 0 |
4,675 | 53,196,063 | For loop on a dictionary giving out of range error | <p>I'm having troubles understanding dictionaries and for loop.
I have this example that takes a nested dictionary representing a playlist of songs. On the first example the code runs just fine, but when I try to create a function and try to clean up the code. It keeps saying index out of range. Can anybody throw thei... | <p>You can use this method to make a string of the names with " and " in between them. </p>
<pre><code>artist_list=["John","Smith"]
y=" and ".join(str(x) for x in artist_list)
print(y)
</code></pre>
<p>This give the output of <code>John and Smith</code></p>
<p>And if you make the artist list: <code>["John","Smith"... | python | 1 |
4,676 | 65,379,646 | How to create a table by iterating words in sentence in python? | <p>For the example given below, I would like to create a table for the list of 'Directors' and 'Stars'. The idea is to iterate the sentences, detect words which exist between word 'Director:' and 'Stars:' and put into respective cells.</p>
<p>The sentence.</p>
<pre><code>Director:
Peter
Jackson,
John
Marsh
Stars:
Elija... | <p>Try this:</p>
<pre><code>import pandas as pd
l=[]
with open('yourtxtfile.txt') as f:
for i in f:
l.append(i)
l=[i.replace('\n', '') for i in l]
Director=l[1:l.index('Stars')]
Stars=l[l.index('Stars')+1:]
for i in range(len(Director)-len(Stars)):
Director.append('')
df=pd.DataFrame({'Director':Di... | python|nltk|text-processing | 0 |
4,677 | 68,464,284 | Multiplying all negative values in a list | <p>can someone help me write code in Python for this problem?</p>
<pre><code>x = [10,-5,6,-7,2,4,-9,12,-55,33,44,77]
</code></pre>
<p>Write up some code to multiply only the negative values. Print the result of these multiplications. Include a loop of some kind as well as an if-statement to grab just the negative numbe... | <p>IIUC, here's one way via <a href="https://docs.python.org/3/library/functools.html" rel="nofollow noreferrer">reduce</a></p>
<pre><code>from functools import reduce
x = [10, -5, 6, -7, 2, 4, -9, 12, -55, 33, 44, 77, -1]
result = reduce(lambda x, y: x*y, (i for i in x if i < 0))
</code></pre>
<p>OUTPUT:</p>
<pre>... | python|list|multiplication | 0 |
4,678 | 10,797,026 | python segmentation fault | <p>i want to display a message in pop-up window in python ...so i wrote this code...please check </p>
<pre><code>import sys
from PyQt4.Qt import *
class MyPopup(QWidget):
def __init__(self):
print "6"
QWidget.__init__(self)
class MainWindow(QMainWindow):
def __init__(self, *args):
pr... | <p>There is supposed to be just one QApplication object in an application. I guess your problem is that you attempt to create several in a loop.</p>
<p>If you want your user to close the main window four times before it actually closes, you can add an event handler:</p>
<pre><code>class MainWindow(QMainWindow):
d... | python|pyqt|pyqt4 | 0 |
4,679 | 5,040,119 | Querying csv with raw_input in Python | <p>I'm new to programming but I decided to take on python.</p>
<p>I have this csv file about logged hours by users that looks roughly like this (but containing around 200 rows):</p>
<blockquote>
<p>User,Project,Hours<br>
User1,ProjectA,5<br>
User1,ProjectB,10<br>
User2,ProjectA,7<br>
User2,ProjectB,12`</p>
... | <p>Jakob's answer is a good read. In answer to "mistakes":</p>
<pre><code>if User == User in reader
</code></pre>
<p>This is obviously wrong. The <code>User == User</code> is <code>True</code>, which isn't likely to be in the <code>reader</code> object.</p>
<p>If you want to print an empty line, in stead of using <c... | python|csv|raw-input | 2 |
4,680 | 67,549,486 | Difference between list and NumPy array memory size | <p>I've heard that Numpy arrays are more efficient then python built in list and that they take less space in memory. As I understand Numpy stores this objects next to each other in memory, while python implementation of the list stores 8 bytes pointers to given values. However, when I try to test in jupyter notebook i... | <p><code>getsizeof</code> is not a good measure of memory use, especially with lists. As you note the list has a buffer of pointers to objects elsewhere in memory. <code>getsizeof</code> notes the size of the buffer, but tells us nothing about the objects.</p>
<p>With</p>
<pre><code>In [66]: list(range(4))
Out[66]: [... | python|arrays|list|numpy | 1 |
4,681 | 67,199,764 | scrabing using requests in python | <p>I am trying to get some info from this <code>API</code> site :</p>
<p><a href="https://billing.te.eg/api/Account/Inquiry" rel="nofollow noreferrer">https://billing.te.eg/api/Account/Inquiry</a></p>
<p>(originial here : <a href="https://billing.te.eg/ar-eg" rel="nofollow noreferrer">https://billing.te.eg/ar-eg</a>) ,... | <p>can i do the same thing for this site (pay.jumia.com.eg/services/internet-bills/we-dsl) , please do it in detais and if there is any detailed refrence for learn requesets with sites that need information to path and how i got them from google chrome</p> | python|automation|python-requests|screen-scraping | 0 |
4,682 | 10,907,087 | Authentication with the Google Docs List API, Python and OAuth 2 | <p>I'm trying to use the Google Docs API with Python+Django and OAuth 2. I've got the OAuth access token, etc. via google-api-python-client, with the code essentially copied from <a href="http://code.google.com/p/google-api-python-client/source/browse/samples/django_sample/plus/views.py" rel="nofollow">http://code.goog... | <p>The OAuth 2.0 sequence is something like the following (given suitably defined application constants for your registered app).</p>
<ol>
<li><p>Generate the request token.</p>
<pre><code>token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
... | python|oauth-2.0|google-docs-api | 5 |
4,683 | 56,651,341 | I am getting "SystemExit: 2" how can I fix this? | <p>I am brand new to coding and need lots of help. I am trying to create a code that can do image processing for me. I keep getting errors and I have no idea how to fix it.</p>
<p>I am using an online code as my baseline that is this:</p>
<pre><code>import numpy as np
import argparse
import cv2
def fill_holes(imInput... | <p>The problem that you should solve is: <strong>the following arguments are required: -i/--image</strong> </p>
<p>The argument parser (argparse) is printing it and call 'sys.exit(2)' </p>
<p>So you need to supply the image to the program.</p>
<p>In your code there is a declaration of required argument:</p>
<pre><c... | python|argparse | 0 |
4,684 | 56,593,385 | Display all x values of a graph | <p>I know it has already been asked, but I could not solve my problem.
I have three pandas column, One with dates, and other with values.
I can get my graph with the two curves depending on date.</p>
<p>However, I cannot display all dates in the x axis. Can you help me?</p>
<pre><code>import pandas as pd
import matp... | <p>Usually, <code>plt.xticks()</code> is used to display x axis values. </p>
<p>As I'm not sure it is 100% compatible with a pandas structure, you may need to store your data in a classical table or a numpy array. </p>
<p><a href="https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks" rel="nofollow nore... | python|matplotlib | 0 |
4,685 | 69,987,422 | Create new column in Python and use value from previous row | <p>Im totally beginner in Python but I need to use the value from previous row. I read a lot of articles but I didn't catch the point :(</p>
<p>I have an Excel file with data, I sorted the data by 'D_i' column and here I found a problem. I need to add new column 'C_i' which contains in 1st row value from column 'Time',... | <p>What you're trying to do is known as a cumulative sum. There is a built in function for this in pandas already, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer">pd.cumsum()</a></p>
<p>From what I can gather from your question, adding the line... | python|pandas|dataframe | 0 |
4,686 | 18,018,796 | unknown RT error message | <p>I'm trying to debug a script that's trying to talk to RT (Request Tracker) and I'm getting the following output:</p>
<pre><code>RT/3.6.6 409 Syntax Error
# Syntax Error
>>ARRAY(0x2b3495f37750)
</code></pre>
<p>I have no idea what this error means in the context of RT given the astounding lack of detail mak... | <p>You'll find much more information in the logs on the RT server itself, especially if you up the log level to debug. You might have better luck using one of the <a href="http://requesttracker.wikia.com/wiki/REST#Convenience_libraries" rel="nofollow">python libraries</a> available for calling RT. However, the version ... | python|rest|syntax-error|rt | 1 |
4,687 | 18,191,273 | numpy: log with -inf not nans | <p>Is there an efficient way to write a log-like function for a numpy array that gives <code>-inf</code> for negative numbers?</p>
<p>The behaviour I would like is:</p>
<pre><code>>>> log_inf(exp(1))
1.0
>>> log_inf(0)
-inf
>>> log_inf(-1)
-inf
</code></pre>
<p>with <code>-inf</code> ret... | <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html" rel="nofollow noreferrer"><code>numpy.log</code></a> with a conditional test for negative numbers:</p>
<pre><code>import numpy as np
def log_inf(x):
return np.log(x) if x>0 else -float('Inf')
log_inf(-1)
-inf
log_inf... | python|numpy|nan|logarithm | 4 |
4,688 | 65,936,123 | Flask / jinja how to calculate average | <p>I am trying to study jinja / flash / python combination, but having problems. I found this kind of example from the internet and got it working nicely, but now i'd want to improve the code and dont know how. I tried many different kind of actions to print the average of grades that are given by user, but can't get i... | <p>To calculate the grades add them up and divide by the number of grades. Or you could use the <a href="https://docs.python.org/3/library/statistics.html#statistics.mean" rel="nofollow noreferrer"><code>statistics.mean()</code></a> function:</p>
<pre><code>import statistics
@app.route('/result',methods = ['POST', 'GE... | python|html|flask|jinja2 | 1 |
4,689 | 65,924,997 | Why the point size using sns.lmplot is different when I used plt.scatter? | <p>I want to do a scatterplot according x and y variables, and the points size depend of a numeric variable and the color of every point depend of a categorical variable.</p>
<p>First, I was trying this with plt.scatter:</p>
<p>Graph 1
<a href="https://i.stack.imgur.com/LKtsi.png" rel="nofollow noreferrer"><img src="ht... | <p>Your question is no so much descriptive but i guess you want to control the size of the marker. Here is more <a href="https://seaborn.pydata.org/generated/seaborn.scatterplot.html" rel="nofollow noreferrer">documentation</a></p>
<p>Here is the start point for you.
A numeric variable can also be assigned to <code>siz... | pandas|matplotlib|graph|seaborn|lmplot | 0 |
4,690 | 69,272,292 | How can I print several ASCII art graphics horizontally instead of vertically? | <p>I am working on a yahtzee project, and want to display dice text graphics on screen from left to right, and not up and down</p>
<p>This is the code that I have now:</p>
<pre><code>import random
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
die4 = random.randint(1,6)
die5 = random.... | <p>Here is a quick snippet for this.</p>
<p>First, redefine your function to return a list containing each line of the of the dice graphic rather than printing them directly.</p>
<pre class="lang-py prettyprint-override"><code>def diepic(die):
if die == 1:
return ["=========",
&quo... | python | 4 |
4,691 | 68,938,987 | Fill area between two rectangles | <p>I use the following code to plot two rectangles.</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
def main():
# Box 1
x1_1, y1_1 = 1.0, 2.0
x1_2, y1_2 = 8.0, 9.0
height1 = y1_2 - y1_1
width1 = x1_2 - x1_1
# Box 2
x2_1, y2_1 = 3.0, 4.0
x2_2, y2... | <p>If you draw the larger rectangle first (which it appears you do) I believe if you attempted to fill the boxes with colors it would do what you are asking. I added small changes to your code to do this:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
def main():
# Box 1
... | python|matplotlib | 1 |
4,692 | 59,274,310 | UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 433: ordinal not in range(128) when creating a conda environment | <p>So I am using a server machine and I am not a sudoer there. Is there any way I could fix this error without being a sudoer?</p>
<pre><code>[jalal@scc2 jalal]$ pwd
/projectnb/ivcgroup/jalal
[jalal@scc2 jalal]$ conda env create -p /projectnb/ivcgroup/jalal/dpk -f test-dlc.yaml
Collecting package metadata (repodat... | <p>You declared a dependency to <a href="https://github.com/jgraving/DeepPoseKit" rel="nofollow noreferrer">DeepPoseKit</a> which tries setting its <a href="https://github.com/jgraving/DeepPoseKit/blob/bdfcd238e2d6171653d2844588bfe02b3406ee37/setup.py#L42" rel="nofollow noreferrer"><code>long_description</code> by read... | python-3.x|pip|ascii|conda | 2 |
4,693 | 59,443,718 | Why am I getting the 'referenced before assignment' error? | <p>This code is the start of a pool scoreboard. It works up until I press the button and then it comes up with a traceback saying 'referenced before assignment'. Here is the full code although you probably won't need it all:</p>
<pre><code>from tkinter import*
import tkinter.messagebox as box
window = Tk()
window.co... | <p>You've declared <code>stripes</code> before the functions and then referred to it inside the functions but inside each function you have to declare that you want to use the global variable <code>stripes</code> by adding <code>global stripes</code>. You should do this for each variable that causes an exception.</p>
... | python|tkinter | 1 |
4,694 | 72,970,618 | How to find any list value in a dictionary | <p>In my python project, I have a variable called "Dictionary" that is a dictionary of various string keys with integer values.</p>
<p>I also have a variable that is a list containing lots and lots of strings.</p>
<p>I would like my code to compare the strings in the list with the keys in the dictionary and, ... | <p>The function split() returns an array of string as you can see here <a href="https://docs.python.org/3.3/library/stdtypes.html?highlight=split#str.split" rel="nofollow noreferrer">https://docs.python.org/3.3/library/stdtypes.html?highlight=split#str.split</a> so actually <code>tempstring</code> is a list of strings.... | python | 1 |
4,695 | 63,116,717 | Python/Pandas: Comparing two string columns from different CSV files that are of different lengths and finding where the data is the same | <p>I have two CSV files that contain items that accomplish a specific task. I want to see if within these two files there are items that are in both of the data frames. The data frames are of different lengths so I've run into some trouble. The location of the same item on the other list may be 20 items lower than wher... | <p>You can use a set.
You add all the elements of the first frame. Then you add those of the second frame.
The set will remove duplicates.</p> | python|pandas|csv | 0 |
4,696 | 62,073,863 | How to wait for an element to be contain the attribute style="display:none;" using Selenium and Python | <p>When using Selenium/Python, I need to wait/pause until: <code>style="display:none;"</code> is displayed for a <code><div id="notification"..</div></code></p>
<hr>
<p>After clicking a button, the following is displayed (<strong>Loading..</strong>.)</p>
<p><code><div id="notification" class="notificatio... | <p>Once you click the desired button the element with text as <code>Loading...</code> becomes visible. Hence you see the element within the <a href="https://www.w3schools.com/js/js_htmldom.asp" rel="nofollow noreferrer">HTML DOM</a> as:</p>
<pre><code><div id="notification" class="notification_info" style="opacity:... | python|selenium|xpath|css-selectors|display | 4 |
4,697 | 35,618,557 | Finding the number of matching letters in two different string at the same indices | <p>I am having trouble finish python code.</p>
<p>overlap('','hello') → 0.</p>
<p>I have managed to get the number back when the length of the strings match but if one of the strings has a smaller length than the other. I keep getting index out of range. Can someone help me finish this.</p>
<pre><code>def overlap(st... | <p>Create <strong>one</strong> <code>for</code> loop which iterates through <code>min(len(string1), len(string2))</code> and you would avoid problem when one string is smaller than another, see sample below:</p>
<pre><code>def overlap(string1,string2):
count = 0
for i in range(min(len(string1), len(string2)))... | python | 5 |
4,698 | 35,354,285 | How to use a while loop to start at the right end of the list | <p>So I have a list of numbers that I want to increment only when a condition is met. In this case, the list contains the numbers 0-9. </p>
<p>What I want to do is change 9's in my list to 0's and if the next element isn't a 9, add one until it is = 9. Eventually it should be a list of zeros. </p>
<p>this is what I h... | <p>So you want to change the last number in <code>self.numbers</code> which is not <code>0</code>: if it is <code>9</code>, change it to <code>0</code>; otherwise increment it by <code>1</code>. You can do:</p>
<pre><code>def increment(self):
for i, num in enumerate(reversed(self.numbers)):
if num: # that... | python|list|python-2.7 | 2 |
4,699 | 73,371,057 | Python / win32com / Michrosoft Visio / Macro | <p>I need to convert many visio files, but when opining them there is a msg coming from Windows which asks a confirmation.</p>
<p>Here is my call :</p>
<pre><code>application = win32com.client.Dispatch("Visio.Application")
application.AlertResponse = 7
</code></pre>
<p>Msg occurs whatever the alertresponse is... | <p>My solution was to use</p>
<pre><code>doc = application.Documents.OpenEx(path_input + file,128)
</code></pre>
<p>to prevent the warning, as 128 is the decimal number of H80</p> | python|visio | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.