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 |
|---|---|---|---|---|---|---|
72,565,884 | I have a following code that handle with sockets in Python:
```py
import socket
HOST = "127.0.0.1"
PORT = 4999
TIMEOUT = 1
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT)) #
s.listen()
conn, addr = s.accept()
conn.settimeout(TIMEOUT)
with conn:
prin... | 2022/06/09 | [
"https://Stackoverflow.com/questions/72565884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14667788/"
] | You don't need threads to handle serial connections, and your example "with threads" didn't use threads at all. It just created (and didn't save) a `threading.Lock` object. Use a `while` loop to accept the next connection:
```py
import socket
HOST = ''
PORT = 4999
with socket.socket() as s:
s.bind((HOST, PORT... | Something like this:
Main thread receives data and append to list.
Thread monitors list for data to do whatever.
```
def receive_tcp_packets(self):
server_socket.bind(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.listen()
server_conn, address = server_socket.accept()
# Wait for ... | 9,990 |
65,047,449 | I am trying to fetch data from a MySQL database using python connector. I want to fetch records matching the `ID`. The ID has an integer data type. This is the code:
```py
custID = int(input("Customer ID: "))
executeStr = "SELECT * FROM testrec WHERE ID=%d"
cursor.execute(executeStr, custID)
custData = cursor.fetchal... | 2020/11/28 | [
"https://Stackoverflow.com/questions/65047449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14631135/"
] | The string only accepts %s or %(name)s , not %d.
```
executeStr = "SELECT * FROM testrec WHERE ID=%s"
```
and the variables are supposed to be in a tuple, although that varies by implementation depending on what version you are using, you might need to use:
```
cursor.execute(executeStr, (custID,))
```
More infor... | Your should try %s not %d. This is because your data type of MYSQL may be int but the parameter you should pass to cursor must be string.
Try this:
```
custID = int(input("Customer ID: "))
executeStr = 'SELECT * FROM testrec WHERE ID=%s'%(custID,)
cursor.execute(executeStr, custID)
custData = cursor.fetchall()
if ... | 9,991 |
50,807,953 | I am trying to write a code that finds repeated characters in a word using python 3.x.
For instance,
```
"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabBcde" -> 2 # 'a' occurs twice and 'b' twice (bandB)
"indivisibility" -> 1 # 'i' occurs six times
```
Here is the code I have... | 2018/06/12 | [
"https://Stackoverflow.com/questions/50807953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7852656/"
] | I don't understand what your code is supposed to do: you never put anything in `final` and you `return` immediately.
The below solution keeps two `set`s as it iterates over the input. One is every character we've seen, the other is every character that occurs more than once. We use `set`s because they have very fast ... | >
> I want to grow in my python skills so I want to understand what's going wrong with it and why.
>
>
> Any ideas?
>
>
>
Well, for one thing, since you never actually put anything in "final" you will never have a case for which "i" is in "final"...
Here's a function that will do what you want:
```
def do_stuf... | 9,993 |
50,721,735 | I have both the version of python.I have also installed jupyter notebook individually and when i open the jupyter notebook and go to new section it is showing python 2
I want to use python3 for newer packages.So how can we upgrade the python version. | 2018/06/06 | [
"https://Stackoverflow.com/questions/50721735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8722059/"
] | Creating an instance that uses a service account requires you have the compute.instances.setServiceAccount permission on that service account. To make this work, grant the [iam.serviceAccountUser](https://cloud.google.com/compute/docs/access/iam#the_serviceaccountuser_role) role to your service account (either on the e... | ### Find out who you are first
* if you are using Web UI: what **email** address did you use to login?
* if you are using local `gcloud` or `terraform`: find the json file that contains your credentials for gcloud (often named similarly to `myproject*.json`) and see if it contains the **email**: `grep client_email myp... | 9,994 |
22,883,337 | Hey all am new to python programming and i have noticed some code which is really confusing me.
```
import collectors
s = 'mississippi'
d = collectors.defaultdict(int)
for k in s:
d[k] += 1
d.items()
```
The thing i need to know is the use of d[k] here ..I know k is the value in the string s.But i didnt unders... | 2014/04/05 | [
"https://Stackoverflow.com/questions/22883337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3501595/"
] | Dictionaries in Python are "mapping" types. (This applies to both regular `dict` dictionaries and the more specialized variations like `defaultdict`.) A mapping takes a key and "maps" it to a value. The syntax `d[k]` is used to look up the key `k` in the dictionary `d`. Depending on where it appears in your code, it ca... | Here you go
```
d[key]
Return the item of d with key key. Raises a KeyError if key is not in the map.
```
Straigth from the [python docs](https://docs.python.org/2/library/stdtypes.html), under mapping types.
Go to <https://docs.python.org/> and bookmark it. It will become your best friend. | 9,997 |
45,471,477 | I need the sacred package for a new code base I downloaded. It requires sacred.
<https://pypi.python.org/pypi/sacred>
conda install sacred fails with
PackageNotFoundError: Package missing in current osx-64 channels:
- sacred
The instruction on the package site only explains how to install with pip. What do you do... | 2017/08/02 | [
"https://Stackoverflow.com/questions/45471477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058511/"
] | That package is not available as a conda package at all. You can search for packages on anaconda.org: <https://anaconda.org/search?q=sacred> You can see the type of package in the 4th column. Other Python packages may be available as conda packages, for instance, NumPy: <https://anaconda.org/search?q=numpy>
As you can... | It happens some issue to me before. If your system default Python environment is Conda, then you could download those files from <https://pypi.python.org/pypi/sacred#downloads>
and manually install by
```
pip install C:/Destop/some-file.whl
``` | 9,998 |
60,699,328 | I'm getting the following error when trying to install pychalk:
```
pip install pychalk --user
```
```
FileNotFoundError: [Errno 2] No such file or directory: 'c:\\users\\jokzc\\appdata\\roaming\\python\\python38\\site-packages\\MarkupSafe-1.1.1.dist-info\\METADATA'
``` | 2020/03/16 | [
"https://Stackoverflow.com/questions/60699328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12868860/"
] | You are using Python 3.8.
>
> ...python\\python38\\site-packages\...
>
>
>
The [last release for pychalk](https://pypi.org/project/pychalk/#history) was 2018, before the [releases for Python3.8](https://www.python.org/dev/peps/pep-0569/#schedule) came out.
The package is probably not updated yet to support Py... | you just need to delete the OpenCV-python folder from the(path=**C:\Users\rahul\AppData\Local\Programs\Python\Python37\Lib\site-packages\opencv\_python-3.4.2.17.dist-info**) and then again you have to install that library
you can see the picture below.
here I have attached two pics in which first is showing error messa... | 9,999 |
52,425,065 | How can I use Python 3.7 in my command line?
My Python interpreter is active on Python 3.7 and my python.pythonPath is `/usr/local/bin/python3`, though my Python version in my command line is 2.7. I've already installed Python 3.7 on my mac.
```
lorenzs-mbp:Python lorenzkort$ python --version
Python 2.7.13
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52425065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7866979/"
] | If you open tab "Terminal" in your VSCode then your default python is called (in your case python2).
If you want to use python3.7 try to use following command:
```
python3 --version
```
Or just type the full path to the python folder:
```
/usr/local/bin/python3 yourscript.py
```
In case you want to change defaul... | You should use `python3` instead of `python` for running any commands you want to run then it will use the python3 version interpreter.
Also if you are using `pip` then use `pip3`.
Hope this helps. | 10,000 |
44,628,186 | I encounter many tasks in which I need to filter python (2.7) list to keep only ordered unique values. My usual approach is by using `odereddict` from collections:
```
from collections import OrderedDict
ls = [1,2,3,4,1,23,4,12,3,41]
ls = OrderedDict(zip(ls,['']*len(ls))).keys()
print ls
```
the output is:
>
> ... | 2017/06/19 | [
"https://Stackoverflow.com/questions/44628186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3861108/"
] | If you need to preserve the order **and** get rid of the duplicates, you can do it like:
```
ls = [1, 2, 3, 4, 1, 23, 4, 12, 3, 41]
lookup = set() # a temporary lookup set
ls = [x for x in ls if x not in lookup and lookup.add(x) is None]
# [1, 2, 3, 4, 23, 12, 41]
```
This should be **considerably** faster than yo... | You could use a [set](https://docs.python.org/2/library/stdtypes.html#set) like this:
```
newls = []
seen = set()
for elem in ls:
if not elem in seen:
newls.append(elem)
seen.add(elem)
``` | 10,002 |
38,521,553 | I have two files representing records with intervals.
file1.txt
```none
a 5 10
a 13 19
a 27 39
b 4 9
b 15 19
c 20 33
c 39 45
```
and
file2.txt
```none
something id1 a 4 9 commentx
something id2 a 14 18 commenty
something id3 a 1 4 commentz
something id5 b 3 9 commentbla
something id6 b 16 18 commentbla
something ... | 2016/07/22 | [
"https://Stackoverflow.com/questions/38521553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613786/"
] | Do looping in a loop is not a good way. Try to avoid to do such things.
I think you could cache the content of file1 first use a dict object. Then, when looping file2 you can use the dict object to find your need things.So, i will code like bellow:
```
with open("file1.csv", "r") as protein, open("file2.csv", "r") as ... | For your code to work, you will have to change three things:
1. Your loop over the position reader is only run once, because the reader runs through the file, the first time the loop is run. Afterwards, he searches for the next item at the end of the file. You'll have to rewind the file each time, before the loop is r... | 10,007 |
65,891,227 | this is probably a pretty dumb question..
I was fooling around some in python and decided to make two version of prime number apps, one that just indefinately counts up all prime-numbers from start until you fry ur pc and one that lets the user input a number and then checks if the number is a prime number or not.
So ... | 2021/01/25 | [
"https://Stackoverflow.com/questions/65891227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15040876/"
] | You need to fix `scripts/start.js` file.
There is a line in this file:
```
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
```
You need to change it to
```
const compiler = createCompiler({ webpack, config, appName, urls, useYarn });
```
This change will fix your current error but proba... | Try updating your `node` part for webpack 5 as well. What was
```
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
}
```
has to be under `resolve.fallback`.
Source: <https://webpack.js.org/migrate/5/#clean-up-configuration> | 10,012 |
12,243,891 | How do i achieve line 9 and 10 i.e the two `for` loops in python
```
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
newMatrix = []
for (i=0; i < len(matrix); i++):
for (j=0; j < len(matrix[i]); j++):
newMatrix[j][i] = matrix[i][j]
print newMatrix
```
PS: i know i can do `[[row[i]... | 2012/09/03 | [
"https://Stackoverflow.com/questions/12243891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/406659/"
] | Use `range` (or `xrange`).
```
for i in range(len(matrix)):
for j in range(len(matrix[i])):
```
FYI, assigning to `newMatrix[i][j]` will fail, because `newMatrix` is an empty `list`. You need to add a new empty `list` to `newMatrix` for every row and then append the new value to that list in every iteration. | You can use the [`enumerate()` function](http://docs.python.org/library/functions.html#enumerate) to loop over both the matrix values and give you indices:
```
newMatrix = [[0] * len(matrix) for _ in xrange(len(matrix[0]))]
for i, row in enumerate(matrix):
for j, value in enumerate(row):
newMatrix[j][i] = ... | 10,014 |
1,478,178 | Usually, the best practice in python, when using international languages, is to use unicode and to convert early any input to unicode and to convert late to a string encoding (UTF-8 most of the times).
But when I need to do RegEx on unicode I don't find the process really friendly. For example, if I need to find the '... | 2009/09/25 | [
"https://Stackoverflow.com/questions/1478178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146481/"
] | I haven't used a JDBC-ODBC bridge in quite a few years, but I would expect that the ODBC driver's fetch size would be controlling. What ODBC driver are you using and what version of the ODBC driver are you using? What is the fetch size specified in the DSN?
As a separate issue, I would seriously question your decision... | Use JDBC. There is no advantage in using ODBC bridge. In PreparedStatement or CallableStatement you can call setFetchSize() to restrict the rowset size. | 10,017 |
59,357,940 | The below piece of code uses openCV module to identify lanes on road. I use the python 3.6 for coding (I use atom IDE for development. This info is being provided because stackoverflow isn't letting me post the info without unnecessary lines of info. so please ignore the comments in bracket)
The code runs fine with a g... | 2019/12/16 | [
"https://Stackoverflow.com/questions/59357940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12181181/"
] | In some of the frames all the slope are > 0 hence left\_fit list is empty. Because of that you are getting error when you are calculating left\_fit average. One of the way to solve this problem to use left\_fit average from previous frame. I have solved it using the same approach. Please see the code below and let me k... | `HoughLinesP` returns a list and that can be an empty list and not necessarily `None`
So the lines in the function `average_slope_intercept`
```
if lines is None:
return None
```
is not much of use.
You need to check `len(lines) == 0` | 10,019 |
55,554,816 | In python2.7, I have one list
```
['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q']
```
and I need to transform into a dict like
```
{
'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':['H','I'],
'E':['J','K'],
'F':['L','M'],
'G':['N','O'],
'H':['P','Q'],
'I':[],
'J':[],
'K':[],
'L':[],
'M':[],
... | 2019/04/07 | [
"https://Stackoverflow.com/questions/55554816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11322996/"
] | With `zip()` and `itertools.izip_longest()` you can do that like:
### Code:
```
import itertools as it
in_data = list('ABCDEFGHIJKLMNOPQ')
out_data = {k: list(v) if v else [] for k, v in
it.izip_longest(in_data, zip(in_data[1::2], in_data[2::2]))}
import json
print(json.dumps(out_data, indent=2))
```
... | You can use `itertools`:
```
from itertools import chain, repeat
data = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q']
lists = [[first, second] for first, second in zip(data[1::2], data[2::2])]
result = {char: list(value) for char, value in zip(data, chain(lists, repeat([])))}
... | 10,020 |
51,961,416 | i am trying to copy line from text file in zip folder by matching partial string,
zip folders are in a shared folder
is there a way to copy strings from text files and send it to one output text file.
how to do it using python..
is it possible with zip\_archive?
i tried using this, with no luck.
```
zf = zipfile.ZipF... | 2018/08/22 | [
"https://Stackoverflow.com/questions/51961416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10258075/"
] | Unlike *@strava* answer, you don't actually have to extract... `zipfile` gives you excellent [API](https://docs.python.org/3/library/zipfile.html) for manipulating files. Here is a simple example of reading each file inside a simple zip (I zipped only one `.txt` file):
```
import zipfile
zip_path = r'C:\Users\avi_na\D... | You could try extracting them first, and then treating them as normal csv files
```
zf = zipfile.ZipFile( path to zip )
zf.extract('first.csv', path to save directory )
file = open('path\first.csv')
``` | 10,029 |
69,979,362 | I have a csv that I need to convert to XML using Python. I'm a novice python dev.
Example CSV data:
```
Amount,Code
CODE50,1246
CODE50,6290
CODE25,1077
CODE25,9790
CODE100,5319
CODE100,4988
```
Necessary output XML
```
<coupon-codes coupon-id="CODE50">
<code>1246</code>
<code>1246</code>
<coupon-codes/>
<c... | 2021/11/15 | [
"https://Stackoverflow.com/questions/69979362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9803155/"
] | Here how you do it:
```
Expanded(
child: CustomPaint(
painter: MyCustomPainter(),
size: Size.infinite,
),
),
``` | You can get height and width of the screen by using MediaQuery and use them
```
final width = MediaQuery.of(context).size.width;
final height = MediaQuery.of(context).size.height;
return CustomPaint(
size: Size(width,height),
painter: Sky(),
child: const Center(
child: Text(
... | 10,031 |
1,984,871 | I've been a Perl guy for over 10 years but a friend convinced me to try Python and told me how much faster it is than Perl. So just for kicks I ported an app I wrote in Perl to Python and found that it runs about 3x slower. Initially my friend told me that I must have done it wrong, so I rewrote and refactored until I ... | 2009/12/31 | [
"https://Stackoverflow.com/questions/1984871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241470/"
] | python is slower then perl. It may be faster to develop but it doesnt execute faster here is one benchmark <http://xodian.net/serendipity/index.php?/archives/27-Benchmark-PHP-vs.-Python-vs.-Perl-vs.-Ruby.html> -edit- a terrible benchmark but it is at least a real benchmark with numbers and not some guess. To bad theres... | I'm not up-to-date on everything with Python, but my first idea about this benchmark was the difference between Perl and Python numbers. In Perl, we have numbers. They aren't objects, and their precision is limited to the sizes imposed by the architecture. In Python, we have objects with arbitrary precision. For small ... | 10,032 |
25,100,309 | I have a memory constraint of 4GB RAM. I need to have 2.5 GB of data in RAM in order to perform further things
```
import numpy
a = numpy.random.rand(1000000,100)## This needs to be in memory
b= numpy.random.rand(1,100)
c= a-b #this need to be in code in order to perform next operation
d = numpy.linalg.norm(numpy.asar... | 2014/08/02 | [
"https://Stackoverflow.com/questions/25100309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3413239/"
] | If the creation of `a` doesn't cause a memory problem, and you don't need to preserve the values in `a`, you could compute `c` by modifying `a` in place:
```
a -= b # Now use `a` instead of `c`.
```
Otherwise, the idea of working in smaller chunks or batches is a good one. With your list comprehension solution, you... | If memory is the reason your code is slowing down and crashing why not just use a generator instead of list comprehension?
d =(numpy.sqrt(numpy.dot(i-b,i-b)) for i in a)
A generator essentially provides steps to get the next object in an iterator. In other words no operation is made and no data is stored until you ca... | 10,042 |
72,177,222 | Description.
------------
While trying to use pre-commit hooks, I am experiencing some difficulties, including [the latest Lava-nc release by Intel in `.tar.gz` format](https://github.com/lava-nc/lava/releases/download/v0.3.0/lava-nc-0.3.0.tar.gz) `pip` package in a Conda environment.
MWE
---
The following Conda `en... | 2022/05/09 | [
"https://Stackoverflow.com/questions/72177222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7437143/"
] | this is unfortunately a known bug in `conda` -- though I'm unfamiliar with the status on it. they're mistakenly shipping a `python3.1` binary as the default executable (it should be called `python3.10` -- they have a [2020](https://github.com/asottile/flake8-2020) problem that's probably a `sys.version[:3]` somewhere)
... | There was a ticked opened regarding the observation in pre-commit repository <https://github.com/pre-commit/pre-commit/issues/1375>
One of pre-commit contributers suggest to use `language_version: python3` for black config in `.pre-commit-config.yaml`
```yaml
repo: https://github.com/psf/black
rev: 22.3.0
hoo... | 10,043 |
29,224,447 | I have a python function that takes a imported module as a parameter:
```
def printModule(module):
print("That module is named '%s'" % magic(module))
import foo.bar.baz
printModule(foo.bar.baz)
```
What I want is to be able to extract the module name (in this case `foo.bar.baz`) from a passed reference to the m... | 2015/03/24 | [
"https://Stackoverflow.com/questions/29224447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268006/"
] | The `__name__` attribute seems to work:
```
def magic(m):
return m.__name__
``` | If you have a string with the module name, you can use pkgutil.
```
import pkgutil
pkg = pkgutil.get_loader(module_name)
print pkg.fullname
```
From the module itself,
```
import pkgutil
pkg = pkgutil.get_loader(module.__name__)
print pkg.fullname
``` | 10,044 |
1,519,276 | I've tried to debug memory crash in my Python C extension and tried to run script under valgrind. I found there is too much "noise" in the valgrind output, even if I've ran simple command as:
```
valgrind python -c ""
```
Valgrind output full of repeated info like this:
```
==12317== Invalid read of size 4
==12317=... | 2009/10/05 | [
"https://Stackoverflow.com/questions/1519276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65736/"
] | This is quite common, in any largish system. You can use Valgrind's [suppression system](http://valgrind.org/docs/manual/mc-manual.html#mc-manual.suppfiles) to explicitly suppress warnings that you're not interested in. | There is another option I found. James Henstridge has custom build of python which can detect the fact that python running under valgrind and in this case pymalloc allocator is disabled, with PyObject\_Malloc/PyObject\_Free passing through to normal malloc/free, which valgrind knows how to track.
Package available her... | 10,045 |
32,553,827 | ---I am on Ubuntu---
I am trying to setup Django Crispy forms and getting the following error:
```
Exception Type: TemplateDoesNotExist
Exception Value:
bootstrap3/layout/buttonholder.html
```
Settings.py template setup
==========================
```
TEMPLATES = [
{
'BACKEND': 'django.template.back... | 2015/09/13 | [
"https://Stackoverflow.com/questions/32553827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5054204/"
] | `ButtonHolder` isn't part of the Bootstrap template pack. It's documented as not being so.
See [this issue for discussion](https://github.com/maraujop/django-crispy-forms/issues/478)
Best bet is to use `FormActions` instead | Where do you currently save your static content. The issue seems to be due to Django's inability to find your static content from bootstrap. | 10,055 |
55,910,797 | Hello I've started using python fairly recently. I'm having so much trouble with this one segment of my code that gives me a keyerror when I try to remove an element from my set:
tiles.remove(m)
KeyError: 'B9'
EDIT: I forgot to mention that the m value changes everytime I call another function before the for loop. Al... | 2019/04/29 | [
"https://Stackoverflow.com/questions/55910797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8817267/"
] | You have a loop
```
for d in domain[m].copy():
```
where you are trying to `tiles.remove(m)` in every iteration. After it's removed in the first iteration, the dictionary won't have the key any more and you would get a keyerror in subsequent iterations. | The ‘remove’ statement needs to be included in the ‘if’ statement, otherwise it is never prevented. | 10,056 |
47,870,297 | I have a list with tuples in it looking like this:
```
my_list = (u'code', u'somet text', u'integer', [(u'1', u'text1'), (u'2', u'text2'), (u'3', u'text3'), (u'4', u'text4'), (u'5', u'text5')])
```
I'd like to iterate over `my_list[3]` and copy the rest so I would get n lists looking like this:
```
(u'code', u'some... | 2017/12/18 | [
"https://Stackoverflow.com/questions/47870297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6139149/"
] | You can achieve this using simple tuple concatenation with `+`:
```
nlists = [my_list[:-1] + tpl for tpl in my_list[-1]]
[(u'code', u'somet text', u'integer', u'1', u'text1'),
(u'code', u'somet text', u'integer', u'2', u'text2'),
(u'code', u'somet text', u'integer', u'3', u'text3'),
(u'code', u'somet text', u'inte... | Firstly unpack your tuple:
`a,b,c,d = my_list`
This, of course, assumes 4 elements exactly to your tuple or you'll get an exception.
Then iterate over d:
`for d1,d2 in d:
print('({},{},{},{},{})'.format(a,b,c,d1,d2))` | 10,057 |
47,648,133 | I want to calculate Mean Absolute percentage error (MAPE) of predicted and true values. I found a solution from [here](https://stackoverflow.com/questions/42250958/how-to-optimize-mape-code-in-python), but this gives error and shows invalid syntax in the line `mask = a <> 0`
```
def mape_vectorized_v2(a, b):
... | 2017/12/05 | [
"https://Stackoverflow.com/questions/47648133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7972408/"
] | In Python for compare by not equal need `!=`, not `<>`.
So need:
```
def mape_vectorized_v2(a, b):
mask = a != 0
return (np.fabs(a - b)/a)[mask].mean()
```
Another solution from [stats.stackexchange](https://stats.stackexchange.com/a/294069):
```
def mean_absolute_percentage_error(y_true, y_pred):
y_... | Here is an improved version that is mindful of Zero:
```
#Mean Absolute Percentage error
def mape(y_true, y_pred,sample_weight=None,multioutput='uniform_average'):
y_type, y_true, y_pred, multioutput = _check_reg_targets(y_true, y_pred, multioutput)
epsilon = np.finfo(np.float64).eps
mape = np.abs(y_p... | 10,062 |
52,135,293 | I'm following the `Quickstart` on <https://developers.google.com/drive/api/v3/quickstart/python>. I've enabled the drive API through the page, loaded the **credentials.json** and can successfully list files in my google drive. However when I wanted to download a file, I got the message
```
`The user has not granted t... | 2018/09/02 | [
"https://Stackoverflow.com/questions/52135293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767754/"
] | Once you go through the `Quick-Start Tutorial` initially the Scope is given as:
```
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
```
So after listing files and you decide to download, it won't work as you need to generate the the token again, so changing scope won't recreate or prompt you for ... | I ran into the same error. I authorized the entire scope, then retrieved the file, and use the io.Base class to stream the data into a file. Note, you'll need to create the file first.
```
from __future__ import print_function
from googleapiclient.discovery import build
import io
from apiclient import http
from googl... | 10,072 |
48,634,071 | I'm very new to python, so please bear with me. I'm having trouble to visualize an excel/csv file with seaborn's lmplot. This code:
```
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df=pd.read_csv("C:/Users/me/Documents/Jupyter Notebooks/Seaborn/Test.csv")
sns.set_style('... | 2018/02/06 | [
"https://Stackoverflow.com/questions/48634071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9319446/"
] | ```
sns.lmplot(x=df["TestX"],y=df["TestY"], data=df)
```
x, y : strings, optional
Input variables, these should be column names in data.
You can try again with:
```
sns.lmplot(x="TestX",y="TestY", data=df)
``` | ```
import pandas as pd
import numpy as np
import matplotlib
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="darkgrid")
df = pd.read_csv('data.csv')
sns.lmplot(x="Duration", y="Maxpulse", data=df)
plt.show()
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
```
"Duration" and "Maxpluse"... | 10,075 |
57,624,731 | I would like to assert that two dictionaries are equal, using Python's [`unittest`](https://docs.python.org/3/library/unittest.html), but ignoring the values of certain keys in the dictionary, in a convenient syntax, like this:
```py
from unittest import TestCase
class Example(TestCase):
def test_example(self):
... | 2019/08/23 | [
"https://Stackoverflow.com/questions/57624731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247696/"
] | There is [`unittest.mock.ANY`](https://docs.python.org/3/library/unittest.mock.html#any) which compares equal to everything.
```
from unittest import TestCase
import unittest.mock as mock
class Example(TestCase):
def test_happy_path(self):
result = {
"name": "John Smith",
"year_of_... | You can simply ignore the selected keys in the `result` dictionary.
```
self.assertEqual({k: v for k, v in result.items()
if k not in ('image_url', 'unique_id')},
{"name": "John Smith",
"year_of_birth": 1980})
``` | 10,076 |
62,155,242 | I'm trying to compile a python script with sklearn, pandas, numpy and igraph, but the Pyinstaller executable doesn't run correctly because it can't find version.json in tmp folder.
```
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Usuario\\AppData\\Local\\Temp\\_MEI106882\\wcwidth\\version.json'
... | 2020/06/02 | [
"https://Stackoverflow.com/questions/62155242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11902728/"
] | You'll need to include the `wcwidth` project directory in your data since it isn't considered a package or a module, its a data file.
In your spec file:
```
...
import wcwidth
a = Analysis(['main.py'],
pathex=[],
binaries=[],
datas=[
(os.path.dirname(wcwidth._... | I hit this issue when creating a binary from a virtual environment. It seems installing ipython within the virtual environment is causing this.
Recreating a new virtual environment without ipython seems to overcome the issue. | 10,077 |
58,308,911 | 1) I first map the key names to a dictionary called main\_dict with an empty list (the actual problem has many keys hence the reason why I am doing this)
2) I then loop over a data matrix consisting of 3 columns
3) When I append a value to a column (the key) in the dictionary, the data is appended to wrong keys.
Whe... | 2019/10/09 | [
"https://Stackoverflow.com/questions/58308911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6685541/"
] | Without using numpy (which is a heavy weight package for what you are doing) I would do this:
```
keys = ["A", "B", "C"]
main_dict = {key: [] for key in keys}
data = [[2018, 1.1, 3.3], [2017, 2.1, 5.4], [2016, 3.1, 1.4]]
# since you are reading from a file
for datum in data:
for index, key in enumerate(keys):
... | The problem is in
```
main_dict = main_dict.fromkeys(key_names, val)
```
The same list val is referenced by all the keys since python passes reference. | 10,078 |
42,585,598 | When I try to deploy to my Elastic Beanstalk environment I am getting this python error. Everything was working fine a few days ago.
```
$ eb deploy
ERROR: AttributeError :: 'NoneType' object has no attribute 'split'
```
I've thus far attempted to update everything to no effect by issuing the following commands:
``... | 2017/03/03 | [
"https://Stackoverflow.com/questions/42585598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2767129/"
] | I had the same issue. Turns out that when you enable CodeCommit the CLI looks for a remote called "codecommit-origin" and if you don't have a git remote with that *specific* name it will throw that error.
Posting this for anyone else who stumbles upon the same issue. | I fixed this with `eb codesource local && eb deploy`, so it forgets about CodeCommit. | 10,079 |
36,051,751 | I am trying to sort 4 integers input by the user into numerical order using only the min() and max() functions in python. I can get the highest and lowest number easily, but cannot work out a combination to order the two middle numbers? Does anyone have an idea? | 2016/03/17 | [
"https://Stackoverflow.com/questions/36051751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6074977/"
] | So I'm guessing your input is something like this?
```
string = input('Type your numbers, separated by a space')
```
Then I'd do:
```
numbers = [int(i) for i in string.strip().split(' ')]
amount_of_numbers = len(numbers)
sorted = []
for i in range(amount_of_numbers):
x = max(numbers)
numbers.remove(x)
s... | LITERALLY just min and max? Odd, but, why not. I'm about to crash, but I think the following would work:
```
# Easy
arr[0] = max(a,b,c,d)
# Take the smallest element from each pair.
#
# You will never take the largest element from the set, but since one of the
# pairs will be (largest, second_largest) you will at so... | 10,082 |
29,989,956 | I want to share a variable value between a function defined within a python class and an externally defined function. So in the code below, when the internalCompute() function is called, self.data is updated. How can I access this updated data value inside a function that is defined outside the class, i.e inside the re... | 2015/05/01 | [
"https://Stackoverflow.com/questions/29989956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833722/"
] | >
> determine the physical size of an iPhone (in inches)
>
>
>
This will never be possible, because the physical screen is made up of *pixels* (square LEDs), and there is no way to ask the size of one of those.
Thus, for example, an app that presents a ruler (inches / centimetres) would need to know *in some othe... | I'm using this code im my pch file:
```
#define IS_IPAD ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
#define IS_IPHONE6PLUS (!IS_IPAD && [[UIScreen mainScreen] bounds].size.height >= 736)
#define IS_IPHONE6 (!IS_IPAD && !IS_PHONE6PLUS && [[UIScreen mainScreen] bounds].size.height >= 667)
... | 10,087 |
49,901,249 | I have searched everywhere for how to fix this and I could not find anything, so I'm sorry if there is already a thread existing on this issue. Also, I'm fairly new to Linux, GDP, and StackOverflow, this is my first post.
First, I am running on Debian GNU/Linux 9 (stretch) with the Windows subsystem for Linux and when... | 2018/04/18 | [
"https://Stackoverflow.com/questions/49901249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9664285/"
] | When you build the project it generates .war file as you know.You can extract it and find all the dependent jar files at {.war}\WEB-INF\lib\ | My suggestion is, go to C:\Users\<>.m2\repository (your maven directory) and search \*.jar...it will list out all the jars in the window.
Copy all the jars and paste in your directory. | 10,088 |
34,295,670 | I have a problem with a litlle program in python:
what I want is to write on a archive called text numbers from 0 to 10, but the program give me error all the time and doesn't print anything.
```
i=0
while(i<11):
outfile = open('text.txt', 'a')
outfile.write('\n'+i)
outfile.close()
i=i+1
```
I tried... | 2015/12/15 | [
"https://Stackoverflow.com/questions/34295670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5631254/"
] | I'm guessing that the error you're getting involves concatenating a string with an integer.
try:
```
outfile.write(str(i) + '\n')
``` | Assuming you want a file that looks like this:
```
1
2
3
4
5
6
7
8
9
```
Did you try it this way?
```
>>> fo = open('outfile.txt', 'w')
>>> for i in range(1,10):
... fo.write(str(i)+"\n")
>>> fo.close()
```
The error you probably are getting is this :
>
> TypeError: unsupported operand type(s) for +: 'int'... | 10,089 |
45,860,272 | My goal is to run a Python script that uses Anaconda libraries (such as Pandas) on `Azure WebJob` but can't seem to figure out how to load the libraries.
I start out just by testing a simple Azure blob to blob file copy which works when run locally but hit into an error `"ImportError: No module named 'azure'"` when ra... | 2017/08/24 | [
"https://Stackoverflow.com/questions/45860272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6329714/"
] | It seems like you've kown about deployment of Azure WebJobs, I offer the below steps for you to show how to load external libraries in python scripts.
Step 1 :
Use the **virtualenv** component to create an independent python runtime environment in your system.Please install it first with command `pip install virtualen... | You can point your Azure WebJob to your main WebApp environment (and thus its real site packages). This allows you to use the newest fastest version of Python supported by the WebApp (right now mine is 364x64), much better than 3.4 or 2.7 in x86. Another huge benefit is then you don't have to maintain an additional set... | 10,094 |
59,103,401 | I am currently implementing a MINLP optimization problem in Python GEKKO for determining the optimal operational strategy of a trigeneration energy system. As I consider the energy demand during all periods of different representative days as input data, basically all my decision variables, intermediates, etc. are 2D a... | 2019/11/29 | [
"https://Stackoverflow.com/questions/59103401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12456060/"
] | Extra square brackets are needed for 2D list definition. This gives a 2D list with 3 rows and 4 columns.
```py
[[p+10*z for p in range(3)] for z in range(4)]
# Result: [[0, 1, 2], [10, 11, 12], [20, 21, 22], [30, 31, 32]]
```
If you leave out the inner brackets, it is a 1D list of length 12.
```py
[p+10*z for p in ... | To diagnose the problem, I added a call to open the run folder before the solve command.
```py
#_____Solve Problem_____
m.open_folder()
m.solve()
```
I opened the `gk_model0.apm` model file with a text editor to look at a text version of the model. At the bottom it shows that there are problems with the last two int... | 10,095 |
42,329,346 | I am trying to learn Cloudformation im stuck with a senario where I need a second EC2 instance started after one EC2 is provisioned and good to go.
This is what i have in UserData of Instance one
```
"#!/bin/bash\n",
"#############################################################################################\n",
"s... | 2017/02/19 | [
"https://Stackoverflow.com/questions/42329346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/907937/"
] | The first thing I notice is that you have two `GET`s, instead of a `GET` and then a `POST` (as you noticed yourself).
But let's assume the HTML form is correct, since it works in development. That makes me suspect there is some Javascript that is throwing things off. One common problem when moving things from develop... | I am no expert but since your code is working on local just try the following to get an idea where the problem might be:
a) Run production environment on your local, see if the problem persists there.
b) Try to test run without any javascript enabled or atleast disable custom ones on the production server.
c) Try to... | 10,096 |
16,256,341 | I am trying to go back to the top of a function (not restart it, but go to the top) but can not figure out how to do this. Instead of giving you the long code I'm just going to make up an example of what I want:
```
used = [0,0,0]
def fun():
score = input("please enter a place to put it: ")
if score == "this o... | 2013/04/27 | [
"https://Stackoverflow.com/questions/16256341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2255589/"
] | What you are looking for is a `while` loop. You want to set up your loop to keep going until a place is found. Something like this:
```
def fun():
found_place = False
while not found_place:
score = input("please enter a place to put it: ")
if score == "here"
if used[1] == 0:
... | As Ashwini correctly points out, you should do a `while` loop
```
def fun():
end_condition = False
while not end_condition:
score = input("please enter a place to put it: ")
if score == "here":
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Alrea... | 10,102 |
44,628,435 | I am making a request to my api.ai chatbot after following the instructions given on their official github website [here](https://github.com/api-ai/apiai-python-client/blob/master/examples/send_text_example.py). The following is the code for which I am getting an error, to which the solution is supposedly to call the f... | 2017/06/19 | [
"https://Stackoverflow.com/questions/44628435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7872066/"
] | >
> I've tried various casting attempts
>
>
>
Have you tried this one?
```
.FirstOrDefault(ids => ids.Contains((T)propertyInfo.GetValue(item, null)))
```
Since `ids` is of type `IGrouping<TKey, TElement>` where `TElement` is of type `T` in your case, casting the value of property to `T` will allow for the compa... | Ok, so I cracked it in the end. I needed to add more detail in my generic method header/signature.
```
public static IEnumerable<T> MixObjectsByProperty<T, U>(
IEnumerable<T> objects, string propertyName, IEnumerable<IEnumerable<U>> groupsToMergeByProperty = null)
where T : class
where U : ... | 10,103 |
53,311,721 | This question is killing me softly at the moment.
I am trying to learn python, lambda, and Dynamodb.
Python looks awesome, I am able to connect to MySQL while using a normal MySQL server like Xampp, the goal is to learn to work with Dynamodb, but somehow I am unable to get\_items from the Dynamodb. This is really ki... | 2018/11/15 | [
"https://Stackoverflow.com/questions/53311721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9821202/"
] | Thats to @ippi.
It was the quotes that I am using.
```
table.get_item(Key={"id": '1'})
```
needed to be
```
table.get_item(Key={"id": 1})
```
As I am using a numeric and not a string.
Hope this helps for the next person(s) with the same problem. | You're facing this problem because you have created a table with a partition key whose data type is an integer.
Now you're performing a read an item operation specifying partition as a string which needs to be an integer that causes this issue.
I'm the author of Lucid-Dynamodb, a minimalist wrapper to AWS DynamoDB. It... | 10,106 |
61,973,288 | currently im learning how to use Apache Airflow and trying to create a simple DAG script like this
```
from datetime import datetime
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
def print_hello():
return 'Hello worl... | 2020/05/23 | [
"https://Stackoverflow.com/questions/61973288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Put a ROW ID on your tables
```
df_1 <- read_table("A B C
2.3 5 3
12 3 1
0.4 13 2") %>%
rowid_to_column("ROW")
df_2 <- read_table("A B C
4.3 23 1
1 7 2
0.4 10 2") %>%
rowid_to_column("ROW")
df_3 <- read_table("A B ... | You can put all the dataframes in a list :
```
list_df <- mget(ls(pattern = 'df_\\d+'))
```
Then calculate the stats for each column separately.
```
data.frame(A = Reduce(`+`, lapply(list_df, `[[`, 1))/length(list_df),
B = apply(do.call(rbind, lapply(list_df, `[[`, 2)), 2, median),
C = apply... | 10,107 |
28,741,772 | I am a novice writing a simple script to analyse a game. The data I would like to use describes "Items" and they have statistics associated with them (eg. "Attack Speed").
To clarify: The game is not something I have access to beyond being a player, my script is to compare combinations of the items. I will manually l... | 2015/02/26 | [
"https://Stackoverflow.com/questions/28741772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4610057/"
] | Without further info, I would say to use JSON, as it's easy to use and human-readable:
```
{
"Attack Speed": 5,
"Items": ["Dirt", "Flower", "Egg"]
}
``` | Well, You got many more options. From least to most complicated :
* [Pickle](https://wiki.python.org/moin/UsingPickle)
* [Shelve](http://pymotw.com/2/shelve/)
* [SQLite](http://zetcode.com/db/sqlitepythontutorial/)
* [SQLAlchemy](http://www.sqlalchemy.org/)
What You should use really depends on what are Your needs ex... | 10,108 |
19,228,516 | Here is my argparse sample say sample.py
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-p", nargs="+", help="Stuff")
args = parser.parse_args()
print args
```
Python - 2.7.3
I expect that the user supplies a list of arguments separated by spaces after the -p option. For example, if yo... | 2013/10/07 | [
"https://Stackoverflow.com/questions/19228516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44124/"
] | >
> Note: python 3.8 adds an `action="extend"` which will create the desired list of ['x','y']
>
>
>
To produce a list of ['x','y'] use `action='append'`. Actually it gives
```
Namespace(p=[['x'], ['y']])
```
For each `-p` it gives a list `['x']` as dictated by `nargs='+'`, but `append` means, add that value to... | I ran into the same issue. I decided to go with the custom action route as suggested by mgilson.
```
import argparse
class ExtendAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if getattr(namespace, self.dest, None) is None:
setattr(namespace, self.dest, [])
... | 10,109 |
55,376,876 | I would like to setup the local pgadmin in server mode behind the reverse proxy. The reverse proxy and the pgadmin could be on the same machine. I tried to set up but it always fails.
Here is mypgadmin conf:
```
Listen 8080
<VirtualHost *:8080>
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/pgadmin.crt
SSLCe... | 2019/03/27 | [
"https://Stackoverflow.com/questions/55376876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2886412/"
] | this work for me. I make pgadmin proxy to sub directory (https://localhost/pgadmin)
```
<VirtualHost *:80>
ServerName localhost
DocumentRoot "/var/www"
<Directory "/var/www">
AllowOverride all
</Directory
ProxyPass /ws/ ws://0.0.0.0:8888/
ProxyPass /phpmyadmin/ http://phpmyadmin/
... | Have you tried with latest version, I think it is fixed this commit Ref: [LINK](https://git.postgresql.org/gitweb/?p=pgadmin4.git;a=commit;h=f401def044c8b47974d58c71ff9e6f71f34ef41d)
Online Docs: <https://www.pgadmin.org/docs/pgadmin4/dev/server_deployment.html> | 10,110 |
13,336,628 | I have very simple web page example read from html file using python. the html called led.html as in bellow:
```
<html>
<body>
<br>
<p>
<p>
<a href="?switch=1"><img src="images/on.png"></a>
</body>
</html>
```
and the python code is:
```
import cherrypy
import os.path
import struct
class Server(object):
led_swi... | 2012/11/11 | [
"https://Stackoverflow.com/questions/13336628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1813738/"
] | If you require to swap *all* first (of pair) elements (and not just `(1, 36)` and `(0, 36)`), you can do
`fwd_count_sort=sorted(rvs_count.items(), key=lambda x: (x[0][1],-x[0][0]), reverse=True)` | I'm not exactly sure on the definition of your sorting criteria, but this is a method to sort the `pair` list according to the values in `fwd_count` and `rvs_count`. Hopefully you can use this to get to the result you want.
```
def keyFromPair(pair):
"""Return a tuple (f, r) to be used for sorting the pairs by fre... | 10,112 |
63,851,302 | I need to execute below function based on user input:
>
> If `X=0`, then from line `URL ....Print('Success` should be written to a file & get saved as `test.py`.
>
>
>
At the backend, the saved file (`Test.py`) would automatically get fetched by Task scheduler from the saved location & would run periodically.
An... | 2020/09/11 | [
"https://Stackoverflow.com/questions/63851302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13824611/"
] | Given a scalar `x` and a vector `v` the expression `x <=quantile (v, .95)` can be written as `sum( x > v) < Q` where `Q = .95 * numel(v)` \*.
Also `A_1` can be splitted before the loop to avoid extra indexing.
Moreover the most inner loop can be removed in favor of vectorization.
```
Af_1 = A_1(:,1);
Af_2 = A_2(:,1);... | Option 1:
Because all numbers are positive, you can do some optimizations. 95 percentile will be only higher if you add `A1` to the mix - if you find the `j` and `k` of greatest 95 percentile of `A2+A3` on the right side compared to the sum of the first 2 elements, you can simply take that for every `i`.
```
maxDif = ... | 10,113 |
19,479,644 | I saw a python example today and it used -> for example this was what I saw:
```
spam = None
bacon = 42
def monty_python(a:spam,b:bacon) -> "different:":
pass
```
What is that code doing? I'm not quite sure I've never seen code like that I don't really get what
```
a:spam,b:bacon
```
is doing either, can ... | 2013/10/20 | [
"https://Stackoverflow.com/questions/19479644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2805788/"
] | It is function annotation for a return type. [`annotations`](https://stackoverflow.com/questions/3038033/what-are-good-uses-for-python3s-function-annotations) do nothing inside the code, they are there to help a user with code completion (in my experience).
Here is the [PEP](http://www.python.org/dev/peps/pep-3107/) f... | They're [function annotations](http://ceronman.com/2013/03/12/a-powerful-unused-feature-of-python-function-annotations/). They don't really do anything by themselves, but they can be used for documentation or in combination with metaprogramming. | 10,114 |
13,700,045 | I'm trying to build a graph library in python (along with standard graph-algorithms). I've tried to implement DFS and this is what it looks like
```
def DFS(gr, s, path):
""" Depth first search
Returns a list of nodes "findable" from s """
if s in path: return False
path.append(s)
for each in gr.n... | 2012/12/04 | [
"https://Stackoverflow.com/questions/13700045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/427069/"
] | Just make a wrapper method that calls the one you already have:
```
def DFS(gr, s):
path = []
DFS2(gr, s, path)
return path
```
Here `DFS2` is the method you showed above. | Actually why don't you just set `path` to have a default of an empty list?
So using your same code but slightly different arguments:
```
# Original
def DFS(gr, s, path):
# Modified
def DFS(gr, s, path=[]):
# From here you can do
DFS(gr, s)
``` | 10,115 |
12,127,869 | I'm trying to build a package from source by executing `python setup.py py2exe`
This is the section of code from setup.py, I suppose would be relevant:
```
if sys.platform == "win32": # For py2exe.
import matplotlib
sys.path.append("C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\redist\\x86\\Microsoft.VC... | 2012/08/26 | [
"https://Stackoverflow.com/questions/12127869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193653/"
] | I would recommend ignoring the dependency outright. Add `MSVCP90.dll` to the list of `dll_excludes` given as an option to `py2exe`. Users will have to install the Microsoft Visual C++ 2008 redistributable. An example:
```
setup(
options = {
"py2exe":{
...
"dll_excludes": ["MSVCP... | (new answer, since the other answer describes an alternate solution)
You can take the files from the WinSxS directory and copy them to the `C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT` directory (normally created by Visual Studio, which you don't have). Copy them to get the following ... | 10,117 |
48,716,989 | I'm trying to create an infinite loop that will output the Y axis of a sine wave, and want to use variables specifying the amplitude of the wave, frequency, and resolution. Where frequency is the number of full sine waves in a second like electrical AC frequency.
I'm trying to do something like this:
```
#!/usr/bin/... | 2018/02/10 | [
"https://Stackoverflow.com/questions/48716989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6058228/"
] | How about something like this:
```
DELETE FROM inventory
WHERE updated NOT IN (
SELECT updated FROM (
SELECT MAX(updated) updated
FROM inventory
GROUP BY DATE(updated)
) i
)
```
This would work well if you have the `updated` indexed (ordered).
Basically the sub query gets all the max... | Get the most recent time in a subquery, join that with the table, and delete.
```
DELETE i1
FROM inventory AS i1
JOIN (SELECT DATE(updated) AS date, MAX(updated) AS latest
FROM inventory
WHERE itemname = '24T7351'
GROUP BY date) AS i2 ON DATE(i1.updated) = i2.date AND i1.updated != i2.latest
WHERE i... | 10,122 |
62,892,652 | I have a class that gets the data from the form, makes some changes and save it to the database.
I want to have several method inside.
* Get
* Post
* And some other method that will make some changes to the data from the form
I want the post method to save the data from the form to the database and pass the instanse... | 2020/07/14 | [
"https://Stackoverflow.com/questions/62892652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13197641/"
] | ```
class AddSiteView(View):
form_class = AddSiteForm
template_name = 'home.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, { 'form': form })
def post(self, request, *args, **kwargs):
form = self.form_class(requ... | One must return a response from the `post` method. This code returns a `Site` instance on these lines. Not sure what is the intended behavior, either a `redirect` or `render` should be used.
```
try:
site_id = Site.objects.get(url=site_url)
except ObjectDoesNotExist:
site_instan... | 10,125 |
36,682,832 | Exactly how should python models be exported for use in c++?
I'm trying to do something similar to this tutorial:
<https://www.tensorflow.org/versions/r0.8/tutorials/image_recognition/index.html>
I'm trying to import my own TF model in the c++ API in stead of the inception one. I adjusted input size and the paths, bu... | 2016/04/17 | [
"https://Stackoverflow.com/questions/36682832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5452997/"
] | At first, you need to graph definition to file by using following command
```
with tf.Session() as sess:
//Build network here
tf.train.write_graph(sess.graph.as_graph_def(), "C:\\output\\", "mymodel.pb")
```
Then, save your model by using saver
```
saver = tf.train.Saver(tf.global_variables())
saver.save(sess, "... | You can try this (modify name of output layer):
```
import os
import tensorflow as tf
from tensorflow.python.framework import graph_util
def load_graph_def(model_path, sess=None):
sess = sess if sess is not None else tf.get_default_session()
saver = tf.train.import_meta_graph(model_path + '.meta')
saver.r... | 10,126 |
61,578,697 | I am trying to wrap my head around python. Basically I am trying to remove a duplicate string (a date to be more precise) in some data. So for example:
```
2019-03-31
2019-06-30
2019-09-30
2019-12-31
2020-03-31
2020-03-31
```
notice 2020-03-31 is duplicated. I would like to find the duplicated date and rename it as... | 2020/05/03 | [
"https://Stackoverflow.com/questions/61578697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13461709/"
] | Use a [`set`](https://docs.python.org/3/library/stdtypes.html#set) to keep track of items you've seen. If any items are already in the set, append the desired string (use `= "last quarter"` if you want a full rename; it's unclear).
```
data = """2019-03-31
2019-06-30
2019-09-30
2019-12-31
2020-03-31
2020-03-31""".spli... | For your function, if you have list of elements then your function will be :
```
def checkForDuplicates(listOfElems):
check=[]
for i in range(len(listOfElems)):
if listofElems[i] in check:
#then it is a duplicate and you can rename it
listofElems[i]='last quarter'
else:
... | 10,128 |
44,610,150 | I downloaded Python 3.6 from Python's website (from the download page for Windows) and it seems only the interpreter is available. I don't see anything else (Standard Library or something) in my system. Is it included in the interpreter and hidden or something?
I tried to install ibm\_db 2.0.7 as an extension of Pytho... | 2017/06/17 | [
"https://Stackoverflow.com/questions/44610150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8176681/"
] | Timeout is for raising a timeout error if an event isn't emitted within a certain time period. You probably want Observable.interval:
```
return
Observable.interval(1000).mergeMap(t=> this.http.get(matchUrl))
.toPromise()
.then(response => response.json().participants as Match[]);
```
if you want to ... | Use `debounceTime` operator as below
```
getMatch(matchId: number): Promise<Match[]> {
let matchUrl: string = 'https://br1.api.riotgames.com/lol/match/v3/matches/'+ matchId +'?api_key=';
return this.http.get(matchUrl)
.debounceTime(1000)
.toPromise()
.then(respo... | 10,131 |
5,395,782 | In a python/google app engine app, I've got a choice between storing some static data (couple KB in size) in a local json/xml file or putting it into the datastore and querying it from there. The data is created by me, so there's no issues with badly formed data. In specific terms such as saving quota, less resource us... | 2011/03/22 | [
"https://Stackoverflow.com/questions/5395782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614453/"
] | If your data is small, static and infrequently changed, you'll get the best performance by just writing your data as a `dict` in it's own module and just `import` it where you need it. This would take advantage of the fact that Python will cache your modules on import. | It is faster to keep your data in a static file instead of the datastore. As you said, this saves on datastore quota, and also saves time in round-trips to the datastore.
However, any **data you store in static files is static and cannot be changed by your application** (see the ["Sandbox" section here](http://code.go... | 10,132 |
32,977,076 | Related: [ImportError: No module named bootstrap3 even while using virtualenv](https://stackoverflow.com/questions/29781872/importerror-no-module-named-bootstrap3-even-while-using-virtualenv)
Every time I attempt to use manage.py (startapp, shell, etc) or load my page (using Apache), I get the error below. I'm running... | 2015/10/06 | [
"https://Stackoverflow.com/questions/32977076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1303827/"
] | As it is said in docs, you need `django-bootstrap3` package to use bootstrap3. Here is the [link](https://github.com/dyve/django-bootstrap3). | I defer to the answer above. Just pointing out that the django-bootstrap-toolkit, which is for v2 of Bootstrap, could be removed. Thanks for using these libraries! | 10,135 |
5,880,781 | Can anybody tell me what is wrong in this program? I face
```
syntaxerror unexpected character after line continuation character
```
when I run this program:
```
f = open(D\\python\\HW\\2_1 - Copy.cp,"r");
lines = f.readlines();
for i in lines:
thisline = i.split(" ");
``` | 2011/05/04 | [
"https://Stackoverflow.com/questions/5880781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/642564/"
] | You need to quote that filename:
```
f = open("D\\python\\HW\\2_1 - Copy.cp", "r")
```
Otherwise the bare backslash after the D is interpreted as a line-continuation character, and should be followed by a newline. This is used to extend long expressions over multiple lines, for readability:
```
print "This is a lon... | Replace
`f = open(D\\python\\HW\\2_1 - Copy.cp,"r");`
by
`f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")`
1. File path needs to be a string (constant)
2. need colon in Windows file path
3. space after comma for better style
4. ; after statement is allowed but fugly.
What tutorial are you using? | 10,136 |
16,297,892 | Upgrade to 13.04 has totally messed my system up .
I am having this issue when running
```
./manage.py runserver
Traceback (most recent call last):
File "./manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
File "/home/rats/rats/local/lib/python2.7/site-packages/django/... | 2013/04/30 | [
"https://Stackoverflow.com/questions/16297892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1080407/"
] | If you are using virtualenvwrapper then you can recreate the virtualenv on top of the existing one (with no environment currently active):
`mkvirtualenv <existing name>`
which should pull in the latest (upgraded) python version from the system and fix any mismatch errors. | I have just solved that problem on my machine.
The problem was that Ubuntu 13.04 use python 2.7.4. That makes conflict with the Python version of the `virtualenv`.
What I do was to re-create the `virtualenv` with the new version of python. I think it's the simplest way, but you can try to upgrade the python version w... | 10,139 |
51,531,429 | I have an ndarray of N 1x3 arrays I'd like to perform dot multiplication with a 3x3 matrix. I can't seem to figure out an efficient way to do this, as all the multi\_dot and tensordot, etc methods seem to recursively sum or multiply the results of each operation. I simply want to apply a dot multiply the same way you c... | 2018/07/26 | [
"https://Stackoverflow.com/questions/51531429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6587755/"
] | Try This:
```
import numpy as np
N = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6]])
m = np.asarray([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
re0 = np.asarray([np.dot(m, a) for a in N]) # original
re1 = np.dot(m, N.T).T # efficient
print("result0:\n{}".format(re0))
print("result1:\n{}".format(r... | First, regarding your last question. There's a difference between a (3,) `N` and (1,3):
```
In [171]: np.dot(m,[1,2,3])
Out[171]: array([140, 320, 500]) # (3,) result
In [172]: np.dot(m,[[1,2,3]])
---------------------------------------------------------------------------
ValueError ... | 10,142 |
25,570,507 | Still working with LDAP...
The problem i submit today is this: i'm creating a posixGroup on a server LDAP using a custom method developed in python using Django framework. I attach the method code below.
The main issue is that attribute **gidNumber is compulsory of posixGroup class**, but usually is not required w... | 2014/08/29 | [
"https://Stackoverflow.com/questions/25570507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3963403/"
] | See paragraph a "Note on Minification" in <https://docs.angularjs.org/tutorial/step_05>
It is used to keep a string reference of your injections of dependencies after minifications :
>
> Since Angular infers the controller's dependencies from the names of
> arguments to the controller's constructor function, if you... | Controllers are callables, and their arguments must be injected with existing/valid/registered dependencies. Angular takes three ways:
1. If the passed controller (this also applies to providers) is an array, the last item is the controller, and the former items are expected to be strings with the names of dependencie... | 10,143 |
8,127,648 | I have two threads in python (2.7).
I start them at the beginning of my program. While they execute, my program reaches the end and exits, killing both of my threads before waiting for resolution.
I'm trying to figure out how to wait for both threads to finish before exiting.
```
def connect_cam(ip, execute_lock):
... | 2011/11/14 | [
"https://Stackoverflow.com/questions/8127648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6367/"
] | `Thread` is meant as a lower level primitive interface to Python's threading machinery - use [`threading`](http://docs.python.org/library/threading.html#thread-objects) instead. Then, you can use `threading.join()` to synchronize threads.
>
> Other threads can call a thread’s join() method. This blocks the
> calling... | First, you ought to be using the [threading](http://docs.python.org/library/threading.html#module-threading) module, not the thread module. Next, have your main thread [join()](http://docs.python.org/library/threading.html#threading.Thread.join) the other threads. | 10,144 |
43,603,199 | I am using Docker on a Python Flask webapp, but am getting an error when I try and run it.
```
$ sudo docker run -t imgcomparer6
unable to load configuration from app.py
```
**Python**
In my app.py file, my only instance of `app.run()` in the webapp is within the `'__main__':` function (seen [here](https://stackove... | 2017/04/25 | [
"https://Stackoverflow.com/questions/43603199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1258509/"
] | I think your code is ok.
You need close resultset, statement and connection in block finally. | Though your code works, I strongly suggest to **refactor it for better maintenance and readability** as shown below. Also, ensure that the resources are closed properly:
```
public void dashboardReports() {
handleTotalStocks();
handleTotalSales();
handleTotalPurchages();
//Add others
}
```
**hand... | 10,146 |
47,961,437 | I'm using Jupyter Notebook to develop some Python. This is my first stab at logging errors and I'm having an issue where no errors are logged to my error file.
I'm using:
```
import logging
logger = logging.getLogger('error')
logger.propagate = False
hdlr = logging.FileHandler("error.log")
formatter = logging.Formatt... | 2017/12/24 | [
"https://Stackoverflow.com/questions/47961437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694657/"
] | If **spark-shell** doesn't show this line on start:
>
> Spark context available as 'sc' (master = local[\*], app id = local-XXX).
>
>
>
Run
```
val sc = SparkContext.getOrCreate()
``` | The issue is that you created `sc` of type `SparkConfig` not `SparkContext` (both have the same initials).
---
For using parallelize method in Spark 2.0 version or any other version, `sc` should be `SparkContext` and not `SparkConf`. The correct code should be like this:
```
import org.apache.spark.SparkContext
im... | 10,156 |
16,913,086 | I want to run third part tool written in python on my ubuntu machine ([corgy tool](https://github.com/pkerpedjiev/corgy)).
However I don't know how to add additional modules to Python path.
```
cat doc/download.rst
There is currently no setup.py, so you need to manually add
the download directory to your P... | 2013/06/04 | [
"https://Stackoverflow.com/questions/16913086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1286528/"
] | Create a `.bash_profile` in your home directory. Then, add the line
```
PYTHONPATH=$PYTHONPATH:new_dir
EXPORT $PYTHONPATH
```
Or even better:
```
if [ -d "new_dir" ] ; then
PYTHONPATH="$PYTHONPATH:new_dir"
fi
EXPORT $PYTHONPATH
```
The `.bash_profile` properties are loaded every time you log in.
The `source` c... | [@fedorqui](https://stackoverflow.com/users/1983854/fedorqui-so-stop-harming)'s answer above was almost good for me, but there is at least one mistake (I am not sure about the `export` statement in all caps, I am a complete newbie).
There should not be a `$` sign preceding PYTHONPATH in the export statement. So the opt... | 10,163 |
54,503,298 | I have a list of list of lists (all of lists have same size) in python like this:
```
A = [[1,2,3,4],['a','b','c','d'] , [12,13,14,15]]
```
I want to remove some columns (i-th elements of all lists).
Is there any way that does this without `for` statements? | 2019/02/03 | [
"https://Stackoverflow.com/questions/54503298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7789910/"
] | As mentioned, you can't do this without loop. However, using built-in functions here's a functional approach that doesn't explicitly use any loop:
```
In [24]: from operator import itemgetter
In [25]: def remove_col(arr, ith):
...: itg = itemgetter(*filter((ith).__ne__, range(len(arr[0]))))
...: retur... | You could easily use [list comprehension](https://www.pythonforbeginners.com/basics/list-comprehensions-in-python) and [slices](https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/) :
```
A = [[1,2,3,4],['a','b','c','d'] , [12,13,14,15]]
k = 1
B = [l[:k]+l[k+1:] for l in A]
print(B) # >> retur... | 10,164 |
60,171,622 | I'm working with large data sets. I'm trying to use the NumPy library where I can or python features to process the data sets in an efficient way (e.g. LC).
First I find the relevant indexes:
```
dt_temp_idx = np.where(dt_diff > dt_temp_th)
```
Then I want to create a mask containing for each index a sequence start... | 2020/02/11 | [
"https://Stackoverflow.com/questions/60171622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080562/"
] | Using masks (boolean arrays) are efficient being memory-efficient and performant too. We will make use of [`SciPy's binary-dilation`](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.binary_dilation.html) to extend the thresholded mask.
Here's a step-by-step setup and solution run-
... | `dt_temp_idx` is a numpy array, but still a Python iterable so you can use a good old Python list comprehension:
```
lst = [ i for j in dt_temp_idx for i in range(j, j+11)]
```
If you want to cope with sequence overlaps and make it back a np.array, just do:
```
result = np.array({i for j in dt_temp_idx for i in ran... | 10,168 |
5,077,625 | I'm trying to write a short program that will read in the contents of e-mails within a folder on my exchange/Outlook profile so I can manipulate the data. However I'm having a problem finding much information about python and exchange/Outlook integration. A lot of stuff is either very old/has no docs/not explained. I'v... | 2011/02/22 | [
"https://Stackoverflow.com/questions/5077625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559504/"
] | I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.
```
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
... | I have created my own iterator to iterate over Outlook objects via python. The issue is that python tries to iterates starting with Index[0], but outlook expects for first item Index[1]... To make it more Ruby simple, there is below a helper class Oli with following
methods:
.items() - yields a tuple(index, Item)...... | 10,169 |
32,150,849 | I'm writing a simple Flask app, with the sole purpose to learn Python and MongoDB.
I've managed to reach to the point where all the collections are defined, and CRUD operations work in general. Now, one thing that I really want to understand, is how to refresh the collection, after updating its structure. For example,... | 2015/08/21 | [
"https://Stackoverflow.com/questions/32150849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971392/"
] | Solution is easier then I expected:
```
db.getCollection('user').update(
// query
{},
// update
{
$rename: {
'companies': 'company'
}
},
// options
{
"multi" : true, // update all documents
"upsert" : false // insert a new document, if no e... | >
> I have updated my `user.py` to match my new requests, but anytime I interact with the db its self, since the table's structure was not refreshed, I get the following error
>
>
>
MongoDB does not have a "table structure" like relational databases do. After a document has been inserted, you can't change it's sch... | 10,174 |
66,684,265 | The case is if I want to reverse select a python list to `n` like:
```
n = 3
l = [1,2,3,4,5,6]
s = l[5:n:-1] # s is [6, 5]
```
OK, it works, but how can I set `n`'s value to select the whole list?
let's see this example, what I expect the first line is `[5, 4, 3, 2, 1]`
```
[40]: for i in range(-1, 5):
...: ... | 2021/03/18 | [
"https://Stackoverflow.com/questions/66684265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2955827/"
] | I was led to answer from <https://github.com/JeffreyWay/laravel-mix/issues/2896;>
they seemed to upgrade the syntax the documentation can be found here:
<https://github.com/JeffreyWay/laravel-mix/blob/467f0c9b01b7da71c519619ba8b310422321e0d6/UPGRADE.md#vue-configuration> | When I tried your solution it did not work.
Here is how I managed to fix this issue, using this new/changed property additionalData, in previous versions this property was data or prependData.
```
mix.webpackConfig({
module: {
rules: [
{
test: /\.scss$/,
use: [
... | 10,175 |
67,792,538 | i'm writing a python script which reads emails from Outlook then extract the body
The problem is that when it reads an email answer, the body contains the previous emails.
Is there away to avoid that and just extract the body of the email.
This is a part of my code :
```
import requests
import json
import base64
utl... | 2021/06/01 | [
"https://Stackoverflow.com/questions/67792538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15268168/"
] | Try this solution that uses `zoo` (and `dplyr`, which I'm inferring you're already using):
```r
library(dplyr)
eg <- expand.grid(Sample.Type = unique(dat$Sample.Type),
date = seq(min(dat$date), max(dat$date), by = "day"),
stringsAsFactors = FALSE)
dat %>%
mutate(a=TRUE) %>%
full... | You just need to `lag()` while grouping by `Sample.Type`.
1. Toy dataset. I just added a third Sample.Type
```r
library(dplyr)
library(lubridate)
typeday <- tibble(
Sample.Type = c("A", "B", "A", "B", "A", "A","B", "C", "C"),
date = as.Date(c("2020-10-05", "2020-10-05", "2020-10-06",
"20... | 10,176 |
65,888,118 | I deployed a flask app to IIS using FastCGI and WSGI Handler. The steps that I have followed are
1. Created a virtual environment for Python and installed all packages including wfastCGI.
2. Set the Handler mappings and included the FastCGI settings.
3. Assigned the necessary permissions for the folders by adding IIS\... | 2021/01/25 | [
"https://Stackoverflow.com/questions/65888118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6831630/"
] | You use the wrong css.
The `translateX` is the state, not the animation. Use `animation` instead.
```css
@keyframes menu-open {
from {width: 0px;}
to {width: 220px;}
}
.open {
animation-name: menu-open;
animation-duration: 1s;
animation-fill-mode: forwards;
}
@keyframes menu-close {
from {width: 220px;}... | You should specify both transform properties in style attribute like so:
style={{transform: this.showMenu ? "translateX(0%)" : "translateX(100%)"}} | 10,177 |
63,899,935 | I'm writing a code to take a rain time-series and save hourly files for each day in order to feed a hydrological model, so, basically, I need to save each file with the hour of the day with tho digits, like this:
```
rain_20200101_0000.txt
rain_20200101_0100.txt
...
rain_20200101_0900.txt
rain_20200101_1000.txt
..
rai... | 2020/09/15 | [
"https://Stackoverflow.com/questions/63899935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7335001/"
] | I experienced the same case, for me, what worked was what has been commented before:
Change the value of 'cwd' property in launch.json to the value of the project directory.
{
...
"cwd": "${workspaceFolder}"
}
to
{
...
"cwd": "${workspaceFolder}/SATestUtils.API"
}
All the credits to Bemm...
[](https://i.stack.imgur.com/gwMzt.png) | 10,178 |
60,836,709 | So after doing some web scraping and turning data frames into lists, I want to compare one list to another that I have created myself. But, if one list doesn’t have a value from another, I want it added in the exact order of the list I’m comparing it to.
For example, if I’m comparing one list of snacks with another
... | 2020/03/24 | [
"https://Stackoverflow.com/questions/60836709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11583556/"
] | Assuming that prices in `ListPrices` are consistent, i.e. if `List1` has two bananas, both have the same price, you can create a `dict` by `zip`ing `List1` and `ListPrices` and then look up the price for the items in `List2` in that dict, or use `nan` as a default.
```
prices = dict(zip(List2, ListPrices))
# {'apples'... | You can convert it to a dictionary for a simple look up
```
d = dict(zip(List2,ListPrices))
[d.get(i,None) for i in List1]
``` | 10,179 |
17,980,691 | I'm having difficulty getting my sizers to work properly in wxpython. I am trying to do a simple one horizontal bar at top (with text in it) and two vertical boxes below (with gridsizers \* the left one should only be 2 columns!! \* inside each). I want the everything in the image to stretch and fit my panel as well (w... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17980691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936911/"
] | Is this what you're after?

```
import wx
class Frame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent)
self.panel = wx.Panel(self)
main_sizer = wx.BoxSizer(wx.VERTICAL)
# Title
sel... | something like this??
```
import wx
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,"Test Stretching!!")
p1 = wx.Panel(self,-1,size=(500,100))
p1.SetMinSize((500,100))
p1.SetBackgroundColour(wx.GREEN)
hsz = wx.BoxSizer(wx.HORIZONTAL)
p2... | 10,182 |
45,876,059 | I have this server
<https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/echo_tls/server.py>
And I want to connect to the server with this code:
```
ws = create_connection("wss://127.0.0.1:9000")
```
What options do I need to add to `create_connection`? Adding `sslopt={"cert_reqs": ... | 2017/08/25 | [
"https://Stackoverflow.com/questions/45876059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1238675/"
] | This works
```
import asyncio
import websockets
import ssl
async def hello():
async with websockets.connect('wss://127.0.0.1:9000',ssl=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)) as websocket:
data = 'hi'
await websocket.send(data)
print("> {}".format(data))
response = await websoc... | For me the option from the question seems to work:
```
from websocket import create_connection
import ssl
ws = create_connection("wss://echo.websocket.org", sslopt={"cert_reqs": ssl.CERT_NONE})
ws.send("python hello!")
print (ws.recv())
ws.close()
```
See also here:
<https://github.com/websocket-client/websocket-c... | 10,184 |
17,986,923 | I have a python dictionary of the form :
```
a1 = {
'SFP_1': ['cat', '3'],
'SFP_0': ['cat', '5', 'bat', '1']
}
```
The end result I need is a dictionary of the form :
```
{'bat': '1', 'cat': '8'}
```
I am currently doing this:
```
b1 = list(itertools.chain(*a1.values()))
c1 = dict(itertools... | 2013/08/01 | [
"https://Stackoverflow.com/questions/17986923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2054020/"
] | Using [defaultdict](http://docs.python.org/2/library/collections.html#collections.defaultdict):
```
import itertools
from collections import defaultdict
a1 = {u'SFP_1': [u'cat', u'3'], u'SFP_0': [u'cat', u'5', u'bat', u'1']}
b1 = itertools.chain.from_iterable(a1.itervalues())
c1 = defaultdict(int)
for animal, count ... | ```
In [8]: a1 = {
'SFP_1': ['cat', '3'],
'SFP_0': ['cat', '5', 'bat', '1']
}
In [9]: answer = collections.defaultdict(int)
In [10]: for L in a1.values():
for k,v in itertools.izip(itertools.islice(L, 0, len(L), 2),
... | 10,185 |
45,045,147 | I'm trying to migrate a table with SQLAlchemy Migrate, but I'm getting this error:
```
sqlalchemy.exc.UnboundExecutionError: Table object 'responsibles' is not bound to an Engine or Connection. Execution can not proceed without a database to execute against.
```
When I run:
```
python manage.py test
```
This is ... | 2017/07/11 | [
"https://Stackoverflow.com/questions/45045147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1934510/"
] | did you create your engine? like this
`engine = create_engine('sqlite:///:memory:')`
and then do
`meta.bind = engine
meta.create_all(engine)` | You need to supply `engine` or `connection`
[`sqlalchemy.schema.MetaData.bind`](http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.MetaData.bind)
For e.g.:
```
engine = create_engine("someurl://")
metadata.bind = engine
``` | 10,192 |
70,596,608 | In the office we have a fileWatcher that converts pointclouds to .laz files.
We just started working with Revit but came to the conclusion that it is not possible to import .laz in Revit.
So I googled and found a solution execept it is written in python and our watcher is in c#.
Below the python script.
`<location>/dec... | 2022/01/05 | [
"https://Stackoverflow.com/questions/70596608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411687/"
] | Convert the columns to `Date` class and use `difftime`
```
df1$Difference <- with(df1, as.numeric(difftime(as.Date(DeliveryDate),
as.Date(ExpectedDate), units = "days")))
```
---
Or using `tidyverse`
```
library(dplyr)
library(lubridate)
df1 %>%
mutate(Difference = as.numeric(difftime(ymd(DeliveryD... | First change your date to lubridate date:
2022-01-05 would be
```
date1 <- ymd("2022-01-05")
date2 <- ymd("2022-01-07")
diff_days <- difftime(date2, date1, units="days")
``` | 10,193 |
49,154,899 | I want to create a virtual environment using conda and yml file.
Command:
```
conda env create -n ex3 -f env.yml
```
Type ENTER it gives following message:
```
ResolvePackageNotFound:
- gst-plugins-base==1.8.0=0
- dbus==1.10.20=0
- opencv3==3.2.0=np111py35_0
- qt==5.6.2=5
- libxcb==1.12=1
- libgcc==5.2.0=0
... | 2018/03/07 | [
"https://Stackoverflow.com/questions/49154899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7722305/"
] | I got the same issue and found a [GitHub issue](https://github.com/conda/conda/issues/6073#issuecomment-356981567) related to this. In the comments, @kalefranz posted an ideal solution by using the `--no-builds` flag with conda env export.
```
conda env export --no-builds > environment.yml
```
However, even remove b... | I had a similar issue and was able to work around it. My issue wasn't related to pip but rather because the export platform wasn't the same as the import platform (Ref: nehaljwani's November 2018 answer on <https://github.com/conda/conda/issues/7311>).
@Shixiang Wang's answer point towards a part of the solution. The ... | 10,194 |
65,822,290 | I made two components using python functions and I am trying to pass data between them using files, but I am unable to do so. I want to calculate the sum and then send the answer to the other component using a file. Below is the partial code (The code works without the file passing). Please assist.
```
# Define your c... | 2021/01/21 | [
"https://Stackoverflow.com/questions/65822290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13435688/"
] | Here is a slightly simplified version of your pipeline that I tested and which works.
It doesn't matter what class type you pass to `OutputTextFile` and `InputTextFile`. It'll be read and written as `str`. So this is what you should change:
* While writing to `OutputTextFile`: cast `sum_` from `float to str`
* While r... | `('out', comp.OutputTextFile(float))`
This is not really valid. The `OutputTextFile` annotation (and other similar annotations) can only be used in the function parameters. The function return value is only for outputs that you want to output as values (not as files).
Since you already have `f: comp.OutputTextFile(fl... | 10,204 |
41,006,153 | Using python 3.4.3 or python 3.5.1 I'm surprised to see that:
```
from decimal import Decimal
Decimal('0') * Decimal('123.456789123456')
```
returns:
```
Decimal('0E-12')
```
Worse part is that this specific use case works with float.
Is there anything I could do to make sure the maths work and 0 multiplied by a... | 2016/12/06 | [
"https://Stackoverflow.com/questions/41006153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6451083/"
] | `0E-12` actually is `0` (it's short for `0 * 10 ** -12`; since the coefficient is 0, that's still 0), `Decimal` just provides the `E-12` bit to indicate the "confidence level" of the `0`. What you've got will still behave like zero (it's falsy, additive identity, etc.), the only quirk is in how it prints.
If you need ... | Do the multiplication with floats and convert to decimal afterwards.
```
x = 0
y = 123.456789123456
Decimal(x*y)
```
returns (on Python 3.5.2):
```
Decimal('0')
``` | 10,205 |
32,407,824 | I am new to python programming. I need to read contents from a csv file and print based on a matching criteria. The file contains columns like this:
abc, A, xyz, W
gfk, B, abc, Y, xyz, F
I want to print the contents of the adjacent column based on the matching input string. For e.g. if the string is abc it should... | 2015/09/04 | [
"https://Stackoverflow.com/questions/32407824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5298602/"
] | Your approach made it more difficult to print adjacent values, because even if you used `enumerate` to get the indices, you would have to search the row again, after finding each pattern (after `if i in row:` you wouldn't immediately know where it was in the row). By structuring the data in a dictionary it becomes simp... | You can adapt this for the CSV, but it basically do what you ask for
```
csv = [['abc', 'A', 'xyz', 'W'],
['gfk', 'B', 'abc', 'Y', 'xyz', 'F']]
match_string = ['abc','xyz','gfk']
for row in csv:
for i, column_content in enumerate(row):
if column_content in match_string:
print row[i + ... | 10,211 |
45,622,443 | I started using Retrofit in my android app consuming RESTful web services.
I managed to get it working with a simple object. But when trying with a more complex object it remains desperately empty. I put Okhttp in debug, and the json I'm expecting is present in the response, so I think there is a problem during the cr... | 2017/08/10 | [
"https://Stackoverflow.com/questions/45622443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4208537/"
] | Try first sending data to your WebServices using clients like [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop), this is a very usefull tool. You can check what's your WebService sending to your Android app | I faced with the same problem by using retrofit on kotlin.
it was:
```
data class MtsApprovalResponseData(
@field:Element(name = "MessageId", required = false)
@Namespace(reference = WORKAROUND_NAMESPACE)
var messageId: String? = null,
@field:Element(name = "Version", required = false)
@Namespac... | 10,212 |
72,944,672 | In one directory there are several folders that their names are as follows: 301, 302, ..., 600.
Each of these folders contain two folders with the name of `A` and `B`. I need to copy all the image files from A folders of each parent folder to the environment of that folder (copying images files from e.g. 600>A to 600 f... | 2022/07/11 | [
"https://Stackoverflow.com/questions/72944672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11140344/"
] | I recommend you to use the [Pathlib](https://docs.python.org/3/library/pathlib.html).
```
from pathlib import Path
import shutil
from tqdm import tqdm
folder_to_be_sorted = Path("/your/path/to/the/folder")
for folder_named_number_i in tqdm(list(folder_to_be_sorted.iterdir())):
# folder_named_number_i is 301, 302... | @hellohawii gave an excellent answer. Following code also works and you only need change value of *Source* when using.
```
import shutil
import os, sys
from tqdm import tqdm
exepath = sys.argv[0] # current path of code
Source = os.path.dirname(os.path.abspath(exepath))+"\\Credits\\" # path of folders:301, 302... 6... | 10,213 |
67,707,605 | I am trying to use python to place orders through the TWS API. My problem is getting the next valid order ID.
Here is what I am using:
```
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import TickerId
from ibapi import contract, order, common
from threading import Thread
class... | 2021/05/26 | [
"https://Stackoverflow.com/questions/67707605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15524510/"
] | The `nextValidId` method is a wrapper method. From the client, you need to call `reqIds` to get an Order ID.
```
ib_api.reqIds(-1)
```
The parameter of `reqIds` doesn't matter. Also, it doesn't have a return value. Instead, `reqIds` sends a message to IB, and when the response is received, the wrapper's `nextValidId... | Add some delay after `reqIds`
-----------------------------
In the wrapper class for receiving updates from `ibapi`,
override `nextValidId` function as it is used by `ib_api.reqIds` to respond back.
```
from ibapi.wrapper import iswrapper
@iswrapper
def nextValidId(self, orderId: int):
super().nextValidId(orderI... | 10,214 |
68,164,039 | I'm a python beginner and I'm trying to solve a cubic equation with two independent variables and one dependent variable. Here is the equation, which I am trying to solve for v:
3pv^3−(p+8t)v^2+9v−3=0
If I set p and t as individual values, I can solve the equation with my current code. But what I would like to do is ... | 2021/06/28 | [
"https://Stackoverflow.com/questions/68164039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16334402/"
] | You can simply use a for loop I think. This is what seems to work:
```
for p in range(10):
solution = solve(3*p*(v**3)-(v**2)*(p+8*t)+9*v-3, v)
print(solution)
```
Also, note that range(10) goes from 0 to 9 (inclusive) | Same idea as previous answer, but I think it's generally good practice to keep imports at the top and to separate equation and solution to separate lines etc. Makes it a bit easier to read
```
from sympy.solvers import solve
from sympy import Symbol
import numpy as np
tc = 300
t1 = 315
t = t1/tc
v = Symbol('v') # Va... | 10,215 |
54,853,332 | I tried using pip install sendgrid, but got this error:
>
> Collecting sendgrid
> Using cached <https://files.pythonhosted.org/packages/24/21/9bea4c51f949497cdce11f46fd58f1a77c6fcccd926cc1bb4e14be39a5c0/sendgrid-5.6.0-py2.py3-none-any.whl>
> Requirement already satisfied: python-http-client>=3.0 in /home/avin/.loca... | 2019/02/24 | [
"https://Stackoverflow.com/questions/54853332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512538/"
] | This is a very useful command `pip install --ignore-installed <package>`
It will make your life easy :) | Solved.
It required another package that I missed: `pip install python-HTTP-Client`.
After that I no longer needed the `--user` and the imports worked fine | 10,216 |
18,564,642 | So I have been trying to install SimpleCV for some time now. I was finally able to install pygame, but now I have ran into a new error. I have used pip, easy\_install, and cloned the SimpleCV github repository to try to install SimpleCV, but I get this error from all:
```
ImportError: No module named scipy.... | 2013/09/02 | [
"https://Stackoverflow.com/questions/18564642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2364997/"
] | From my understanding, what you trying to do is showing a custom dialog or alertview and only on its return value, the code should execute further.
So lets say, If you display a `UIAlertView` with `UITextView` inside for adding more information, you should move your `sendEmail` method to the callback of alertview's bu... | The flow needs to be designed so that when the email is prompted it has set everything up and created a window with a button, at that point your code has finished and is not doing anything. Then when the button is pressed the next function/method is called that uses the data that was prepared before hand. | 10,217 |
7,561,640 | Executive summary: a Python module is linked against a different version of `libstdc++.dylib` than the Python executable. The result is that calls to `iostream` from the module crash.
Backstory
---------
I'm creating a Python module using SWIG on an older computer (running 10.5.8). For various reasons, I am using GCC... | 2011/09/26 | [
"https://Stackoverflow.com/questions/7561640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118160/"
] | Solved it. I discovered that this problem is not too uncommon when mixing GCC versions on the mac. After reading [this solution for mpich](http://www.mail-archive.com/[email protected]/msg02756.html) and checking the [mpich source code](http://anonscm.debian.org/gitweb/?p=debian-science/packages/mpich... | Run Python in GDB, set a breakpoint on `malloc_error_break`. That will show you what's being freed that's not allocated. I doubt that this is an error between ABIs between the versions of libstdc++. | 10,219 |
70,190,565 | Kinda long code by complete beginner ahead, please help out
I have a database with the following values:
| Sl.No | trips | sales | price |
| --- | --- | --- | --- |
| 1 | 5 | 20 | 220 |
| 2 | 8 | 30 | 330 |
| 3 | 9 | 45 | 440 |
| 4 | 3 | 38 | 880 |
I am trying to use mysql-connector and python to get the sum of the ... | 2021/12/01 | [
"https://Stackoverflow.com/questions/70190565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17184842/"
] | It’s *possible*, but this doesn't look like great design. What happens when a new stage is added? I suspect your issues will disappear if you make a separate "Stage" table with two columns: Stage\_Number and Stage\_Value. Then finding the last filled in stage is a simple MAX query (and the rejection comes from adding o... | You can convert the columns to a JSON structure, then unnest the keys, sort them and pick the first one:
```
select t.*,
(select x.col
from jsonb_each_text(jsonb_strip_nulls(to_jsonb(t) - 'id' - 'status')) as x(col, val)
order by x.col desc
limit 1) as final_stage
from the_table t
```
... | 10,220 |
24,175,446 | I'd like to assign each pixel of a mat `matA` to some value according to values of `matB`, my code is a nested for-loop:
```
clock_t begint=clock();
for(size_t i=0; i<depthImg.rows; i++){
for(size_t j=0; j<depthImg.cols; j++){
datatype px=depthImg.at<datatype>(i, j);
if(px==0)
depthImg.... | 2014/06/12 | [
"https://Stackoverflow.com/questions/24175446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1150712/"
] | I am unable to replicate your timing results on my machine Your C++ code runs in under 1ms on my machine. However, whenever you have slow iteration, `at<>()` should be immediately suspect. OpenCV has a [tutorial on iterating through images](http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images... | In your C++ code, at every pixel you are making a function call, and passing in two indices which are getting converted into a flat index doing something like `i*depthImageCols + j`.
My C++ skills are mostly lacking, but using [this](http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-begin) as a templat... | 10,221 |
19,872,942 | Alright, so I've been wrestling with this problem for a good two hours now.
I want to use a settings module, local.py, when I run my server locally via this command:
```
$ python manage.py runserver --settings=mysite.settings.local
```
However, I see this error when I try to do this:
```
ImportError: Could no... | 2013/11/09 | [
"https://Stackoverflow.com/questions/19872942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2744684/"
] | The underlying value is the same anyway. How you display it is a matter of **formatting**. Formatting in SQL is usually unnecessary. Formatting should be done on the client that receives the data from the database system.
Don't change anything in SQL. Simply format your grid to display the required number of digits. | Convert number in code side.
ex. :
```
string.Format("{0:0.##}", 256.583); // "256.58"
string.Format("{0:0.##}", 256.586); // "256.59"
string.Format("{0:0.##}", 256.58); // "256.58"
string.Format("{0:0.##}", 256.5); // "256.5"
string.Format("{0:0.##}", 256.0); // "256"
//===============================
string.F... | 10,222 |
65,356,299 | I am running VS Code (Version 1.52) with extensions Jupyter Notebook (2020.12) and Python (2020.12) on MacOS Catalina.
**Context:**
I have problems getting Intellisense to work properly in my Jupyter Notebooks in VS Code. Some have had some success with adding these config parameters to the global settings of VS Code... | 2020/12/18 | [
"https://Stackoverflow.com/questions/65356299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5197386/"
] | Since Nov 2020 the Jupyter extension is seperated from Python extension for VS Code. The setting key has been renamed from `python.dataScience` to `jupyter`[^update](https://devblogs.microsoft.com/python/introducing-the-jupyter-extension-for-vs-code/)
So in your case please rename `python.dataScience.runStartupCommand... | According to your description, you could refer to the following:
1. Whether in the "`.py`" file or the "`.ipynb`" file, we can use the shortcut key `"Ctrl+space`" to open the code suggested options:
[](https://i.stack.imgur.com/K3MlT.png)
2. It is re... | 10,232 |
49,145,059 | In a dynamic system my base values are all functions of time, `d(t)`. I create the variable `d` using `d = Function('d')(t)` where `t = S('t')`
Obviously it's very common to have derivatives of d (rates of change like velocity etc.). However the default printing of `diff(d(t))` gives:-
```
Derivative(d(t), t)
```
a... | 2018/03/07 | [
"https://Stackoverflow.com/questions/49145059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4443898/"
] | I do this by substitution. It is horribly stupid, but it works like a charm:
```
q = Function('q')(t)
q_d = Function('\\dot{q}')(t)
```
and then substitute with
```
alias = {q.diff(t):q_d, } # and higher derivatives etc..
hd = q.diff(t).subs(alias)
```
And the output hd has a pretty dot over it's head!
As I said... | The [vector printing](http://docs.sympy.org/latest/modules/physics/vector/api/printing.html) module that you already found is the only place where such printing is implemented in SymPy.
```
from sympy.physics.vector import dynamicsymbols
from sympy.physics.vector.printing import vpprint, vlatex
d = dynamicsymbols('d'... | 10,233 |
38,645,486 | I'm sure that this is a pretty simple problem and that I am just missing something incredibly obvious, but the answer to this predicament has eluded me for several hours now.
My project directory structure looks like this:
```
-PhysicsMaterial
-Macros
__init__.py
Macros.py
-Modules
__init__.py... | 2016/07/28 | [
"https://Stackoverflow.com/questions/38645486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6649949/"
] | This occurs because you're running the script as `__main__`. When you run a script like this:
```
python /path/to/package/module.py
```
That file is loaded as `__main__`, not as `package.module`, so it can't do relative imports because it isn't part of a package.
This can lead to strange errors where a class defin... | [How to fix "Attempted relative import in non-package" even with \_\_init\_\_.py](https://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py)
Well, guess it's on to using sys.path.append now. Clap and a half to @BrenBarn, @fireant, and @Ignacio Vazquez-Abrams | 10,234 |
70,922,321 | I've been coding with R for quite a while but I want to start learning and using python more for its machine learning applications. However, I'm quite confused as to how to properly install packages and set up the whole working environment. Unlike R where I suppose most people just use RStudio and directly install pack... | 2022/01/31 | [
"https://Stackoverflow.com/questions/70922321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14540717/"
] | I had to import the metada of the `Table` I manually defined | I came to this page because autogenerating migrations no longer worked with the upgrade to SQLAlchemy 1.4, as the metadata were no longer recognized and the automatically generated migration deleted every table (DROP table in upgrade, CREATE TABLE in downgrade).
I have first tried to import the tables metadata like th... | 10,235 |
72,640,228 | I'm trying to replace a single character '°' with '?' in an [edf](https://www.edfplus.info/specs/edf.html) file with binary encoding.([File](https://github.com/warren-manuel/sleep-edf/tree/main/Files)) I need to change all occurances of it in the first line.
I cannot open it without specifying read binary. (The follow... | 2022/06/16 | [
"https://Stackoverflow.com/questions/72640228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4126542/"
] | You need to have **Advanced Access** to **business\_management** permission.
You can submit app review for advanced access, if it approved, you can call /bm-id/adaccount to create ad account with required parameter. | Also, you can't create an ad account on a real FB user. It works with test users well, but you need special permissions from FB to do this on a real user's account. | 10,236 |
7,558,814 | >
> **Possible Duplicate:**
>
> [Python replace multiple strings](https://stackoverflow.com/questions/6116978/python-replace-multiple-strings)
>
>
>
I am looking to replace `“ “`, `“\r”`, `“\n”`, `“<”`, `“>”`, `“’”` (single quote), and `‘”’` (double quote) with `“”` (empty). I’m also looking to replace `“;”` a... | 2011/09/26 | [
"https://Stackoverflow.com/questions/7558814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/454488/"
] | If you want to remove all occurrences of those characters, just put them all in a character class and do [`re.sub()`](http://docs.python.org/library/re.html#re.sub)
```
your_str = re.sub(r'[ \r\n\'"]+', '', your_str)
your_str = re.sub(r'[;|]', ',', your_str)
```
You have to call `re.sub()` for every replacement rule... | ```
import re
reg = re.compile('([ \r\n\'"]+)|([;|]+)')
ss = 'bo ba\rbu\nbe\'bi"by-ja;ju|jo'
def repl(mat, di = {1:'',2:','}):
return di[mat.lastindex]
print reg.sub(repl,ss)
```
Note: '|' loses its speciality between brackets | 10,237 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.