qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How ca... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | Use `ipython` rather than `python` for your REPL It has better code completion and introspection and when you paste indented code it can automatically "de-indent" the pasted code.
Thus you can put your experimental code in a test function and then paste in parts without worrying and having to de-indent your code.
If ... | I think the standard ('Pythonic') way to deal with this is to do it like so:
```
class MyClass(object):
...
def my_function():
...
if __name__ == '__main__':
# testing code here
```
**Edit after your comment**
I don't think what you want is possible using a plain Python interpreter. You could have a l... |
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How ca... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | Use `ipython` rather than `python` for your REPL It has better code completion and introspection and when you paste indented code it can automatically "de-indent" the pasted code.
Thus you can put your experimental code in a test function and then paste in parts without worrying and having to de-indent your code.
If ... | Follow something like option 2.
I usually put experimental code in a main method.
```
def main ():
*experimental code goes here *
```
Then if you want to execute the experimental code just call the main.
```
main()
``` |
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How ca... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | I think the standard ('Pythonic') way to deal with this is to do it like so:
```
class MyClass(object):
...
def my_function():
...
if __name__ == '__main__':
# testing code here
```
**Edit after your comment**
I don't think what you want is possible using a plain Python interpreter. You could have a l... | I suggest you use a proper version control system to keep the "real" and the "experimental" parts separated.
For example, using Git, you could only include the real code without the experimental parts in your commits (using [`add -p`](https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging#Staging-Patches)), and ... |
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How ca... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | Follow something like option 2.
I usually put experimental code in a main method.
```
def main ():
*experimental code goes here *
```
Then if you want to execute the experimental code just call the main.
```
main()
``` | Another possibility is to put tests as [*doctests*](https://docs.python.org/2/library/doctest.html) into the docstrings of your code, which admittedly is only practical for simpler cases.
This way, they are only treated as executable code by the `doctest` module, but as comments otherwise. |
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How ca... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | With python-mode.el mark arbitrary chunks as section - for example via `py-sectionize-region`.
Than call `py-execute-section`.
Updated after comment:
python-mode.el is delivered by melpa.
M-x list-packages RET
Look for python-mode - the built-in python.el provides 'python, while python-mode.el provides 'python-mod... | I suggest you use a proper version control system to keep the "real" and the "experimental" parts separated.
For example, using Git, you could only include the real code without the experimental parts in your commits (using [`add -p`](https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging#Staging-Patches)), and ... |
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How ca... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | Use `ipython` rather than `python` for your REPL It has better code completion and introspection and when you paste indented code it can automatically "de-indent" the pasted code.
Thus you can put your experimental code in a test function and then paste in parts without worrying and having to de-indent your code.
If ... | Unfortunately, there is no widely (or any) standard describing what you are talking about, so getting a bunch of python specific things to work like this will be difficult.
However, you could wrap these commands in such a way that they only read until a signifier. For example (assuming you are on a unix system):
```
... |
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How ca... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | Use `ipython` rather than `python` for your REPL It has better code completion and introspection and when you paste indented code it can automatically "de-indent" the pasted code.
Thus you can put your experimental code in a test function and then paste in parts without worrying and having to de-indent your code.
If ... | Another possibility is to put tests as [*doctests*](https://docs.python.org/2/library/doctest.html) into the docstrings of your code, which admittedly is only practical for simpler cases.
This way, they are only treated as executable code by the `doctest` module, but as comments otherwise. |
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How ca... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | Unfortunately, there is no widely (or any) standard describing what you are talking about, so getting a bunch of python specific things to work like this will be difficult.
However, you could wrap these commands in such a way that they only read until a signifier. For example (assuming you are on a unix system):
```
... | I suggest you use a proper version control system to keep the "real" and the "experimental" parts separated.
For example, using Git, you could only include the real code without the experimental parts in your commits (using [`add -p`](https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging#Staging-Patches)), and ... |
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How ca... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | Unfortunately, there is no widely (or any) standard describing what you are talking about, so getting a bunch of python specific things to work like this will be difficult.
However, you could wrap these commands in such a way that they only read until a signifier. For example (assuming you are on a unix system):
```
... | With python-mode.el mark arbitrary chunks as section - for example via `py-sectionize-region`.
Than call `py-execute-section`.
Updated after comment:
python-mode.el is delivered by melpa.
M-x list-packages RET
Look for python-mode - the built-in python.el provides 'python, while python-mode.el provides 'python-mod... |
19,167,550 | My code goes through a number of files reading them into lists with the command:
```
data = np.loadtxt(myfile, unpack=True)
```
Some of these files are empty (I can't control that) and when that happens I get this warning printed on screen:
```
/usr/local/lib/python2.7/dist-packages/numpy/lib/npyio.py:795: UserWarn... | 2013/10/03 | [
"https://Stackoverflow.com/questions/19167550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391441/"
] | You will have to wrap the line with `catch_warnings`, then call the `simplefilter` method to suppress those warnings. For example:
```
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
data = np.loadtxt(myfile, unpack=True)
```
Should do it. | One obvious possibility is to pre-check the files:
```
if os.fstat(myfile.fileno()).st_size:
data = np.loadtxt(myfile, unpack=True)
else:
# whatever you want to do for empty files
``` |
22,345,798 | I currently have a working python code in command line. How can I convert this into a GUI program. I know how to design a GUI(make buttons,callback function, create text field, label widget...). My question is how should be the GUI connected to the existing program. *should I make a python file called gui.py and impor... | 2014/03/12 | [
"https://Stackoverflow.com/questions/22345798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2332665/"
] | As the GUI is the user front-end, and because your function already exists, the easiest is to make GUI class to import the function. On event, the GUI would call the function and handle the display to the user.
In fact, it's exactly what you have done with a Command-Line Interface (CLI) in your example code :) | I would say the answer strongly depends on your choice of GUI-framework to use. For a small piece of code like the one you posted you probably may want to rely on "batteries included" tkinter. In this case I agree to the comment of shaktimaan to simply include the tkinter commands in your existing code. But you have ma... |
63,580,623 | Right now I'm sitting on a blank file which consists only of the following:
```
import os
import sys
import shlex
import subprocess
import signal
from time import monotonic as timer
```
I get this error when I try to run my file: ImportError: Cannot import name monotonic
If it matters, I am on linux and my python v... | 2020/08/25 | [
"https://Stackoverflow.com/questions/63580623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10847907/"
] | You'll need to use regular Producer and execute the serialization functions yourself
```
from confluent_kafka import avro
from confluent_kafka.avro import CachedSchemaRegistryClient
from confluent_kafka.avro.serializer.message_serializer import MessageSerializer as AvroSerializer
avro_serializer = AvroSerializer(sche... | `AvroProducer` assumes that both keys and values are encoded with the schema registry, prepending a magic byte and the schema id to the payload of both the key and the value.
If you want to use a custom serialization for the key, you could use a `Producer` instead of an `AvroProducer`. But it will be your responsibili... |
69,833,702 | I keep running into this use and I haven't found a good solution. I am asking for a solution in python, but a solution in R would also be helpful.
I've been getting data that looks something like this:
```
import pandas as pd
data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69833702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167846/"
] | In `R`,
```
data <- data.frame(
Col1 = c('Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex' , '200', 'Third Street', '')
)
k<-which(grepl("Street", data$Col1) == TRUE)
j <- k-1
i <- k-2
data.frame(
Name = data[i,],
Adress = data[j,],
Street = data[k,]
)
Name Adress Street
1 ... | ### Python3
In Python 3, you can convert your DataFrame into an array and then reshape it.
```py
n = df.shape[0]
df2 = pd.DataFrame(
data=df.to_numpy().reshape((n//4, 4), order='C'),
columns=['Name', 'Address', 'Street', 'Empty'])
```
This produces for your sample data this:
```
Name Address Str... |
69,833,702 | I keep running into this use and I haven't found a good solution. I am asking for a solution in python, but a solution in R would also be helpful.
I've been getting data that looks something like this:
```
import pandas as pd
data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69833702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167846/"
] | In `R`,
```
data <- data.frame(
Col1 = c('Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex' , '200', 'Third Street', '')
)
k<-which(grepl("Street", data$Col1) == TRUE)
j <- k-1
i <- k-2
data.frame(
Name = data[i,],
Adress = data[j,],
Street = data[k,]
)
Name Adress Street
1 ... | In python i believe this may help u.
```
1 import pandas as pd
2
3 data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex' , '200', 'Third Street', '']}
4
5 var = list(data.values())[0]
6 var2 = []
7 for aux in range(int(len(var)/4)):
8 var2.append(var[aux*4: au... |
69,833,702 | I keep running into this use and I haven't found a good solution. I am asking for a solution in python, but a solution in R would also be helpful.
I've been getting data that looks something like this:
```
import pandas as pd
data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69833702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167846/"
] | In `R`,
```
data <- data.frame(
Col1 = c('Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex' , '200', 'Third Street', '')
)
k<-which(grepl("Street", data$Col1) == TRUE)
j <- k-1
i <- k-2
data.frame(
Name = data[i,],
Adress = data[j,],
Street = data[k,]
)
Name Adress Street
1 ... | Another R solution. This solution is based on the `tidyverse` package. The example data frame `data` is from Park's post (<https://stackoverflow.com/a/69833814/7669809>).
```
library(tidyverse)
data2 <- data %>%
mutate(ID = cumsum(Col1 %in% "")) %>%
filter(!Col1 %in% "") %>%
group_by(ID) %>%
mutate(Type = cas... |
69,833,702 | I keep running into this use and I haven't found a good solution. I am asking for a solution in python, but a solution in R would also be helpful.
I've been getting data that looks something like this:
```
import pandas as pd
data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69833702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167846/"
] | In `R`,
```
data <- data.frame(
Col1 = c('Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex' , '200', 'Third Street', '')
)
k<-which(grepl("Street", data$Col1) == TRUE)
j <- k-1
i <- k-2
data.frame(
Name = data[i,],
Adress = data[j,],
Street = data[k,]
)
Name Adress Street
1 ... | The values of the DataFrame are reshaped by unknown rows and 4 columns, then the first 3 columns of the entire array are taken out by slicing and converted into a DataFrame, and finally the columns of DataFrame are reset by set\_axis
```
result = pd.DataFrame(df.values.reshape(-1, 4)[:, :-1])\
.set_axis(['Name', ... |
69,833,702 | I keep running into this use and I haven't found a good solution. I am asking for a solution in python, but a solution in R would also be helpful.
I've been getting data that looks something like this:
```
import pandas as pd
data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69833702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167846/"
] | ### Python3
In Python 3, you can convert your DataFrame into an array and then reshape it.
```py
n = df.shape[0]
df2 = pd.DataFrame(
data=df.to_numpy().reshape((n//4, 4), order='C'),
columns=['Name', 'Address', 'Street', 'Empty'])
```
This produces for your sample data this:
```
Name Address Str... | In python i believe this may help u.
```
1 import pandas as pd
2
3 data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex' , '200', 'Third Street', '']}
4
5 var = list(data.values())[0]
6 var2 = []
7 for aux in range(int(len(var)/4)):
8 var2.append(var[aux*4: au... |
69,833,702 | I keep running into this use and I haven't found a good solution. I am asking for a solution in python, but a solution in R would also be helpful.
I've been getting data that looks something like this:
```
import pandas as pd
data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69833702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167846/"
] | ### Python3
In Python 3, you can convert your DataFrame into an array and then reshape it.
```py
n = df.shape[0]
df2 = pd.DataFrame(
data=df.to_numpy().reshape((n//4, 4), order='C'),
columns=['Name', 'Address', 'Street', 'Empty'])
```
This produces for your sample data this:
```
Name Address Str... | Another R solution. This solution is based on the `tidyverse` package. The example data frame `data` is from Park's post (<https://stackoverflow.com/a/69833814/7669809>).
```
library(tidyverse)
data2 <- data %>%
mutate(ID = cumsum(Col1 %in% "")) %>%
filter(!Col1 %in% "") %>%
group_by(ID) %>%
mutate(Type = cas... |
69,833,702 | I keep running into this use and I haven't found a good solution. I am asking for a solution in python, but a solution in R would also be helpful.
I've been getting data that looks something like this:
```
import pandas as pd
data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69833702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167846/"
] | ### Python3
In Python 3, you can convert your DataFrame into an array and then reshape it.
```py
n = df.shape[0]
df2 = pd.DataFrame(
data=df.to_numpy().reshape((n//4, 4), order='C'),
columns=['Name', 'Address', 'Street', 'Empty'])
```
This produces for your sample data this:
```
Name Address Str... | The values of the DataFrame are reshaped by unknown rows and 4 columns, then the first 3 columns of the entire array are taken out by slicing and converted into a DataFrame, and finally the columns of DataFrame are reset by set\_axis
```
result = pd.DataFrame(df.values.reshape(-1, 4)[:, :-1])\
.set_axis(['Name', ... |
56,746,773 | I had a college exercise which contains a question which asked to write a function which returns how many times a particular key repeats in an object in python. after researching on dictionaries I know that python automatically ignores duplicate keys only keeping the last one. I tried to loop over each key the conventi... | 2019/06/25 | [
"https://Stackoverflow.com/questions/56746773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9096030/"
] | Just to mention other options note that you can use the `filter` function here:
```
julia> filter(row -> row.a == 2, df)
1×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ String │
├─────┼───────┼────────┤
│ 1 │ 2 │ y │
```
or
```
julia> df[filter(==(2), df.a), :]
1×2 DataFrame
│ Row │ a │ b ... | Fortunately, you only need to add one character: `.`. The `.` character enables broadcasting on any Julia function, even ones like `==`. Therefore, your code would be as follows:
```
df = DataFrame(a=[1,2,3], b=["x", "y", "z"])
df2 = df[df.a .== 2, :]
```
Without the broadcast, the clause `df.a == 2` returns `false`... |
38,212,340 | I am trying to extract all those tags whose class name fits the regex pattern frag-0-0, frag-1-0, etc. from [this link](http://de.vroniplag.wikia.com/wiki/Aak/002)
I am trying to retrieve it using the following code
```
driver = webdriver.Chrome(chromedriver)
for frg in frgs:
driver.get(URL + frg[1:])... | 2016/07/05 | [
"https://Stackoverflow.com/questions/38212340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6213939/"
] | Try to remove DownloadCachePluginBootstrap.cs and FilePluginBootstrap.cs just leave manual setup inside InitializeLastChance(). It seems that there is a problem with loading order. | As @Piotr mentioned:
>
> Try to remove DownloadCachePluginBootstrap.cs and FilePluginBootstrap.cs just
> leave manual setup inside InitializeLastChance(). It seems that there is a
> problem with loading order.
>
>
>
That fixed the issue for me as well.
I just want to share my code in the Setup.cs of the iOS... |
44,206,346 | How can I stop pgadmin 4 process?
I ran pgadmin 4 next method:
`python3 /usr/local/pgAdmin4.py`
My idea using Ctrl-c. | 2017/05/26 | [
"https://Stackoverflow.com/questions/44206346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8071434/"
] | If you are using pgAdmin 4 on mac OS or Ubuntu, you can use system tool bar (at the top of the screen) icon for this. After you start pgAdmin server the icon with elephant head should appear. If you click it you will have an option `Shut down server`. | You can shut down the server[](https://i.stack.imgur.com/qzpud.png) from the top menu as shown.
Just click the Shutdown server and it will work. |
74,495,864 | I have a huge list of sublists, each sublist consisting of a tuple and an int. Example:
```
[[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]]
```
I want to create a unique list of those tuples cor... | 2022/11/18 | [
"https://Stackoverflow.com/questions/74495864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20543467/"
] | From the helpfile you can read:
>
> If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if **row.names is missing, the rows are numbered**.
>
>
>
That explains the same behavior when you set row.names=NULL o... | The first two executions are functionally the same, when you don't use row.names parameter of read.table, it's assumed that its value is NULL.
The third one fails because `1` is interpreted as being a vector with length equal to the number of rows filled with the value 1. Hence the error affirming you can't have two r... |
10,104,805 | I have installed python 32 package to the
>
> C:\python32
>
>
>
I have also set the paths:
>
> PYTHONPATH | C:\Python32\Lib;C:\Python32\DLLs;C:\Python32\Lib\lib-tk;
>
>
> PATH ;C:\Python32;
>
>
>
I would like to use the "2to3" tool, but CMD does not recognize it.
```
CMD: c:\test\python> 2to3 test.py
`... | 2012/04/11 | [
"https://Stackoverflow.com/questions/10104805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1318239/"
] | 2to3 is actually a Python script found in the Tools/scripts folder of your Python install.
So you should run it like this:
```
python.exe C:\Python32\Tools\scripts\2to3.py your-script-here.py
```
See this for more details: <http://docs.python.org/library/2to3.html> | You can set up 2to3.py to run as a command when you type 2to3 by creating a batch file in the same directory as your python.exe file (assuming that directory is already on your windows path - it doesn't have to be this directory it just is a convenient, relatively logical spot).
Lets assume you have python installed i... |
10,104,805 | I have installed python 32 package to the
>
> C:\python32
>
>
>
I have also set the paths:
>
> PYTHONPATH | C:\Python32\Lib;C:\Python32\DLLs;C:\Python32\Lib\lib-tk;
>
>
> PATH ;C:\Python32;
>
>
>
I would like to use the "2to3" tool, but CMD does not recognize it.
```
CMD: c:\test\python> 2to3 test.py
`... | 2012/04/11 | [
"https://Stackoverflow.com/questions/10104805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1318239/"
] | 2to3 is actually a Python script found in the Tools/scripts folder of your Python install.
So you should run it like this:
```
python.exe C:\Python32\Tools\scripts\2to3.py your-script-here.py
```
See this for more details: <http://docs.python.org/library/2to3.html> | Make a batch file then rename it to `2to3.bat` and paste this code in it:
```
@python "%~dp0\Tools\Scripts\2to3.py" %*
```
Copy that file beside your python.exe file, for me that folder is:
`C:\Users\Admin\AppData\Local\Programs\Python\Python38`
Usage:
```
2to3 mycode.py
``` |
10,104,805 | I have installed python 32 package to the
>
> C:\python32
>
>
>
I have also set the paths:
>
> PYTHONPATH | C:\Python32\Lib;C:\Python32\DLLs;C:\Python32\Lib\lib-tk;
>
>
> PATH ;C:\Python32;
>
>
>
I would like to use the "2to3" tool, but CMD does not recognize it.
```
CMD: c:\test\python> 2to3 test.py
`... | 2012/04/11 | [
"https://Stackoverflow.com/questions/10104805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1318239/"
] | You can set up 2to3.py to run as a command when you type 2to3 by creating a batch file in the same directory as your python.exe file (assuming that directory is already on your windows path - it doesn't have to be this directory it just is a convenient, relatively logical spot).
Lets assume you have python installed i... | Make a batch file then rename it to `2to3.bat` and paste this code in it:
```
@python "%~dp0\Tools\Scripts\2to3.py" %*
```
Copy that file beside your python.exe file, for me that folder is:
`C:\Users\Admin\AppData\Local\Programs\Python\Python38`
Usage:
```
2to3 mycode.py
``` |
8,576,104 | Just for fun, I've been using `python` and `gstreamer` to create simple Linux audio players. The first one was a command-line procedural script that used gst-launch-0.10 playbin to play a webstream. The second version was again procedural but had a GUI and used playbin2 to create the gstreamer pipeline. Now I'm trying ... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8576104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1106979/"
] | If you use this, you will pass the element value as param.
```
javascript:checkStatus('{$k->bus_company_name}','{$k->bus_id}','{$k->bus_time}',document.getElementById('dt').value)
```
But you also can get inside the function checkStatus. | Since you're looping through a list of items, I would recommend using the current index at each iteration to create a unique date ID. You can then pass this to your script and get the element's value by ID there:
```
{foreach name = feach key = i item = k from = $allBuses}
{$k->bus_company_name}<br />
... |
29,476,054 | I have a list of things I want to filter out of a csv, and I'm trying to figure out a pythonic way to do it. EG, this is what I'm doing:
```
with open('output.csv', 'wb') as outf:
with open('input.csv', 'rbU') as inf:
read = csv.reader(inf)
outwriter = csv.writer(outf)
notstrings = ['and... | 2015/04/06 | [
"https://Stackoverflow.com/questions/29476054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2898989/"
] | You can use the [`any()` function](https://docs.python.org/2/library/functions.html#any) to test each of the words in your list against a column:
```
if not any(w in row[3] for w in notstrings):
# none of the strings are found, write the row
```
This will be true if *none* of those strings appear in `row[3]`. It... | You can use sets. In this code, I transform your list into a set. I transform your `row[3]` into a set of words and I check the intersection between the two sets. If there is not intersection, that means none of the words in notstrings are in `row[3]`.
Using sets, you make sure that you match only words and not parts ... |
62,514,068 | I am trying to develop a AWS lambda to make a `rollout restart deployment` using the python client. I cannot find any implementation in the github repo or references. Using the -v in the `kubectl rollout restart` is not giving me enough hints to continue with the development.
Anyways, it is more related to the python ... | 2020/06/22 | [
"https://Stackoverflow.com/questions/62514068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13791762/"
] | The python client interacts directly with the Kubernetes API. Similar to what `kubectl` does. However, `kubectl` added some utility commands which contain logic that is not contained in the Kubernetes API. Rollout is one of those utilities.
In this case that means you have two approaches. You could reverse engineer th... | @Andre Pires, it can be done like this way :
```
data := fmt.Sprintf(`{"spec":{"template":{"metadata":{"annotations":{"kubectl.kubernetes.io/restartedAt":"%s"}}}},"strategy":{"type":"RollingUpdate","rollingUpdate":{"maxUnavailable":"%s","maxSurge": "%s"}}}`, time.Now().String(), "25%", "25%")
newDeployment, err := cli... |
51,314,875 | Seems fairly straight forward but whenever I try to merely import the module I get this:
```
from pptx.util import Inches
from pptx import Presentation
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
~\AppData\... | 2018/07/12 | [
"https://Stackoverflow.com/questions/51314875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9459261/"
] | I've finally figured it out by creating a small app and trying to reproduce it. As Dmitry and Paulo have pointed out, it should work. However, it should work for any new project and in my case the project is 10 years old and has lots of legacy configurations.
**TL;DR:** The `async`/`await` keywords do not work very we... | For retrieving files in `ASP.NET Core` try using [`IFileProvider`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.ifileprovider) instead of `HttpContext` - see [File Providers in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers) documentation for m... |
35,796,968 | I have a python GUI application. And now I need to know what all libraries the application links to. So that I can check the license compatibility of all the libraries.
I have tried using strace, but strace seems to report all the packages even if they are not used by the application.
And, I tried python ModuleFinder... | 2016/03/04 | [
"https://Stackoverflow.com/questions/35796968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109788/"
] | You can give a try to the library
<https://github.com/bndr/pipreqs>
found following the guide
<https://www.fullstackpython.com/application-dependencies.html>
---
The library `pipreqs` is pip installable and automatically generates the file `requirements.txt`.
It contains all the imports libraries with versions you a... | Install yolk for python2 with:
```
pip install yolk
```
Or install yolk for python3 with:
```
pip install yolk3k
```
Call the following to get the list of eggs in your environment:
```
yolk -l
```
Alternatively, you can use [snakefood](http://furius.ca/snakefood/) for graphing your dependencies, as answered in... |
35,796,968 | I have a python GUI application. And now I need to know what all libraries the application links to. So that I can check the license compatibility of all the libraries.
I have tried using strace, but strace seems to report all the packages even if they are not used by the application.
And, I tried python ModuleFinder... | 2016/03/04 | [
"https://Stackoverflow.com/questions/35796968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109788/"
] | Install yolk for python2 with:
```
pip install yolk
```
Or install yolk for python3 with:
```
pip install yolk3k
```
Call the following to get the list of eggs in your environment:
```
yolk -l
```
Alternatively, you can use [snakefood](http://furius.ca/snakefood/) for graphing your dependencies, as answered in... | To get all the installed packages or modules. A very easy way is by going to your virtual environment directory on the terminal (The one with (venv) behind your computer's username) and run on the terminal one of these commands
`pip freeze > requirements.txt`
If you are using python3
`pip3 freeze > requirements.txt`... |
35,796,968 | I have a python GUI application. And now I need to know what all libraries the application links to. So that I can check the license compatibility of all the libraries.
I have tried using strace, but strace seems to report all the packages even if they are not used by the application.
And, I tried python ModuleFinder... | 2016/03/04 | [
"https://Stackoverflow.com/questions/35796968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109788/"
] | You can give a try to the library
<https://github.com/bndr/pipreqs>
found following the guide
<https://www.fullstackpython.com/application-dependencies.html>
---
The library `pipreqs` is pip installable and automatically generates the file `requirements.txt`.
It contains all the imports libraries with versions you a... | To get all the installed packages or modules. A very easy way is by going to your virtual environment directory on the terminal (The one with (venv) behind your computer's username) and run on the terminal one of these commands
`pip freeze > requirements.txt`
If you are using python3
`pip3 freeze > requirements.txt`... |
36,075,407 | I'm developing python flask app.
I have a problem mysqldb.
If I type 'import MySQLdb' on python console.
It show "ImportError: No module named 'MySQLdb' "
On my computer MySQL-python installed and running on <http://127.0.0.1:5000/>
How can I solve this problem? | 2016/03/18 | [
"https://Stackoverflow.com/questions/36075407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5736099/"
] | If you are using Python **2.x**, one of the following command will install `mysqldb` on your machine:
```
pip install mysql-python
```
or
```
easy_install mysql-python
``` | **for python 3.x install**
pip install mysqlclient |
36,075,407 | I'm developing python flask app.
I have a problem mysqldb.
If I type 'import MySQLdb' on python console.
It show "ImportError: No module named 'MySQLdb' "
On my computer MySQL-python installed and running on <http://127.0.0.1:5000/>
How can I solve this problem? | 2016/03/18 | [
"https://Stackoverflow.com/questions/36075407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5736099/"
] | Please follow these steps to get mysql support in your Flask app.
* Install the dev package for mysql depending on your Linux distro
* Make sure you have virtualenv installed and activated for your Flask app
* Install the mysqlclient package by using `pip install mysqlclient`
All of the above steps are independent of... | **for python 3.x install**
pip install mysqlclient |
37,691,320 | Im very new to `c` and am trying to make a `while` loop that checks if the parameter is less than or equal to a certain number but also if it is greater than or equal to a different number as well. I usually code in `python` and this is example of what I'm looking to do in `c`:
`while(8 <= x <= 600)` | 2016/06/08 | [
"https://Stackoverflow.com/questions/37691320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5355216/"
] | ```
while (x >= 8 && x <= 600){
}
``` | The relational and equality operators (`<`, `<=`, `>`, `>=`, `==`, and `!=`) don't work like that in C. The expression `a <= b` will evaluate to 1 if the condition is true, 0 otherwise. The operator is *left-associative*, so `8 <= x <= 600` will be evaluated as `(8 <= x) <= 600`. `8 <= x` will evaluate to 0 or 1, both ... |
37,691,320 | Im very new to `c` and am trying to make a `while` loop that checks if the parameter is less than or equal to a certain number but also if it is greater than or equal to a different number as well. I usually code in `python` and this is example of what I'm looking to do in `c`:
`while(8 <= x <= 600)` | 2016/06/08 | [
"https://Stackoverflow.com/questions/37691320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5355216/"
] | ```
while (x >= 8 && x <= 600){
}
``` | this one means if x>=8,if x is bigger than 8 ,it turns 1 <= 600 ;(always true)
if not , Then it turns 0<=600 ; (always fause) |
37,691,320 | Im very new to `c` and am trying to make a `while` loop that checks if the parameter is less than or equal to a certain number but also if it is greater than or equal to a different number as well. I usually code in `python` and this is example of what I'm looking to do in `c`:
`while(8 <= x <= 600)` | 2016/06/08 | [
"https://Stackoverflow.com/questions/37691320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5355216/"
] | The relational and equality operators (`<`, `<=`, `>`, `>=`, `==`, and `!=`) don't work like that in C. The expression `a <= b` will evaluate to 1 if the condition is true, 0 otherwise. The operator is *left-associative*, so `8 <= x <= 600` will be evaluated as `(8 <= x) <= 600`. `8 <= x` will evaluate to 0 or 1, both ... | this one means if x>=8,if x is bigger than 8 ,it turns 1 <= 600 ;(always true)
if not , Then it turns 0<=600 ; (always fause) |
69,090,032 | Using Python.
I have two data frames
df1:
```
email timezone country_app_web
0 nhvfstdfg@vxc.com Europe/Paris NaN
1 taifoor096@gmail.com NaN FR
2 nivo1996@gmail.com US/Eastern NaN
3 jorgehersan90@gmail.com NaN UK
4 s... | 2021/09/07 | [
"https://Stackoverflow.com/questions/69090032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16677735/"
] | if you want to remove all object in `products`
use this
```
db.collection.update({},
{
$set: {
products: {}
}
})
```
<https://mongoplayground.net/p/aBSnpRhblxt>
if you want to delete specific key (gCx5qSTLvdWeel8E2Yo7m) from product use this
```
db.collection.update({},
{
$unset: {
"products.gCx5qSTL... | Thank you for your answer Mohammad but I think this works for MongoDB, but in mongoose, we need to set the value as 1 to remove the item with unset.
Here is my working example
```js
const { ids } = req.body;
try {
const order = await Order.findById(req.params.id).populate('user', 'name').exec();
if (!order)... |
61,746,984 | I have a script which has been simplified to provide me with a sequence of numbers.
I have run this under windows 10, using both Python3.6 and Python3.8
If the script is run with the line the line : pal\_gen.send(10 \*\* (digits)) commented out, I get what I expected. But I want to change the sequence when num % 10 = ... | 2020/05/12 | [
"https://Stackoverflow.com/questions/61746984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5467308/"
] | I don't know why you expect result `0, 10, 20, 20, 20` if you send `10`, `100`, `1000`, `10000`
In second version you have to send
```
i = pal_gen.send(10*(digits-1))
```
but it will gives endless `20` so if you expect other values then it will need totally different code.
---
```
def infinite_pal():
num = ... | Many thanks for the above comments. In case anyone else is new to generators in Python, I make the following comments. The first example came from a web site (2 sites in fact) that supposedly explained Python generators. I appreciate there was an error in the .send parameter, but my real concern was why the first appro... |
45,851,791 | I am running the docker image for snappydata v0.9. From inside that image, I can run queries against the database. However, I cannot do so from a second server on my machine.
I copied the python files from snappydata to the installed pyspark (editing snappysession to SnappySession in the imports) and (based on the ans... | 2017/08/24 | [
"https://Stackoverflow.com/questions/45851791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767565/"
] | Try this:
```
from random import randint
print( "You rolled " + ",".join(str(randint(1,6)) for j in range(6)) )
``` | If you're using python 3, which it appears you are, you could very simply print like that printing "you rolled" and then the numbers one at a time with the print argument 'end' set to a blank string
```
print("You rolled ", end='')
for i in range(6):
print(str(random.randint(1,6)), end='')
if i < 5:
... |
45,851,791 | I am running the docker image for snappydata v0.9. From inside that image, I can run queries against the database. However, I cannot do so from a second server on my machine.
I copied the python files from snappydata to the installed pyspark (editing snappysession to SnappySession in the imports) and (based on the ans... | 2017/08/24 | [
"https://Stackoverflow.com/questions/45851791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767565/"
] | Try this:
```
from random import randint
print( "You rolled " + ",".join(str(randint(1,6)) for j in range(6)) )
``` | You want a comma-separated list of numbers, but you are only generating one number at a time.
You say:
```
for i in range(6):
roll1 =int(random.randint(1,6))
print ("You rolled",roll1)
```
>
> I need it to print out like
>
>
>
```
you rolled 3,4,5,6,2
```
First, let's try working with what you alread... |
10,656,147 | I figured out how to run my Django application via `sudo python /home/david/myproject/manage.py runserver 68.164.125.221:80`. However, after I quit terminal, the server stops running.
I tried to run this process in the background, but the server just shuts down quickly after I execute `sudo python /home/david/myprojec... | 2012/05/18 | [
"https://Stackoverflow.com/questions/10656147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795319/"
] | Meet [screen](http://www.gnu.org/software/screen/).
Connect through ssh, start screen. This open a virtual console emulator on top of the one provided by ssh. Start your server there.
Then press Ctrl-a, then d. This detach the screen session, keeping it running in the background.
To [R]e-attach to it, use screen -r.... | Use `screen` to create a new virtual window, and run the server there.
```
$ screen
$ python manage.py runserver
```
You will see that Django server has started running.
Now press `Ctrl+A` and then press the `D` key to detach from that screen. It will say:
```
$ [detached from ###.pts-0.hostname]
```
You can no... |
10,656,147 | I figured out how to run my Django application via `sudo python /home/david/myproject/manage.py runserver 68.164.125.221:80`. However, after I quit terminal, the server stops running.
I tried to run this process in the background, but the server just shuts down quickly after I execute `sudo python /home/david/myprojec... | 2012/05/18 | [
"https://Stackoverflow.com/questions/10656147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795319/"
] | Meet [screen](http://www.gnu.org/software/screen/).
Connect through ssh, start screen. This open a virtual console emulator on top of the one provided by ssh. Start your server there.
Then press Ctrl-a, then d. This detach the screen session, keeping it running in the background.
To [R]e-attach to it, use screen -r.... | Use nohup. Change your command as follows:
```
nohup sudo python /home/david/myproject/manage.py runserver 68.164.125.221:80 &
``` |
10,656,147 | I figured out how to run my Django application via `sudo python /home/david/myproject/manage.py runserver 68.164.125.221:80`. However, after I quit terminal, the server stops running.
I tried to run this process in the background, but the server just shuts down quickly after I execute `sudo python /home/david/myprojec... | 2012/05/18 | [
"https://Stackoverflow.com/questions/10656147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795319/"
] | Use `screen` to create a new virtual window, and run the server there.
```
$ screen
$ python manage.py runserver
```
You will see that Django server has started running.
Now press `Ctrl+A` and then press the `D` key to detach from that screen. It will say:
```
$ [detached from ###.pts-0.hostname]
```
You can no... | Use nohup. Change your command as follows:
```
nohup sudo python /home/david/myproject/manage.py runserver 68.164.125.221:80 &
``` |
34,086,062 | today I'm updated the elastic search from 1.6 to 2.1, because 1.6 is vulnerable version, after this update my website not working, give this error :
```
Traceback (most recent call last):
File "manage.py", line 8, in <module>
from app import app, db
File "/opt/project/app/__init__.py", line 30, in <module>
... | 2015/12/04 | [
"https://Stackoverflow.com/questions/34086062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5544303/"
] | `jeuResultats.next();` moves your result to the next row. You start with 0th row, i.e. when you call `.next()` it reads the first row, then when you call it again, it tries to read the 2nd row, which does not exist.
*Some additional hints, not directly related to the question:*
1. Java Docs are a good place to star... | Make the below changes in you code. Currently the next() method is shifting result list to fetch the data at 1st index, whereas the data is at the 0th Index:
```
boolean result = false;
try{
result = jeuResultats.next();
} catch (SQLException e) {
e.printStackTrace();
}
if (!result) {
loadJSP("/... |
34,086,062 | today I'm updated the elastic search from 1.6 to 2.1, because 1.6 is vulnerable version, after this update my website not working, give this error :
```
Traceback (most recent call last):
File "manage.py", line 8, in <module>
from app import app, db
File "/opt/project/app/__init__.py", line 30, in <module>
... | 2015/12/04 | [
"https://Stackoverflow.com/questions/34086062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5544303/"
] | `jeuResultats.next();` moves your result to the next row. You start with 0th row, i.e. when you call `.next()` it reads the first row, then when you call it again, it tries to read the 2nd row, which does not exist.
*Some additional hints, not directly related to the question:*
1. Java Docs are a good place to star... | Replace your code by below code:
```
requete = "SELECT Login, Password, DroitModifAnnuaire, DroitRecepteurDem, DroitResponsableDem, PiloteIso, Administrateur, DroitNews, DroitTenues, DroitEssai, Nom, Prenom FROM Annuaire WHERE Login = '"
+ (request.getParameter("login") + "'");
instruction = connexion.cr... |
34,086,062 | today I'm updated the elastic search from 1.6 to 2.1, because 1.6 is vulnerable version, after this update my website not working, give this error :
```
Traceback (most recent call last):
File "manage.py", line 8, in <module>
from app import app, db
File "/opt/project/app/__init__.py", line 30, in <module>
... | 2015/12/04 | [
"https://Stackoverflow.com/questions/34086062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5544303/"
] | Make the below changes in you code. Currently the next() method is shifting result list to fetch the data at 1st index, whereas the data is at the 0th Index:
```
boolean result = false;
try{
result = jeuResultats.next();
} catch (SQLException e) {
e.printStackTrace();
}
if (!result) {
loadJSP("/... | Replace your code by below code:
```
requete = "SELECT Login, Password, DroitModifAnnuaire, DroitRecepteurDem, DroitResponsableDem, PiloteIso, Administrateur, DroitNews, DroitTenues, DroitEssai, Nom, Prenom FROM Annuaire WHERE Login = '"
+ (request.getParameter("login") + "'");
instruction = connexion.cr... |
48,074,568 | as part of Unity's ML Agents images fed to a reinforcement learning agent can be converted to greyscale like so:
```
def _process_pixels(image_bytes=None, bw=False):
s = bytearray(image_bytes)
image = Image.open(io.BytesIO(s))
s = np.array(image) / 255.0
if bw:
s = np.mean(s, axis=2)
s ... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48074568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3515869/"
] | Won't just doing this work?
```
plt.imshow(s[..., 0])
plt.show()
```
Explanation
`plt.imshow` expects either a 2-D array with shape `(x, y)`, and treats it like grayscale, or dimensions `(x, y, 3)` (treated like RGB) or `(x, y, 4)` (treated as RGBA). The array you had was `(x, y, 1)`. To get rid of the last dimensi... | It looks like the grayscale version has an extra single dimension at the end. To plot, you just need to collapse it, e.g. with [`np.squeeze`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.squeeze.html):
```
plt.imshow(np.squeeze(s))
``` |
38,510,140 | What is the difference between a list & a stack in python?
I have read its explanation in the python documentation but there both the things seems to be same?
```
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> sta... | 2016/07/21 | [
"https://Stackoverflow.com/questions/38510140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6621144/"
] | A stack is a *data structure concept*. The documentation uses a Python `list` object to implement one. That's why that section of the tutorial is named *Using Lists as Stacks*.
Stacks are just things you add stuff to, and when you take stuff away from a stack again, you do so in reverse order, first in, last out style... | A "stack" is a specific application of `list`, with operations limited to appending (pushing) to and popping (pulling) from the end. |
38,510,140 | What is the difference between a list & a stack in python?
I have read its explanation in the python documentation but there both the things seems to be same?
```
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> sta... | 2016/07/21 | [
"https://Stackoverflow.com/questions/38510140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6621144/"
] | A stack is a *data structure concept*. The documentation uses a Python `list` object to implement one. That's why that section of the tutorial is named *Using Lists as Stacks*.
Stacks are just things you add stuff to, and when you take stuff away from a stack again, you do so in reverse order, first in, last out style... | In python lists can also be used as stacks. Think of a list like a combination between your normal lists and a stack.
This is also described [here](https://docs.python.org/3/tutorial/datastructures.html)
>
> The list methods make it very easy to use a list as a stack, where the
> last element added is the first ele... |
38,510,140 | What is the difference between a list & a stack in python?
I have read its explanation in the python documentation but there both the things seems to be same?
```
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> sta... | 2016/07/21 | [
"https://Stackoverflow.com/questions/38510140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6621144/"
] | A stack is a *data structure concept*. The documentation uses a Python `list` object to implement one. That's why that section of the tutorial is named *Using Lists as Stacks*.
Stacks are just things you add stuff to, and when you take stuff away from a stack again, you do so in reverse order, first in, last out style... | Stack works in the concept of Last in First out.
We can perform push and pop operations in the stack
But compare to stack list is easy to do all operations like add,insert,delete,concat etc...
Stack is the application of stack and it's like data structures we use it more. |
38,510,140 | What is the difference between a list & a stack in python?
I have read its explanation in the python documentation but there both the things seems to be same?
```
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> sta... | 2016/07/21 | [
"https://Stackoverflow.com/questions/38510140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6621144/"
] | A "stack" is a specific application of `list`, with operations limited to appending (pushing) to and popping (pulling) from the end. | Stack works in the concept of Last in First out.
We can perform push and pop operations in the stack
But compare to stack list is easy to do all operations like add,insert,delete,concat etc...
Stack is the application of stack and it's like data structures we use it more. |
38,510,140 | What is the difference between a list & a stack in python?
I have read its explanation in the python documentation but there both the things seems to be same?
```
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> sta... | 2016/07/21 | [
"https://Stackoverflow.com/questions/38510140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6621144/"
] | In python lists can also be used as stacks. Think of a list like a combination between your normal lists and a stack.
This is also described [here](https://docs.python.org/3/tutorial/datastructures.html)
>
> The list methods make it very easy to use a list as a stack, where the
> last element added is the first ele... | Stack works in the concept of Last in First out.
We can perform push and pop operations in the stack
But compare to stack list is easy to do all operations like add,insert,delete,concat etc...
Stack is the application of stack and it's like data structures we use it more. |
18,971,162 | I am trying to create a simple python calculator for an assignment. The basic idea of it is simple and documented all over online, but I am trying to create one where the user actually inputs the operators. So instead of printing 1: addition, 2: subtraction, etc, the user would select + for addition, - for subtraction,... | 2013/09/24 | [
"https://Stackoverflow.com/questions/18971162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2809161/"
] | First off, you don't need to assign `choice` to zero
Second, you have your code right, but you need to put quotes around the operators in your if statements like this
```
if choice == '+':
```
to show that you are checking for a string
make your loop like this:
```
while 1: #or while True:
#do stuff
elif... | You should try replacing `if choice == +` by `if choice == "+"`.
What you're getting from the input is actually a string, which means it can contain any character, even one that represents an operator. |
57,624,355 | I deploy a Python app to Google Cloud Functions and got this very vague error message:
```
$ gcloud functions deploy parking_photo --runtime python37 --trigger-http
Deploying function (may take a while - up to 2 minutes)...failed.
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Fun... | 2019/08/23 | [
"https://Stackoverflow.com/questions/57624355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/502780/"
] | Most likely your function is raising a `FileNotFound` error, and Cloud Functions interprets this as `main.py` not existing. A minimal example that will cause the same error:
```
$ cat main.py
with open('missing.file'):
pass
def test(request):
return 'Hello World!'
```
You should check to make sure that any ... | I’ve tried to reproduce the error that you are describing by deploying a new Cloud Function without any function with the name of the CF and I got the following error:
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function failed on loading user code. Error message: File main.py is expected to contai... |
57,624,355 | I deploy a Python app to Google Cloud Functions and got this very vague error message:
```
$ gcloud functions deploy parking_photo --runtime python37 --trigger-http
Deploying function (may take a while - up to 2 minutes)...failed.
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Fun... | 2019/08/23 | [
"https://Stackoverflow.com/questions/57624355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/502780/"
] | Most likely your function is raising a `FileNotFound` error, and Cloud Functions interprets this as `main.py` not existing. A minimal example that will cause the same error:
```
$ cat main.py
with open('missing.file'):
pass
def test(request):
return 'Hello World!'
```
You should check to make sure that any ... | I want to expand on Dustins answer:
A similar error occurs with any error that happens when initializing the function.
```
OperationError: code=3, message=Function failed on loading user code. Error message: File main.py is expected to contain a function named function-test
```
The following snippet can reproduce th... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | >
> and my question how can i get any peace and navigate between nodes of this data with the most efficient way that will not take much RAM and CPU, i can't read the file line by line because i need to get any peace of data when i have to,
>
>
>
It's plain text JSON and you have no indexes, so it's impossible to p... | **Try Reducing You Bulk Data Complexity For Faster File I/O**
JSON is a great format to store data in, but it comes at the cost of needing to read the entire file to parse it.
Making your data structure simpler but more spread out across several files can allow you to read a file line-by-line which is much faster tha... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | >
> and my question how can i get any peace and navigate between nodes of this data with the most efficient way that will not take much RAM and CPU, i can't read the file line by line because i need to get any peace of data when i have to,
>
>
>
It's plain text JSON and you have no indexes, so it's impossible to p... | You may Split your arrays into chunks using
`array_chunk()` Function
>
> The `array_chunk()` function is an inbuilt function in PHP which is
> used to split an array into parts or chunks of given size depending
> upon the parameters passed to the function. The last chunk may contain
> fewer elements than the desired... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | My approach will be reading the `JSON FILE` in chunks.
>
> If these json objects have a consistent structure, you can easily detect when a json object in a file starts, and ends.
>
>
> Once you collect a whole object, you insert it into a db, then go on
> to the next one.
>
>
> There isn't much more to it. the al... | As you say correctly you won't get around with reading line per line. Using SQL as suggested just moves the problem to another environment. I would personally do it this way:
1. When a new JSON file comes in, put it in a storage, easiest would be S3 with `Storage::disk('s3')->put(...);` (<https://laravel.com/docs/7.x/... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | JSON is a great format and way better alternative to XML.
In the end JSON is almost one on one convertible to XML and back.
Big files can get bigger, so we don't want to read all the stuff in memory and we don't want to parse the whole file. I had the same issue with XXL size JSON files.
I think the issue lays not in... | You may Split your arrays into chunks using
`array_chunk()` Function
>
> The `array_chunk()` function is an inbuilt function in PHP which is
> used to split an array into parts or chunks of given size depending
> upon the parameters passed to the function. The last chunk may contain
> fewer elements than the desired... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | Your problem is basically related to the memory management performed by each specific programming language that you might use in order to access the data from a huge (storage purpose) file.
For example, when you amass the operations by using the code that you just mentioned (as below)
`$data = json_decode(file_get_co... | As you say correctly you won't get around with reading line per line. Using SQL as suggested just moves the problem to another environment. I would personally do it this way:
1. When a new JSON file comes in, put it in a storage, easiest would be S3 with `Storage::disk('s3')->put(...);` (<https://laravel.com/docs/7.x/... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | Your problem is basically related to the memory management performed by each specific programming language that you might use in order to access the data from a huge (storage purpose) file.
For example, when you amass the operations by using the code that you just mentioned (as below)
`$data = json_decode(file_get_co... | >
> and my question how can i get any peace and navigate between nodes of this data with the most efficient way that will not take much RAM and CPU, i can't read the file line by line because i need to get any peace of data when i have to,
>
>
>
It's plain text JSON and you have no indexes, so it's impossible to p... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | Your problem is basically related to the memory management performed by each specific programming language that you might use in order to access the data from a huge (storage purpose) file.
For example, when you amass the operations by using the code that you just mentioned (as below)
`$data = json_decode(file_get_co... | My approach will be reading the `JSON FILE` in chunks.
>
> If these json objects have a consistent structure, you can easily detect when a json object in a file starts, and ends.
>
>
> Once you collect a whole object, you insert it into a db, then go on
> to the next one.
>
>
> There isn't much more to it. the al... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | JSON is a great format and way better alternative to XML.
In the end JSON is almost one on one convertible to XML and back.
Big files can get bigger, so we don't want to read all the stuff in memory and we don't want to parse the whole file. I had the same issue with XXL size JSON files.
I think the issue lays not in... | My approach will be reading the `JSON FILE` in chunks.
>
> If these json objects have a consistent structure, you can easily detect when a json object in a file starts, and ends.
>
>
> Once you collect a whole object, you insert it into a db, then go on
> to the next one.
>
>
> There isn't much more to it. the al... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | Your problem is basically related to the memory management performed by each specific programming language that you might use in order to access the data from a huge (storage purpose) file.
For example, when you amass the operations by using the code that you just mentioned (as below)
`$data = json_decode(file_get_co... | You may Split your arrays into chunks using
`array_chunk()` Function
>
> The `array_chunk()` function is an inbuilt function in PHP which is
> used to split an array into parts or chunks of given size depending
> upon the parameters passed to the function. The last chunk may contain
> fewer elements than the desired... |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | Your problem is basically related to the memory management performed by each specific programming language that you might use in order to access the data from a huge (storage purpose) file.
For example, when you amass the operations by using the code that you just mentioned (as below)
`$data = json_decode(file_get_co... | **Try Reducing You Bulk Data Complexity For Faster File I/O**
JSON is a great format to store data in, but it comes at the cost of needing to read the entire file to parse it.
Making your data structure simpler but more spread out across several files can allow you to read a file line-by-line which is much faster tha... |
39,942,061 | I'm having a weird problem with a piece of python code.
The idea how it should work:
1. a barcode is entered (now hardcode for the moment);
2. barcode is looked up in local mysqldb, if not found, the barcode is looked up via api from datakick, if it's not found there either, step 3
3. i want to add the barcode to my l... | 2016/10/09 | [
"https://Stackoverflow.com/questions/39942061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6944323/"
] | `UNORDERED` essentially means that the collector is both associative (required by the spec) and commutative (not required).
Associativity allows splitting the computation into subparts and then combining them into the full result, but requires the combining step to be strictly ordered. Examine this snippet from the [... | The inner `Collector.Characteristics` class itself is fairly terse in its description, but if you spend a few seconds exploring the context you will notice that the containing [Collector](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html) interface provides additional information
>
> For colle... |
39,942,061 | I'm having a weird problem with a piece of python code.
The idea how it should work:
1. a barcode is entered (now hardcode for the moment);
2. barcode is looked up in local mysqldb, if not found, the barcode is looked up via api from datakick, if it's not found there either, step 3
3. i want to add the barcode to my l... | 2016/10/09 | [
"https://Stackoverflow.com/questions/39942061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6944323/"
] | In the absence of special pleading, stream operations must behave as if the elements are processed in the encounter order of the source. For some operations -- such as reduction with an associative operation -- one can obey this constraint and still get efficient parallel execution. For others, though, this constraint ... | The inner `Collector.Characteristics` class itself is fairly terse in its description, but if you spend a few seconds exploring the context you will notice that the containing [Collector](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html) interface provides additional information
>
> For colle... |
15,526,996 | After installing the latest [Mac OSX 64-bit Anaconda Python distribution](http://continuum.io/downloads.html), I keep getting a ValueError when trying to start the IPython Notebook.
Starting ipython works fine:
```
3-millerc-~:ipython
Python 2.7.3 |Anaconda 1.4.0 (x86_64)| (default, Feb 25 2013, 18:45:56)
Type "copy... | 2013/03/20 | [
"https://Stackoverflow.com/questions/15526996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655733/"
] | I summarize here the solution to be found on: <http://blog.lobraun.de/2009/04/11/mercurial-on-mac-os-x-valueerror-unknown-locale-utf-8/>
I added these lines to my `.bash_profile`:
```
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
```
I reloaded the profile:
```
source ~/.bash_profile
```
I then ran `ipython... | As your `LC_CTYPE` is wrong, you should find out where that wrong value is set and change it to something like `en_US.UTF-8`. |
15,526,996 | After installing the latest [Mac OSX 64-bit Anaconda Python distribution](http://continuum.io/downloads.html), I keep getting a ValueError when trying to start the IPython Notebook.
Starting ipython works fine:
```
3-millerc-~:ipython
Python 2.7.3 |Anaconda 1.4.0 (x86_64)| (default, Feb 25 2013, 18:45:56)
Type "copy... | 2013/03/20 | [
"https://Stackoverflow.com/questions/15526996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655733/"
] | I summarize here the solution to be found on: <http://blog.lobraun.de/2009/04/11/mercurial-on-mac-os-x-valueerror-unknown-locale-utf-8/>
I added these lines to my `.bash_profile`:
```
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
```
I reloaded the profile:
```
source ~/.bash_profile
```
I then ran `ipython... | This is a bug in the OS X Terminal app that only shows up in certain locales (country/language combinations). Open Terminal in /Applications/Utilities and uncheck the box “Set locale environment variables on startup”.
[](https://i.stack.imgur.com/EwOj... |
15,526,996 | After installing the latest [Mac OSX 64-bit Anaconda Python distribution](http://continuum.io/downloads.html), I keep getting a ValueError when trying to start the IPython Notebook.
Starting ipython works fine:
```
3-millerc-~:ipython
Python 2.7.3 |Anaconda 1.4.0 (x86_64)| (default, Feb 25 2013, 18:45:56)
Type "copy... | 2013/03/20 | [
"https://Stackoverflow.com/questions/15526996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655733/"
] | I summarize here the solution to be found on: <http://blog.lobraun.de/2009/04/11/mercurial-on-mac-os-x-valueerror-unknown-locale-utf-8/>
I added these lines to my `.bash_profile`:
```
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
```
I reloaded the profile:
```
source ~/.bash_profile
```
I then ran `ipython... | in iTerm going to the menu
```
Preferences -> Profiles -> Terminal -> (Environment)
```
and then unchecking
```
"Set locale variables automatically"
```
made this error go away. |
15,526,996 | After installing the latest [Mac OSX 64-bit Anaconda Python distribution](http://continuum.io/downloads.html), I keep getting a ValueError when trying to start the IPython Notebook.
Starting ipython works fine:
```
3-millerc-~:ipython
Python 2.7.3 |Anaconda 1.4.0 (x86_64)| (default, Feb 25 2013, 18:45:56)
Type "copy... | 2013/03/20 | [
"https://Stackoverflow.com/questions/15526996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655733/"
] | This is a bug in the OS X Terminal app that only shows up in certain locales (country/language combinations). Open Terminal in /Applications/Utilities and uncheck the box “Set locale environment variables on startup”.
[](https://i.stack.imgur.com/EwOj... | As your `LC_CTYPE` is wrong, you should find out where that wrong value is set and change it to something like `en_US.UTF-8`. |
15,526,996 | After installing the latest [Mac OSX 64-bit Anaconda Python distribution](http://continuum.io/downloads.html), I keep getting a ValueError when trying to start the IPython Notebook.
Starting ipython works fine:
```
3-millerc-~:ipython
Python 2.7.3 |Anaconda 1.4.0 (x86_64)| (default, Feb 25 2013, 18:45:56)
Type "copy... | 2013/03/20 | [
"https://Stackoverflow.com/questions/15526996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655733/"
] | in iTerm going to the menu
```
Preferences -> Profiles -> Terminal -> (Environment)
```
and then unchecking
```
"Set locale variables automatically"
```
made this error go away. | As your `LC_CTYPE` is wrong, you should find out where that wrong value is set and change it to something like `en_US.UTF-8`. |
15,526,996 | After installing the latest [Mac OSX 64-bit Anaconda Python distribution](http://continuum.io/downloads.html), I keep getting a ValueError when trying to start the IPython Notebook.
Starting ipython works fine:
```
3-millerc-~:ipython
Python 2.7.3 |Anaconda 1.4.0 (x86_64)| (default, Feb 25 2013, 18:45:56)
Type "copy... | 2013/03/20 | [
"https://Stackoverflow.com/questions/15526996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655733/"
] | This is a bug in the OS X Terminal app that only shows up in certain locales (country/language combinations). Open Terminal in /Applications/Utilities and uncheck the box “Set locale environment variables on startup”.
[](https://i.stack.imgur.com/EwOj... | in iTerm going to the menu
```
Preferences -> Profiles -> Terminal -> (Environment)
```
and then unchecking
```
"Set locale variables automatically"
```
made this error go away. |
26,005,454 | I am creating a fast method of generating a list of primes in the range(0, limit+1). In the function I end up removing all integers in the list named removable from the list named primes. I am looking for a fast and pythonic way of removing the integers, knowing that both lists are always sorted.
I might be wrong, but... | 2014/09/23 | [
"https://Stackoverflow.com/questions/26005454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3987360/"
] | This is quite fast and clean, it does `O(n)` set membership checks, and in amortized time it runs in `O(n)` (first line is `O(n)` amortized, second line is `O(n * 1)` amortized, because a membership check is `O(1)` amortized):
```
removable_set = set(removable)
primes = [p for p in primes if p not in removable_set]
`... | The most important thing here is to remove the quadratic behavior. You have this for two reasons.
First, calling `remove` searches the entire list for values to remove. Doing this takes linear time, and you're doing it once for each element in `removable`, so your total time is `O(NM)` (where `N` is the length of `pri... |
59,160,291 | Is there a way how to simplify this static methods in python? I'm looking to reduce typing of the arguments every time I need to use a function.
```
class Ibeam:
def __init__ (self, b1, tf1, tw, h, b2, tf2, rt, rb):
self.b1 = b1
self.tf1 = tf1
self.tw = tw
self.h = h
self.b2 = b2
self.tf2 = t... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59160291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448859/"
] | You could use good default values if such exist.
```py
def area(b1=None, tf1=None, tw=None, h=None, b2=None, tf2=None, rt=None, rb=None):
....
```
An even better solution would be to design your class in a way that it does not require so many parameters. | When having functions with many arguments it might be useful to think about "related" arguments and group them together. For example, consider a function that calculates the distance between two points. You could write a function like the following:
```
def distance(x1, y1, x2, y2):
...
return distance
print(di... |
59,160,291 | Is there a way how to simplify this static methods in python? I'm looking to reduce typing of the arguments every time I need to use a function.
```
class Ibeam:
def __init__ (self, b1, tf1, tw, h, b2, tf2, rt, rb):
self.b1 = b1
self.tf1 = tf1
self.tw = tw
self.h = h
self.b2 = b2
self.tf2 = t... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59160291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448859/"
] | I'm not sure if it's what you are looking for:
But for me it looks like you want to have a class and use the functions in it.
```
class Ibeam:
def __init__ (self, b1, tf1, tw, h, b2, tf2, rt, rb):
self.b1 = b1
self.tf1 = tf1
self.tw = tw
self.h = h
self.b2 = b2
self.tf2 = tf2
self.rt = ... | You could use good default values if such exist.
```py
def area(b1=None, tf1=None, tw=None, h=None, b2=None, tf2=None, rt=None, rb=None):
....
```
An even better solution would be to design your class in a way that it does not require so many parameters. |
59,160,291 | Is there a way how to simplify this static methods in python? I'm looking to reduce typing of the arguments every time I need to use a function.
```
class Ibeam:
def __init__ (self, b1, tf1, tw, h, b2, tf2, rt, rb):
self.b1 = b1
self.tf1 = tf1
self.tw = tw
self.h = h
self.b2 = b2
self.tf2 = t... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59160291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448859/"
] | I'm not sure if it's what you are looking for:
But for me it looks like you want to have a class and use the functions in it.
```
class Ibeam:
def __init__ (self, b1, tf1, tw, h, b2, tf2, rt, rb):
self.b1 = b1
self.tf1 = tf1
self.tw = tw
self.h = h
self.b2 = b2
self.tf2 = tf2
self.rt = ... | When having functions with many arguments it might be useful to think about "related" arguments and group them together. For example, consider a function that calculates the distance between two points. You could write a function like the following:
```
def distance(x1, y1, x2, y2):
...
return distance
print(di... |
59,493,383 | I'm currently working on a project and I am having a hard time understanding how does the Pandas UDF in PySpark works.
I have a Spark Cluster with one Master node with 8 cores and 64GB, along with two workers of 16 cores each and 112GB. My dataset is quite large and divided into seven principal partitions consisting e... | 2019/12/26 | [
"https://Stackoverflow.com/questions/59493383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932364/"
] | >
> Does Spark try to convert one whole partition at once (78M lines) ?
>
>
>
That's exactly what happens. Spark 3.0 adds support for chunked UDFs, which operate on iterators of Pandas `DataFrames` or `Series`, but if *operations on the dataset, that can only be done using Python, on a Pandas dataframe*, these mi... | To answer the general question about using a Pandas UDF on a large pyspark dataframe:
If you're getting out-of-memory errors such as
`java.lang.OutOfMemoryError : GC overhead limit exceeded` or `java.lang.OutOfMemoryError: Java heap space` and increasing memory limits hasn't worked, ensure that pyarrow is enabled. It ... |
20,317,792 | I want my interactive bash to run a program that will ultimately do things like:
echo Error: foobar >/dev/tty
and in another(python) component tries to prompt for and read a password from /dev/tty.
I want such reads and writes to fail, but not block.
Is there some way to close /dev/tty in the parent script and then... | 2013/12/01 | [
"https://Stackoverflow.com/questions/20317792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727810/"
] | You are doing a [UNION ALL](http://dev.mysql.com/doc/refman/5.0/en/union.html)
`at_tot` results are being appended to `a_tot`.
`at_prix` results are being appended to `a_tva`.
`at_pax` results are being appended to `v_tot`.
`at_vente` results are being appended to `v_tva`.
The [SQL UNION ALL](http://www.w3s... | When you use UNION , the alias that end up in the result are the one from the first select in the union. So `at_tot` (from second select of union) is replaced with a\_tot.
What you do is the same as doing:
```sql
SELECT SUM(IF(status=0,montant,0)) AS a_tot,
SUM(IF(status=0, montant * (tvaval/100),0)) AS a_tva... |
49,757,771 | So I wrote a python file creating the single topology ( just to check if custom topology works) without using any controller at first. the code goes:
```
#!/usr/bin/python
from mininet.node import CPULimitedHost, Host, Node
from mininet.node import OVSSwitch
from mininet.topo import Topo
class Single1(Topo):
"Singl... | 2018/04/10 | [
"https://Stackoverflow.com/questions/49757771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7463091/"
] | This is an older question and probably no longer of interest to the original poster, but I landed here from a mininet related search so I thought I'd provide a working example in case other folks find there way here in the future.
First, there are a number of indentation problems with the posted code, but those are si... | The hosts must be in same subnet in order to avoid routing protocols. Otherwise you need static routes |
49,757,771 | So I wrote a python file creating the single topology ( just to check if custom topology works) without using any controller at first. the code goes:
```
#!/usr/bin/python
from mininet.node import CPULimitedHost, Host, Node
from mininet.node import OVSSwitch
from mininet.topo import Topo
class Single1(Topo):
"Singl... | 2018/04/10 | [
"https://Stackoverflow.com/questions/49757771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7463091/"
] | This is an older question and probably no longer of interest to the original poster, but I landed here from a mininet related search so I thought I'd provide a working example in case other folks find there way here in the future.
First, there are a number of indentation problems with the posted code, but those are si... | It's strange but now I can ping all of a sudden..I don't know why or how..I didn't change anything. |
49,757,771 | So I wrote a python file creating the single topology ( just to check if custom topology works) without using any controller at first. the code goes:
```
#!/usr/bin/python
from mininet.node import CPULimitedHost, Host, Node
from mininet.node import OVSSwitch
from mininet.topo import Topo
class Single1(Topo):
"Singl... | 2018/04/10 | [
"https://Stackoverflow.com/questions/49757771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7463091/"
] | This is an older question and probably no longer of interest to the original poster, but I landed here from a mininet related search so I thought I'd provide a working example in case other folks find there way here in the future.
First, there are a number of indentation problems with the posted code, but those are si... | By default, Mininet emulates the switches by Open VSwitch.
And if not connected to a controller, OVS will act like a normal L2 switch with its default rules.
That's the reason you can do pingall().
However, I also get into problems that Mininet hosts can't ping each other even if they are actually connected. After a f... |
2,332,164 | I use python debugger pdb. I use emacs for python programming. I use python-mode.el. My idea is to make emacs intuitive. So I need the following help for python programs (.py)
1. Whenever I press 'F9' key, the emacs should put "import pdb; pdb.set\_trace();" statements in the current line and move the current line to ... | 2010/02/25 | [
"https://Stackoverflow.com/questions/2332164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | to do 1)
```
(defun add-py-debug ()
"add debug code and move line down"
(interactive)
(move-beginning-of-line 1)
(insert "import pdb; pdb.set_trace();\n"))
(local-set-key (kbd "<f9>") 'add-py-debug)
```
to do 2) you probably have to change the syntax highlighting of the python mode, or ... | I've found that [Xah's Elisp Tutorial](http://xahlee.info/emacs/emacs/elisp.html) is an excellent starting point in figuring out the basics of Emacs Lisp programming. [There](https://sites.google.com/site/steveyegge2/effective-emacs) [are](https://steve-yegge.blogspot.com/2008/01/emergency-elisp.html) [also](https://st... |
41,936,098 | I am trying to install the `zipline` module using `"pip install zipline"` but I get this exception:
```
IOError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/editor.pyc'` - any help would be greatly appreciated
Failed building wheel for numexpr
Running setup.py clean for numexpr
Fa... | 2017/01/30 | [
"https://Stackoverflow.com/questions/41936098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7283601/"
] | AS you are not root. You can use sudo to obtain superuser permissions:
```
sudo pip install zipline
```
Or else
**For GNU/Linux :**
On Debian-derived Linux distributions, you can acquire all the necessary binary dependencies from apt by running:
```
$ sudo apt-get install libatlas-base-dev python-dev gfortran pkg... | Avoid using `sudo` to install packages with `pip`. Use the `--user` option instead or, even better, use virtual environments.
See [this SO answer](https://stackoverflow.com/a/42021993/3577054). I think this question is a duplicate of that one. |
60,917,385 | My aim:
To count the frequency of a user entered word in a text file.(in python)
I tried this.But it gives the frequency of all the words in the file.How can i modify it to give the frequency of a word entered by the user?
```
from collections import Counter
word=input("Enter a word:")
def word_count(test6):
w... | 2020/03/29 | [
"https://Stackoverflow.com/questions/60917385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13140422/"
] | Hi I just solved the problem.
After you run
`docker build .`
run the `docker-compose build` instead of `docker-compose up`.
And then finally run `docker-compose up` | instead of
```
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system
```
you may use:
```
RUN pip install pipenv
COPY pipfile* /tmp
RUN cd /tmp && pipenv lock --requirements > requirements.txt
RUN pip install -r /tmp/requirements.txt
```
this is a snippet from [here](https://pythonspe... |
42,216,370 | Installation of python-devel fails with attached message
Configuration is as follows:
- CentOS 7.2
- Python 2.7 Installed
1. I re-ran with yum load as suggested in output and it failed with same message.
2. yum info python ==> Installed package python 2.7.5 34.el7
3. yum info python-devel ==> NOT installed. Avail... | 2017/02/14 | [
"https://Stackoverflow.com/questions/42216370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070752/"
] | From the yum documentation, here's the safest way to handle each of your 5 errors:
First remove duplicates and resolve any errors after running this:
```
package-cleanup --cleandupes
```
If the above comes with a missing package-cleanup error, then run this first:
```
yum install yum-utils
```
Then address the o... | Removed packages python-argparse and redhat-upgrade-tool.
Then did a yum install python-devel and it succeed's this time. I am thinking there is a hard dependency for those 2 packages on older python 2.6.
Sudhir Nallagangu |
42,216,370 | Installation of python-devel fails with attached message
Configuration is as follows:
- CentOS 7.2
- Python 2.7 Installed
1. I re-ran with yum load as suggested in output and it failed with same message.
2. yum info python ==> Installed package python 2.7.5 34.el7
3. yum info python-devel ==> NOT installed. Avail... | 2017/02/14 | [
"https://Stackoverflow.com/questions/42216370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070752/"
] | From the yum documentation, here's the safest way to handle each of your 5 errors:
First remove duplicates and resolve any errors after running this:
```
package-cleanup --cleandupes
```
If the above comes with a missing package-cleanup error, then run this first:
```
yum install yum-utils
```
Then address the o... | The problem is that you are on CentOS 7, but have CentOS 6 packages installed.
* python-argparse-1.2.1-2.1.el6.noarch
* redhat-upgrade-tool-1:0.7.22-3.el6.centos.noarch
Get a list of all installed el6 packages (`rpm -qa | grep el6`) and remove them or update them to their el7 equivalents. You should be able remove ar... |
46,480,621 | I upgraded my ansible to 2.4 and now I cannot manage my CentOS 5 hosts which are running python 2.4. How do I fix it?
<http://docs.ansible.com/ansible/2.4/porting_guide_2.4.html> says ansible 2.4 will not support any versions of python lower than 2.6 | 2017/09/29 | [
"https://Stackoverflow.com/questions/46480621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055115/"
] | After I upgraded to ansible 2.4 I was not able to manage hosts running python 2.6+. These were CentOS 5 hosts and this is how I fixed the problem.
First, I installed `python26` from epel repo. After enabling epel repo, `yum install python26`
Then in my hosts file, for the CentOS 5 hosts, I added `ansible_python_inter... | And what about python26-yum package? It is required to use yum module to install packages using Ansible. |
46,480,621 | I upgraded my ansible to 2.4 and now I cannot manage my CentOS 5 hosts which are running python 2.4. How do I fix it?
<http://docs.ansible.com/ansible/2.4/porting_guide_2.4.html> says ansible 2.4 will not support any versions of python lower than 2.6 | 2017/09/29 | [
"https://Stackoverflow.com/questions/46480621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055115/"
] | After I upgraded to ansible 2.4 I was not able to manage hosts running python 2.6+. These were CentOS 5 hosts and this is how I fixed the problem.
First, I installed `python26` from epel repo. After enabling epel repo, `yum install python26`
Then in my hosts file, for the CentOS 5 hosts, I added `ansible_python_inter... | My experience so far has been that anisible works (gather facts) but that some modules (in particular yum / package) do not because yum uses python 2.4.
I ended up using yum via command and shell modules (not pretty but works).
1) Before you can install python26 you need to fix the repos as CentOS5 is end of life:
( [... |
46,480,621 | I upgraded my ansible to 2.4 and now I cannot manage my CentOS 5 hosts which are running python 2.4. How do I fix it?
<http://docs.ansible.com/ansible/2.4/porting_guide_2.4.html> says ansible 2.4 will not support any versions of python lower than 2.6 | 2017/09/29 | [
"https://Stackoverflow.com/questions/46480621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055115/"
] | And what about python26-yum package? It is required to use yum module to install packages using Ansible. | My experience so far has been that anisible works (gather facts) but that some modules (in particular yum / package) do not because yum uses python 2.4.
I ended up using yum via command and shell modules (not pretty but works).
1) Before you can install python26 you need to fix the repos as CentOS5 is end of life:
( [... |
57,588,744 | How do you quit or halt a python program without the error messages showing?
I have tried quit(), exit(), systemexit(), raise SystemExit, and others but they all seem to raise an error message saying the program has been halted. How do I get rid of this? | 2019/08/21 | [
"https://Stackoverflow.com/questions/57588744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11939397/"
] | you can structure your program within a function then `return` when you wish to halt/end the program
ie
```
def foo():
# your program here
if we_want_to_halt:
return
if __name__ == "__main__":
foo()
``` | You would need to handle the exit in your python program.
For example:
```
def main():
x = raw_input("Enter a value: ")
if x == "a value":
print("its alright")
else:
print("exit")
exit(0)
```
Note: This works in python 2 because raw\_input is included by default there but the con... |
57,588,744 | How do you quit or halt a python program without the error messages showing?
I have tried quit(), exit(), systemexit(), raise SystemExit, and others but they all seem to raise an error message saying the program has been halted. How do I get rid of this? | 2019/08/21 | [
"https://Stackoverflow.com/questions/57588744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11939397/"
] | You are trying too hard. Write your program using the regular boilerplate:
```
def main():
# your real code goes here
return
if __name__ == "__main__":
main()
```
and just return from function `main`. That will get you back to the `if`-clause, and execution will fall out the bottom of the program.
You ... | You would need to handle the exit in your python program.
For example:
```
def main():
x = raw_input("Enter a value: ")
if x == "a value":
print("its alright")
else:
print("exit")
exit(0)
```
Note: This works in python 2 because raw\_input is included by default there but the con... |
57,588,744 | How do you quit or halt a python program without the error messages showing?
I have tried quit(), exit(), systemexit(), raise SystemExit, and others but they all seem to raise an error message saying the program has been halted. How do I get rid of this? | 2019/08/21 | [
"https://Stackoverflow.com/questions/57588744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11939397/"
] | you can structure your program within a function then `return` when you wish to halt/end the program
ie
```
def foo():
# your program here
if we_want_to_halt:
return
if __name__ == "__main__":
foo()
``` | you can try the following code to terminate the program.
```
import sys
sys.exit()
``` |
57,588,744 | How do you quit or halt a python program without the error messages showing?
I have tried quit(), exit(), systemexit(), raise SystemExit, and others but they all seem to raise an error message saying the program has been halted. How do I get rid of this? | 2019/08/21 | [
"https://Stackoverflow.com/questions/57588744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11939397/"
] | You are trying too hard. Write your program using the regular boilerplate:
```
def main():
# your real code goes here
return
if __name__ == "__main__":
main()
```
and just return from function `main`. That will get you back to the `if`-clause, and execution will fall out the bottom of the program.
You ... | you can try the following code to terminate the program.
```
import sys
sys.exit()
``` |
57,588,744 | How do you quit or halt a python program without the error messages showing?
I have tried quit(), exit(), systemexit(), raise SystemExit, and others but they all seem to raise an error message saying the program has been halted. How do I get rid of this? | 2019/08/21 | [
"https://Stackoverflow.com/questions/57588744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11939397/"
] | You are trying too hard. Write your program using the regular boilerplate:
```
def main():
# your real code goes here
return
if __name__ == "__main__":
main()
```
and just return from function `main`. That will get you back to the `if`-clause, and execution will fall out the bottom of the program.
You ... | you can structure your program within a function then `return` when you wish to halt/end the program
ie
```
def foo():
# your program here
if we_want_to_halt:
return
if __name__ == "__main__":
foo()
``` |
60,327,453 | I am new to tensorflow and Convolutional Neural Networks, and I would like to build an AI that learns to find the mode of floating point numbers. But whenever I try to run the code, I run into some errors.
Here is my code so far:
```
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers imp... | 2020/02/20 | [
"https://Stackoverflow.com/questions/60327453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Finally **SOLVED**:
**HTML:**
```
<mat-form-field>
<mat-label>Course</mat-label>
<mat-select
[formControl]="subjectControl"
[attr.data-tag]="this.subjectControl.value"
required
>
<mat-option>-- None --</mat-option>
<mat-optgroup *ngFor="l... | Your code looks correct to me. I tried adding it to an existing stackblitz example, and it showed up in the HTML. Maybe it will help to figure it out:
<https://stackblitz.com/edit/angular-material-select-compare-with?embed=1&file=app/app.html>
```
<mat-option class="mat-option ng-star-inserted" data-tag="Three" role=... |
51,878,354 | Is there a built-in function that works like zip(), but fills the results so that the length of the resulting list is the length of the longest input and fills the list **from the left** with e.g. `None`?
There is already an [answer](https://stackoverflow.com/a/1277311/2648551) using [zip\_longest](https://docs.python... | 2018/08/16 | [
"https://Stackoverflow.com/questions/51878354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648551/"
] | Use **`zip_longest`** but reverse lists.
**Example**:
```
from itertools import zip_longest
header = ["title", "firstname", "lastname"]
person_1 = ["Dr.", "Joe", "Doe"]
person_2 = ["Mary", "Poppins"]
person_3 = ["Smith"]
print(dict(zip_longest(reversed(header), reversed(person_2))))
# {'lastname': 'Poppins', 'first... | Simply use `zip_longest` and read the arguments in the reverse direction:
```
In [20]: dict(zip_longest(header[::-1], person_1[::-1]))
Out[20]: {'lastname': 'Doe', 'firstname': 'Joe', 'title': 'Dr.'}
In [21]: dict(zip_longest(header[::-1], person_2[::-1]))
Out[21]: {'lastname': 'Poppins', 'firstname': 'Mary', 'title'... |
51,878,354 | Is there a built-in function that works like zip(), but fills the results so that the length of the resulting list is the length of the longest input and fills the list **from the left** with e.g. `None`?
There is already an [answer](https://stackoverflow.com/a/1277311/2648551) using [zip\_longest](https://docs.python... | 2018/08/16 | [
"https://Stackoverflow.com/questions/51878354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648551/"
] | Use **`zip_longest`** but reverse lists.
**Example**:
```
from itertools import zip_longest
header = ["title", "firstname", "lastname"]
person_1 = ["Dr.", "Joe", "Doe"]
person_2 = ["Mary", "Poppins"]
person_3 = ["Smith"]
print(dict(zip_longest(reversed(header), reversed(person_2))))
# {'lastname': 'Poppins', 'first... | ```
def magic_zip(*lists):
max_len = max(map(len, lists))
return zip(*([None] * (max_len - len(l)) + l for l in lists))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.