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 |
|---|---|---|---|---|---|---|
14,411,394 | I'm trying to send a signal to the django development server to kill the parent and child processes.
```
$ python manage.py runserver
Validating models...
0 errors found
Django version 1.4.1, using settings 'myproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
$... | 2013/01/19 | [
"https://Stackoverflow.com/questions/14411394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246871/"
] | Put a dash in front of the process, this should kill the process group.
```
kill -s SIGINT -4189
``` | `kill -9 4189`
Have a try, it should work! | 6,165 |
11,941,027 | Python beginner here.
I have two text files with the same format of tab-delimited information. They contain rows with 3 columns (identifier, chromosome and position) eg:
File 1:
```
2323 2 125
2324 3 754
```
... etc
File 2:
```
2323 2 150
2324 3 12000
```
... etc
I want to create a list or matrix (not sure ex... | 2012/08/13 | [
"https://Stackoverflow.com/questions/11941027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/964689/"
] | There can be several answers to your question:
1. If you plan to use extensive computations with matrices, I advice you to look at [numpy](http://numpy.scipy.org/) library that is very efficient. You can see how to create matrices with numpy [here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html)... | You could use a dictionary having the identifier as the key and a list of the positions as the value. Then you can calculate the difference between the positions and have it as the 3rd element of the list. You can then iterate through the dictionary finding the largest value in position [2] of the dictionary's values.
... | 6,171 |
61,232,982 | This is my code:
```
users.age.mean().astype(int64)
```
(where users is the name of dataframe and age is a column in it)
This is the error I am getting:
```
AttributeError
Traceback (most recent call last)
<ipython-input-29-10b672e7f7ae> in <module>
----> 1 users.age.mean().astype(int64... | 2020/04/15 | [
"https://Stackoverflow.com/questions/61232982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13322571/"
] | `users.age.mean()` returns a float not a series. Floats don't have `astype`, only pandas series.
Try:
`x = numpy.int64(users.age.mean())`
Or:
`x = int(users.age.mean())` | Try `int` before your function example:
```
X = int(users.age.mean())
```
Hope it helps! | 6,173 |
997,419 | Is there any lib available to connect to yahoo messenger using either the standard protocol or the http way from python? | 2009/06/15 | [
"https://Stackoverflow.com/questions/997419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
] | Google is your friend.
The [Python Package Index](http://pypi.python.org/pypi) has [several](http://pypi.python.org/pypi?%3Aaction=search&term=yahoo&submit=search) modules to do with Yahoo, including this [one](http://pypi.python.org/pypi/pyahoolib/0.2) which matches your requirements. | There is also the [Yahoo IM SDK](http://developer.yahoo.com/messenger/guide/index.html) that might help. | 6,174 |
5,342,359 | is it possible to Insert a python tuple in a postgresql database | 2011/03/17 | [
"https://Stackoverflow.com/questions/5342359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/654796/"
] | Yes it is, PostgreSQL supports array as column type.
```
CREATE TABLE tuples_table (
tuple_of_strings text[],
tuple_of_ints integer[]
);
```
Then inserting is done like this:
```
INSERT INTO tuples_table VALUES (
('{"a","b","c"}', '{1,2}'),
('{"e",'f... etc"}', '{3,4,5}')
);
``` | Really we need more information. What data is **inside** the tuple? Is it just integers? Just strings? Is it megabytes of images?
If you had a Python tuple like `(4,6,2,"Hello",7)` you could insert **the string** `'(4,6,2,"Hello",7)'` into a Postgres database, but that's probably not the answer you're looking for.
Yo... | 6,175 |
65,764,302 | I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input.
My code looks like this, mind you I am n... | 2021/01/17 | [
"https://Stackoverflow.com/questions/65764302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15025453/"
] | So my understanding is you want the function to run indefinitely. this is my approach, through the use of a while loop
```
print("Enter a number")
while True:
c = int(input(""))
numberCheck(c)
``` | You could use a `while` loop with `True`:
```py
while True:
c = int(input())
numberCheck(c)
``` | 6,179 |
2,341,972 | I'm writing a basic html-proxy in python (3), and up to now I'm not using prebuild classes like http.server.
I'm just starting a socket which accepts connection:
```
self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listen_socket.bind((socket.gethostname(), 4321))
self.listen_socket.listen(5... | 2010/02/26 | [
"https://Stackoverflow.com/questions/2341972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258267/"
] | You need to include an encoding when converting to a string, for example use:
```
>>> str(b'GET http://...', 'UTF-8')
'GET http://...'
```
If you don't use an encoding then as you've discovered you get something a little less helpful:
```
>>> str(b'GET http://...')
"b'GET http://...'"
``` | Also, you might want to check the `*HTTPServer` classes. They provide a wrapper around being HTTP servers and will also parse headers for you.
If you can't, well, at the very least they will provide source code examples on how to do it! | 6,182 |
19,806,494 | I'm attempting to write a cython interface to the complex version of the MUMPS solver (zmumps). I'm running into some problems as I have no previous experience with either C or cython. Following the example of the [pymumps package](https://github.com/bfroehle/pymumps) I was able to get the real version of the code (dmu... | 2013/11/06 | [
"https://Stackoverflow.com/questions/19806494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2661958/"
] | Form a user standpoint hovering 1 cm over the screens highly inconvenient compared to placing a finger over the screen. Swipes seen by a front facing camera with a small aperture will be contaminated with the motion blur for a reasonable speed of swipe.
A few years back I solved this problem by considering how motion... | You can't detect the motion vector with the proximity sensor. But there usually is a much smarter sensor that allows for much more precision: the front camera. It is more complex to read gestures with a camera, but you can definitely do that with OpenCV, for example. | 6,185 |
50,242,147 | It's easy in python to calculate simple permutations using [itertools.permutations()](https://docs.python.org/3/library/itertools.html#itertools.permutations).
You can even find some [possible permutations of multiple lists](https://stackoverflow.com/q/2853212).
```
import itertools
s=[ [ 'a', 'b', 'c'], ['d'], ['e',... | 2018/05/08 | [
"https://Stackoverflow.com/questions/50242147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/99923/"
] | Like you suggested, do:
```
s = [x for y in s for x in y]
```
and then use your solution for finding permutations of different lengths:
```
for L in range(0, len(s)+1):
for subset in itertools.combinations(s, L):
print(subset)
```
would find:
```
()
('a',)
('b',)
('c',)
('d',)
('e',)
('f',)
('a', 'b'... | Here's a simple one liner (You can replace `feature_cols` instead of `s`)
**Combinations:**
```py
[combo for i in range(1, len(feature_cols) + 1) for combo in itertools.combinations(feature_cols, i) ]
```
**Permutations:**
```py
[combo for i in range(1, len(feature_cols) + 1) for combo in itertools.permutations(fe... | 6,186 |
63,096,451 | I am pretty good at python and couldn't figure out how to use the Mojang API with python.
I want to d something like `GET https://api.mojang.com/users/profiles/minecraft/<username>?at=<timestamp>`(from the API) but I can't figure out how to do it! Does anyone know how to do this? I'm in python 3.8.
<https://wiki.vg/M... | 2020/07/26 | [
"https://Stackoverflow.com/questions/63096451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13996262/"
] | It's pretty straightforward, just replace `<username>` with the person's username, and the response will give your their `uuid`.
Here is an example using **[`requests`](https://2.python-requests.org/en/master/)**:
```
import requests
username = 'KrisJelbring'
url = f'https://api.mojang.com/users/profiles/minecraft/{u... | The documentation is relatively straightforward.
You want to send a `GET` request with their username:
```py
import requests
username = "Bob"
resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{username}")
uuid = resp.json()["id"]
print(f"Bob's current UUID is {uuid}")
```
Optionally, you can ... | 6,187 |
65,073,434 | I'm using the Mask\_RCNN package from this repo: `https://github.com/matterport/Mask_RCNN`.
I tried to train my own dataset using this package but it gives me an error at the beginning.
```
2020-11-30 12:13:16.577252: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library ... | 2020/11/30 | [
"https://Stackoverflow.com/questions/65073434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11919189/"
] | Go to mrcnn/model.py and add:
```
class AnchorsLayer(KL.Layer):
def __init__(self, anchors, name="anchors", **kwargs):
super(AnchorsLayer, self).__init__(name=name, **kwargs)
self.anchors = tf.Variable(anchors)
def call(self, dummy):
return self.anchors
def get_config(self):
... | ROOT CAUSE:
The bahavior of Lambda layer of Keras in Tensorflow 2.X was changed from Tensorflow 1.X.
In Keras in Tensorflow 1.X, all tf.Variable and tf.get\_variable are automatically tracked into the layer.weights via variable creator context so they receive gradient and trainable automatically. Such approach has prob... | 6,189 |
37,848,815 | I develop a web-app using Flask under Python3. I have a problem with postgresql enum type on db migrate/upgrade.
I added a column "status" to model:
```
class Banner(db.Model):
...
status = db.Column(db.Enum('active', 'inactive', 'archive', name='banner_status'))
...
```
Generated migration by `python m... | 2016/06/16 | [
"https://Stackoverflow.com/questions/37848815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2111562/"
] | I decided on this problem using that.
I changed the code of migration, and migration looks like this:
```
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status')
banner_stat... | I think this way is more simple:
```
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
# others_column = ...
banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status', create_type=False), nullable=False)
```
Also added the `... | 6,190 |
12,576,734 | I have a list which needs to be alphabetized(ignoring lower and uppercase) and printed with spaces and "+" seperating each element in the list. Here's my code:
```
#!/usr/bin/python3.2
fruit = ['A', 'banana', 'Watermelon', 'mango'] #list containing fruits name
for diet in sorted(fruit):
print(diet)
```
This pr... | 2012/09/25 | [
"https://Stackoverflow.com/questions/12576734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1687755/"
] | ```
In [10]: fruit = ['A', 'banana', 'Watermelon', 'mango']
In [11]: ' + '.join(sorted(fruit, key=str.lower))
Out[11]: 'A + banana + mango + Watermelon'
```
for more detials visit :
<http://docs.python.org/library/stdtypes.html#str.join>
<http://wiki.python.org/moin/HowTo/Sorting/> | ```
print(" + ".join(sorted(fruit, key=str.lower)))
``` | 6,191 |
39,505,630 | This is my first question on stack overflow so bear with me, please.
I am trying to download automatically (i.e. scrape) the text of some Italian laws from the website: [http://www.normattiva.it/](http://www.normattiva.it)
I am using this code below (and similar permutations):
```
import requests, sys
debug = {'ve... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39505630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6696413/"
] | Once you click any link on the page with dev tools open, under the doc tab under Network:
[](https://i.stack.imgur.com/orZHr.png)
You can see three links, the first is what we click on, the second returns the html that allows you to jump to a specifi... | wonderful, wonderful, wonderful Padraic. It works. Just had to edits slightly to clear imports but it's works wonderfully. Thanks very much. I am just discovering python's potential and you have made my journey much easier with this specific task. I would have not solved it alone.
```
import requests, sys
import os
f... | 6,192 |
61,209,143 | Python : 3.7.6
rpy2: 3.2.7
R: 3.3.3
I’m using GCE at AI Platform to perform some clustering.
I’ve installed the r-base, updated properly, installed the python-rpy2 and I’m getting this error.
```py
import rpy2.robjects as robjects
error: symbol 'R_tryCatchError' not found in library '/usr/lib/R/lib/libR.so': /usr/... | 2020/04/14 | [
"https://Stackoverflow.com/questions/61209143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13214910/"
] | Here's a one-liner to update it without mutating the original array:
```js
const updatedPersons = persons.map(p => p.id === id ? {...p, lastname} : p);
``` | ```
persons.forEach(person => {
if(this.id === person.id) person.lastname = this.lastname
})
``` | 6,193 |
14,693,256 | I've just finished up installing mod\_wsgi but I'm having problems starting my Pyramid application.
I'm using python 2.7, Apache 2.2.3, mod\_wsgi 3.4 on CentOS 5.8
Here is my httpd.config file
```
WSGISocketPrefix run/wsgi
<VirtualHost *:80>
ServerName myapp.domain.com
ServerAlias myapp
WSGIApplicationGroup %{G... | 2013/02/04 | [
"https://Stackoverflow.com/questions/14693256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210711/"
] | Often when you get syntax errors the preceding line is the culprit. Looking at [the Pyramid source](https://github.com/Pylons/pyramid/blob/master/pyramid/request.py) we see that the preceding line is:
```
@implementer(IRequest)
```
This is a class-decorator. Class-decorators were added to Python in version 2.6. The ... | I see two different wsgi files mentioned in the error
/var/wsgi\_sites/project\_name\_api/apache.wsgi
and
/var/wsgi\_sites/myapp/apache.wsgi
I cannot see any project\_name path reference in the httpd.conf that you pasted.
You might want to start by reviewing that. If the problem persists then please post additiona... | 6,195 |
47,747,532 | I'm confronted with a problem as below and hoping some body could give some advice.
I need to convert a lot of excel tables in different shapes into constructed data, the excel tables are as below.
```
|--------------------|----|----|
|user:Sam | | |
|--------------------|----|----|
|mail:sam@ex... | 2017/12/11 | [
"https://Stackoverflow.com/questions/47747532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8226471/"
] | Looking at the patterns you have provided in your question we see that the data is sometimes in a separate cell, other times encoded in the text with a ':' separator. I'd flatten it out and parse the assembled text for a linear pattern.
I suggest you read the excel file using something like [xlrd](https://pypi.python.... | You have 4 types of files.
If that is all you can write 1 function with 4 if statements.
```
def table_sort(file):
If file == condition:
extract_data_this_way
elif file == other_condition:
extract_data_this_way
elif file == other_condition:
extract_data_this_way
else:
... | 6,196 |
18,314,228 | I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g:
```
List = [a, bb, aa, ccc, dddd]
Sublist1 = [a]
Sublist2= [bb, aa]
Sublist3= [ccc]
Sublist2= [dddd]
```
How can i achieve this in python ?
Thank you | 2013/08/19 | [
"https://Stackoverflow.com/questions/18314228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413734/"
] | I think you should use dictionaries
```
>>> dict_sublist = {}
>>> for el in List:
... dict_sublist.setdefault(len(el), []).append(el)
...
>>> dict_sublist
{1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['dddd']}
``` | Assuming you're happy with a list of lists, indexed by length, how about something like
```
by_length = []
for word in List:
wl = len(word)
while len(by_length) < wl:
by_length.append([])
by_length[wl].append(word)
print "The words of length 3 are %s" % by_length[3]
``` | 6,197 |
29,997,120 | I have a problem with a little server-client assignment in python 2.7.
The client can send 5 types of requests to the server:
1. get the server's IP
2. get contents of a directory on the server
3. run cmd command on the server and get the output
4. open a calculator on the server
5. disconnect
This is the error I ge... | 2015/05/02 | [
"https://Stackoverflow.com/questions/29997120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3554255/"
] | In code shown in your question:
```
HashTable::HashTable(int buckets) {
this->buckets = buckets;
vector<Entry>* table = new vector<Entry>[buckets];
}
```
you create a local variable `table` which is a pointer to `vector<Entry>` and then leak that memory. Then in `HashTable::insert` you try to access member v... | ```
HashTable::HashTable(int buckets) {
this->buckets = buckets;
vector<Entry>* table = new vector<Entry>[buckets]; // this table is local to this function, also a memory leek.
}
```
As I can see in your `HashTable` constructor, you are initializing a local `vector<Entry>* table` to your const... | 6,203 |
54,233,559 | I am generating a doc using python docx module.
I want to bold the specific cell of a row in python docx
here is the code
```
book_title = '\n-:\n {}\n\n'.format(book_title)
book_desc = '-: {}\n\n:\n{}\n\n :\n{}'.format(book.author,book_description,sales_point)
row1.cells[1].text = (book_title + book_desc)
```
I ... | 2019/01/17 | [
"https://Stackoverflow.com/questions/54233559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6892109/"
] | Here is how I understand it:
Paragraph is holding the run objects and styles (bold, italic) are methods of run.
So following this logic here is what might solve your question:
```
row1_cells[0].paragraphs[0].add_run(book_title + book_desc).bold=True
```
This is just an example for the first cell of the table. Please... | Since you are using the docx module, you can style your text/paragraph by explicitly defining the style.
In order to apply a style, use the following code snippet referenced from docx documentation [here](https://python-docx.readthedocs.io/en/latest/user/styles-using.html#apply-a-style).
```
>>> from docx import Docu... | 6,204 |
10,216,019 | So I was developing an app in Django and needed a function from the 1.4 version so I decided to update.
But then a weird error appeared when I wanted to do `syncdb`
I am using the new `manage.py` and as You can see it makes some of the tables but then fails :
```
./manage.py syncdb
Creating tables ...
Creating ... | 2012/04/18 | [
"https://Stackoverflow.com/questions/10216019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1092459/"
] | I had the same issue, the definition for my custom field was missing the connection parameter.
```
from django.db import models
class BigIntegerField(models.IntegerField):
def db_type(self, connection):
return "bigint"
``` | Although already old, answered and accepted question but I am adding my understanding I have added it because I am not using customized type and it is a Django Evolution error (but not syncdb)`evolve --hint --execute`. I think it may be helpful for someone in future. .
I am average in Python and new to Django. I als... | 6,208 |
35,689,139 | I am writing a simple web application where I want to use a print out a few korean characters. Although I changed the encoding in the header, the web application, when opened in chrome, prints out gibberish instead of regular Korean characters. I also changed my chrome language settings to display korean as well. Here'... | 2016/02/28 | [
"https://Stackoverflow.com/questions/35689139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4590749/"
] | Change your encoding/charset to a charset that supports all the characters. For example by replacing both occurrences of `iso-8859-1` to `utf-8`. [UTF-8](https://en.wikipedia.org/wiki/UTF-8) can support Korean characters and basically any writing systems that exist. | You can use the [korean package](https://pypi.python.org/pypi/korean) :
Example :
```
from korean import Noun
fmt = u'{subj:은} {obj:을} 먹었다.'
print fmt.format(subj=Noun(u'나'), obj=Noun(u'밥'))
print fmt.format(subj=Noun(u'학생'), obj=Noun(u'돈까스'))
```
Output :
```
나은 밥을 먹었다.
학생은 돈까스을 먹었다.
``` | 6,209 |
67,663,059 | I m testing my incomplete kivy app to grap a suitable apk of that. using buildozer and ubuntu i generate the apk, but it crashes right after starting it on android device. Is buildozer spec file the root cause should change something inside that? , or its incompatible version issue.
please share kivy, kivymd, python an... | 2021/05/23 | [
"https://Stackoverflow.com/questions/67663059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13331490/"
] | Try using `kivy 2.0.0rc4`. Install it in plugins trough settings in pycharm. And your `buildozer.spec` should be like this:
```
requirements = python3,kivy==2.0.0rc4
``` | Refer to the requirements specidied in buildozer.spec file for the KivyMD-kitchen\_sink app in the repo.
This is the link -> [Kitchen\_Sink\_Repo](https://github.com/kivymd/KivyMD/blob/master/demos/kitchen_sink/buildozer.spec)
**Tip**
If, after changing the `requirements` you still see your app crashing, run the fol... | 6,210 |
60,389,566 | I am new to multi-processing and python, from the documentation,
<https://docs.python.org/3/library/multiprocessing.html>
I was able to run the below code.
```
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
```
But if... | 2020/02/25 | [
"https://Stackoverflow.com/questions/60389566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9066431/"
] | Maybe you are looking for [`starmap`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.starmap)?
>
> `starmap(func, iterable[, chunksize])`
>
>
> Like map() except that the elements of the iterable are expected to be iterables that are unpacked as arguments.
>
>
> Hence an iterable... | Use [`p.starmap()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.starmap), it's meant for exactly this case. | 6,211 |
70,074,369 | I have a list of words like this:
```
word_list=[{"word": "python",
"repeted": 4},
{"word": "awsome",
"repeted": 3},
{"word": "frameworks",
"repeted": 2},
{"word": "programing",
"repeted": 2},
{"word": "stackoverflow",
"repeted": 2},
{"word": "work",
"repeted": 1},
{"wo... | 2021/11/23 | [
"https://Stackoverflow.com/questions/70074369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17483739/"
] | numpy broadcasting is so useful here:
```py
bm = df_other.values[:, 0] == df.values
```
Output:
```py
>>> bm
array([[ True, True, False, False, False],
[False, False, True, False, False],
[False, False, False, True, False]])
```
If you need it as ints:
```py
>>> bm.astype(int)
array([[1, 1, 0, 0... | Another way to do this using pandas methods are as follows:
```
pd.crosstab(df_other['a'], df_other['c']).reindex(df['a']).to_numpy(dtype=int)
```
Output:
```
array([[1, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0]])
``` | 6,212 |
63,759,451 | I'm trying to check the validity of comma-separated strings in python. That is, it's possible that the strings contain mistakes whereby there are more than one comma used.
Here is a valid string:
```
foo = "a, b, c, d, e"
```
This is a valid string as it is comma-delimited; only one comma, not several or spaces onl... | 2020/09/05 | [
"https://Stackoverflow.com/questions/63759451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269850/"
] | It appears the best way to accomplish this is with regex:
Here is a valid string:
```
valid = "a, b, c, foo, bar, dog, cat"
```
Here are various invalid strings:
```
## invalid1 is invalid as it contains multiple , i.e. `,,` and :
invalid1 = "a,, b, c,,,,d, e,,; f, g"
## invalid2 is invalid as it contains `, ,`
... | Here you have some way to check if it's valid:
```
def is_valid(comma_sep_str):
if ';' in comma_sep_str or ',,' in comma_sep_str:
return 'Not valid'
else:
return 'Valid'
myString1 = "a,, b, c,,,,d, e,,; f, g"
myString2 = "a, b, c, d, e"
print(is_valid(myString1))
print(is_valid(myString2))
```
PS: Mayb... | 6,213 |
62,882,592 | I have a `df` named `data` as follows:
```
id upper_ci lower_ci max_power_contractual
0 12858 60.19878860406808 49.827481214215204 0
1 12858 60.61189293066522 49.298784196530896 0
2 12858 60.34397624424309 49.718421137642885 70
3 12858 59.87472261936114 49.464255779713476 10
4 12858 60.2735279... | 2020/07/13 | [
"https://Stackoverflow.com/questions/62882592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11853632/"
] | You can use `np.where` to add the new column:
```
df['up_threshold'] = np.where(df['max_power_contractual'].fillna(0) == 0, df['upper_ci'],
np.where(df['max_power_contractual'] > df['upper_ci'], df['upper_ci'], df['max_power_contractual'])
)
print(df)
```
Prints:
```
id upper_ci lower_ci max_power_c... | Not the efficient way but easier to understand
```
In [17]: def process(data):
...: result = None
...: if (data['max_power_contractual'] in (0, np.nan)) or (data['max_power_contractual'] > data['upper_ci']):
...: result = data['upper_ci']
...: elif (data['upper_ci'] > data['max_power... | 6,214 |
39,666,183 | Im trying to extract all the images from a page. I have used Mechanize Urllib and selenium to extract the Html but the part i want to extract is never there. Also when i view the page source im not able to view the part i want to extract. Instead of the Description i want to extract there is this:
```
<div class="lo... | 2016/09/23 | [
"https://Stackoverflow.com/questions/39666183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6736217/"
] | Possibly you're trying to get elements that are created with a client sided script. I don't think javascript elements run when you just send a GET/POST request (which is what I'm assuming you mean by "view source"). | At the time I was not aware how much content is loaded in through js after the page is loaded.
Mechanize does not have a JavaScript interpreter.
The way I ended up solving this is extracting the links from the \*.js file and redoing the get commend with urllib and getting the required content that way. | 6,216 |
32,302,725 | Hi there am new to OOP and python, I am currently trying to increment a User Id variable from a child Class, when I create an instance of the parent class using inheritance it doesn't seem to recognise the Id Variable from its parent class. Example here
```
class User:
_ID = 0
def __init__(self, name):
... | 2015/08/31 | [
"https://Stackoverflow.com/questions/32302725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2374021/"
] | First, the way to get hold of the ListView itself is relatively easy. In an Activity subclass, you would do this:
```
ListView itemList = (ListView) findViewById(R.id.ItemList);
```
In your example above, the ArrayAdapter needs a layout id in it's constructor. This layout should contain a single TextView element (or... | Writing apps for Android is much more complicated than writing apps for Windows in vb6. You should really study basics and do some tutorials. Start [here!](http://developer.android.com/training/index.html)
But for your question, to get access to xml control in your code, first you have to make object of that control, ... | 6,217 |
51,420,803 | I have been trying to install `python-poppler-qt4` but it shows the error that `ModuleNotFoundError: No module name sipdistutils`.
When I tried installing the `sipdistutils`, it again showed the error.
**Error Message**
[](https://i.stack.imgur.com/... | 2018/07/19 | [
"https://Stackoverflow.com/questions/51420803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10104837/"
] | I have found a simillar issue here: <https://github.com/wbsoft/python-poppler-qt5/issues/14>
I think that `sipdistutils` should be part of `sip` package. Please verify if you have it installed:
```
$ pip freeze | grep sip
sip==4.19.1
```
If there's no output install it with `pip install sip`.
If this won't work so... | It is true that using `sipdistutils` for building python extensions is no longer the way to do things. So, the absolute fix is to modify the build procedure for the package but since I am not in control of that (though I may try to find time to contribute to the project) I did find a work-around.
In our case, on Ubunt... | 6,221 |
52,750,669 | I want to create a new list (V) from other lists (a, b, c) and using a function, but I would like to take advantage of python and apply the function to the three lists and not element by element.
For example, I have the lists a, b and c; and the result after apply the function should be V. Thanks.
```
def mag(a, b, ... | 2018/10/11 | [
"https://Stackoverflow.com/questions/52750669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8766822/"
] | You want to first zip the arguments, then map the function on the unpacked tuples:
```
from itertools import starmap
starmap(mag, zip(a,b,c))
```
See [here](https://ideone.com/uTNa5L) for an example. | What about using only built-in functions? Like [zip](https://docs.python.org/3.3/library/functions.html#zip)
```
>>> [mag(a_, b_, c_) for a_,b_,c_ in zip(a, b, c)]
[10, 78, 30]
```
Plus another python buit-in function, [map](https://docs.python.org/3.3/library/functions.html#map) which returns an
iterator and thus m... | 6,222 |
12,246,908 | What is my requirement ?
--> I need Exception notifier which will email to some specific configured user, about any sort of exception occurring in plain python app and web.py.
I want something similar to this <http://matharvard.ca/posts/2011/jul/31/exception-notification-for-rails-3/>
Is there anything same sort pre... | 2012/09/03 | [
"https://Stackoverflow.com/questions/12246908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486565/"
] | You can get what you want by:
* Wrapping your code in `try..except` clause.
* Using `logging` module to log the exceptions with a certain level of severity e.g `ERROR`.
* Setting an `SMTPHandler` for exceptions of and above certain level.
This way is quite flexible. Your messages can be send to several places (like l... | You can overwrite the `excepthook` function from the [`sys`](http://docs.python.org/library/sys.html#sys.excepthook) module, and handle any uncought exceptions there. | 6,227 |
3,027,394 | what does the '~' mean in python?
i found this BF interpreter in python a while ago.
```
import sys
#c,i,r,p=0,0,[0]*255,raw_input()
c=0
i=0
p=raw_input()
r=[0]*255
while c<len(p):
m,n,u=p[c],0,r[i]
if m==">":i+=1
if m=="<":i-=1
if m=="+":r[i]+=1
if m=="-":r[i]-=1
if m==".":sys.stdo... | 2010/06/12 | [
"https://Stackoverflow.com/questions/3027394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/365060/"
] | Bitwise NOT, just like in C.
In two's complement representation, `~n` is equivalent to `-n - 1`. | `~` is bitwise-not.
I can't really think of a good way to illustrate it (unless you know that `-1` is the bitwise negation of `0`), but [the wikipedia entry](http://en.wikipedia.org/wiki/Bitwise_NOT#NOT) is pretty good. | 6,231 |
67,183,501 | ```
import os
import numpy as np
from scipy.signal import *
import csv
import matplotlib.pyplot as plt
from scipy import signal
from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds
from brainflow.data_filter import DataFilter, FilterTypes, AggOperations, WindowFunctions, DetrendOperati... | 2021/04/20 | [
"https://Stackoverflow.com/questions/67183501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15708550/"
] | Here's a simple case that produces your error message:
```
In [19]: np.asarray([[1,2,3],[4,5]],float)
Traceback (most recent call last):
File "<ipython-input-19-72fd80bc7856>", line 1, in <module>
np.asarray([[1,2,3],[4,5]],float)
File "/usr/local/lib/python3.8/dist-packages/numpy/core/_asarray.py", line 102, ... | I was getting the same error.
I was opening a txt file that contains a table of values, and saving it into a NumPy array defining the dtype as float since otherwise, the numbers would be strings.
```
with open(dirfile) as fh:
next(fh)
header = next(fh)[2:]
next(fh)
data = np.array([line.strip().split()... | 6,235 |
68,654,663 | I'm trying to aggregate my data by getting the sum every 30 seconds. I would like to know if the result of this aggregation is zero, this will happen if there are no rows in that 30s region.
Here's a minimal working example illustrating the result I would like with pandas, and where it falls short with pyspark.
Input... | 2021/08/04 | [
"https://Stackoverflow.com/questions/68654663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2550114/"
] | The HTML5 specification now has a whole section on [Button Layout](https://html.spec.whatwg.org/multipage/rendering.html#button-layout)
Sometimes it's treated like a replaced element, and sometimes like an inline-block element. But it's never treated as a non-replaced inline element.
In detail, it says that:
>
> Bu... | If you want more clarification...it seems that the **button element is a replaced element** in most modern browsers today and in the past, which means no matter how you style it, even after changing the default UA browser styles, it still retains width and height characteristics regardless of display properties. It the... | 6,238 |
43,934,830 | According to [PythonCentral](http://pythoncentral.io/pyside-pyqt-tutorial-qwebview/) :
>
> QWebView ... allows you to display web pages from URLs, arbitrary HTML, *XML with XSLT stylesheets*, web pages constructed as QWebPages, and other data whose MIME types it knows how to interpret
>
>
>
However, the xml conte... | 2017/05/12 | [
"https://Stackoverflow.com/questions/43934830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508402/"
] | Try converting to NSData then storing to nsuserdefaults like below
```
func saveListIdArray(_ params: NSMutableArray = []) {
let data = NSKeyedArchiver.archivedData(withRootObject: params)
UserDefaults.standard.set(data, forKey: "test")
UserDefaults.standard.synchronize()
}
```
For retrieving the data use
```
if ... | You are force unwrapping the NSMutableArray for a key. Don't force unwrap when you try to get the value from a dictionary or UserDefault for a key because there may be a chance that the value does not exist for that key and force unwrapping will crash your app.
Do this as:
```
//to get array from user default
if ... | 6,239 |
39,010,366 | While executing the code below, I'm getting `AttributeError: attribute '__doc__' of 'type' objects is not writable`.
```
from functools import wraps
def memoize(f):
""" Memoization decorator for functions taking one or more arguments.
Saves repeated api calls for a given value, by caching it.
"""
... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39010366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2264738/"
] | `@wraps(f)` is primarily designed to be used as a *function* decorator, rather than as a class decorator, so using it as the latter may lead to the occasional odd quirk.
The specific error message you're receiving relates to a limitation of builtin types on Python 2:
```
>>> class C(object): pass
...
>>> C.__doc__ =... | The `wraps` decorator you're trying to apply to your class doesn't work because you can't modify the docstring of a class after it has been created. You can recreate the error with this code:
```
class Foo(object):
"""inital docstring"""
Foo.__doc__ = """new docstring""" # raises an exception in Python 2
```
Th... | 6,241 |
65,460,702 | I am having an issue with my personal project, my python skills are pretty basic but any help would be greatly appreciated
Question:
TASK 1
To simulate the monitoring required, write a routine that allows entry of the baby’s temperature in
degrees Celsius. The routine should check whether the temperature is within the... | 2020/12/26 | [
"https://Stackoverflow.com/questions/65460702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14861692/"
] | According to the discord.py docs [bot.run()](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.run) is "A blocking call that abstracts away the event loop initialisation from you." and further they said if we want more control over the loop we could use start() coroutine instead of run(). So now we sho... | You are not returning anything from your `send_message` function. Something like this should do good.
```py
@app.post("/items/")
async def create_item(item: Item):
msg = await send_message()
return msg
async def send_message():
user = await bot.fetch_user(USER_ID)
return await user.send('')
``` | 6,243 |
57,445,907 | I want to detect malicious sites using python.
Now, I've tried using `requests` module to get the contents of a website, then would search for `malicious words` in it. But, I didn't get it to work.
[](https://i.stack.imgur.com/f3vOj.png)
this my ... | 2019/08/10 | [
"https://Stackoverflow.com/questions/57445907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675882/"
] | It doesn't work because you're using the `requests` library wrong.
In your code, you essentially only get the HTML of the virus site (line of code: `req_check = requests.get(url, verify=False)` and `if 'example for detect ' in req_check.content:`{source: <https://pastebin.com/6x24SN6v>})
In Chrome, the browser runs ... | Tell the user to enter a website, then use selenium or something to upload the url to virustotal.com | 6,245 |
54,806,005 | I have a list of dictionaries that looks something like this->
```
list = [{"id":1,"path":"a/b", ........},
{"id":2,"path":"a/b/c", ........},
{"id":3,"path":"a/b/c/d", ........}]
```
Now I want to create a dict of path to id mapping.
That should look something like this->
```
d=dict()
... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54806005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9593015/"
] | Make outer div `fixed` then inner 4 div element will show next to each other.
```css
.groups {
display: flex;
display: -webkit-flex;
position: fixed;
margin: 0 auto;
left: 0;
right: 0;
justify-content: space-around;
max-width: 500px;
}
.g{
height: 70px;
... | Otherwise you can do it with flex:
```css
.g{
height: 70px;
width: 70px;
background-color: black;
margin: 5px;
}
.groups {
display: flex;
justify-content: space-between;
width: 400px
}
```
```html
<div class="groups">
<div class="g g1"></div>
<div class="g g2"></div>
<div class="g g3"... | 6,247 |
29,704,139 | I am trying to apply `_pickle` to save data onto disk. But when calling `_pickle.dump`, I got an error
```
OverflowError: cannot serialize a bytes object larger than 4 GiB
```
Is this a hard limitation to use `_pickle`? (`cPickle` for python2) | 2015/04/17 | [
"https://Stackoverflow.com/questions/29704139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2880978/"
] | Not anymore in Python 3.4 which has PEP 3154 and Pickle 4.0
<https://www.python.org/dev/peps/pep-3154/>
But you need to say you want to use version 4 of the protocol:
<https://docs.python.org/3/library/pickle.html>
```
pickle.dump(d, open("file", 'w'), protocol=4)
``` | Yes, this is a hard-coded limit; from [`save_bytes` function](https://hg.python.org/cpython/file/2d8e4047c270/Modules/_pickle.c#l1958):
```c
else if (size <= 0xffffffffL) {
// ...
}
else {
PyErr_SetString(PyExc_OverflowError,
"cannot serialize a bytes object larger than 4 GiB");
return ... | 6,251 |
53,012,388 | When I do `python -mzeep https://testingapi.ercot.com/2007-08/Nodal/eEDS/EWS/?WSDL`
the operations are blank. When I pull that up in a browser I can find many things under an `<operation>` tag. What am I missing?
I'm not sure if this is relevant but I hate to exclude this info if it is. The site has a zip file of XS... | 2018/10/26 | [
"https://Stackoverflow.com/questions/53012388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1818713/"
] | >
> I actually don't need those serialized into the JSON file
>
>
>
In JSON.NET there is a `[JsonIgnore]` attribute that you can decorate properties with.
Related: [Newtonsoft ignore attributes?](https://stackoverflow.com/questions/6309725/newtonsoft-ignore-attributes) | To serialize and write it to a file, just do this:
```
string json = JsonConvert.SerializeObject(theme);
System.IO.File.WriteAllText("yourfile.json", json);
``` | 6,254 |
53,356,449 | I'm having trouble carrying out what I think should be a pretty straightforward task on a NIDAQ usb6002: I have a low frequency sine wave that I'm measuring at an analog input channel, and when it crosses zero I would like to light an LED for 1 second. I'm trying to use the nidaqmx Python API, but haven't been able to ... | 2018/11/17 | [
"https://Stackoverflow.com/questions/53356449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10397841/"
] | In short: Web worksers do not ignore messages even if the web worker thread is blocked.
All browsers events, including web worker `postMessage()`/`onmessage()` events are queued. This is the fundamental philosophy of JavaScript (`onmessage()` is done in JS even if you use WebAssembly). Have a look at ["Concurrency mod... | Considering you are targeting recent browsers (WebAssembly), you can most likely rely on SharedArrayBuffer and Atomics. Have a look at these solutions [Is it possible to pause/resume a web worker externally?](https://stackoverflow.com/questions/57701464/is-it-possible-to-pause-resume-a-web-worker-externally/71888014#71... | 6,255 |
30,019,283 | I was wondering how to parse the CURL JSON output from the server into variables.
Currently, I have -
```
curl -X POST -H "Content: agent-type: application/x-www-form-urlencoded" https://www.toontownrewritten.com/api/login?format=json -d username="$USERNAME" -d password="$PASSWORD" | python -m json.tool
```
But it ... | 2015/05/03 | [
"https://Stackoverflow.com/questions/30019283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3152204/"
] | Find and install `jq` (<https://stedolan.github.io/jq/>). `jq` is a JSON parser. JSON is not reliably parsed by line-oriented tools like `sed` because, like XML, JSON is not a line-oriented data format.
In terms of your question:
```
source <(
curl -X POST -H "$content_type" "$url" -d username="$USERNAME" -d pass... | Here's an example of [Extract a JSON value from a BASH script](https://gist.github.com/cjus/1047794)
```
#!/bin/bash
function jsonval {
temp=`echo $json | sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's... | 6,256 |
13,774,443 | I'm making a request in python to a web service which returns AMF. I don't know if it's AMF0 or AMF3 yet.
```
r = requests.post(url, data=data)
>>> r.text
u'\x00\x03...'
```
([Full data here](http://pastebin.com/sdZnU8Ds))
How can I take `r.text` and convert it to a python object or similar? I found [amfast](http:/... | 2012/12/08 | [
"https://Stackoverflow.com/questions/13774443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246265/"
] | **EDIT:** I had calculated some of my probabilities wrongly. Also I've now mentioned that we need to randomly pick 2 distinct inputs for the function f in order to guarantee that, if f is balanced, then we know the probabilities of seeing the various possible outcomes.
The fact that the prior probability of the functi... | Look at the probabilities for the different types of functions to return different results for two given values:
```
constant 0,0 50%
constant 1,1 50%
balanced 0,0 4/8 * 3/7 = 21,4%
balanced 0,1 4/8 * 4/7 = 28.6%
balanced 1,0 4/8 * 4/7 = 28.6%
balanced 1,1 4/8 * 3/7 = 21.4%
```
If the results are 0,0 or ... | 6,258 |
17,081,363 | I'm trying to convert C++ code to python but I'm stuck
original C++ code
```
int main(void)
{
int levels = 40;
int xp_for_first_level = 1000;
int xp_for_last_level = 1000000;
double B = log((double)xp_for_last_level / xp_for_first_level) / (levels - 1);
double A = (double)xp_for_first_level / (ex... | 2013/06/13 | [
"https://Stackoverflow.com/questions/17081363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1934748/"
] | Change the `print` line to:
```
print("%i %i" % (i, new_xp - old_xp))
```
Refer to this [list of allowed type conversion specifiers](http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) for more informations.
Or use the new [format](http://docs.python.org/3/library/functions.html#format) m... | Depending on the version of python you are using, the cast to double in the C++ code
```
(double)xp_for_last_level / xp_for_first_level
```
might need to be taken into account in the python code. In python 3 you will get a float, in older python you can do
```
from __future__ import division
```
then `xp_for_last... | 6,259 |
57,169,697 | When I use the PIL.ImageTk library to load a png to my GUI and use logging to log some events, it creates some unwanted logs in DEBUG mode.
I have tried changing the `level` of `logging` to `INFO` or `WARNING` (or higher). But that does not help:
```
logging.basicConfig(filename='mylog.log', filemode='a', format='%(a... | 2019/07/23 | [
"https://Stackoverflow.com/questions/57169697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2365866/"
] | Problem is because module already created root logger and now `basicConfig` uses this logger but it can't change level for existing logger.
Doc: [basicConfig](https://docs.python.org/3/library/logging.html#logging.basicConfig)
>
> This function does nothing if the root logger already has handlers configured for it.
... | Instead Of Using:
```
...
level=logging.DEBUG
...
```
Use:
```
...
level=logging.INFO
...
```
And Your File Will Be:
>
> DD/MM/YYYY HH:MM:SS PM INFO: This is a test log...
>
>
> | 6,261 |
60,414,356 | I have a GUI application made using PySide2 and it some major modules it uses are OpenVino(2019), dlib, OpenCV-contrib(4.2.x) and Postgres(psycopg2) and I am trying to freeze the application using PyInstaller (--debug is True).
The program gets frozen without errors but during execution, I get the following error:
``... | 2020/02/26 | [
"https://Stackoverflow.com/questions/60414356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8243797/"
] | You changed the python version. So, you have to give a new path according to the Python version.
Just remove all older version and the current one and reinstall new Python v.3.8.1 | You need to include base\_library.zip in your application folder | 6,264 |
41,923,890 | I'm attempting to create a simple selection sort program in python without using any built in functions. My problem right now is my code is only sorting the first digit of the list. What's wrong?
Here's my sort
```
def selectionsort(list1):
for x in range(len(list1)):
tiniest = minimum(list1)
swap(t... | 2017/01/29 | [
"https://Stackoverflow.com/questions/41923890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6843896/"
] | Some simplification will make it more readable/comprehensible:
```
def swap(lst, i1, i2):
lst[i1], lst[i2] = lst[i2], lst[i1] # easy-swapping by multi assignment
def minimum(lst, s): # s: start index
min_val, min_index = lst[s], s
for i in range(s+1, len(lst)):
if lst[i] < min_val:
min_val, min_ind... | It seems `minimum` returns the value of the smallest element in `list1`, but your `swap` expects an index instead. Try making `minimum` return the index instead of the value of the smallest element. | 6,265 |
74,101,582 | I am calculating concentrations from a file that has separate Date and Time columns. I set the date and time columns as indexes as they are not suppose to change. However when I print the new dataframe it only prints the "date" one time like this:
```
55...
Date Time ... | 2022/10/17 | [
"https://Stackoverflow.com/questions/74101582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19096358/"
] | From the Pandas [to\_string() docs](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_string.html#pandas-dataframe-to-string).
>
> sparsify : bool, optional, default True
>
> Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row.
>
>
>
---
```
print(co... | remove `inplace=True` and replace it with `reset_index()` at the end
here is the code (first two lines)
```
df = pd.read_csv('csv2.txt',delimiter=r'\s+',engine = 'python')
df.set_index(['Date', 'Time'] ).reset_index()
# cannot do calculation step, as sample column is not present in the sample data
```
```
Date ... | 6,266 |
65,463,877 | I've installed Spark and components locally and I'm able to execute PySpark code in Jupyter, iPython and via spark-submit - however receiving the following WARNING's:
```
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/Users/ayu... | 2020/12/27 | [
"https://Stackoverflow.com/questions/65463877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9372996/"
] | Install Java 8 instead of Java 11, which is known to give this sort of warnings with Spark. | If you run your PySpark code often and you are tired (like me) of looking through all these warnings again and again before you see **your** output, bash/zsh process substitution comes to the rescue:
```
$ spark-3.0.1-bin-hadoop3.2/bin/spark-submit test.py 2> >(tail -n +8 >&2) | cat
```
Here we redirect STDERR of ou... | 6,267 |
68,959,506 | Lets say I have a CSV file that looks like this:
```
name,country,email
john,US,[email protected]
brad,UK,[email protected]
James,US,[email protected]
```
I want to search for any county that equals US and if its exists, then print their email address. How would I do this in python without using pandas? | 2021/08/27 | [
"https://Stackoverflow.com/questions/68959506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12260632/"
] | You can do something like:
```
with open('file.csv', 'r') as f:
f.readline()
for line in f:
data = line.strip().split(',')
```
Then you can access the stuff inside of `data` to get what you need. | So to read an CSV as dataframe you need:
```
import pandas as pd
df = pd.read_csv("filename.csv")
```
Next, I will generate a dummy df and show you how to get the US users and then print their emails in a list:
```
df= pd.DataFrame({"Name":['jhon','brad','james'], "Country":['US','UK','US'],
"email":['[email protected]... | 6,270 |
64,167,192 | I am a begginer programer in python and when i run this code
```
from PIL import Image
im = Image.open(r'C:\\images\\imagetest.png')
width, height = im.size
print(width, height)
im.show()
```
I get this error:
```
im = Image.open(r'C:\\images\\imagetest.png')
File "C:\Users\danie\AppData\Local\Programs\Pytho... | 2020/10/02 | [
"https://Stackoverflow.com/questions/64167192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14378032/"
] | r strings don't need their backslashes escaped
Remove the r before the string declaration or remove the double backslashes | The path of the image is not correct. You have to write it like that:
im = Image.open(r'C:\images\imagetest.png') | 6,271 |
44,517,641 | I want to connect to my database from Python shell
```
import MySQLdb
db = MySQLdb.connect(host="localhost",user="milenko",passwd="********",db="classicmodels")
```
But
```
File "/home/milenko/anaconda3/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__
super(Connection, self).__init__(... | 2017/06/13 | [
"https://Stackoverflow.com/questions/44517641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8006605/"
] | this generally means you do not have permissions to access the server from that particular machine. to fix it, either create user 'milenko'@'localhost' or 'milenko'@'%' using your root server user
OR
grant your user privileges on that particular db | Make sure your local server (e.g WampServer) is turned on. | 6,273 |
56,576,470 | I am confused about the runtime of the binary operator of the set in Python.
e.g. -
`set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa.
I went through some websites but I am not able to find any clea... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56576470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9072927/"
] | I had the same problem. Following command worked for me:
After the `./gradlew bundleRelease` command we get a *.aab* version of our app. To get APK, you should run the app with release version on any device with the below command.
* Make sure you have connected an android device
* For the production ready app, firstl... | step - 1) ./gradlew bundleRelease
step - 2) react-native run-android --variant=release
Make sure you have connected an android device
For the production-ready app, firstly you have to remove the previous app from the device | 6,274 |
31,977,245 | Let's say I have a web bot written in python that sends data via POST request to a web site. The data is pulled from a text file line by line and passed into an array. Currently, I'm testing each element in the array through a simple for-loop. How can I effectively implement multi-threading to iterate through the data ... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31977245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313602/"
] | This sounds like a recipe for `multiprocessing.Pool`
See here: <https://docs.python.org/2/library/multiprocessing.html#introduction>
```
from multiprocessing import Pool
def test(num):
if num%2 == 0:
return True
else:
return False
if __name__ == "__main__":
list_of_datas_to_test = [0, 1,... | Threads are slow in python because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock). You should consider using multiple processes with the Python `multiprocessing` module instead of threads. Using multiple processes can increase the "ramp up" time of your code, as spawning a real pro... | 6,284 |
31,458,813 | I get a TemplateNotFound after I installed django-postman and django-messages. I obviously installed them separately - first django-postman, and then django-messages. This is so simple and yet I've spent hours trying to resolve this.
I'm using Django 1.8, a fresh base install using pip. I then installed the two above ... | 2015/07/16 | [
"https://Stackoverflow.com/questions/31458813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4431105/"
] | The issue is because it extends from the site's base.html. It is also mentioned in postman documentation :- <https://django-postman.readthedocs.org/en/latest/quickstart.html#templates>
```
The postman/base.html template extends a base.html site template, in which some blocks are expected:
title: in <html><head><t... | The problem was resolved for django-messages after reviewing a called template and changing the extends/inheritance parameter.
The file that was being called, inbox.html, inherited "django\_messages/base.html" ... which worked fine. "base.html" then inherited from "base.html," so there appeared to be some circular log... | 6,285 |
44,112,399 | I run a Python Discord bot. I import some modules and have some events. Now and then, it seems like the script gets killed for some unknown reason. Maybe because of an error/exception or some connection issue maybe? I'm no Python expert but I managed to get my bot working pretty well, I just don't exactly understand ho... | 2017/05/22 | [
"https://Stackoverflow.com/questions/44112399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1689179/"
] | You can write another `python code (B)` to call your original `python code (A)` using `Popen` from `subprocess`. In `python code (B)`, ask the program to `wait` for your `python code (A)`. If `'A'` exits with an `error code`, `recall` it from `B`.
I provide an example for python\_code\_B.py
```
import subprocess
fi... | for problem you stated i prefer to use python [subprocess](https://docs.python.org/3.4/library/subprocess.html) call to rerun python script or use [try blocks](https://docs.python.org/3.4/tutorial/errors.html).
This might be helpful to you.
check this sample try block code:
```
try:
import xyz # consider it is not e... | 6,286 |
55,290,527 | How do I write python scrip to solve this?
```
l=[1,2,3] Length A
X=[one,two,three,.... ] length A
```
how do print/write to file
output should be
```
1=one 2=two 3=three ....
```
Trying to use something like but since the Length A is variable this won't work
```
logfile.write('%d=%s %d=%s %d=%s %d=%s \n' % (... | 2019/03/21 | [
"https://Stackoverflow.com/questions/55290527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7038853/"
] | Use `zip`:
```
l = [1, 2, 3]
X = ['one', 'two', 'three']
' '.join('{}={}'.format(first, second) for first, second in zip(l, X))
```
Output:
```
'1=one 2=two 3=three'
``` | You could also use an fString to make this more concise:
```
numbers = [1, 2, 3]
strings = ['one', 'two', 'three']
print(' '.join(f'{n}={s}' for n,s in zip(numbers,strings)))
``` | 6,287 |
3,929,096 | A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ... | 2010/10/14 | [
"https://Stackoverflow.com/questions/3929096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/227567/"
] | Your operating system is almost certainly buffering/caching disk writes already. It's not surprising the RAM disk is so close in performance.
Without knowing exactly what you're writing or how, we can only offer general suggestions. Some ideas:
* If you have 2 GB RAM you probably have a decent processor, so you could... | I know that Windows is very aggressive about caching disk data in RAM, and 100K would fit easily. The writes are going directly to cache and then perhaps being written to disk via a non-blocking write, which allows the program to continue. The RAM disk probably wouldn't support non-blocking operations because it expect... | 6,289 |
4,149,274 | Okay, I'm having one of those moments that makes me question my ability to use a computer. This is not the sort of question I imagined asking as my first SO post, but here goes.
Started on Zed's new "Learn Python the Hard Way" since I've been looking to get back into programming after a 10 year hiatus and python was a... | 2010/11/10 | [
"https://Stackoverflow.com/questions/4149274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/502486/"
] | When you type the name of a file at the windows command prompt, cmd can check the windows registry for the default file association, and use that program to open it. So if the Inkscape installer associated .py files with its own version of python, cmd might preferentially run that and ignore the PATH entirely. See [thi... | Based on your second edit, you may have more than one copy of pydoc.py in your path, with the 'wrong' one first such that when it starts up it doesn't have the correct environment in which to execute. | 6,299 |
68,272,509 | I'm a Python beginner, and trying to improve my skill.
Recently I read the source cord of some python packages, and found these codes.
```
while True:
x = string_variable != -1
if x:
time.sleep(1)
else:
break
```
So, what does the second line mean?
You can find the original cord in 149t... | 2021/07/06 | [
"https://Stackoverflow.com/questions/68272509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15340967/"
] | Just to add here, the actual code you are looking at is not a simple string variable test like your example:
```
in_process = status_container.text.find(Constant.UPLOADED) != -1
```
is effectively doing this:
```
string_var.find("foo") != -1
```
which is looking for an occurrence of "foo" inside the string\_var. ... | This line has two operators
```
x = string_variable != -1
```
`=` is assignment operator and `!=` is logical operator which means `NOT EQUALS`
so, `x` will hold a boolean value based on the evaluation of the logical operator `!=`. | 6,306 |
33,107,224 | I have 5 astronomy images in python, each for a different wavelength, therefore they are of different angular resolutions and grid sizes and in order to compare them so that i can create temperature maps i need them to be the same angular resolution and grid size.
I have managed to Gaussian convolve each image to the ... | 2015/10/13 | [
"https://Stackoverflow.com/questions/33107224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4596311/"
] | If the image headers have the correct World Coordinate System data, you can use the reproject package to resample the images:
<http://reproject.readthedocs.org/en/stable/> | You can use FITS\_tools (<https://pypi.python.org/pypi/FITS_tools>, it can also be installed via `$ pip install FITS_TOOLS` in the anaconda distribution of python).
Both images must have wcs in the header information.
```
import FITS_tools
to_be_projected = 'fits_file_to_be_projected.fits'
reference_fits = 'fits_fil... | 6,307 |
9,577,252 | In ipython, if I press 'esc' followed by 'enter' (and possibly other characters?), readline breaks. I can no longer search through command history using the 'up' key, and some commands (e.g., control-K) fail.
Is there a way to reset readline within an ipython session? What is going on when I press these keys? | 2012/03/06 | [
"https://Stackoverflow.com/questions/9577252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814354/"
] | The poster's suggested answer doesn't seem to work for me in iPython 0.12+. I can run:
```
get_ipython().init_readline()
```
but that doesn't seem to help.
However I noticed that I sometimes see similar problems in my iPython sessions. It appears that I had inadvertently switched from the default Emacs readline edi... | Got impatient. Solution is:
```
IPython.InteractiveShell.init_readline(get_ipython())
```
Looks like this might be a known bug too: <http://www.catonmat.net/blog/bash-vi-editing-mode-cheat-sheet/> | 6,308 |
40,327,136 | [This is how I setted up my python3 envirnoment on Ubuntu 16.04.](https://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-local-programming-environment-on-ubuntu-16-04)
And I installed TensorFlow 0.8 with Virtualenv installation.
[As I wanted to start TensorFlow tutorial MNIST For ML Beg... | 2016/10/30 | [
"https://Stackoverflow.com/questions/40327136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7090901/"
] | Sorry for the very late update, I had update tensorflow to the latest version.
And I think I had some mistakes back then.
Since I install the tensorflow via Virtualenv installation, so I should load tensorflow and other packages in Virtualenv environment.
```
source ~/tensorflow/bin/activate
```
Then run the exist... | Try installing it with PIP using
```
sudo apt-get install python-pip
sudo pip install numpy==1.11.1
```
or in your case use pip3 instead of pip for python 3 like
```
sudo apt-get install python3-pip
sudo pip3 install numpy==1.11.1
```
this will help | 6,309 |
12,197,806 | I have this script which runs well in Python 2.7 but not in 2.6:
```
def main():
tempfile = '/tmp/tempfile'
stats_URI="http://x.x.x.x/stats.json"
hits_ = 0
advances_ = 0
requests = 0
failed = 0
as_data = urllib.urlopen(stats_URI).read()
data = json.loads(as_data)
for x, y in data['hits-se... | 2012/08/30 | [
"https://Stackoverflow.com/questions/12197806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1579819/"
] | When creating a `typedef` alias for a function pointer, the alias is in the function *name* position, so use:
```
typedef unsigned (__stdcall *task )(void *);
```
`task` is now a type alias for: *pointer to a function taking a `void` pointer and returning `unsigned`*. | Since hmjd's answer has been deleted...
In C++11 a whole newsome *alias* syntax has been developed, to make such things much easier:
```
using task = unsigned (__stdcall*)(void*);
```
is equivalent the to `typedef unsigned (__stdcall* task)(void*);` (note the position of the alias in the middle of the function sign... | 6,311 |
55,249,689 | I am using this Docker (FROM lambci/lambda:python3.6) and I need to install a private repository package. The problem is the Docker does not have git and I can not install git using apt-get or apk install because the Docker is not Linux.
Is there any possible way to fix this installing git? Or is there any other bette... | 2019/03/19 | [
"https://Stackoverflow.com/questions/55249689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6763224/"
] | add this to makefile:
```
# makefile
git clone REPO
cd REPO_DIR; python setup.py bdist_wheel
cp REPO_DIR/dist/* .
rm -rf REPO_DIR/
```
add this to dockerfile:
```
# dockerfile
RUN pip install REPO*.whl
```
and then the package is successfully installed within docker | can you `pip install` the git repo next to your source code and mount it together with your code into the container?
```
cd WORKING_DIRECTORY
pip install --target ./ GIT_URL
``` | 6,314 |
36,712,967 | I want to add search box to a single select drop down option.
**Code:**
```
<select id="widget_for" name="{{widget_for}}">
<option value="">select</option>
{% for key, value in dr.items %}
<input placeholder="This ">
<option value="{% firstof value.id key %}" {% if key in selected_value %}selected{% endif %}>{% fi... | 2016/04/19 | [
"https://Stackoverflow.com/questions/36712967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324868/"
] | Simply use select2 plugin to implement this feature
Plugin link: [Select2](https://select2.github.io/examples.html)
[](https://i.stack.imgur.com/6ora6.png) | you can use **semantic ui** to implement this feature
<https://semantic-ui.com/introduction/new.html> | 6,322 |
53,174,590 | Im currently making my own model and all works fine with the tensorflow-for-poets-2 demo. I trained multiple pictures in different folders, and the app recognized it.
Now I want to display a bounding box around the object. I found an example [here](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/e... | 2018/11/06 | [
"https://Stackoverflow.com/questions/53174590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8531947/"
] | You need to set **tinymce.suffix = '.min';** before you init TinyMCE
```
tinymce.suffix = '.min';
tinymce.baseURL = '/js/tinymce';
tinymce.init({
selector: '#editor',
menubar: false,
plugins: 'code'
});
``` | TinyMCE should work out to load minified (or non-minified) files based on which TinyMCE file you load (`tinymce.js` or `tinymce.min.js`).
Not sure what's happening in your case but that logic appears to be failing.
If you grab the DEV package from <https://www.tiny.cloud/get-tiny/self-hosted/> it would come with bot... | 6,332 |
23,007,203 | Write a program that prompts the user for the name of a file, opens the file for reading,
and then outputs how many times each character of the alphabet appears in the file.
```
#!/usr/local/bin/python
name=raw_input("Enter file name: ")
input_file=open(name,"r")
list=input_file.readlines()
count = 0
counter = 0
for... | 2014/04/11 | [
"https://Stackoverflow.com/questions/23007203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1836292/"
] | Create style like this-
```
<style name="Theme.MyAppTheme" parent="Theme.Sherlock.Light">
<item name="android:actionBarStyle">@style/Theme.MyAppTheme.ActionBar</item>
<item name="actionBarStyle">@style/Theme.MyAppTheme.ActionBar</item>
</style>
<style name="Theme.MyAppTheme.ActionBar" parent="Wi... | Try to use this one:
```
<style name="Theme.white_style" parent="@android:style/Theme.Holo.Light.DarkActionBar">
<item name="android:actionBarSize">55dp</item>
<item name="actionBarSize">55dp</item>
</style>
``` | 6,334 |
12,735,852 | The question is an attempt to get the exact instruction on how to do that. There were few attempts before, which don't seem to be full solutions:
[solution to move the file inside the package](https://stackoverflow.com/questions/3071327/problem-accessing-config-files-within-a-python-egg)
[solution to read as zip](htt... | 2012/10/04 | [
"https://Stackoverflow.com/questions/12735852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673423/"
] | Setuptools/distribute/pkg\_resources is designed to be a sort of transparent overlay to standard Python distutils, which are pretty limited and don't allow a good way of distributing code.
eggs are just a way of putting together a bunch of python files, data files, and metadata, somewhat similar to Java JARs - but pyt... | The [`zipimporter`](http://docs.python.org/library/zipimport.html#zipimporter-objects) used to load a module can be accessed using the [`__loader__`](http://www.python.org/dev/peps/pep-0302/#specification-part-1-the-importer-protocol) attribute on the module, so accessing a file within the egg should be as simple as:
... | 6,335 |
59,821,535 | I have a JSON file name.json with below contents,
```
{
"Name": [{
"firstName": "John",
"lastName": "Stark"
}]
}
```
Using python how to add the members of Stark family to the JSON file using following list
`firstNameList=['Sansa','Arya','Brandon']`
Expected Output
```
{
"Name": [{
... | 2020/01/20 | [
"https://Stackoverflow.com/questions/59821535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10522495/"
] | The following should do the trick:
```
import json
with open('name.json', 'r+') as f:
data = json.load(f)
for name in firstNameList:
data["Name"].append({"firstName": name, "lastName": "Stark"})
``` | ```
dicts = {
"Name": [{
"firstName": "John",
"lastName": "Stark"
}
]
}
firstNameList = ['Sansa','Arya','Brandon']
for j in firstNameList:
dicts["Name"].append({'firstName': j, 'lastName': 'Stark'})
print(dicts)
```
And you will get
```
{'Name': [{'firstName': 'John', ... | 6,336 |
7,610,001 | Could you explain to me what the difference is between calling
```
python -m mymod1 mymod2.py args
```
and
```
python mymod1.py mymod2.py args
```
It seems in both cases `mymod1.py` is called and `sys.argv` is
```
['mymod1.py', 'mymod2.py', 'args']
```
So what is the `-m` switch for? | 2011/09/30 | [
"https://Stackoverflow.com/questions/7610001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/621944/"
] | The first line of the `Rationale` section of [PEP 338](http://www.python.org/dev/peps/pep-0338/) says:
>
> Python 2.4 adds the command line switch -m to allow modules to be located using the Python module namespace for execution as scripts. The motivating examples were standard library modules such as pdb and profile... | It's worth mentioning **this only works if the package has a file `__main__.py`** Otherwise, this package can not be executed directly.
```
python -m some_package some_arguments
```
The python interpreter will looking for a `__main__.py` file in the package path to execute. It's equivalent to:
```
python path_to_pa... | 6,338 |
11,021,405 | I am designing a text processing program that will generate a list of keywords from a long itemized text document, and combine entries for words that are similar in meaning. There are metrics out there, however I have a new issue of dealing with words that are not in the dictionary that I am using.
I am currently usi... | 2012/06/13 | [
"https://Stackoverflow.com/questions/11021405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1287834/"
] | Looks like you need a spelling corrector to match words in your dictionary.
The code below works and taken directly from this blog <http://norvig.com/spell-correct.html> written by Peter Norvig,
```
import re, collections
def words(text): return re.findall('[a-z]+', text.lower())
def train(features):
model = co... | Your task sounds like it's really just non-word spelling correction, so a relatively straight-forward solution would be to use an existing spell checker like aspell with a custom dictionary.
A quick and dirty approach would be to just use a phonetic mapping like metaphone (which is one the algorithms used by aspell). ... | 6,348 |
73,247,351 | I found a way to query all global address in outlook with python,
```
import win32com.client
import csv
from datetime import datetime
# Outlook
outApp = win32com.client.gencache.EnsureDispatch("Outlook.Application")
outGAL = outApp.Session.GetGlobalAddressList()
entries = outGAL.AddressEntries
# Create a dateID
date... | 2022/08/05 | [
"https://Stackoverflow.com/questions/73247351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9821792/"
] | Actually your program works fine except that one problem with removing element from list, look:
```
l = [1,2,3]
print(l.remove(1)) # None
print(l) # [2,3]
```
So `list.remove()` modifies **mutable** list and doesn't return new one like in case of e.g. **immutable** strings
```
s = "abc"
print(s.upper()) # ABC
print... | The only problem was the `three.remove(smallest_1)`.
Change this and it becomes:
```py
def sum_two_smallest_numbers(numbers, index=0, two=[]):
if index == 0:
two = [numbers[0], numbers[1]]
index += 2
if index < len(numbers) and index >= 2:
three = two + [numbers[index]]
smalles... | 6,351 |
28,296,476 | I finished installing pip on linux, the `pip list` command works. But when using the `pip install` command it got the following error:
```
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/basecommand.py", line 232, in main
status = self.run(options, args)
... | 2015/02/03 | [
"https://Stackoverflow.com/questions/28296476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1305814/"
] | [pip 6.1.0](https://pypi.python.org/pypi/pip/6.1.0) has been released, fixing this issue. You can upgrade with:
```
pip --trusted-host pypi.python.org install -U pip
```
to self-upgrade.
---
*Original answer*:
This is caused by a change in Python 2.7.9, which `urllib3` needs to account for. See [issue #543](https... | It is related to urllib3.
You can resolve it with urllib3 version 1.25.8.
Download that version of urllib3 manually and install it.
Even though you install thia version, pip will still use its own version.So you have to remove it and replace it.
Usually, installed module is on PythonXX/Lib/site-packages
1. Delete ur... | 6,352 |
63,019,336 | I am yet to learn the 'lambda' concept in python, I tried to look for answers and every answer includes lambda in it. This is my code, can you please suggest me a way to sort it by values.
```html
sorted_dict = {'sir': '113', 'to': '146', 'my': '9', 'jesus': '4', 'saving': '275', 'changing': '72', 'apologize': '285', ... | 2020/07/21 | [
"https://Stackoverflow.com/questions/63019336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13967182/"
] | lambda is often used as the key to sort every value in an iterator.
The same step from turning dictionaries to list of tuples, can be done using the dict method `dict.items()`.
and i used lambda in sorting, as a key to tell the sorted function that, i want to sort based on the value in each tuple located in the 1st i... | if you are familiar with other programming concepts, you may have heard of what is called an "inline function"...
Lambda is an "inline function" equivalent in Python..
its a function which doesnt have a function name, and is restricted to have only a single line of code.
now coming to the problem of sort, the sort f... | 6,357 |
3,351,218 | If a string contains `*SUBJECT123`, how do I determine that the string has `subject` in it in python? | 2010/07/28 | [
"https://Stackoverflow.com/questions/3351218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277603/"
] | ```
if "subject" in mystring.lower():
# do something
``` | If you want to have `subject` match `SUBJECT`, you could use [`re`](http://docs.python.org/library/re.html)
```
import re
if re.search('subject', your_string, re.IGNORECASE)
```
Or you could transform the string to lower case first and simply use:
```
if "subject" in your_string.lower()
``` | 6,358 |
29,276,668 | I have created a new project in django. when I run **python manage.py runserver**, I am getting the msg in command prompt like below.
```
/var/www/samplepro/myapp$ python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
March 26, 2015 - 10:52:31
Django version 1.7.7... | 2015/03/26 | [
"https://Stackoverflow.com/questions/29276668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2522688/"
] | You stated that you are running the server on Ubuntu while you are trying to connect it from another PC running Windows. In that case, you should replace the `127.0.0.1` with the actual IP address of Ubuntu server (the one you use for PuTTY). | I am also developing in a virtual machine.
Use `ifconfig` to figure out the IP address that has been assigned to your virtual machine.
Then start the server with:
```
python manage.py runserver <IP>:8000
```
Of course you could also use a different port instead of `8000`. Then use that address and port in your hos... | 6,364 |
27,595,162 | I am looking for an algorithm or modification of an efficient way to get the sum of run through of a tree depth, for example:
```
Z
/ \
/ \
/ \
/ \
X Y
/ \ / \
/ \ / \
A B ... | 2014/12/22 | [
"https://Stackoverflow.com/questions/27595162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3947332/"
] | You can recurse over the nodes of the tree keeping the sum from the root down to this point. When you reach a leaf node, you return the current sum in a list of one element. In the internal nodes, you concatenate the lists returned from children.
Sample Code:
```
class Node:
def __init__(self, value, children):
... | Here is what you are looking for. In this example, trees are stored as dicts with a "value" and a "children" keys, and "children" maps to a list.
```
def triesum(t):
if not t['children']:
return [t['value']]
return [t['value'] + n for c in t['children'] for n in triesum(c)]
```
Example
```
trie = {'... | 6,365 |
24,828,771 | I am in the process of writing a python script that will (1) obtain a list of y-values for each subplot to plot against a common set of x-values, (2) make each of these subplots a scatter-plot and put it in the appropriate location in the subplot grid, and (3) complete these tasks for different sizes of subplot grids. ... | 2014/07/18 | [
"https://Stackoverflow.com/questions/24828771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3421870/"
] | A useful function for things like this is `plt.subplots(nrows, ncols)` which will return an array (a numpy object array) of subplots on a regular grid.
As an example:
```
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=4, ncols=4, sharex=True, sharey=True)
# "axes" is a 2D array of... | If you are going to use Python, you will want to take a stroll through the [Python Tutorial](https://docs.python.org/2.7/tutorial/index.html) to learn the the language and data structures available to you, there is good instructional material online, you might want to consider some of the *computer science 101* courses... | 6,366 |
43,159,565 | I've been using the script below to download technical videos for later analysis. The script has worked well for me and retrieves the highest resolution version available for the videos that I have needed.
Now I've come across a [4K YouTube video](https://youtu.be/vzS1Vkpsi5k), and my script only saves an mp4 with 128... | 2017/04/01 | [
"https://Stackoverflow.com/questions/43159565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3904031/"
] | In Windows you will need to right click a .py, and press Edit to edit the file using IDLE. Since the default action of double clicking a .py is executing the file with python on a shell prompt.
To open just IDLE:
Click on that. `C:\Python36\Lib\idlelib\idle.bat` | If your using Windows 10 just type in `idle` where it says: "Type here for search" | 6,367 |
49,327,630 | I am new to python 3 and I'm working on sentiment analysis of tweets. My code begins with a for loop that takes in 50 tweets, which i clean and pre-process. After this (still inside the for loop) i want to save each tweet in a text file(every tweet on a new line)
Here's how the code goes:
```
for loop:
..
... | 2018/03/16 | [
"https://Stackoverflow.com/questions/49327630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9504637/"
] | I'm not sure if this is exactly what you want to do but you can change this
```
filename=open("withnouns.txt","a")
sys.stdout = filename
print(new_words)
print("\n")
sys.stdout.close()
```
to
```
filename=open("withnouns.txt","a")
filename.write(new_words + "\n")
filename.write("\n\n")
filename.close()
```
altern... | You're confusing two different kinds of writing to file.
`sys.stdout` pipes your output to the console/terminal. This can be written to file but it's very roundabout.
Writing to file is different. In python you should look at the [`csv` module](https://docs.python.org/3/library/csv.html) if you're writing lists of va... | 6,376 |
67,293,952 | In short, I have to scrape Flipkart and store the data in Mongodb.
Firstly, use [MongoDB Atlas](https://www.mongodb.com/cloud/atlas/lp/try2-in) to get yourself a free managed Mongodb server. Test if you are able to connect to it using python's library pymongo.
Secondly, install [Scrapy](https://docs.scrapy.org/en/lat... | 2021/04/28 | [
"https://Stackoverflow.com/questions/67293952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15781486/"
] | I had the same issue, and here's what I figured out:
You need to include `Store` from redux, and use it as your type definition for your own `store` return value. Short answer:
```
import {combineReducers, Store} from 'redux';
[...]
const store:Store = configureStore([...])
[...]
export default store;
```
Longer an... | A potential solution would be to extend the RootState type to include $CombinedState as follows:
```
import { $CombinedState } from '@reduxjs/toolkit';
export type RootState = ReturnType<typeof store.getState> & {
readonly [$CombinedState]?: undefined;
};
``` | 6,378 |
50,847,000 | I have a csv file which has contents like the following:
**stores.csv**
```
Site, Score, Rank
roolee.com,100,125225
piperandscoot.com,29.3,222166
calledtosurf.com,23.8,361542
cladandcloth.com,17.9,208670
neeseesdresses.com,9.6,251016
...
```
Here's my model.
**models.py**
```
class SimilarStore(models.Model):
... | 2018/06/13 | [
"https://Stackoverflow.com/questions/50847000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9393766/"
] | You can read the csv file through pandas and then convert it to your desired object ny using pandas funtion 'infer\_objects()'. I hope the code below helps you in this regard,
```
import pandas as pd
SimilarStore_df = pd.read_csv('./store.csv') #importing csv file as pandas DataFrame
SimilarStore_df.columns = ['Domain... | Just find the table name in your Database also find the corresponding column names with the table and use the to\_sql command in pandas | 6,379 |
6,906,515 | Okay, so I'm writing a very simplistic password cracker in python that brute forces a password with alphanumeric characters. Currently this code only supports 1 character passwords and a password file with a md5 hashed password inside. It will eventually include the option to specify your own character limits (how many... | 2011/08/02 | [
"https://Stackoverflow.com/questions/6906515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/856255/"
] | The way to allow a `KeyboardInterrupt` to end your program is to **do nothing**. They work by depending on nothing catching them in an `except` block; when an exception bubbles all the way out of a program (or thread), it terminates.
What you have done is to trap the `KeyboardInterrupt`s and handle them by printing a ... | This is what worked for me...
```
import sys
try:
....code that hangs....
except KeyboardInterrupt:
print "interupt"
sys.exit()
``` | 6,380 |
28,168,732 | Here is my JSON string which I need to parse.
```
{
"192.168.1.2_151b3a32-ce00-114a-e000-0004a50c1c6d_stream1" : {
"@class" : "com.barco.compose.media.transcode.internal.h264.H264Gateway",
"id" : "192.168.1.2_151b3a32-ce00-114a-e000-0004a50c1c6d_stream1",
"uri" : {
"high" : "rtp://239.1.1.2:5006",
... | 2015/01/27 | [
"https://Stackoverflow.com/questions/28168732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4498089/"
] | Your `JSON` object contains several root (or top) objects indexed with keys such as `"192.168.1.2_151b3a32-ce00-114a-e000-0004a50c1c6d_stream1"`. From your question it seems you want to access the `id` field of these elements. For that the simple way is probably using the `json` module - included in the standard librar... | The following expression is what you need:
```
$..id
```
Proof:
```
In [12]: vv = json.loads(my_input_string)
In [13]: jsonpath_expr = parse('$..id')
In [14]: [x.value for x in jsonpath_expr.find(vv)]
Out[14]:
[u'192.168.1.2_151b3a32-ce00-114a-e000-0004a50c1c6d_stream1',
u'192.168.1.2_151b3a32-ce00-114a-e000-00... | 6,384 |
12,730,524 | On this sample code i want to use the variables on the `function db_properties` at the function `connect_and_query`. To accomplish that I choose the `return`. So, using that strategy the code works perfectly. But, in this example the db.properties files only has 4 variables. That said, if the properties file had 20+ va... | 2012/10/04 | [
"https://Stackoverflow.com/questions/12730524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1323826/"
] | If there are a lot of variables, or if you want to easily change the variables being read, return a dictionary.
```
def db_properties(self, *variables):
cfgFile='c:\test\db.properties'
parser = SafeConfigParser()
parser.read(cfgFile)
return {
variable: parser.get('database', variable) for varia... | You certainly don't want to call `db_properties()` 4 times; just call it once and store the result.
It's also almost certainly better to return a dict rather than a tuple, since as it is the caller needs to know what the method returns in order, rather than just having access to the values by their names. As the numbe... | 6,391 |
405,282 | I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.
So, my question:
How can I automatically give a name to an object?
I was thinking of creating a "Herd" class whi... | 2009/01/01 | [
"https://Stackoverflow.com/questions/405282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Hm, well you normally just stuff all those instances in a list and then iterate over that list if you want to do something with them. If you want to automatically keep track of each instance created you can also make the adding to the list implicit in the class' constructor or create a factory method that keeps track o... | you could make an 'animal' class with a name attribute.
Or
you could programmically define the class like so:
```
from new import classobj
my_class=classobj('Foo',(object,),{})
```
Found this:
<http://www.gamedev.net/community/forums/topic.asp?topic_id=445037> | 6,396 |
57,814,535 | I figured out this is a popular question, but still I couldn't find a solution for that.
I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws ... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57814535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204706/"
] | try this:
```
conda install pytorch torchvision cudatoolkit=10.2 -c pytorch
``` | Uninstalling the packages and reinstalling it with pip instead solved it for me.
1.`conda remove pytorch torchvision torchaudio cudatoolkit`
2.`pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116` | 6,404 |
10,891,670 | I'm using the [runwithfriends](http://apps.facebook.com/runwithfriends) example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files:
### conf.py:
```
# Facebook Application ID and Secret.
FACEBOOK_APP_ID = ''
FACEBOOK_APP_SECRET = '... | 2012/06/05 | [
"https://Stackoverflow.com/questions/10891670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137527/"
] | Read the [documentation for `__del__`](http://docs.python.org/reference/datamodel.html#object.__del__) and [for the garbage collector](http://docs.python.org/library/gc.html#gc.garbage). `__del__` doesn't do what you probably think it does, nor does `del`. `__del__` is not necessarily called when you do a `del`, and ma... | Because the garbage collector has no way of knowing which can safely be deleted first. | 6,414 |
53,784,485 | I am using python to collect temperature data but only want to store the last 24 hours of data.
I am currently generating my .csv file with this
```
while True:
tempC = mcp.temperature
tempF = tempC * 9 / 5 + 32
timestamp = datetime.datetime.now().strftime("%y-%m-%d %H:%M ")
f = open("24hr.csv", "a... | 2018/12/14 | [
"https://Stackoverflow.com/questions/53784485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10792002/"
] | You've done most of the work already. I've got a couple of suggestions.
1. Use `with`. This will mean that if there's an error mid-way through your program and an exception is raised, the file will be closed properly.
2. Parse the timestamp from the file and compare it with the current time.
3. Use `len` to check the ... | Are u using linux ? If u jus need last 144 lines u can try
```
tail -n 144 file.csv
```
U can find tail for windows too, I got one with CMDer.
If u have to use python and u have small file which fit in RAM, load it with readlines() into list, cut it (lst = lst[:144]) and rewrite. If u dont shure how many lines u h... | 6,418 |
47,128,570 | I have a set of data that looks like the following:
```
index 902.4 909.4 915.3
n 0.6 0.3 1.4
n.1 0.4 0.3 1.3
n.2 0.3 0.2 1.1
n.3 0.2 0.2 1.3
n.4 0.4 0.3 1.4
DCIS 0.3 1.6
DCIS.1 0.3 1.2
DCIS.2 1.1
DCIS.3 0.2 1.2
DCIS.4 0.2 ... | 2017/11/06 | [
"https://Stackoverflow.com/questions/47128570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8147329/"
] | You can use this:
```
plt.title("Histograms for " + str(df.columns[i]))
``` | Try
```
plt.title("Histograms for {0:.2f}".format(df.columns[i]))
```
The characters inside the curly brackets are from the [Format Specification Mini-Language](https://docs.python.org/3/library/string.html#format-specification-mini-language). This example formats a float with 2 decimal places. If you follow the lin... | 6,421 |
62,741,775 | With my python script below, I wanted to check if a cron job is defined in my linux (centOS 7.5) server, and if it doesn't exist, I will add one by using python-crontab module.. It was working well until I gave CRONTAB -R to delete existing cron jobs and when I re-execute my python script, it is saying cronjob exists e... | 2020/07/05 | [
"https://Stackoverflow.com/questions/62741775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11999777/"
] | The problem is that you have initialized a new Cron job before checking if it exists. You assumed that `Cron.find_command()` is only identifying enabled cron jobs. But it also identifies cronjobs that are created, but not enabled yet.
So, you have to check if the cronjob exists before creating a new job. Then, if it d... | Another Solution might be to add the items to an list as the output of the find command is an generator object but by putting the items into an list makes it easier to work on. This is what I did to solve the problem you had
Below here based on everything else already being initialized
```
List_A=[]
basic_iter... | 6,423 |
46,418,897 | I have a list as shown below which contain some dictionaries.
```
dlist=[
{
"a":1,
"b":[1,2]
},
{
"a":3,
"b":[4,5]
},
{
"a":1,
"b":[1,2,3]
}
]
```
I want the result to be as in this form as shown below
```
dlist=[
{
"a":1,
"b":[1,2,3]
},
{
"a":3,
"b":[4,5]
}
]
```
I can so... | 2017/09/26 | [
"https://Stackoverflow.com/questions/46418897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6858122/"
] | Here is a solution that uses a temporary defaultdict:
```python
from collections import defaultdict
dd = defaultdict(set) # create temporary defaultdict
for d in dlist: dd[d["a"]] |= set(d["b"]) # union set(b) for each a
l = [{"a":k, "b":list(v)} for k,v in dd.items()] # generat... | if My understanding is right
```
uniques, theNewList = set(), []
for d in dlist:
cur = d["a"] # Avoid multiple lookups of the same thing
if cur not in uniques:
theNewList.append(d)
uniques.add(cur)
print(theNewList)
``` | 6,424 |
18,305,026 | I want to monitor a dir , and the dir has sub dirs and in subdir there are somes files with `.md`. (maybe there are some other files, such as \*.swp...)
I only want to monitor the .md files, I have read the doc, and there is only a `ExcludeFilter`, and in the issue : <https://github.com/seb-m/pyinotify/issues/31> says... | 2013/08/19 | [
"https://Stackoverflow.com/questions/18305026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1276501/"
] | I think you basically have the right idea, but that it could be implemented more easily.
The `ProcessEvent` class in the **pyinotify** module already has a hook you can use to filter the processing of events. It's specified via an optional `pevent` keyword argument given on the call to the constructor and is saved in ... | There's nothing particularly wrong with your solution, but you want your inotify handler to be as fast as possible, so there are a few optimizations you can make.
You should move your match suffixes out of your function, so the compiler only builds them once:
```
EXTS = set([".md", ".markdown"])
```
I made them a s... | 6,425 |
40,613,590 | I would like to design a function `f(x : float, up : bool)` with these input/output:
```
# 2 decimals part rounded up (up = True)
f(142.452, True) = 142.46
f(142.449, True) = 142.45
# 2 decimals part rounded down (up = False)
f(142.452, False) = 142.45
f(142.449, False) = 142.44
```
Now, I know about Python's `round... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1974842/"
] | Have you considered a mathematical approach using `floor` and `ceil`?
If you always want to round to 2 digits, then you could premultiply the number to be rounded by 100, then perform the rounding to the nearest integer and then divide again by 100.
```
from math import floor, ceil
def rounder(num, up=True):
dig... | `math.ceil()` rounds up, and `math.floor()` rounds down. So, the following is an example of how to use it:
```
import math
def f(x, b):
if b:
return (math.ceil(100*x) / 100)
else:
return (math.floor(100*x) / 100)
```
This function should do exactly what you want. | 6,427 |
5,104,366 | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
```
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
```
Is there any possibility that I ca... | 2011/02/24 | [
"https://Stackoverflow.com/questions/5104366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632263/"
] | >
> It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not c... | I am lost in all these diverse answers.
But I think that what you need is expressed in the following code:
```
class P:
pvar=1 # <--- class attribute
def __init__(self,name):
self.cname = name
class C(P):
def __init__(self,name):
self.cname = name
c1=C('1')
c2=C('2')... | 6,430 |
72,509,585 | I have information about places and purchases in a table, and I need to find the name of all the places where, for all the clients who purchased in that place, the total of their purchases is at least 70%.
I've already found the answer on python, I've sum the number of purchases per client, then the purchases per clie... | 2022/06/05 | [
"https://Stackoverflow.com/questions/72509585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9535697/"
] | Schema and insert statements:
```
create table c(client_id int, place_name varchar(50), total_purchase int, detail_purchase int);
insert into c values(1 ,'place1', 10, 7);
insert into c values(1 ,'place2', 10, 3);
insert into c values(2 ,'place1', 5, 4);
insert into c values(2 ,'place3', 5, 1);
```
Query:... | If I understand your question correctly, you could just use a where statement
```
SELECT place_name
FROM purchases
where (detail_purchase/total_purchase) >=0.7
GROUP BY place_name
```
[db fiddle](https://www.db-fiddle.com/f/w4EVh4WrdPJWJBKzqJ8RQb/1) | 6,440 |
39,448,135 | I have an application generating a weird config file
```
app_id1 {
key1 = val
key2 = val
...
}
app_id2 {
key1 = val
key2 = val
...
}
...
```
And I am struggling on how to parse this in python. The keys of each app may vary too.
I can't change the application to generate the configuration file in some easily parsable... | 2016/09/12 | [
"https://Stackoverflow.com/questions/39448135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3821298/"
] | Based on the fact you said it had a button where you can view source, this sounds like a WYSIWIG (What you see is what you get) editor like CKeditor, TinyMCE, Froala, etc. They take standard HTML textarea elements and using Javascript and CSS convert them into more robust editors. They allow you to do simple text forma... | It`s not much information, so I‘ll take a guess:
For `<strong><em>`: The website could eventually use a div with the `contenteditable="true"` attribute ([more info on mdn](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable)) as the input method. When you then paste in text from another... | 6,442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.