qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
57,712,218 | I try to use requests to get a url of file. It works well locally but it doesn't work with nameko.
I tried 3 libs of python3.7. But all has the same error.
import urllib.request,urllib3,requests
it works well locally like this:
```py
import requests
url = "https://www.python.org/static/img/python-logo.png"
r = reque... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57712218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11994979/"
] | It is an eventlet bug. If it is possible you need to downgrade to Python 3.6.
<https://github.com/eventlet/eventlet/issues/526>
Nameko has a PR for this issue which is on pause until the above is fixed.
<https://github.com/nameko/nameko/pull/644> | I caught the same error with python 3.7, eventlet 0.25.2, requests 2.24.0.
It works fine with requests 2.23.0 | 6,944 |
6,918,719 | Whenever I try to create a table using python and sqlite3, it gives me the following error:
```
Traceback (most recent call last)
File "directory.py", line 14, in <module>
'Children' TEXT, 'Other' TEXT, 'Masul' TEXT);''')
sqlite3.OperationalError: near ")": syntax error
```
The way I'm trying to create the table is:... | 2011/08/02 | [
"https://Stackoverflow.com/questions/6918719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764746/"
] | Often when you get this kind of error it is because you are using keywords as column (or table) names.
I see that you have a column called `primary`.
You will want to put backticks around it or rename it because [it is a keyword in SQLite](http://www.sqlite.org/lang_keywords.html); e.g.:
```
...
`Primary` TEXT,
..... | You have a trailing "," before the closing parenthesis. | 6,945 |
2,811,822 | In other languages (ruby, python, ...) I can use `zip(list1, list2)` which works like this:
If `list1 is {1,2,3,4}` and `list2 is {a,b,c}`
then `zip(list1, list2)` would return: `{(1,a), (2,b), (3,c), (d,null)}`
Is such a method available in .NET's Linq extensions? | 2010/05/11 | [
"https://Stackoverflow.com/questions/2811822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545/"
] | .NET 4 gives us a [`Zip`](http://msdn.microsoft.com/en-us/library/dd267698.aspx) method but it is not available in .NET 3.5. If you are curious, [Eric Lippert provides an implementation of `Zip`](http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx) that you may find useful. | neither implementation will fill in the missing values (or check that the lengths are the same) as the question asked.
here is an implementation that can:
```
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult> (this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TRes... | 6,947 |
31,823,262 | I just started python a few days ago and have been working on a calculator (not extremely basic, but also not advanced). The problem doesn't prevent code from running or anything, it is just a visual thing.
Output in the console looks like this (stuff in parenthesis is explaining what is happening and is not actually p... | 2015/08/05 | [
"https://Stackoverflow.com/questions/31823262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5166610/"
] | Your problem is that you're asking for `input()` without specifying what you want. So if you take a look at the first one: `firstNumber = float(input())` It's executing properly, but you hit `enter` it gives an error which is only then you're specifying what you want.
Try replacing with these:
```
...
try
firstNu... | That's a [nice exercise](http://alfasin.com/2015/08/05/a-simple-calculator-in-python/), and as I wrote in the comments, I would ignore whitespaces, take the expression as a whole from the user and then parse it and calculate the result. Here's a small demo:
```
def is_number(s):
try:
float(s)
retur... | 6,948 |
12,632,421 | I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.... | 2012/09/28 | [
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] | You're overthinking it
This part is trying to do too much
```
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
```
See how simple it really should be
```
def get_powerset (string):
perm = [... | Here's a refactored iterative solution **without** the `itertools` module:
```
def powerset(s):
a = ['']
for i,c in enumerate(s):
for k in range(2**i):
a.append(a[k]+c)
return a
``` | 6,949 |
9,887,319 | I am running a server with cherrypy and python script. Currently, there is a web page containing data of a list of people, which i need to get. The format of the web page is as follow:
```
www.url1.com, firstName_1, lastName_1
www.url2.com, firstName_2, lastName_2
www.url3.com, firstName_3, lastName_3
```
I wish to... | 2012/03/27 | [
"https://Stackoverflow.com/questions/9887319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008340/"
] | You need the `split(',')` method on each string:
```
data = [ line.split(',') for line in fptr.readlines() ]
``` | ```
lists = []
for line in data:
lists.append([x.strip() for x in line.split(',')])
``` | 6,959 |
46,188,797 | I use a script to parce some sites and get news from there.
Each function in this script parse one site and return list of articles and then I want to combine them all in one big list.
If I parce site by site it takes to long and I desided to use multithreading.
I found a sample like this one in the bottom, but it seem... | 2017/09/13 | [
"https://Stackoverflow.com/questions/46188797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6217484/"
] | Solution without `Queue`:
```
NEWS = []
LOCK = Lock()
def gather_news(url):
while True:
news = news_from(url)
if not news: break
with LOCK:
NEWS.append(news)
if __name__ == '__main__':
T = []
for url in ['url1', 'url2', 'url3']:
t = Thread(target=gather_news, ... | All, that you should do, is using a single queue and extend your result array:
```
q1 = Queue()
Thread(target=wrapper, args=(last_news_from_bar, q1)).start()
Thread(target=wrapper, args=(last_news_from_foo, q1)).start()
all_news = []
all_news.extend(q1.get())
all_news.extend(q1.get())
print(all_news)
``` | 6,964 |
1,874,592 | As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "th... | 2009/12/09 | [
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] | Since neighboring string constants are automatically concatenated, you can code it like this:
```
s = ("this is my really, really, really, really, really, really, "
"really long string that I'd like to shorten.")
```
Note no plus sign, and I added the extra comma and space that follows the formatting of your ... | I've used textwrap.dedent in the past. It's a little cumbersome so I prefer line continuations now but if you really want the block indent, I think this is great.
Example Code (where the trim is to get rid of the first '\n' with a slice):
```
import textwrap as tw
x = """\
This is a yet another test.
T... | 6,965 |
43,540,159 | I am trying to build an executable out of my .py script using Pyinstaller. The problem is that it builds it using Python 2.7 instead of Python 3.5, so my executable won't even run.
```
cali@californiki-pc ~/Desktop $ pyinstaller --onefile Vocabulary.py
25 INFO: PyInstaller: 3.2.1
25 INFO: Python: 2.7.12
26 INFO: Plat... | 2017/04/21 | [
"https://Stackoverflow.com/questions/43540159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | To overcome the problem you face install PyInstaller using:
>
> pip3 install pyinstaller
>
>
>
Then take care that you run the right one (there will then be two of them in different locations, one in the path of Python2.7 modules and one in the path of Python3.5 modules)
Just installed PyInstaller for Python 3.5... | Just set an option -upx-dir in pyinstaller specifying your path for python 3.5. It can be the virtual environment too. For instance:
```
pyinstaller --upx-dir="$HOME/virtual-envs/<your-virtual-env>/lib/python3.5/site-packages/" <your-script>.py'
``` | 6,975 |
61,250,928 | ```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid ... | 2020/04/16 | [
"https://Stackoverflow.com/questions/61250928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13111498/"
] | Change the if statement:
```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
while True:
if 0 <= score <= 100:
break
score = int(inp... | try this one:
```
array = []
total = 0
num_of_students = int(input("How many students in your class: "))
print("\n")
for x in range(num_of_students):
score = int(input("Input score {} : ".format(x + 1)))
while True:
if score < 0 or score > 100:
score = int(input("Invalid score, please re-e... | 6,977 |
62,214,293 | I usually start all my scripts with the shebang line
```
#!/usr/bin/env python
```
However our production server has Python 2 as the default `python`, while all of our new scripts and programs are being built under Python 3. To help keep people from accidentally running the script with the default Python 2, I am con... | 2020/06/05 | [
"https://Stackoverflow.com/questions/62214293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5359531/"
] | Yes, this is a safe bet.
[PEP 394](https://www.python.org/dev/peps/pep-0394/) recommends Python 3 be available under the binary name `python3` and most Linux distributions follow this recommendation. In fact, this is the *only* name under which Python 3 has been available in most distributions (the only outlier being ... | I believe that a python 3 version only install's `python3` if there is already another version of python installed, no matter if it is a python 2 or python 3 version, because the standard `python` command would then not work properly for the new version of python.
But please correct me if I'm wrong! | 6,982 |
38,811,966 | I'm trying to create an exe for my python script using pyinstaller each time it runs into errors which can be found in a pastebin [here](http://pastebin.com/DJrZjVkv).
Also when I double click the exe file it shows this error:
>
> C:Users\Afro\AppData\Local\Temp\_MEI51322\VCRUNTIME140.dll is either not designed to ... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38811966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483094/"
] | I was haunted with similar issue. It might be that in your case UPX is breaking vcruntime140.dll.
Solution to this is turning off UPX, so just add **--noupx** to your pyinstaller call.
```
pyinstaller --noupx --onedir --onefile --windowed get.py
```
Long explanation here: [UPX breaking vcruntime140.dll (64bit)](htt... | In my case it was:
```
pyinstaller --clean --win-private-assemblies --noupx --onedir --onefile script.py
```
**--windowed** caused problems with wxWidgets | 6,983 |
45,628,653 | I have written a small program in `tkinter` in `python 3.5`
I'm making executable out of it using `pyintaller`
I have included a custom icon to the window to replace default feather icon of tkinter
```
from tkinter import *
from tkinter import messagebox
import webbrowser
calculator = Tk()
calculator.title("TBE Cal... | 2017/08/11 | [
"https://Stackoverflow.com/questions/45628653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3719167/"
] | Uninstall and re install the visual studio with azure service fabric tools resolved the problem. | 
I have install only runtime this way. Hope this will help you to install runtime only. | 6,988 |
52,287,641 | I have a the below `df1`:
```
Date Tickers Qty
01-01-2018 ABC 25
02-01-2018 BCD 25
02-01-2018 XYZ 31
05-01-2018 XYZ 25
```
and another `df2` as below
```
Date ABC BCD XYZ
01-01-2018 123 5 78
02-01-2018 125 7 79
03-01-2018 127 6 81
04-01-2018 126 ... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52287641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6577574/"
] | Use:
```
df11 = df1.pivot('Date', 'Tickers','Qty')
df22 = df2.set_index('Date')
s = df22.mul(df11).bfill(axis=1).iloc[:, 0]
print (s)
Date
01-01-2018 3075.0
02-01-2018 175.0
03-01-2018 NaN
04-01-2018 NaN
05-01-2018 2075.0
Name: ABC, dtype: float64
```
Solution for add new column to `df1`:... | you need to set 'Date' as index and multiply,
```
df1=df1.set_index('Date')
df2=df2.set_index('Date')
df3=(df2['ABC']*df1['Qty']).reset_index()
print(df3)
Date 0
0 01-01-2018 3075.0
1 02-01-2018 3125.0
2 03-01-2018 NaN
3 04-01-2018 NaN
4 05-01-2018 3100.0
``` | 6,989 |
55,514,933 | am trying to write a loop that gets .json from an url via requests, then writes the .json to a .csv file. Then I need it to it over and over again until my list of names (.txt file) is finished(89 lines). I can't get it to go over the list, it just get the error:
```py
AttributeError: module 'response' has no attribut... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55514933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6553605/"
] | VS2019 also introduced new "enhanced" colors for .NET languages, for which there is a separate option to toggle on and off:
[](https://i.stack.imgur.com/IpRoV.png)
The same checkbox... | It is possible to change in `Options->Environment->Fonts and Colors`. There is a list with different `User Memebers - ...` and `User Tyeps - ...` that define these colors.
[](https://i.stack.imgur.com/D6XSR.png)
I have actually changed `User Members ... | 6,990 |
72,066,195 | I want to insert zero at certain locations in an array, but the index position of the location exceeds the size of the array
I wanted that as the numbers get inserted one by one, size also gets increased in that process (of the array X), so till it reaches index 62, it will not produce that error.
```
import numpy as... | 2022/04/30 | [
"https://Stackoverflow.com/questions/72066195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18746410/"
] | Make a copy of `X` into `X_new` so the array gets longer in loop as you desire.
```
X_new = X.copy()
for i in desired_location:
X_new = np.insert(X_new, i, 0)
``` | how silly I was.
```
import numpy as np
X = np.arange(0,57,1)
desired_location = [ 0, 1, 24, 25, 26, 27, 62, 63]
for i in desired_location:
X = np.insert(X,i,0)
print(X)
``` | 6,996 |
2,686,520 | For what I've read I need Python-Dev, how do I install it on OSX?
I think the problem I have, is, my Xcode was not properly installed, and I don't have the paths where I should.
This previous question:
[Where is gcc on OSX? I have installed Xcode already](https://stackoverflow.com/questions/2685887/where-is-gcc-on... | 2010/04/21 | [
"https://Stackoverflow.com/questions/2686520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] | Might depend on what version of Mac OSX you have, I have it in these spots:
```
/Developer/SDKs/MacOSX10.5.sdk/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/Python.h
/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/Python.h
```
Also I believe the version of pyth... | Are you sure you want to build Mercurial from source? There are [binary packages available](https://www.mercurial-scm.org/downloads), including the nice [MacHg](http://jasonfharris.com/machg/) which comes with a bundled Mercurial. | 6,999 |
67,211,732 | I'm trying to update my Heroku DB from a Python script I have on my computer. I set up my app on Heroku with NodeJS (because I just like Javascript for that sort of thing), and I'm not sure I can add in a Python script to manage everything. I was able to fill out the DB once, with the script, and it had no hangups. Whe... | 2021/04/22 | [
"https://Stackoverflow.com/questions/67211732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11790979/"
] | The "month" view provided by fullCalendar does not have this flexibility - it always starts at the beginning of the month, like a traditional paper calendar.
IMHO it would be confusing to many users if it appeared differently.
Other types of view are more flexible - they will respond to the `visibleRange` setting if y... | Change **type: 'dayGridMonth'** to **type: 'dayGrid'** | 7,002 |
66,214,454 | Ansible version: 2.8.3 or Any
I'm using `-m <module>` Ansible's **ad-hoc** command to ensure the following package is installed **--OR--** let's say if I have a task to install few yum packages, like (i.e. How can I do the same within a task (possibly when ***I'm not using ansible's shell / command*** modules):
```
... | 2021/02/15 | [
"https://Stackoverflow.com/questions/66214454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1499296/"
] | You should add this line to your **MouseArea** to work:
```
anchors.fill: parent
``` | thanks @Farshid616 for the help. The problem was that my MouseArea wasn't inside the Rectangular. So only I needed is open code and move Mouse Area into Rectangular area, so that the MouseArea would be child of the Rectangular. | 7,003 |
67,484,068 | I have a model with a unique "code" field and a form for the same model where the "code" field is hidden. I need to set the "code" value in the view after the user has copied the form, but I get an IntegrityError exception.
**model**
```
class Ticket(models.Model):
codice = models.CharField(unique=True, max_lengt... | 2021/05/11 | [
"https://Stackoverflow.com/questions/67484068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14293891/"
] | To check for email and operate on it you are probably better of using Spring Integration which has out-of-the-box [email support](https://docs.spring.io/spring-integration/docs/current/reference/html/mail.html).
Regarding your question I suspect you misunderstood the [`ApplicationListener`](https://docs.spring.io/spri... | I think you misunderstood the concept of spring context listeners.
Spring application context starts during the startup of spring driven application.
It has various "hooks" - points that you could listen to and be notified once they happen. So yes, context can be refreshed and when it happens, the listener "fires" and... | 7,004 |
1,487,022 | HI All,
Has anybody been able to extract the device tokens from the binary data that iPhone APNS feedback service returns using PHP? I am looking for something similar to what is been implementented using python here
[http://www.google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#m5eOMDWiKUs/APNSWrapper/**init**.py&q=feedba... | 2009/09/28 | [
"https://Stackoverflow.com/questions/1487022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130985/"
] | [PHP technique to query the APNs Feedback Server](https://stackoverflow.com/questions/1278834/php-technique-to-query-the-apns-feedback-server) | The best place to go for this is actually the Apple developer forums in internal to the iPhone portal - the have a bunch of examples in different languages for working with these push requests.
I'm also currently at an 360iDev push session, and they noted an open source PHP server can be found at:
<http://code.google... | 7,005 |
13,336,623 | I'm using Python 2.6.2. I have a list of tuples `pair` which I like to sort using two nested conditions.
1. The tuples are first sorted in descending count order of `fwd_count`,
2. If the value of count is the same for more than one tuple in `fwd_count`, only those tuples having equal count need to be sorted in desce... | 2012/11/11 | [
"https://Stackoverflow.com/questions/13336623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1611813/"
] | If you require to swap *all* first (of pair) elements (and not just `(1, 36)` and `(0, 36)`), you can do
`fwd_count_sort=sorted(rvs_count.items(), key=lambda x: (x[0][1],-x[0][0]), reverse=True)` | I'm not exactly sure on the definition of your sorting criteria, but this is a method to sort the `pair` list according to the values in `fwd_count` and `rvs_count`. Hopefully you can use this to get to the result you want.
```
def keyFromPair(pair):
"""Return a tuple (f, r) to be used for sorting the pairs by fre... | 7,007 |
69,281,148 | I have around 30000 Urls in my csv. I need to check if it has meta content is present or not, for each url. I am using request\_cache to basically cache the response to a sqlite db. It was taking about 24hrs even after using a caching sys. Therefore I moved to concurrency. I think I have done something wrong with `out ... | 2021/09/22 | [
"https://Stackoverflow.com/questions/69281148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16433326/"
] | I have tried to emulate your functionality. The following code executes in under 4 minutes:-
```
from bs4 import BeautifulSoup as BS
import concurrent.futures
import time
import queue
import requests
URLs = [
"https://www.jython.org",
"http://olympus.realpython.org/dice"
] * 15_000
user_agent = 'Mozilla/5.0 ... | AttributeError: 'str' object has no attribute 'items'
=====================================================
This error is happening in `requests.models.PrepareRequest.prepare_headers()`. When you call `executor.map(networkCall, sites, headers)`, it's casting `headers` to a list, so you end up with `request.headers = '... | 7,008 |
18,937,057 | I am searching for items that are not repeated in a list in python.
The current way I do it is,
```
python -mtimeit -s'l=[1,2,3,4,5,6,7,8,9]*99' '[x for x in l if l.count(x) == 1]'
100 loops, best of 3: 12.9 msec per loop
```
Is it possible to do it faster?
This is the output.
```
>>> l = [1,2,3,4,5,6,7,8,9]*99+[... | 2013/09/21 | [
"https://Stackoverflow.com/questions/18937057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994176/"
] | You can use [the `Counter` class](http://docs.python.org/dev/library/collections.html#collections.Counter) from `collections`:
```
from collections import Counter
...
[item for item, count in Counter(l).items() if count == 1]
```
My results:
```none
$ python -m timeit -s 'from collections import Counter; l = [1, 2,... | Basically you want to remove duplicate entries, so there are some answers here:
* [How do you remove duplicates from a list in Python whilst preserving order?](https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order)
* [Remove duplicates in a list while kee... | 7,011 |
66,093,541 | Is there a way in C++ to pass arguments by name like in python?
For example I have a function:
```
void foo(int a, int b = 1, int c = 3, int d = 5);
```
Can I somehow call it like:
```
foo(5 /* a */, c = 5, d = 8);
```
Or
```
foo(5, /* a */, d = 1);
``` | 2021/02/07 | [
"https://Stackoverflow.com/questions/66093541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15114707/"
] | There are no named function parameters in C++, but you can achieve a similar effect with designated initializers from C++20.
Take all the function parameters and put them into a struct:
```
struct S
{
int a{}, b{}, c{}, d{};
};
```
Now modify your function to take an instance of that struct (by `const&` for ef... | **No**
You have to pass the arguments by order, so, to specify a value for *d*, you must also specify one for *c* since it's declared before it, for example | 7,012 |
64,972,907 | Output:
```none
pygame 2.0.0 (SDL 2.0.12, python 3.8.6)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:\Users\New User\Python Projects\Aliens Invasion Game\alien_invasion.py", line 5, in <module>
class AlienInvasion:
File "C:\Users\New User\Py... | 2020/11/23 | [
"https://Stackoverflow.com/questions/64972907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14625233/"
] | The original code you posted has an indentation issue - your `if __name__ == '__main__'` block is indented, meaning it's actually considered to be within the scope of `class AlienInvasion`:
```
import ...
class AlienInvasion:
def __init__(self):
...
def run_game(self):
...
# IMPORPERLY ... | You should remove your main block from the definition of the `AlienInvasion` class.
Your `.py` file should look like this:
```
import sys
import pygame
class AlienInvasion:
"""Overall class to manage game assets and behaviour."""
def __init__(self):
"""Initialize the game, and create game resources.... | 7,013 |
62,657,469 | I want to search for the word in the file and print next value of it using any way using python
Following is the code :
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite:
remove_comment=line.split('#')[0]
... | 2020/06/30 | [
"https://Stackoverflow.com/questions/62657469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11032819/"
] | ```
def matchTest(testsuite, testList):
hashfile = open("hash.txt", 'a')
with open ('text.txt', 'r') as suite:
lines = [line.strip() for line in suite.readlines() if line.strip()]
print(lines)
for line in lines:
f = re.search(r'component=>"(.*?)"', line) # find part you need... | Try this:
```
import re
remove_comment = '''{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:scrip... | 7,014 |
52,451,119 | I have few text files which contain URLs. I am trying to create a SQLite database to store these URLs in a table. The URL table has two columns i.e. primary key(INTEGER) and URL(TEXT).
I try to insert 100,000 entries in one insert command and loop till I finish the URL list. Basically, read all the text files content ... | 2018/09/21 | [
"https://Stackoverflow.com/questions/52451119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139406/"
] | SQLite uses auto-commit mode by default. This permits `begin transaction` be to omitted. But here we want all the inserts to be in a transaction and the only way to do that is to start a transaction with `begin transaction` so that all the statements that are going to be ran are all in that transaction.
The method `ex... | The UNIQUE constraint on column "url" is creating an implicit index on the URL. That would explain the size increase.
I don't think you can populate the table and afterwards add the unique constraint.
Your bottleneck is surely the CPU. Try the following:
1. Install toolz: `pip install toolz`
2. Use this method:
```... | 7,020 |
26,214,328 | After long debugging I found why my application using python regexps is slow. Here is something I find surprising:
```
import datetime
import re
pattern = re.compile('(.*)sol(.*)')
lst = ["ciao mandi "*10000 + "sol " + "ciao mandi "*10000,
"ciao mandi "*1000 + "sal " + "ciao mandi "*1000]
for s in lst:
pr... | 2014/10/06 | [
"https://Stackoverflow.com/questions/26214328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221660/"
] | The Thompson NFA approach changes regular expressions from default greedy to default non-greedy. Normal regular expression engines can do the same; simply change `.*` to `.*?`. You should not use greedy expressions when non-greedy will do.
Someone already built an NFA regular expression parser for Python: <https://git... | ```
^(?=(.*?sol))\1(.*)$
```
You can try this.This reduces backtracking and fails faster.Try your string here.
<http://regex101.com/r/hQ1rP0/22> | 7,021 |
48,568,283 | Here's an example to find the greatest common divisor for positive integers `a` and `b`, and `a <= b`. I started from the smaller `a` and minus one by one to check if it's the divisor of both numbers.
```
def gcdFinder(a, b):
testerNum = a
def tester(a, b):
if b % testerNum == 0 and a % testerNum ... | 2018/02/01 | [
"https://Stackoverflow.com/questions/48568283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4860812/"
] | Answers to **Q2** and **Q4**.
As I wrote in the comments, you can parse the testerNum as parameter.
Your code would then look like this:
```
def gcdFinder(a, b):
testerNum = a
def tester(a, b, testerNum):
if b % testerNum == 0 and a % testerNum == 0:
return testerNum
else:
... | TO hit only question 4, yes, it's better not to use `global` at all. `global` generally highlights poor code design.
You're going to a lot of trouble; I strongly recommend that you look up standard methods of calculating the GCD, and implement Euclid's Algorithm instead. Coding details left as an exercise for the stud... | 7,024 |
70,643,142 | Say I have this array:
```python
array = np.array([[1,2,3],[4,5,6],[7,8,9]])
```
Returns:
```none
123
456
789
```
How should I go about getting it to return something like this?
```none
111222333
111222333
111222333
444555666
444555666
444555666
777888999
777888999
777888999
``` | 2022/01/09 | [
"https://Stackoverflow.com/questions/70643142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16809168/"
] | You'd have to use [`np.repeat`](https://numpy.org/doc/stable/reference/generated/numpy.repeat.html#numpy-repeat) twice here.
```
np.repeat(np.repeat(array, 3, axis=1), 3, axis=0)
# [[1 1 1 2 2 2 3 3 3]
# [1 1 1 2 2 2 3 3 3]
# [1 1 1 2 2 2 3 3 3]
# [4 4 4 5 5 5 6 6 6]
# [4 4 4 5 5 5 6 6 6]
# [4 4 4 5 5 5 6 6 6]
#... | For fun (because the nested `repeat` will be more efficient), you could use `einsum` on the input array and an array of `ones` that has extra dimensions to create a multidimensional array with the dimensions in an ideal order to `reshape` to the expected 2D shape:
```
np.einsum('ij,ikjl->ikjl', array, np.ones((3,3,3,3... | 7,027 |
53,080,894 | I am trying to make a GUI where the quantity of tkinter entries is decided by the user.
My Code:
```
from tkinter import*
root = Tk()
def createEntries(quantity):
for num in range(quantity):
usrInput = Entry(root, text = num)
usrInput.pack()
createEntries(10)
root.mainloop()
```
This code is... | 2018/10/31 | [
"https://Stackoverflow.com/questions/53080894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585009/"
] | The solution is to store the widgets in a data structure such as a list or dictionary. For example:
```
entries = []
for num in range(quantity):
usrInput = Entry(root, text = num)
usrInput.pack()
entries.append(usrInput)
```
Later, you can iterate over this list to get the values:
```
for entry in entri... | With the following Code you can adjust the number of Buttons and Entrys depending on the Var "fields". I hope it helps
```
from tkinter import *
fields = 'Last Name', 'First Name', 'Job', 'Country'
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' ... | 7,028 |
67,878,084 | I'm trying to teach myself python and I am stuck in the for/while loops. Now I know the difference between the two but once nested loops get involved, i'm left feeling all over the place in terms of determining the hierarchy of the loops. Is there a way that I can get better at this? and how do I troubleshoot my loops ... | 2021/06/07 | [
"https://Stackoverflow.com/questions/67878084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16078295/"
] | If you want it to be a `dm` command we can use the restriction `@commands.dm_only()`
However we then also have to check where the `answer` was given, we do that via some kind of custom `check`. I have modified your command a bit, but you can make the changes again personally.
**Take a look at the following code:**
`... | Edited to show full answer.
Hey ho done it lol.
Basically the message object contains a lot of data, so you need to pull the content of the message using answer.conent.
<https://discordpy.readthedocs.io/en/latest/api.html?highlight=message#discord.Message.content> for reference
```
@bot.command()
async def verify(ct... | 7,029 |
1,205,449 | Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types
i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out
if someone could provide examples in python that would be a bi... | 2009/07/30 | [
"https://Stackoverflow.com/questions/1205449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147602/"
] | You have to encode your input and your output to something that can be represented by the neural network units. ( for example 1 for "x has a certain property p" -1 for "x doesn't have the property p" if your units' range is in [-1, 1])
The way you encode your input and the way you decode your output depends on what yo... | More complex data usually means adding more neurons in the input and output layers.
You can feed each "field" of your register, properly encoded as a real value (normalized, etc.) to each input neuron, or maybe you can even decompose even further into bit fields, assigning saturated inputs of 1 or 0 to the neurons... ... | 7,030 |
2,120,332 | I think this is more a python question than Django.
But basically I'm doing at Model A:
```
from myproject.modelb.models import ModelB
```
and at Model B:
```
from myproject.modela.models import ModelA
```
Result:
>
> cannot import name ModelA
>
>
>
Am I doing something forbidden? Thanks | 2010/01/22 | [
"https://Stackoverflow.com/questions/2120332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234167/"
] | A Python module is imported by executing it top to bottom in a new namespace. When module A imports module B, the evaluation of A.py is paused until module B is loaded. When module B then imports module A, it gets the partly-initialized namespace of module A -- in your case, it lacks the `ModelA` class because the impo... | Mutual imports usually mean you've designed your models incorrectly.
When A depends on B, you should not have B also depending on A.
Break B into two parts.
B1 - depends on A.
B2 - does not depend on A.
A depends on B1. B1 depends on B2. Circularity removed. | 7,035 |
5,425,725 | I have created an objective-C framework that I would like to import and access through a python script. I understand how to import this stuff in Python, but what do i need to do on the obj-c side to make that framework importable?
Thanks | 2011/03/24 | [
"https://Stackoverflow.com/questions/5425725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202431/"
] | You can just use [PyObjC](http://pyobjc.sourceforge.net/), which is included in Mac OS X 10.5 and later. | I'm not sure if this particular combination works, but you might be able to use [SWIG](http://swig.org/) to create a Python module out of your Objective-C which can then be imported into Python. | 7,036 |
11,842,202 | I am trying to upgrade my plone version from 3.3.5 to 4.0. For this I went to this site: [updating plone](http://plone.org/documentation/manual/upgrade-guide/version/upgrading-plone-3-x-to-4.0/buildout-3-4). But I got stuck in the first point. In plone 3, I have python version of 2.4. But for plone 4.x I will need pyth... | 2012/08/07 | [
"https://Stackoverflow.com/questions/11842202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596757/"
] | To upgrade python it really depends on the underlying OS (operating system). If a OS specific upgrade fails, download python from <http://www.python.org/download/> and install it from source.
You might have to upgrade some of the paths in your buildout.cfg | You don't upgrade Python, you install a new version in parallell. | 7,039 |
26,230,028 | I just started using Crossbar.io to implement a live stats page. I've looked at a lot of code examples, but I can't figure out how to do this:
I have a Django service (to avoid confusion, you can assume I´m talking about a function in views.py) and I'd like it to publish messages in a specific topic, whenever it gets ... | 2014/10/07 | [
"https://Stackoverflow.com/questions/26230028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1445416/"
] | Django is a blocking WSGI application, and that does not blend well with AutobahnPython, which is non-blocking (runs on top of Twisted or asyncio).
However, Crossbar.io has a built-in REST bridge, which includes a [HTTP Pusher](https://github.com/crossbario/crossbar/wiki/HTTP%20Pusher%20Service) to which you can submi... | I found what I needed: It is possible to do a HTTP POST request to publish on a topic.
You can read the doc for more information: <https://github.com/crossbario/crossbar/wiki/Using-the-REST-to-WebSocket-Pusher> | 7,040 |
21,834,702 | Like I said in the title, my script only seems to work on the first line.
Here is my script:
```
#!/usr/bin/python
import sys
def main():
a = sys.argv[1]
f = open(a,'r')
lines = f.readlines()
w = 0
for line in lines:
spot = 0
cp = line
for char in reversed(cp):
x = -1
if char ==... | 2014/02/17 | [
"https://Stackoverflow.com/questions/21834702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2353168/"
] | The following script do the same thing as your program, more compactly:
```
import fileinput
deleted = 0
for line in fileinput.input(inplace=True):
stripped = line.rstrip()
deleted += len(line) - len(stripped) + 1 # don't count the newline
print(stripped)
print("Whitespace deleted: {}".format(deleted))
... | `rstrip()` is probably what you want to use to achieve this.
```
>>> 'Here is my string '.rstrip()
'Here is my string'
```
A more compact way to iterate backwards over stings is
```
>>> for c in 'Thing'[::-1]:
print(c)
g
n
i
h
T
```
`[::-1]` is slice notation. SLice notaion can be represented as `[... | 7,041 |
56,696,940 | i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\p... | 2019/06/21 | [
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] | **If you have conda installed in your system then follow these steps:**
* conda create -n py36 python=3.6
* activate py36
* conda config --add channels conda-forge
* conda install numpy
* conda install scipy
* conda install dlib
* pip install --no-dependencies face\_recognition | if your OS is windows7 :
1. download and install dlib.whl x64 or x86
2. download and install cmake app and add it to path
3. pip install cmake
4. pip install dlib only on python 3.6 to 3.7 with ".whl" file
5. pip install face\_recognotion
enjoy face\_recognition | 7,043 |
71,822,376 | Is there any way I can make **Excel** add-ins/extensions using Python?
I have tried javascript but haven't found any result about making add-ins on python. | 2022/04/11 | [
"https://Stackoverflow.com/questions/71822376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17767517/"
] | Try this code
```
nav .wrapper{
display: flex;
justify-content: space-between;
}
nav ul{
display: flex;
}
``` | It should contain http
For example
href="https://classroom.udacity.com/nanodegrees/nd004-1mac-v2/dashboard/overview" | 7,053 |
68,384,185 | Hi I'm trying to build out a basic app django within a python/alpine image.
I am getting en error telling me that there is no matching image for the version of Django that I am looking for.
The Dockerfile in using a `python:3.9-alpine3.14` image and my requirements file is targeting `Django>=3.2.5,<3.3`.
From what i... | 2021/07/14 | [
"https://Stackoverflow.com/questions/68384185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3346752/"
] | Continuing a list over multiple section is not a standard task, I think the clean way to go is definitely with a [counter](https://docs.asciidoctor.org/asciidoc/latest/attributes/counters/).
Instead of an ordered list you could instead use a [Description list](https://docs.asciidoctor.org/asciidoc/latest/lists/descrip... | Here's another hack:
```
= Document
== Section A
. item 1
. item 2
+
[discrete]
== Section B
. item 3
. item 4
+
[discrete]
== Section C
. item 5
. item 6
```
That gets the list items to have the correct item numbers, but the "discrete" headings are indented. You could use some CSS customization (say via [docinf... | 7,055 |
41,204,071 | I have implemented the [python-social-auth](https://github.com/python-social-auth) library for Google OAuth2 in my Django project, and am successfully able to log users in with it. The library stores the `access_token` received in the response for Google's OAuth2 flow.
My question is: use of the [google-api-python-cli... | 2016/12/17 | [
"https://Stackoverflow.com/questions/41204071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/306374/"
] | Given you already have the OAuth2 access token you can use the [`AccessTokenCredentials`](https://developers.google.com/api-client-library/python/guide/aaa_oauth#AccessTokenCredentials) class.
>
> The oauth2client.client.AccessTokenCredentials class is used when you have already obtained an access token by some othe... | You can check examples provided by Google Guide API, for example: sending email via gmail application, <https://developers.google.com/gmail/api/guides/sending> | 7,056 |
52,221,769 | I have two floats `no_a` and `no_b` and a couple of ranges represented as two element lists holding the lower and upper border.
I want to check if the numbers are both in one of the following ranges: `[0, 0.33]`, `[0.33, 0.66]`, or `[0.66, 1.0]`.
How can I write that statement neatly in python code? | 2018/09/07 | [
"https://Stackoverflow.com/questions/52221769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682455/"
] | If you just want to get a `True` or `False` result, consider the following.
```
>>> a = 0.4
>>> b = 0.6
>>>
>>> ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]]
>>>
>>> any(low <= a <= high and low <= b <= high for low, high in ranges)
True
```
If you have an arbitrary amount of numbers to check (not just `a` and `b`)... | Have a look at [here](https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html).
Put your `no_a` and `no_b` into an array and check if all events pass your statement.
---
Second Edit:
As pointed out, the built-in `all` function outperforms the numpy version for this small dataset, so the usage of numpy ha... | 7,058 |
17,604,130 | I need help figuring out this code. This is my first programming class and we have a exam next week and I am trying to do the old exams.
There is one class with nested list that I am having trouble understanding. It basically says to convert `(list of [list of ints]) -> int`.
Basically given a list of list which ev... | 2013/07/11 | [
"https://Stackoverflow.com/questions/17604130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2574430/"
] | If I understand correctly and you want to return the index of the first list that contains at least one even number:
```
In [1]: def first_even(nl):
...: for i, l in enumerate(nl):
...: if not all(x%2 for x in l):
...: return i
...: return -1
...:
In [2]: first_even([[9, 1,... | There are some minor problems with your code:
* `L1[i] % 2 = 0` is using the wrong operator. `=` is for assigning variables a value, while `==` is used for equality.
* You probably meant `range(len(L1))`, as range expects an integer.
* Lastly, you're adding the whole list to the count, when you only wanted to add the ... | 7,063 |
62,984,417 | I am trying to format a string in python, but the values are not being replaced.
Here is my example...
```
uid = results[0][0]
query = """
SELECT
m.whiteUid,
m.blackUid,
u1.displayName AS whiteDisplayName,
u2.displayName AS blackDisplayName,
m.created,
m.modifie... | 2020/07/19 | [
"https://Stackoverflow.com/questions/62984417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3321579/"
] | You should do this:
`query = query.format(...)`.
The format method just returns the formatted string, it doesn't change `self`. | String is immutable.
Use f string. It's recommended.
```
query = f"""
SELECT
m.whiteUid,
m.blackUid,
u1.displayName AS whiteDisplayName,
u2.displayName AS blackDisplayName,
m.created,
m.modified
FROM matches m
INNER JOIN users u1 ON u1.uid = m.whiteUid
INNER JOIN users u2 ON u2.uid ... | 7,066 |
37,724,694 | I am just trying to pass random arguments for below python script.
Code:
```
import json,sys,os,subprocess
arg1 = 'Site1'
arg2 = "443"
arg3 = '[email protected]'
arg4 = 'example@123'
arg5 = '--output req.txt'
arg6 = '-h'
obj=json.load(sys.stdin)
for i in range(len(obj['data'])):
print obj['data'][i]['value']
... | 2016/06/09 | [
"https://Stackoverflow.com/questions/37724694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5005270/"
] | It looks to me like you're passing the entire `obj` dictionary into the command. To get the desired invocation, pass `obj['data'][i]['value']` in the arguments list to `subprocess.call`. So, the final line of your script should be
```
subprocess.call(['./malopinfo.py', arg1, arg2, arg3, arg4, obj['data'][i]['value... | You are directly passing an object. Beforehand you need to convert that into string as `subprocess.call` will expect obj to be a string. Get the string value of one of the obj properties like you already have done `obj['data'][i]['value']` and pass it into your `subprocess.call`. | 7,069 |
51,492,621 | I've recently attempted google's iot end-to-end example (<https://cloud.google.com/iot/docs/samples/end-to-end-sample>) out of pure interest. However, towards the final part of the process where I had to connect devices, I kept running into a run time error.
```
Creating JWT using RS256 from private key file rsa_priv... | 2018/07/24 | [
"https://Stackoverflow.com/questions/51492621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10126223/"
] | To solve this, just pass the correct cloud region parameter to the command --cloud\_region=asia-east1 | You can try giving cloud region when running device script Ex : "--cloud\_region=asia-east1"
python cloudiot\_pubsub\_example\_mqtt\_device.py --project\_id=applied-grove-246108 --registry\_id=my-registry --device\_id=my-device --private\_key\_file=rsa\_private.pem --algorithm=RS256 --cloud\_region=asia-east1 | 7,070 |
30,103,965 | Not by word boundaries, that is solvable.
Example:
```
#!/usr/bin/env python3
text = 'เมื่อแรกเริ่ม'
for char in text:
print(char)
```
This produces:
เ
ม
อ
แ
ร
ก
เ
ร
ม
Which obviously is not the desired output. Any ideas?
A portable representation of text is:
```
text = u'\... | 2015/05/07 | [
"https://Stackoverflow.com/questions/30103965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2397101/"
] | tl;dr: Use `\X` regular expression to extract user-perceived characters:
```
>>> import regex # $ pip install regex
>>> regex.findall(u'\\X', u'เมื่อแรกเริ่ม')
['เ', 'มื่', 'อ', 'แ', 'ร', 'ก', 'เ', 'ริ่', 'ม']
```
---
While I do not know Thai, I know a little French.
Consider the letter `è`. Let `s` and `s2` equal... | I cannot exactly reproduce, but here is a slight modified version of you script, with the output on IDLE 3.4 on a Windows7 64 system :
```
>>> for char in text:
print(char, hex(ord(char)), unicodedata.name(char),'-',
unicodedata.category(char), '-', unicodedata.combining(char), '-',
unicodedata... | 7,071 |
20,294,693 | In the following example, I want to change the `a1` key of `d` in place by calling the `set_x()` function of the class `A`. But I don't see how to access a key in a `dict`.
```
#!/usr/bin/env python
class A(object):
def __init__(self, data=''):
self.data = data
self.x = ''
def set_x(self, x):
self.x =... | 2013/11/29 | [
"https://Stackoverflow.com/questions/20294693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1424739/"
] | You need to refer to the object itself, and modify it there.
Take a look at this console session:
```
>>> a = A("foo")
>>> d = {a:10}
>>> d
{A(foo:): 10}
>>> a.set_x('word')
>>> d
{A(foo:word): 10}
```
You can also get the key-value pair from `dict.items()`:
```
a, v = d.items()[0]
a.set_x("word")
```
Hope this... | You can keep the reference to the object and modify it. If you can't keep a reference to the key object, you can still iterate over the dict using `for k, v in d.items():` and then use the value to know which key you have (although this is somewhat backward in how to use a dict and highly ineficient)
```
a1 = A('foo')... | 7,073 |
59,876,292 | I want to run gs command to copy data using python function in cloud function, is it possible to run a shell command inside the cloud function??. | 2020/01/23 | [
"https://Stackoverflow.com/questions/59876292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12309624/"
] | According to the official documentation [Cloud Functions Execution Environment](https://cloud.google.com/functions/docs/concepts/exec):
>
> Cloud Functions run in a fully-managed, serverless environment where
> Google handles infrastructure, operating systems, and runtime
> environments completely on your behalf. ... | Have tried using [subprocess](https://docs.python.org/3/library/subprocess.html) module to see if it helps you achieve what you need? I haven't tried this myself so I can't be sure if it will work.
```
import subprocess
subprocess.run(["ls", "-l"])
```
Alternatively you can also use CloudRun to run [Docker image wi... | 7,074 |
26,292,102 | Because of inherited html parts when using template engines such as twig (PHP) or jinja2 (python), I may need to nest rows like below:
```
<div class="container">
<div class="row">
<div class="row">
</div>
...
<div class="row">
</div>
</div>
<div class="row">
... | 2014/10/10 | [
"https://Stackoverflow.com/questions/26292102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85443/"
] | You shouldn't wrap the nested rows in `.container` elements, but you *should* nest them in columns. Bootstrap's `row` class has negative left and right margins that are negated by the `col-X` classes' positive left and right margins. If you nest two `row` classes without intermediate `col-X` classes, you get double the... | You shouldn't wrap them in another [container](http://getbootstrap.com/css/#grid) - containers are designed for a typical one-page layout. Unless it would look good / work well with your layout, you may want to look into `container-fluid` if you really want to do this.
**tl;dr** don't wrap in another container. | 7,076 |
30,631,299 | First i'm developing a django app, when i try to run the server with:
python manage.py runserver 0.0.0.0:8000
The terminal shows:
```
"django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb"
```
So, i need to install that package:
```
(app1)Me% pip install MySQL-python... | 2015/06/03 | [
"https://Stackoverflow.com/questions/30631299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2544076/"
] | The solution was in reinstalling the developer tools:
```
xcode-select --install
``` | What fixed it for me was:
`sudo pip install --upgrade setuptools`
Make sure you have mysql installed:
```
brew install mysql
``` | 7,077 |
69,685,355 | I'm sorry if that didn't make any sense! I'm very new to python and I could really use some help.
I don't want the question to be solved for me, but I would appreciate some advice as a starting point.
```
listA = [("Aleah", [74, 100, 120, 67]),
("Hannah", [95, 110, 110, 67]),
("Timothy... | 2021/10/23 | [
"https://Stackoverflow.com/questions/69685355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17225072/"
] | You put your listelement inside the same container - so expanding the list would also expand everything.
You can put your listelement outside and/or give it an absolute position.
Minimal changes can be found here: [codepen](https://codepen.io/coyer/pen/KKvapbv)
Basically I wrapped the inputfield in a relative-positio... | Try This
--------
---
```
ul {
max-height: 250px;
overflow-y: scroll;
}
``` | 7,080 |
47,822,740 | I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/d... | 2017/12/14 | [
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] | We usually use `$ python3 -m venv myvenv` to create a new virtualenv (Here `myvenv` is the name of our virtualenv).
Similar to my case, if you have both `python3.5` as well as `python3.6` on your system, then you might get some errors.
**NOTE:** On some versions of Debian/Ubuntu you may receive the following error:
... | Installing `python3.6` and `python3.6-venv` via `ppa:deadsnakes/ppa` instead of `ppa:jonathonf/python-3.6` worked for me
```
apt-get update \
&& apt-get install -y software-properties-common curl \
&& add-apt-repository ppa:deadsnakes/ppa \
&& apt-get update \
&& apt-get install -y python3.6 python3.6-venv
``` | 7,085 |
14,110,709 | Using the python library matplotlib, I've found what suggests to be a solution to this question:
[Displaying (nicely) an algebraic expression in PyQt](https://stackoverflow.com/questions/14097463/displaying-nicely-an-algebraic-expression-in-pyqt) by utilising matplotlibs [TeX markup](http://matplotlib.org/users/math... | 2013/01/01 | [
"https://Stackoverflow.com/questions/14110709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/848292/"
] | The trick is to render the text, then get its bounding box, and finally adjust the figure size and the vertical positioning of text in the new figure. This saves the figure twice, but as is common in any text engine, the correct bounding box and other parameters can only be correctly obtained after the text has been re... | what about
```
import matplotlib.pyplot as plt
params = {
'figure.figsize': [2,2],
}
plt.rcParams.update(params)
formula = r'$x=\frac{3}{100}$'
fig = plt.figure()
fig.text(0.5,0.5,formula)
plt.savefig('formula.png')
```
The first two arguments of the matplotlib text() function set the position of the ... | 7,094 |
23,012,931 | How to generate something like
```
[(), (1,), (1,2), (1,2,3)..., (1,2,3,...n)]
```
and
```
[(), (4,), (4,5), (4,5,6)..., (4,5,6,...m)]
```
then take the product of them and merge into
```
[(), (1,), (1,4), (1,4,5), (1,4,5,6), (1,2), (1,2,4)....(1,2,3,...n,4,5,6,...m)]
```
?
For the first two lists I've tried ... | 2014/04/11 | [
"https://Stackoverflow.com/questions/23012931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1886382/"
] | Please note that, single element tuples are denoted like this `(1,)`.
```
a = [(), (1,), (1, 2), (1, 2, 3)]
b = [(), (4,), (4, 5), (4, 5, 6)]
from itertools import product
for item1, item2 in product(a, b):
print item1 + item2
```
**Output**
```
()
(4,)
(4, 5)
(4, 5, 6)
(1,)
(1, 4)
(1, 4, 5)
(1, 4, 5, 6)
(1, 2... | If you don't want to use any special imports:
```
start = 1; limit = 10
[ range(start, start + x) for x in range(limit) ]
```
With `start = 1` the output is:
`[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8, 9... | 7,097 |
15,920,413 | I have a large ASCII file (~100GB) which consists of roughly 1.000.000 lines of known formatted numbers which I try to process with python. The file is too large to read in completely into memory, so I decided to process the file line by line:
```
fp = open(file_name)
for count,line in enumerate(fp):
data = np.arr... | 2013/04/10 | [
"https://Stackoverflow.com/questions/15920413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2010845/"
] | Have you tried [`numpyp.fromstring`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html)?
```
np.fromstring(line, dtype=np.float, sep=" ")
``` | The [*np.genfromtxt*](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html) function is a speed champion if you can get it to match you input format.
If not, then you may already be using the fastest method. Your line-by-line split-into-array approach exactly matches the [SciPy Cookbook examples](... | 7,099 |
28,031,210 | I have a code who looks like this :
```
# step 1 remove from switch
for server in server_list:
remove_server_from_switch(server)
logger.info("OK : Removed %s", server)
# step 2 remove port
for port in port_list:
remove_ports_from_switch(port)
logger.info("OK : Removed port %s", port)
# step 3 exe... | 2015/01/19 | [
"https://Stackoverflow.com/questions/28031210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4471200/"
] | This is what context managers are for. Read up on the [with statement](https://docs.python.org/2/reference/compound_stmts.html#with) for details, but the general idea is you need to write context manager classes where the `__enter__` and `__exit__` functions do the removal/re-addition of your servers/ports. Then your c... | Maybe something like this will work:
```
undo_dict = {remove_server_from_switch: add_server_to_switch,
remove_ports_from_switch: add_ports_to_switch,
add_server_to_switch: remove_server_from_switch,
add_ports_to_switch: remove_ports_from_switch}
def undo_action(action):
arg... | 7,100 |
2,157,665 | I have created a templatetag that loads a yaml document into a python list. In my template I have `{% get_content_set %}`, this dumps the raw list data. What I want to be able to do is something like
```
{% for items in get_content_list %}
<h2>{{items.title}}</h2>
{% endfor %}`
``` | 2010/01/28 | [
"https://Stackoverflow.com/questions/2157665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245889/"
] | If the list is in a python variable X, then add it to the template context `context['X'] = X` and then you can do
```
{% for items in X %}
{{ items.title }}
{% endfor %}
```
A template tag is designed to render output, so won't provide an iterable list for you to use. But you don't need that as the normal con... | Since writing complex templatetags is not an easy task (well documented though) i would take {% with %} tag source and adapt it for my needs, so it looks like
```
{% get_content_list as content %
{% for items in content %}
<h2>{{items.title}}</h2>
{% endfor %}`
``` | 7,103 |
58,578,181 | I'm try to create python package in **3.6** But I also want backward compatibility to **2.7** How can I write a code for **3.6** and **2.7**
For example I have method called `geo_point()`.
```
def geo_point(lat: float, lng: float):
pass
```
This function work fine in **3.6** but not in **2.7** it show syntax e... | 2019/10/27 | [
"https://Stackoverflow.com/questions/58578181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12280920/"
] | If type hinting is the only issue you have with your code, then look at SO question [Type hinting in Python 2](https://stackoverflow.com/questions/35230635/type-hinting-in-python-2)
It says, that python3 respects also type hinting in comment lines.
Python2 will ignore it and python3 respects this alternative syntax. I... | I doubt it's worth the trouble, but as a proof of concept: You could use a combination of a decorator and the built-in `exec()` function. Using `exec()` is a way to avoid syntax errors due to language differences.
Here's what I mean:
```
import sys
sys_vers_major, sys_vers_minor, sys_vers_micro = sys.version_info[:3... | 7,104 |
4,838,740 | Imagine that I have a model that describes the printers that an office has. They could be ready to work or not (maybe in the storage area or it has been bought but not still in th office ...). The model must have a field that represents the phisicaly location of the printer ("Secretary's office", "Reception", ... ). Th... | 2011/01/29 | [
"https://Stackoverflow.com/questions/4838740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/454760/"
] | There is a [`Queue`](http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue) class within the `multiprocessing` module specifically for this purpose.
Edit: If you are looking for a complete framework for parallel computing which features a `map()` function using a task queue, have a look at the para... | About queue implementations. There are some.
Look at the Celery project. <http://celeryproject.org/>
So, in your case, you can run 12 conversions (one on each CPU) as Celery tasks, add a callback function (to the conversion or to the task) and in that callback function add a new conversion task running when one of th... | 7,107 |
4,240,266 | I have a little module that creates a window (program1). I've imported this into another python program of mine (program2).
How do I make program 2 get self.x and x that's in program1?
This is program1.
```
import Tkinter
class Class(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, p... | 2010/11/21 | [
"https://Stackoverflow.com/questions/4240266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433417/"
] | You can access the variable `self.x` as a member of an instance of `Class`:
```
c = Class(parent)
print(c.x)
```
You cannot access the local variable - it goes out of scope when the method call ends. | I'm not sure exactly what the purpose of 'self.x' and 'x' are but one thing to note in the 'Main' method of class Class
```
def Main(self):
self.button= Tkinter.Button(self,text='hello')
self.button.pack()
self.x = 34
x = 62
```
is that 'x' and 'self.x' are two different variables. T... | 7,116 |
6,372,159 | Can anyone suggest me what is the most pythonic way to import modules in python?
Let me explain - i have read a lot of python code and found several different ways of how to import modules or if to be more precise - when to import:
1. Use one module/several modules which include all the imports(third party modules) w... | 2011/06/16 | [
"https://Stackoverflow.com/questions/6372159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781150/"
] | It *really* doesn't matter, so long as you don't `from ... import *`. The rest is all taste and getting around cyclic import issues. [PEP 8](http://www.python.org/dev/peps/pep-0008/) states that you should import at the top of the script, but even that isn't set in stone. | Python's "import" loads a Python module into its own namespace, so that you have to add the module name followed by a dot in front of references to any names from the imported module
```
import animals
animals.Elephant()
```
"from" loads a Python module into the current namespace, so that you can refer to it without... | 7,117 |
50,105,459 | Hello i have been playing around with python recently and have been trying to learn how to control external peripherals and i/o ports on my laptop.
I have been trying to disable USB ports and disable my network adapter. However when i run my program it does not work. The code does not have a specific syntax error but ... | 2018/04/30 | [
"https://Stackoverflow.com/questions/50105459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7802263/"
] | I think you should try to run such commands as admin in windows. This might help: <https://social.technet.microsoft.com/Forums/windows/en-US/05cce5f6-3c3a-4bb8-8b72-8c1ce4b5eff1/how-to-run-a-program-as-adminitrator-via-the-command-line?forum=w7itproappcompat>
You can also modify your command to print the output in std... | I found the issue with the code. to start with i was using the `subprocess.call` function however trying to run the program with Administrator through python do it through command prompt and use this line of code instead
```
subprocess.run(["powershell","Disable-NetAdapter -Name '*'"])
```
Note\* Yes i changed from ... | 7,122 |
67,915,722 | I am fighiting with some listing all possibilities of command with optional and mandatory parameters in python. I need it to generate some autocomplete script in bash based on help output from some script.
E.g. fictional command:
```
add disk -pool <name> { -diskid <diskid> | -diskid auto [-fx | -tdr] } [-fx] [-statu... | 2021/06/10 | [
"https://Stackoverflow.com/questions/67915722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11387742/"
] | The question is pretty lacking on what exactly wants to be retrieved from Kubernetes but I think I can provide a good baseline.
When you use Kubernetes, you are most probably using `kubectl` to interact with `kubeapi-server`.
Some of the commands you can use to retrieve the information from the cluster:
* `$ kubectl... | If you want to extract just single values, perhaps as part of scripts, then what you are searching for is `-ojsonpath` such as this example:
```
kubectl get svc service-name -ojsonpath='{.spec.ports[0].port}'
```
which will extract jus the value of the first port listed into the service **specs**.
docs - <https://k... | 7,123 |
35,934,735 | I'd like to bind a class method to the object instance so that when the method is invoke as callback it can still access the object instance. I am using an event emitter to generate and fire events.
This is my code:
```
#!/usr/bin/env python3
from pyee import EventEmitter
class Component(object):
_emiter = Event... | 2016/03/11 | [
"https://Stackoverflow.com/questions/35934735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022525/"
] | Get start day && end day:
```
$date = date('Y-m-d');
$startDate = new \DateTime($date);
$endDate = new \DateTime($date);
$endDate->modify("+1 day -1 second");
echo $startDate->format('Y-m-d H:i:s');
return dd($endDate);
``` | change your output to:
```
echo $StartDate->format('Y-m-d H:i:s');
```
Here's a list of all the formatting characters that can be used to customize your output [Link](http://www.w3schools.com/php/func_date_date.asp) | 7,124 |
63,345,326 | I am new to OPC-UA and Eclipse Milo and I am trying to construct a client that can connect to the OPC-UA server of a machine we have just acquired.
I have been able to set up a simple OPC-UA server on my laptop by using this python tutorial series: <https://www.youtube.com/watch?v=NbKeBfK3pfk>. Additionally, I have be... | 2020/08/10 | [
"https://Stackoverflow.com/questions/63345326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8381207/"
] | I see a couple things to try.
First, make sure to set your custom js file to have 'slick-js' as a dependancy. This way it loads *after* slick slider does.
Also, jquery is already part of wordpress, so you **do not** need to enque it again. However, it should be a dependancy for both your custom script and slick:
```... | Thank you very much, now it finally works. One other thing that I that I was not aware of, was that I was to replace the $ with jQuery, so my custom.js looks like this:
```
`jQuery('.slider').slick({
arrows: false,
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
... | 7,125 |
43,037,588 | I have a CSV file in the same directory as my Python script, and I would like to take that data and turn it into a list that I can use later. I would prefer to use Python's CSV module. After reading the the module's documentation and questions regarding it, I have still not found any help.
### Code
```
#!/usr/bin/env... | 2017/03/27 | [
"https://Stackoverflow.com/questions/43037588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6417530/"
] | You need to open the file in read mode, read the contents!
That is,
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
inputfile = 'inputfile.csv'
inputm = []
with open(inputfile, "rb") as f:
reader = csv.reader(f, delimiter="\t")
for row in reader:
inputm.append(row)
```
Output:
```
[['... | You actually need to `open()` the file:
```
inputfile = open('inputfile.csv')
```
You may want to look at the `with` statement:
```
with open('inputfile.csv') as inputfile:
reader = csv.reader(inputfile)
inputm = list(reader)
``` | 7,126 |
11,306,641 | Here on SO people sometimes say something like "you cannot parse X with regular expressions, because X is not a regular language". From my understanding however, modern regular expressions engines can match more than just regular languages in [Chomsky's sense](http://en.wikipedia.org/wiki/Chomsky_hierarchy). My questio... | 2012/07/03 | [
"https://Stackoverflow.com/questions/11306641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | Modern regex engines can certainly parse a bigger set of languages than the regular languages set. So said, none of the four classic Chomsky sets are exactly recognized by regexes. All regular languages are clearly recognized by regexes. There are some classic context-free languages that cannot be recognized by regexes... | You can read about regexes in *[An Introduction to Language And Linguistics
By Ralph W. Fasold, Jeff Connor-Linton P.477](http://books.google.com/books?id=dlzthEZGkmsC&pg=PA477#v=onepage&q&f=false)*
**Chomsky Hierarchy**:
Type0 >= Type1 >= Type2 >= Type3
Computational Linguistics mainly features Type 2 & 3 Grammars... | 7,127 |
34,722,459 | Is there a way to generate a file on HDFS directly?
I want to avoid generating a local file and then over hdfs command line like:
`hdfs dfs -put - "file_name.csv"` to copy to HDFS.
Or is there any python library? | 2016/01/11 | [
"https://Stackoverflow.com/questions/34722459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5773478/"
] | Have you tried with [HdfsCli](http://hdfscli.readthedocs.org/en/latest/quickstart.html)?
To quote the paragraph [Reading and Writing files](http://hdfscli.readthedocs.org/en/latest/quickstart.html#reading-and-writing-files):
```
# Loading a file in memory.
with client.read('features') as reader:
features = reader.r... | Is extremly slow when I use hdfscli the write method?
Is there an any way to speedup with using hdfscli?
```
with client.write(conf.hdfs_location+'/'+ conf.filename, encoding='utf-8', buffersize=10000000) as f:
writer = csv.writer(f, delimiter=conf.separator)
for i in tqdm(10000000000):
row = [column.get_value() f... | 7,130 |
63,170,922 | Is there a way to **try to** decode a bytearray without raising an error if the encoding fails?
**EDIT**: The solution needn't use bytearray.decode(...). Anything library (preferably standard) that does the job would be great.
**Note**: I don't want to ignore errors, (which I could do using `bytearray.decode(errors='... | 2020/07/30 | [
"https://Stackoverflow.com/questions/63170922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4093278/"
] | You could use the [suppress](https://docs.python.org/3/library/contextlib.html#contextlib.suppress) context manager to suppress the exception and have slightly prettier code than with try/except/pass:
```py
import contextlib
...
return_val = None
with contextlib.suppress(UnicodeDecodeError):
return_val = my_bytear... | The `chardet` module can be used to detect the encoding of a bytearray before calling `bytearray.decode(...)`.
**The Code:**
```py
import chardet
identity = chardet.detect(my_bytearray)
```
The method `chardet.detect(...)` returns a dictionary with the following format:
```
{
'confidence': 0.99,
'encoding': 'a... | 7,133 |
41,801,225 | I'm very new to python. I am writing code to generate an array of number but the output is not as I want.
The code is as follows
```
import numpy as np
n_zero=input('Insert the amount of 0: ')
n_one =input('Insert the amount of 1: ')
n_two =input('Insert the amount of 2: ')
n_three = input('Insert the amount of 3:... | 2017/01/23 | [
"https://Stackoverflow.com/questions/41801225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7456346/"
] | It's better to use android latest versions. But you can resolve by replace below code in your `app/build.gradle` file
```
android {
compileSdkVersion 24
buildToolsVersion "24.2.1"
defaultConfig {
minSdkVersion 19
targetSdkVersion 24
...
}
```
Dependencies as follows:
```
compile ... | I have just used Maven google repository in build.gradle(project) :
```
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
maven {
url 'https://maven.google.com'
}
}
... | 7,134 |
70,771,156 | I've converted my python script with tkinter module to a standalone executable file with PyInstaller but it doesn't work without image.png file in the same patch. How I can add this .png file to my app. And why .exe file have an enormous weight of ~350 Mb? | 2022/01/19 | [
"https://Stackoverflow.com/questions/70771156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17971397/"
] | I had the exact same situation with Tkinter and a single image needed in the GUI.
I combined Aleksandr Tyshkevich answer here and Jonathon Reinhart's answer here [Pyinstaller adding data files](https://stackoverflow.com/questions/41870727/pyinstaller-adding-data-files) as I need to send just the exe file to others, so... | It works:
```py
import os
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
path = resource_path("image.png")
photo = tk.PhotoImage(file=path)
``` | 7,144 |
34,712,248 | Trying to download the website with python, but getting errors. My intention is to download the website, extract relevant information from it using python, save result to another file on my hard disk. Having trouble on step 1. Other steps were working until some strange SSL error. I am using python 2.7
```
import urll... | 2016/01/10 | [
"https://Stackoverflow.com/questions/34712248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5771257/"
] | Okay. Let start from simple.
First you need get unique user\_id/dev id combinations
```
select distinct dev_id,user_id from reports
```
Result will be
```
dev_id user_id
------------------
111 1
222 2
111 2
333 3
```
After that you should get number of diffe... | I think following sql query should solve you problem:
```
SELECT t1.user_id, t1.dev_id, count(t2.user_id) as qu
FROM (Select Distinct * from reports) t1
Left Join (Select Distinct * from reports) t2
on t1.user_id != t2.user_id and t2.dev_id = t1.dev_id
group by t1.user_Id, t1.dev_id
```
[SQL Fiddle Link](http://sql... | 7,145 |
45,510,287 | I want to split long math equation by multipliers.
The expression is given as a string where whitespaces are allowed.
For example:
```
"((a*b>0) * (e>500)) * (abs(j)>2.0) * (n>1)"
```
Should return:
```
['a*b>0', 'e>500', 'abs(j)>2.0', 'n>1']
```
If the division is used things get even more complicated, but let... | 2017/08/04 | [
"https://Stackoverflow.com/questions/45510287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3152072/"
] | ```
import re
string = "((a-b>0) * (e + 10>500)) * (abs(j)>2.0) * (n>1)"
signals = {'+','*','/','-'}
###
##
def splitString(string):
arr_equations = re.split(''([\)]+(\*|\-|\+|\/)+[\(])'',string.replace(" ", ""))
new_array = []
for each_equa in arr_equations:
each_equa = each_equa.strip("()")... | You can simply use the `split()` function:
```
ans_list = your_string.split(" * ")
```
Note the spaces around the multiplier sign. This assumes that your string is exactly as you say. | 7,155 |
57,302,048 | How to Fix this error? I tried visiting all the forums searching for answers to rectify this issue.
Here i am trying to perform multi-label classification using keras
```
from keras.preprocessing.text import Tokenizer
from keras.models import Sequential
from keras.layers import Dense
from keras.preprocessing.sequenc... | 2019/08/01 | [
"https://Stackoverflow.com/questions/57302048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11050535/"
] | Adding an index along the lines of the following might help the performance:
```
CREATE INDEX idx ON table_e (Phone_number, bill_date, col1, col2);
```
Here `col1` and `col2` are the other two columns which might appear in the `SELECT` clause. The strategy of this index, if used, would be to scan the relatively smal... | If you can update then it is better to create `index` on `a.invoice_date` and . Please find the [link](https://dev.mysql.com/doc/refman/8.0/en/index-hints.html) for the same. | 7,157 |
26,535,493 | I wrote a custom python module. It consists of several functions divided thematically between 3 .py files, which are all in the same directory called `microbiome` in my home directory. So the whole path to my custom module directory is:
```
/Users/drosophila/microbiome
```
I'm working on OsX Mavericks. I want to imp... | 2014/10/23 | [
"https://Stackoverflow.com/questions/26535493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1954277/"
] | The *right* way to do this, as explained in the [Python Packaging User Guide](https://packaging.python.org/en/latest/), is to create a `setup.py`-based project.
Then, you can just install your code for any particular Python installation (or virtual environment) by using, e.g., `pip3 install .` from the root directory ... | As you've discovered, `/etc/paths` affects `$PATH`. But `$PATH` does not affect where Python looks for modules. Try `$PYTHONPATH` instead. See `man python` for details. | 7,158 |
56,973,032 | So I am trying to install plaidML-keras so I can do tensor-flow stuff on my MacBookPro's gpu (radeon pro 560x). From my research, it can be done using plaidML-Keras ([instalation instrutions](https://github.com/plaidml/plaidml/blob/master/docs/install.rst#macos)). When I run `pip install -U plaidml-keras` it works fine... | 2019/07/10 | [
"https://Stackoverflow.com/questions/56973032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8565630/"
] | Disclaimer: I'm on the PlaidML team, and we're actively working to improve the setup experience and documentation around it. We're sorry you were stuck on this. For now, here's some instructions to get you back on track.
1. Find out where plaidml-setup was installed. Typically, this is some variant of `/usr/local/bin`... | I'm facing the same problem and answers online are not very helpful. In this case, I'd suggest debugging yourself.
Since this is where the problem is:
```
File "/usr/local/lib/python3.7/site-packages/plaidml/settings.py", line 30, in _setup_config
'Could not find PlaidML configuration file: "{}".'.format(filename))
... | 7,159 |
16,580,285 | I am writing a python script to keep a buggy program open and I need to figure out if the program is not respoding and close it on windows. I can't quite figure out how to do this. | 2013/05/16 | [
"https://Stackoverflow.com/questions/16580285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2125510/"
] | On Windows you can do this:
```
import os
def isresponding(name):
os.system('tasklist /FI "IMAGENAME eq %s" /FI "STATUS eq running" > tmp.txt' % name)
tmp = open('tmp.txt', 'r')
a = tmp.readlines()
tmp.close()
if a[-1].split()[0] == name:
return True
else:
return False
```
It ... | Piling up on the awesome answer from @Saullo GP Castro, this is a version using `subprocess.Popen` instead of `os.system` to avoid creating a temporary file.
```py
import subprocess
def isresponding(name):
"""Check if a program (based on its name) is responding"""
cmd = 'tasklist /FI "IMAGENAME eq %s" /FI "ST... | 7,165 |
5,230,699 | ```
gardai-plan-crackdown-on-troublemakers-at-protest-2438316.html': {'dail': 1, 'focus': 1, 'actions': 1, 'trade': 2, 'protest': 1, 'identify': 1, 'previous': 1, 'detectives': 1, 'republican': 1, 'group': 1, 'monitor': 1, 'clashes': 1, 'civil': 1, 'charge': 1, 'breaches': 1, 'travelling': 1, 'main': 1, 'disrupt': 1, '... | 2011/03/08 | [
"https://Stackoverflow.com/questions/5230699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/515263/"
] | There are details on the [ARFF file format here](http://www.cs.waikato.ac.nz/~ml/weka/arff.html) and it's very simple to generate. For example, using a cut-down version of your Python dictionary, the following script:
```
import re
d = { 'gardai-plan-crackdown-on-troublemakers-at-protest-2438316.html':
{'dail'... | I know it's pretty easy to generate an arff file on your own, but I still wanted to make it simpler so I wrote a python package
<https://github.com/ubershmekel/arff>
It's also on pypi so `easy_install arff` | 7,166 |
18,507,559 | Since I too have also seen this question on SO, so this might be a duplicate for many, but I've not found an answer to this question.
I want select an item from the navigation bar and show the content inside another tag by replacing the current data with AJAX-generated data.
Currently I'm able to post the data into ... | 2013/08/29 | [
"https://Stackoverflow.com/questions/18507559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1162512/"
] | change it id
```
<div id="container-fluid"></div>
```
this is id selector `$("#container-fluid")`
[id-selector](http://api.jquery.com/id-selector/)
if you want to access by class you can use
`$(".container-fluid")`
[class-selector](http://api.jquery.com/class-selector/) | try
```
$("#nav_bar li").click(function(){
var text_input = $(this).text(); // works fine
$.ajax({
type: "POST", //able to post the data behind the scenes
url: "/dashboard/",
data : { 'which_nav_bar' : text_input }
success: function(result){
... | 7,169 |
44,830,396 | I am parsing a websocket message and due do a bug in a specific socket.io version (Unfortunately I don't have control over the server side), some of the payload is double encoded as utf-8:
The correct value would be **Wrocławskiej** (note the l letter which is LATIN SMALL LETTER L WITH STROKE) but I actually get back ... | 2017/06/29 | [
"https://Stackoverflow.com/questions/44830396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3450689/"
] | You text was encoding to UTF-8, those bytes were then interpreted as ISO-8859-1 and re-encoded to UTF-8.
`Wrocławskiej` is unicode: 0057 0072 006f 0063 **0142** 0061 0077 0073 006b 0069 0065 006a
Encoding to UTF-8 it is: 57 72 6f 63 **c5 82** 61 77 73 6b 69 65 6a
In [ISO-8859-1](https://en.wikipedia.org/wiki/ISO/I... | Well, double encoding may not be the only issue to deal with. Here is a solution that counts for more then one reason
```
String myString = "heartbroken ð";
myString = new String(myString.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
String cleanedText = StringEscapeUt... | 7,171 |
63,550,237 | Here z is a list of dict().
```
z = [{'loss': [1, 2, 2] , 'val_loss':[2,4,5], 'accuracy':[3,8,9], 'val_accuracy':[5,9,7]},
{'loss': [1, 2, 2] , 'val_loss':[2,4,5], 'accuracy':[3,8,9], 'val_accuracy':[5,9,7]},
{'loss': [1, 2, 2] , 'val_loss':[2,4,5], 'accuracy':[3,8,9], 'val_accuracy':[5,9,7]},
{'loss': ... | 2020/08/23 | [
"https://Stackoverflow.com/questions/63550237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3168982/"
] | The notation `a = b = c = d = []` assign a new list to `d`, then assign the 3 others variable to `d`, so you have 4 variables pointing to one same list, so you put 4\*10 items in the same list.
Do :
```
a, b, c, d = [], [], [], []
```
Using `map` and `itemgetter` you can do
```
from operator import itemgetter
los... | In python, when you create a variable, you are just creating a pointer to an object, and not a copy of the object. In this case, when you are initializing your list with `a = b = c = d = []`, you are actually making a, b, c, and d point to the same list instead of creating four different lists.
Take the following exam... | 7,174 |
300,925 | So, I've spent enough time using ASP.NET webforms to know that I'd almost rather go back to doing classic ASP than use them. But I'm hesitant to move to ASP.NET MVC until it becomes more mature. Are there any open source alternatives?
The main thing I'm looking for is something that's easy to learn and to get a protot... | 2008/11/19 | [
"https://Stackoverflow.com/questions/300925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | Another alternative, with which I have no experience, is [ProMesh](http://www.codeplex.com/promesh). Personally, I moving to ASP.NET MVC. | One alternative that seems interesting is [MonoRail](http://www.castleproject.org/monorail/index.html) although I haven't tested it out fully. | 7,175 |
44,183,891 | Hello community / developers,
I am currently trying to install SCIP with python and found that there is Windows Support and a pip installer based on <https://github.com/SCIP-Interfaces/PySCIPOpt/blob/master/INSTALL.md>.
Nevertheless I run into a problem "Cannot open include file"
Below is a list of the things I perf... | 2017/05/25 | [
"https://Stackoverflow.com/questions/44183891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7646564/"
] | This looks like a `UNION` of two `INNER JOIN`s. One gets the information from `stock` and has `NULL` values in the columns from `sales_item`, the other gets information from `sales_item` and has `NULL` for the columns from `stock`.
```
SELECT i.item_id, i.name, s.stock_id, s.quantity, NULL AS sales_item_id, NULL AS sa... | All the nulls in your example shows that you are trying to join together two completely different result sets: join the items with the stock and get all that data, then join the items with the sales and return all that data. The trickiness is that you have two different kinds of results in your desired join table. The ... | 7,184 |
17,053,103 | I saw [this question](https://stackoverflow.com/questions/903557/pythons-with-statement-versus-with-as), and I understand when you would want to use `with foo() as bar:`, but I don't understand when you would just want to do:
```
bar = foo()
with bar:
....
```
Doesn't that just remove the tear-down benefits of us... | 2013/06/11 | [
"https://Stackoverflow.com/questions/17053103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1388603/"
] | For example when you want to use `Lock()`:
```
from threading import Lock
myLock = Lock()
with myLock:
...
```
You don't really need the `Lock()` object. You just need to know that it is on. | Using `with` without `as` still gets you the exact same teardown; it just doesn't get you a new local object representing the context.
The reason you want this is that sometimes the context itself isn't directly useful—in other words, you're only using it for the side effects of its context enter and exit.
For exampl... | 7,185 |
52,844,036 | I have been trying to create a folder inside a Jenkins pipeline with the following code:
```
pipeline {
agent {
node {
label 'python'
}
}
stages{
stage('Folder'){
steps{
folder 'New Folder'
}
}
}
}
```
But I get the following error message
java.lang.NoSuchMethodErr... | 2018/10/16 | [
"https://Stackoverflow.com/questions/52844036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9131570/"
] | You can pass an updater function to setState. Here's an example of how this might work.
The object returned from the updater function will be merged into the previous state.
```
const updateBubble = ({y, vy, ...props}) => ({y: y + vy, vy: vy + 0.1, ...props})
this.setState(state => ({bubbles: state.bubbles.map(updat... | I would sugest you should change your approach. You should only manage the state as the first you showed, and then, in another component, manage multiple times the component you currently have.
You could use something like this:
```
import React from 'react'
import Box from './box'
export default class Boxes extends... | 7,188 |
39,427,946 | I'm wondering how I can import the six library to python 2.5.2? It's not possible for me to install using pip, as it's a closed system I'm using.
I have tried to add the six.py file into the lib path. and then use "import six". However, it doesnt seem to be picking up the library from this path. | 2016/09/10 | [
"https://Stackoverflow.com/questions/39427946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264975/"
] | According to project history, [version 1.9.0](https://bitbucket.org/gutworth/six/src/a9b120c9c49734c1bd7a95e7f371fd3bf308f107?at=1.9.0) supports Python 2.5. Compatibility broke with 1.10.0 release.
>
> Six supports every Python version since 2.5. It is contained in only
> one Python file, so it can be easily copied ... | You can't use `six` on Python 2.5; it requires Python 2.6 or newer.
From the [`six` project homepage](https://bitbucket.org/gutworth/six):
>
> Six supports every Python version since 2.6.
>
>
>
Trying to install `six` on Python 2.5 anyway fails as the included `setup.py` tries to import the `six` module, which t... | 7,191 |
36,610,806 | Here is a [link](https://drive.google.com/folderview?id=0B0bHr4crS9cpaWlockpxcmJxelE&usp=drive_web) to a project and output that you can use to reproduce the problem I describe below.
I'm using **coverage** with **tox** against multiple versions of python. My tox.ini file looks something like this:
```
[tox]
envlist ... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36610806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3188632/"
] | I came upon this problem today, but couldn't find an easy answer. So, for future reference, here is the solution that I came up with.
1. Create an `envlist` that contains each version of Python that will be tested and a custom env for `cov`.
2. For all versions of Python, set `COVERAGE_FILE` environment varible to sto... | I don't understand why tox wouldn't install coverage in each virtualenv properly. You should get two different coverage reports, one for py27 and one for py35. A nicer option might be to produce one combined report. Use `coverage run -p` to record separate data for each run, and then `coverage combine` to combine them ... | 7,192 |
29,419,322 | I am getting the following error while executing the below code snippet exactly at the line `if uID in repo.git.log():`,
the problem is in `repo.git.log()`, I have looked at all the similar questions on Stack Overflow which suggests to use `decode("utf-8")`.
how do I convert `repo.git.log()` into `decode("utf-8")`?
`... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29419322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | 0x92 is a smart quote(’) of Windows-1252. It simply doesn't exist in unicode, therefore it can't be decoded.
Maybe your file was edited by a Windows machine which basically caused this problem? | After good research, I got the solution. In my case, **`datadump.json`** file was having the issue.
* Simply Open the file in notepad format
* Click on save as option
* Go to encoding section below & Click on "UTF-8"
* Save the file.
Now you can try running the command. You are good to go :)
For your reference, I ha... | 7,193 |
32,586,612 | I was getting started with **AWS' Elastic Beanstalk**.
I am following this [tutorial](https://realpython.com/blog/python/deploying-a-django-app-to-aws-elastic-beanstalk/) to **deploy a Django/PostgreSQL app**.
I did everything before the 'Configuring a Database' section. The deployment was also successful but I am g... | 2015/09/15 | [
"https://Stackoverflow.com/questions/32586612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4201498/"
] | Have you created a `requirements.txt` in the root of your application? [Elastic Beanstalk will automatically install the packages from this file upon deployment.](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/python-configuration-requirements.html) (Note it might need to be checked into source control to be dep... | The answer (<https://stackoverflow.com/a/47209268/6169225>) by [carl-g](https://stackoverflow.com/users/39396/carl-g) is correct. One thing that got me was that `requirements.txt` was in the wrong directory. Let's say you created a django project called `mysite`. This is the directory in which you run the `eb` command(... | 7,198 |
52,308,349 | I have successfully installed mysql-connector using pip.
```
Installing collected packages: mysql-connector
Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
```
However, in PyCharm when I have a script that uses the line:
```
import mysql-connector
```
PyCharm giv... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52308349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8207436/"
] | It may be because you are using a virtual environment inside pyCharm, while you might have installed the library using system's default pip.
Check `Preferences->Project->Python Interpreter` inside Pycharm, and see if your library is listed there. If not, install it using **`+`** icon. Normally, if you use pyCharm's in... | Go to project interpreter and download mysql-connector.You need to install it also in pycharm | 7,201 |
49,076,648 | Doing this seemingly trivial task should be simple and obvious using PIVOT - but isn't.
What is the cleanest way to do the conversion, not necessarily using pivot, **when limited to ONLY using "pure" SQL** (see other factors, below)?
It shouldn't affect the answer, but note that a Python 3.X front end is being used ... | 2018/03/02 | [
"https://Stackoverflow.com/questions/49076648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459519/"
] | **EDIT:**
The answer is incorrect, because it is one type of recursion. It is called indirect recursion <https://en.wikipedia.org/wiki/Recursion_(computer_science)#Indirect_recursion>.
~~I think the simplest way to do this without recursion is the following:~~
```
import java.util.LinkedList;
import java.util.List... | Since the question is very interesting, I have tried to simplify the answer of *hide* :
```
public class Stackoverflow {
static class Handler {
void handle(Chain chain){
chain.process();
System.out.println("yeah");
}
}
static class Chain {
private List<Han... | 7,209 |
59,707,234 | I'm unable to install pygraphviz even after installing graphviz and ensuring that cgraph.h is present in the directory.
I've also manually specified the directory for install. e.g. install-path
fatal error C1083: Cannot open include file: 'graphviz/cgraph.h': No such file or directory
Looking for any and all suggest... | 2020/01/12 | [
"https://Stackoverflow.com/questions/59707234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9682236/"
] | On Ubuntu please do
`sudo apt install graphviz-dev` | For those who visit this page, you may already come across to this [fix](https://github.com/tan-wei/pygraphviz) or this [issue](https://github.com/pygraphviz/pygraphviz/issues/155) on GitHub and try to install GraphViz2.38 manually. But neither of them will work since GraphViz and PyGraphViz are 2 different libraries
... | 7,219 |
14,119,978 | I'm a newbie and was trying something in python 2.7.2 with Numpy which wasn't working as expected so wanted to check if there was something basic I was misunderstanding.
I was calculating a value for a triangle (trinormals) and then updating a value per point of the triangle (vertnormals) using an array of triangle in... | 2013/01/02 | [
"https://Stackoverflow.com/questions/14119978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942439/"
] | First the column in which you store the date should be an long type. This column will store the milliseconds from epoch for the date.
Now for Query
```
Calendar calendar = Calendar.getInstance(); // This will give you the current time.
// Removing the timestamp from current time to point to todays date
ca... | ```
Select *
From TABLE_NAME
WHERE DATEDIFF(day, GETDATE(), COLUMN_TABLE) <= 3
``` | 7,221 |
41,914,398 | I've written this very short spider to go to a U.S. News link and take the names of the colleges listed there.
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import scrapy
class CollegesSpider(scrapy.Spider):
name = "colleges"
start_urls = [
'http://colleges.usnews.rankingsandreviews.com/best-colleges... | 2017/01/28 | [
"https://Stackoverflow.com/questions/41914398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5535448/"
] | Got it! It is because the robot detection.
Encode
```
>>> r = requests.get('http://colleges.usnews.rankingsandreviews.com/best-colleges/rankings/national-universities?_mode=list&acceptance-rate-max=20', headers={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 ... | I am on my mobile so don't remember exact variable name, but it should be robots\_follow
Set it to False | 7,222 |
28,610,556 | I'm a beginner in python, and I'm trying to write a program that makes a call to Weibo(Chinese Twitter) API and receive a json response. It's just a basic keyword search and fetching search result example.
But the problem is I don't know how to make an api call from python, so I'm keep getting error messages. The API ... | 2015/02/19 | [
"https://Stackoverflow.com/questions/28610556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4584513/"
] | If "if clause" has to span more than one lines of code you have to surround it with curly brackets "{}". Change your code to :
```
using System;
class Program
{
static void Main(string[] args)
{
int tal1, tal2;
int slinga;
tal2 = Convert.ToInt32(Console.ReadLine());
for (slin... | Following code lines are wrong
```
if (tal1 == 56)
Console.WriteLine(Addera(slinga, tal1));
tal2--;
else tal1 = 56;
```
You need to update it to
```
if (tal1 == 56){
Console.WriteLine(Addera(slinga, tal1));
tal2--;
}
else {
tal1 = 56;
}
```
Reason : You need `{ }` for multi-lined `if-el... | 7,224 |
27,270,530 | I am worrying that this might be a really stupid question. However I can't find a solution.
I want to do the following operation in python without using a loop, because I am dealing with large size arrays.
Is there any suggestion?
```
import numpy as np
a = np.array([1,2,3,..., N]) # arbitrary 1d array
b = np.array([[... | 2014/12/03 | [
"https://Stackoverflow.com/questions/27270530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3683468/"
] | To avoid Python-level loops, you could use `np.newaxis` to expand `a` (or None, which is the same thing):
```
>>> a = np.arange(1,5)
>>> b = np.arange(1,10).reshape((3,3))
>>> a[:,None,None]*b
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[ 2, 4, 6],
[ 8, 10, 12],
[14, 1... | Didn't understand this multiplication.. but here is a way to make matrix multiplication in python using numpy:
```
import numpy as np
a = np.matrix([1, 2])
b = np.matrix([[1, 2], [3, 4]])
result = a*b
print(result)
>>>result
matrix([7, 10])
``` | 7,226 |
36,774,171 | While building python from source on a MacOS, I accidntally overwrote the python that came with MacOS, now it doesn't have SSL. I tried to build again by running `--with-ssl` option
```
./configure --with-ssl
```
but when I subsequently ran `make`, it said this
```
Python build finished, but the necessary bits to b... | 2016/04/21 | [
"https://Stackoverflow.com/questions/36774171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577455/"
] | Just open `setup.py` and find method `detect_modules()`. It has some lines like (2.7.11 for me):
```
# Detect SSL support for the socket module (via _ssl)
search_for_ssl_incs_in = [
'/usr/local/ssl/include',
'/usr/contrib/ssl/include/'
... | First of all, MacOS only includes LibreSSL 2.2.7 libraries and no headers, you really want to install OpenSSL using homebrew:
```
$ brew install openssl
```
The openssl formula is a *keg-only* formula because the LibreSSL library is shadowing OpenSSL and Homebrew will not interfere with this. This means that you can... | 7,228 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.