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
|
|---|---|---|---|---|---|
43,201,211
|
I hope you can help.
I am currently writing a code to extract historical data for various games on SteamSpy.com. After backing the project on Patreon, you get to view the long history of various metrics for each game. I would like to make comparisons between multiple games, and as such I want to extract the data.
I know from earlier that BeautifulSoup can be very helpful for this task, unfortunately I can not use it in the way I have done earlier. I will describe it in detail below, but the main problem is, that all the relevant data is included inside ONE single tag.
* Example: Dota2
* URL: <http://steamspy.com/app/570>
* Source code: [*view-source:http://steamspy.com/app/570*](http://view-source:http://steamspy.com/app/570)
**Source code**
Here is the part of the source code, that I am interested in (it is obviously far longer when logged in, and you have access to the historical data).
```
<div class="tab-content no-padding bg-transparent">
<div class="tab-pane active relative" id="tab-sales">
<h2>Owners data:</h2>
<div id="nvd3-sales" class="line-chart" data-area-color="master" data-points="false" data-stroke-width="4">
<svg></svg>
</div>
<script>
var data2sales= [
{
"key": "Owners",
"bar": true,
"values": [
[1489363200000, 97073321, ""],
[1489449600000, 97138657, ""],
[1489536000000, 97126694, ""],
[1489622400000, 98535521, ""],
[1489708800000, 98482905, ""],
[1489795200000, 98496091, ""],
[1489881600000, 98627987, "#2B6A94"],
[1489968000000, 98798351, ""],
[1490054400000, 98936652, ""],
[1490140800000, 99025494, ""],
[1490227200000, 99208644, ""],
[1490313600000, 99163634, ""],
[1490400000000, 99097059, ""],
[1490486400000, 98986347, "#2B6A94"],
[1490572800000, 99005343, ""],
[1490659200000, 99023673, ""],
[1490745600000, 99084059, ""],
[1490832000000, 98988641, ""],
[1490918400000, 99120523, ""],
[1491004800000, 99058884, ""],
[1491091200000, 99206546, "#2B6A94"],
[1491177600000, 99155567, ""] ]},{
"key" : "Price",
"values" : [
[1489363200000,, "#ffffff" ],
[1489449600000,, "#ffffff" ],
[1489536000000,, "#ffffff" ],
[1489622400000,, "#ffffff" ],
[1489708800000,, "#ffffff" ],
[1489795200000,, "#ffffff" ],
[1489881600000,, "#ffffff" ],
[1489968000000,, "#ffffff" ],
[1490054400000,, "#ffffff" ],
[1490140800000,, "#ffffff" ],
[1490227200000,, "#ffffff" ],
[1490313600000,, "#ffffff" ],
[1490400000000,, "#ffffff" ],
[1490486400000,, "#ffffff" ],
[1490572800000,, "#ffffff" ],
[1490659200000,, "#ffffff" ],
[1490745600000,, "#ffffff" ],
[1490832000000,, "#ffffff" ],
[1490918400000,, "#ffffff" ],
[1491004800000,, "#ffffff" ],
[1491091200000,, "#ffffff" ],
[1491177600000,, "#ffffff" ]] } ];
</script>
</div>
```
My ultimate goal is to extract the three values for each row in the code below, inside the `<script>` tag, and only the values that begin in the row after `"values": [`.
Below is the part of my code that takes care of collecting the data, I have tried multiple solutions, but all I have found only suggests that I iterate over the tags in the "soup", and collect the data inside, however, here all my data is placed inside one SINGLE tag. I hope you can help out.
Please also tell me, if I can provide more information, that could be useful.
Cheers!
**Code**
My code (I run it inside a session, since I have to log in before collecting the data, I have removed the log in part):
```
### START ###
import requests
from requests import session
import bs4
from bs4 import BeautifulSoup
baseURL = "http://steamspy.com/app/"
appNum = "387990"
fullURL = baseURL + appNum
# log-in information to access the full historical data.
payload = {
'username': 'XXXX',
'password': 'XXXX',
'doLogin': 'doLogin'
}
with requests.Session() as s:
#log in on steamSpy
# q = s.post('https://steamspy.com/login.php', data=payload)
# print(q.status_code)
# print(q.history)
# print(q.url)
#navigate to the desired webpage
r = s.get(fullURL)
soup = bs4.BeautifulSoup(r.text, "lxml")
ownr = soup.find("div", {"id": "tab-sales"}).find("script").get_text()
print(ownr)
```
**Output**
And here is my output, which obviously is similar to what is inside the tag in the source code:
```
C:\Python35\python.exe "C:/Users/nohgjk/Dropbox/Gaming/Project steamSpy/Python/steamSpy - Test/steamSpySoup2.py"
var data2sales= [
{
"key": "Owners",
"bar": true,
"values": [
[1489363200000, 549045, ""],
[1489449600000, 550812, ""],
[1489536000000, 550773, ""],
[1489622400000, 544180, ""],
[1489708800000, 532284, ""],
[1489795200000, 546592, ""],
[1489881600000, 545925, "#2B6A94"],
[1489968000000, 550721, ""],
[1490054400000, 539253, ""],
[1490140800000, 536258, ""],
[1490227200000, 544210, ""],
[1490313600000, 560977, ""],
[1490400000000, 562907, ""],
[1490486400000, 554817, "#2B6A94"],
[1490572800000, 552973, ""],
[1490659200000, 551875, ""],
[1490745600000, 554853, ""],
[1490832000000, 553309, ""],
[1490918400000, 551987, ""],
[1491004800000, 551671, ""],
[1491091200000, 541915, "#2B6A94"],
[1491177600000, 541280, ""] ]},{
"key" : "Price",
"values" : [
[1489363200000, 19.99, ""],
[1489449600000, 19.99, ""],
[1489536000000, 19.99, ""],
[1489622400000, 19.99, ""],
[1489708800000, 19.99, ""],
[1489795200000, 19.99, ""],
[1489881600000, 19.99, "#2B6A94"],
[1489968000000, 19.99, ""],
[1490054400000, 19.99, ""],
[1490140800000, 19.99, ""],
[1490227200000, 19.99, ""],
[1490313600000, 19.99, ""],
[1490400000000, 19.99, ""],
[1490486400000, 19.99, "#2B6A94"],
[1490572800000, 19.99, ""],
[1490659200000, 19.99, ""],
[1490745600000, 19.99, ""],
[1490832000000, 19.99, ""],
[1490918400000, 19.99, ""],
[1491004800000, 19.99, ""],
[1491091200000, 19.99, "#2B6A94"],
[1491177600000, 19.99, ""]] } ];
Process finished with exit code 0
```
|
2017/04/04
|
[
"https://Stackoverflow.com/questions/43201211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3494191/"
] |
You could try
```
SELECT
REPLACE(CONVERT(VARCHAR(11), Date, 6), ' ', '/') + ' 12:00:00 AM' AS Date
FROM
TableFiles
```
|
just an idea: select convert(**date**, yourvalue ) + 0.5) .... should use only date part and add an half day?
|
65,160,481
|
I'm trying to install neovim on Windows and import my previous init.vim file.
I've previously defined my snippets in ultisnips.
I'm using windows and ahve tested this in another version of windows and it works, however, at the moment when I run
```
:checkhealth
```
I get the following error:
```
## Python 3 provider (optional)
30 - WARNING: No Python executable found that can `import neovim`. Using the first available executable for diagnostics.
31 - ERROR: Python provider error:
32 - ADVICE:
33 - provider/pythonx: Could not load Python 3:
34 python3 not found in search path or not executable.
35 python3.7 not found in search path or not executable.
36 python3.6 not found in search path or not executable.
37 python3.5 not found in search path or not executable.
38 python3.4 not found in search path or not executable.
39 python3.3 not found in search path or not executable.
40 python not found in search path or not executable.
41 - INFO: Executable: Not found
```
But I do have python 3.7 installed. I can run python in cmd / powershell, and I can import neovim python module without any issues. Does someone know how to get neovim to pick up python?
|
2020/12/05
|
[
"https://Stackoverflow.com/questions/65160481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427492/"
] |
**Make sure you have Python3 installed, the following answer also works with Python2.**
Check for help:
```
:help provider-python
```
Go to the `PYTHON QUICKSTART` and you will see one of this two options:
* For Python 2 plugins:
* For Python 3 plugins:
*Because you're problem is with python 3 follow this steps that are mentioned in* `For Python 3 plugins:`
```
1. Make sure Python 3.4+ is available in your $PATH.
2. Install the module (try "python" if "python3" is missing): >
python3 -m pip install --user --upgrade pynvim
```
This should fix the problem, if it persist then make sure the right path is being used, go to `~/.vimrc` and add the following:
For python3:
```
let g:python3_host_prog = '/path/to/python3'
```
For Python2:
```
let g:python_host_prog = '/path/to/python'
```
Note: I found this in `PYTHON QUICKSTART` if you continue reading you will find it.
To know the location of python use:
-----------------------------------
* For Linux and Mac
```sh
which python3
```
* For [windows](https://datatofish.com/locate-python-windows/)
Use `:checkhealth` again and it should output the following:
```
## Python 3 provider (optional)
- INFO: Using: g:python3_host_prog = "/usr/local/bin/python3"
- INFO: Executable: /usr/local/bin/python3
- INFO: Python version: 3.9.1
- INFO: pynvim version: 0.4.2
- OK: Latest pynvim is installed.
```
|
It seems, that neovim is confusing python 2 and python 3 somehow. For me it worked just to have renamed python executable in PATH of python 2, that is python.exe -> python2.exe, and now it seems to work fine. However it is maybe not the perfect solution.
|
65,160,481
|
I'm trying to install neovim on Windows and import my previous init.vim file.
I've previously defined my snippets in ultisnips.
I'm using windows and ahve tested this in another version of windows and it works, however, at the moment when I run
```
:checkhealth
```
I get the following error:
```
## Python 3 provider (optional)
30 - WARNING: No Python executable found that can `import neovim`. Using the first available executable for diagnostics.
31 - ERROR: Python provider error:
32 - ADVICE:
33 - provider/pythonx: Could not load Python 3:
34 python3 not found in search path or not executable.
35 python3.7 not found in search path or not executable.
36 python3.6 not found in search path or not executable.
37 python3.5 not found in search path or not executable.
38 python3.4 not found in search path or not executable.
39 python3.3 not found in search path or not executable.
40 python not found in search path or not executable.
41 - INFO: Executable: Not found
```
But I do have python 3.7 installed. I can run python in cmd / powershell, and I can import neovim python module without any issues. Does someone know how to get neovim to pick up python?
|
2020/12/05
|
[
"https://Stackoverflow.com/questions/65160481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427492/"
] |
It seems, that neovim is confusing python 2 and python 3 somehow. For me it worked just to have renamed python executable in PATH of python 2, that is python.exe -> python2.exe, and now it seems to work fine. However it is maybe not the perfect solution.
|
1. Locate the path to the python3 executable using [one of these methods](https://datatofish.com/locate-python-windows/). Copy the path. For me, it was *C:\Users\money\AppData\Local\Programs\Python\Python310*.
2. Then, add this directory to your PATH variable. Search for "View advanced system settings" > "Environment Variables" > "System Variables" > "Path" > "Edit" > "New" and paste the directory there , save and exit.
3. You should be able run python commands from the terminal now.
4. Install the neovim python module by doing `pip3 install pynvim` in the terminal.
Try `:checkhealth provider` again. It should work.
|
65,160,481
|
I'm trying to install neovim on Windows and import my previous init.vim file.
I've previously defined my snippets in ultisnips.
I'm using windows and ahve tested this in another version of windows and it works, however, at the moment when I run
```
:checkhealth
```
I get the following error:
```
## Python 3 provider (optional)
30 - WARNING: No Python executable found that can `import neovim`. Using the first available executable for diagnostics.
31 - ERROR: Python provider error:
32 - ADVICE:
33 - provider/pythonx: Could not load Python 3:
34 python3 not found in search path or not executable.
35 python3.7 not found in search path or not executable.
36 python3.6 not found in search path or not executable.
37 python3.5 not found in search path or not executable.
38 python3.4 not found in search path or not executable.
39 python3.3 not found in search path or not executable.
40 python not found in search path or not executable.
41 - INFO: Executable: Not found
```
But I do have python 3.7 installed. I can run python in cmd / powershell, and I can import neovim python module without any issues. Does someone know how to get neovim to pick up python?
|
2020/12/05
|
[
"https://Stackoverflow.com/questions/65160481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427492/"
] |
**Make sure you have Python3 installed, the following answer also works with Python2.**
Check for help:
```
:help provider-python
```
Go to the `PYTHON QUICKSTART` and you will see one of this two options:
* For Python 2 plugins:
* For Python 3 plugins:
*Because you're problem is with python 3 follow this steps that are mentioned in* `For Python 3 plugins:`
```
1. Make sure Python 3.4+ is available in your $PATH.
2. Install the module (try "python" if "python3" is missing): >
python3 -m pip install --user --upgrade pynvim
```
This should fix the problem, if it persist then make sure the right path is being used, go to `~/.vimrc` and add the following:
For python3:
```
let g:python3_host_prog = '/path/to/python3'
```
For Python2:
```
let g:python_host_prog = '/path/to/python'
```
Note: I found this in `PYTHON QUICKSTART` if you continue reading you will find it.
To know the location of python use:
-----------------------------------
* For Linux and Mac
```sh
which python3
```
* For [windows](https://datatofish.com/locate-python-windows/)
Use `:checkhealth` again and it should output the following:
```
## Python 3 provider (optional)
- INFO: Using: g:python3_host_prog = "/usr/local/bin/python3"
- INFO: Executable: /usr/local/bin/python3
- INFO: Python version: 3.9.1
- INFO: pynvim version: 0.4.2
- OK: Latest pynvim is installed.
```
|
1. Locate the path to the python3 executable using [one of these methods](https://datatofish.com/locate-python-windows/). Copy the path. For me, it was *C:\Users\money\AppData\Local\Programs\Python\Python310*.
2. Then, add this directory to your PATH variable. Search for "View advanced system settings" > "Environment Variables" > "System Variables" > "Path" > "Edit" > "New" and paste the directory there , save and exit.
3. You should be able run python commands from the terminal now.
4. Install the neovim python module by doing `pip3 install pynvim` in the terminal.
Try `:checkhealth provider` again. It should work.
|
65,160,481
|
I'm trying to install neovim on Windows and import my previous init.vim file.
I've previously defined my snippets in ultisnips.
I'm using windows and ahve tested this in another version of windows and it works, however, at the moment when I run
```
:checkhealth
```
I get the following error:
```
## Python 3 provider (optional)
30 - WARNING: No Python executable found that can `import neovim`. Using the first available executable for diagnostics.
31 - ERROR: Python provider error:
32 - ADVICE:
33 - provider/pythonx: Could not load Python 3:
34 python3 not found in search path or not executable.
35 python3.7 not found in search path or not executable.
36 python3.6 not found in search path or not executable.
37 python3.5 not found in search path or not executable.
38 python3.4 not found in search path or not executable.
39 python3.3 not found in search path or not executable.
40 python not found in search path or not executable.
41 - INFO: Executable: Not found
```
But I do have python 3.7 installed. I can run python in cmd / powershell, and I can import neovim python module without any issues. Does someone know how to get neovim to pick up python?
|
2020/12/05
|
[
"https://Stackoverflow.com/questions/65160481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427492/"
] |
**Make sure you have Python3 installed, the following answer also works with Python2.**
Check for help:
```
:help provider-python
```
Go to the `PYTHON QUICKSTART` and you will see one of this two options:
* For Python 2 plugins:
* For Python 3 plugins:
*Because you're problem is with python 3 follow this steps that are mentioned in* `For Python 3 plugins:`
```
1. Make sure Python 3.4+ is available in your $PATH.
2. Install the module (try "python" if "python3" is missing): >
python3 -m pip install --user --upgrade pynvim
```
This should fix the problem, if it persist then make sure the right path is being used, go to `~/.vimrc` and add the following:
For python3:
```
let g:python3_host_prog = '/path/to/python3'
```
For Python2:
```
let g:python_host_prog = '/path/to/python'
```
Note: I found this in `PYTHON QUICKSTART` if you continue reading you will find it.
To know the location of python use:
-----------------------------------
* For Linux and Mac
```sh
which python3
```
* For [windows](https://datatofish.com/locate-python-windows/)
Use `:checkhealth` again and it should output the following:
```
## Python 3 provider (optional)
- INFO: Using: g:python3_host_prog = "/usr/local/bin/python3"
- INFO: Executable: /usr/local/bin/python3
- INFO: Python version: 3.9.1
- INFO: pynvim version: 0.4.2
- OK: Latest pynvim is installed.
```
|
I just solved this problem. So let me say what I did.
In the beginning, I used the `python3.8.8`, which will create the same issues. I tried to `pip install neovim` and failed.
Then I replace the `python3.8.8` with `python3.8.1`. Everything is OK~
So change the version of Python?
|
65,160,481
|
I'm trying to install neovim on Windows and import my previous init.vim file.
I've previously defined my snippets in ultisnips.
I'm using windows and ahve tested this in another version of windows and it works, however, at the moment when I run
```
:checkhealth
```
I get the following error:
```
## Python 3 provider (optional)
30 - WARNING: No Python executable found that can `import neovim`. Using the first available executable for diagnostics.
31 - ERROR: Python provider error:
32 - ADVICE:
33 - provider/pythonx: Could not load Python 3:
34 python3 not found in search path or not executable.
35 python3.7 not found in search path or not executable.
36 python3.6 not found in search path or not executable.
37 python3.5 not found in search path or not executable.
38 python3.4 not found in search path or not executable.
39 python3.3 not found in search path or not executable.
40 python not found in search path or not executable.
41 - INFO: Executable: Not found
```
But I do have python 3.7 installed. I can run python in cmd / powershell, and I can import neovim python module without any issues. Does someone know how to get neovim to pick up python?
|
2020/12/05
|
[
"https://Stackoverflow.com/questions/65160481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427492/"
] |
I just solved this problem. So let me say what I did.
In the beginning, I used the `python3.8.8`, which will create the same issues. I tried to `pip install neovim` and failed.
Then I replace the `python3.8.8` with `python3.8.1`. Everything is OK~
So change the version of Python?
|
1. Locate the path to the python3 executable using [one of these methods](https://datatofish.com/locate-python-windows/). Copy the path. For me, it was *C:\Users\money\AppData\Local\Programs\Python\Python310*.
2. Then, add this directory to your PATH variable. Search for "View advanced system settings" > "Environment Variables" > "System Variables" > "Path" > "Edit" > "New" and paste the directory there , save and exit.
3. You should be able run python commands from the terminal now.
4. Install the neovim python module by doing `pip3 install pynvim` in the terminal.
Try `:checkhealth provider` again. It should work.
|
69,700,550
|
Shown below is the code from my launch.json file for my Flask application. I have various environment variables defined in the `"env": {}` portion. However, when I run my Flask application from the run.py script, it doesn't seem to recognize the variables. Although the `"FLASK_DEBUG"` is set to `"1"`, the application still runs on `**Debug mode: off**`.
Does anyone know why?
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Flask",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "run.py",
"FLASK_ENV": "development",
"FLASK_DEBUG": "1",
"EMAIL_USER": "farmgo.project.21@gmail.com",
"EMAIL_PASS": "password",
},
"args": [
"run",
//"--no-debugger"
],
"jinja": true,
}
],
}
```
If I set:
```
if __name__ == '__main__':
app.run(debug=True)
```
then the app does run in Debug mode. However, I still cannot get the other environment variables:
```
>>> import os
>>> print(os.environ.get('FLASK_DEBUG'))
None
```
|
2021/10/24
|
[
"https://Stackoverflow.com/questions/69700550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16425143/"
] |
This is very inefficient\*, but it meets your requirements:
```ml
let transpose (matrix : List<List<_>>) =
[
if matrix.Length > 0 then
assert(matrix |> List.distinctBy List.length |> List.length = 1)
for i = 0 to matrix.[0].Length - 1 do
yield [
for list in matrix do
yield list.[i]
]
]
```
Example:
```ml
let matrix = [[1; 2; 3]; [4; 5; 6]; [7; 8; 9]; [10; 11; 12]]
transpose matrix |> printfn "%A" // [[1; 4; 7; 10]; [2; 5; 8; 11]; [3; 6; 9; 12]]
```
\* O(n3) where n is the length of a square matrix.
|
For better performance, you can convert the list of list to an Array2D, and then create your transposed list from the Array2D.
```
let transpose' xss =
let xss = array2D xss
let dimx = Array2D.length1 xss - 1
let dimy = Array2D.length2 xss - 1
[ for y=0 to dimy do [
for x=0 to dimx do
yield xss.[x,y]
]
]
```
For non-learning purpose, you should use the built-int `List.transpose`
```
List.transpose lst
```
|
64,768,621
|
Hello I am new into python . practicing web scraping with some demo sites .
I am trying to scrape this website <http://books.toscrape.com/> and want to extract
1. href
2. name/title
3. start rating/star-rating
4. price/price\_color
5. in-stock availbility/instock availability
i written a basic code which goes to each book level.
but after that i am clueless as how i can extract those information.
```
import requests
from csv import reader,writer
from bs4 import BeautifulSoup
base_url= "http://books.toscrape.com/"
r = requests.get(base_url)
htmlContent = r.content
soup = BeautifulSoup(htmlContent,'html.parser')
for article in soup.find_all('article'):
```
|
2020/11/10
|
[
"https://Stackoverflow.com/questions/64768621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13597511/"
] |
It's for folders that are added in you .proj file, but doesn't exist on a hard drive.
My guess is that you are using some kind of version control (git or svn or else) and someone made change to project structure (added folder) but forgot to add that folder to version control system.
|
For me red cross appeared on all projects because while cloning component from git/stash, most of the files and folder path were too long and are not acceptable.
Tried cloning at different path which is smaller and red crosses disappeared.
|
17,055,642
|
I was wondering if there is already available a library which does something similar to scrapely
<https://github.com/scrapy/scrapely>
WHat it does is that you give an example url and then you give the data you want to extract from that html..
```
url1 = 'http://pypi.python.org/pypi/w3lib/1.1'
data = {'name': 'w3lib 1.1', 'author': 'Scrapy project', 'description': 'Library of web-related functions'}
```
and then you initiate this rule by simply:
```
s.train(url1, data)
```
Now, I can extract the same data from different url...
But is there any library which does the same but for raw text...
For example:
```
raw_text = "|foo|bar,name = how cool"
```
And then I want to extract "bar" from this.
I know, I can write a simple regex rules and get done with this.. but is there any library available which solves this as an instance based learning problem..
i.e rather than specifying a regex rule and then passing data over it..
instead I specify an instance and what I would like to extract and it automatically builds rule ?
Hope that I am making some sense.
|
2013/06/11
|
[
"https://Stackoverflow.com/questions/17055642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] |
The likeliest problem is that you're using backslashes in your file name, so they get interpreted as control characters. The IO error is because the filename is mangled.
try
```
stockPath = "C:\\Users\\Dryan\\Desktop\\table.csv" # double slashes to get single slashes in the string
```
or
```
stockPath = "C:/Users/Dryan/Desktop/table.csv" # it's more python-y to always use right slashes.
```
|
As joojaa said, try to avoid using backslashes when you can. I try to always convert any incoming path to a forward slashes version, and just before outputting it I normalize it using os.path.normpath.
```
clean_path = any_path_i_have_to_deal_with.replace("\\", "/")
# do stuff with it
# (concat, XML save, assign to a node attribute...)
print os.path.normpath(clean_path) # back to the OS version
```
|
68,728,817
|
I need some help with respect to changing a dataframe in python.
```
NODE SIGNAL-STRENGTH LOCATION
0 A 76 1
1 A 78 1
2 A 78 1
3 A 79 1
4 A 79 2
5 A 70 2
.
.
.
95 E 111 4
96 E 123 5
97 E 154 5
98 E 113 5
99 E 234 5
```
The above data is a dataframe where there are 5 nodes each with 20 data points which are 5 locations that each send 4 signal strength values to each node. For each node I have 4 signal strength values from a location and the location itself. The location is the label and the signal strength changes for different nodes for different nodes.
I wish to have only 20 rows, with 6 columns. One of the columns will be location. the other five must be the nodes and have the signal strength for that location.
The location order does not change after 20 rows. This means that the 20 locations are in order after the end of each node.
I tried to do groupby but I don't know how to change it to rows.
Final dataframe must be as
```
LOCATION NODEA_SIGNAL NODE_B_SIGNAL NODE_C_SIGNAL NODE_D_SIGNAL NODE_E_SIGNAL
0 1 76 34 55 44 64
1 1 77 33 55 45 65
2 1 77 33 54 43 66
3 1 78 31 53 45 67
4 2 34 42 94 85 12
5 2 37 44 98 82 13
6 2 36 45 97 83 14
7 2 35 44 96 86 16
8 3 23 16 47 65 85
.
.
.
15 4 16 24 64 95 75
16 5 46 74 15 54 34
17 5 47 73 15 55 35
18 5 47 73 14 53 36
19 5 48 71 13 55 37
```
|
2021/08/10
|
[
"https://Stackoverflow.com/questions/68728817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14548962/"
] |
You can do it with a `FULL` join of the tables:
```
SELECT COALESCE(a.name, b.name) AS name,
CASE WHEN a.name IS NULL THEN false ELSE true END AS is_in_A,
CASE WHEN b.name IS NULL THEN false ELSE true END AS is_in_B
FROM a FULL OUTER JOIN b
ON b.name = a.name
```
If your database does not support boolean values like `true` and `false`, change to `1` and `0` or string literals `'true'` and `'false'`.
See a simplified [demo](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=702094c97af48761ab23e9aecbffa2e4).
|
You can use `union all` and aggregation:
```
select name, sum(in_a), sum(in_b)
from ((select name, 1 as in_a, 0 as in_b
from a
) union all
(select name, 0, 1
from b
)
) ab
group by name;
```
|
63,156,890
|
I'm really new to coding and after learning all the syntax for HTML and CSS I figured I'd move on to python but I'd actually learn how to use it to become a python programmer instead of just learning the syntax
So as one of my first small projects I figured id make a small piece of code that'd ask the user for some items they're buying then add the price of those items together to give them the price of their shopping list essentially, However, I couldn't get it working (p.s I'm really new so my code will probably look dumb)
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into
price = []
while items != 'nothing':
input('Another item?: ')
if choice in items:
the_choice = price[choice]
else:
print("Uh oh, I don't know about that item")
```
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63156890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14016707/"
] |
I recommend searching about the python basics and loops
This will make it
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
price = 0
while True:
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
if choice == 'nothing':
break
if choice in items.keys():
price += items[choice]
else:
print("Uh oh, I don't know about that item")
print('your result', price )
```
|
Is this what you want?
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
price = 0
while True:
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
if choice in items:
price += items[choice]
elif choice == 'nothing':
break
else:
print("Uh oh, I don't know about that item")
print('Your total price is: ',price)
```
|
63,156,890
|
I'm really new to coding and after learning all the syntax for HTML and CSS I figured I'd move on to python but I'd actually learn how to use it to become a python programmer instead of just learning the syntax
So as one of my first small projects I figured id make a small piece of code that'd ask the user for some items they're buying then add the price of those items together to give them the price of their shopping list essentially, However, I couldn't get it working (p.s I'm really new so my code will probably look dumb)
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into
price = []
while items != 'nothing':
input('Another item?: ')
if choice in items:
the_choice = price[choice]
else:
print("Uh oh, I don't know about that item")
```
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63156890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14016707/"
] |
I recommend searching about the python basics and loops
This will make it
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
price = 0
while True:
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
if choice == 'nothing':
break
if choice in items.keys():
price += items[choice]
else:
print("Uh oh, I don't know about that item")
print('your result', price )
```
|
Code:
=====
```
# items and their prices
items = {
'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
users_items = [] # The list of purchased items
choice = None
while choice != 'nothing':
choice = input("Select your item(type 'nothing' to make it stop) : ") # Asking for the item
if choice in items.keys():
users_items.append((choice, items[choice]))
else:
print('Item not in item\'s list')
final_cost = sum(val for item, val in users_items)
final_items = [item for item, val in users_items]
print(f'Final sum of users items is: {final_cost}. Items {final_items}')
```
Output:
=======
```
Select your item(type 'nothing' to make it stop)
: banana
Select your item(type 'nothing' to make it stop)
: nothing
Item not in item's list
Final sum of users items is: 3. Items ['banana']
```
Explanation
===========
`users_items` is a list. When user types his choice, then program appends to list a tuple(item, price). After `nothing` the loop ends and results are printed. `final_cost` is the **the sum of 2nd elements of every tuple in the** `users_items`. `final_items` is **the list of 1st elements of every tuple in the** `users_items`.
|
63,156,890
|
I'm really new to coding and after learning all the syntax for HTML and CSS I figured I'd move on to python but I'd actually learn how to use it to become a python programmer instead of just learning the syntax
So as one of my first small projects I figured id make a small piece of code that'd ask the user for some items they're buying then add the price of those items together to give them the price of their shopping list essentially, However, I couldn't get it working (p.s I'm really new so my code will probably look dumb)
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into
price = []
while items != 'nothing':
input('Another item?: ')
if choice in items:
the_choice = price[choice]
else:
print("Uh oh, I don't know about that item")
```
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63156890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14016707/"
] |
I recommend searching about the python basics and loops
This will make it
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
price = 0
while True:
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
if choice == 'nothing':
break
if choice in items.keys():
price += items[choice]
else:
print("Uh oh, I don't know about that item")
print('your result', price )
```
|
@Vasyl Yovdiy has the most straightforward answer that's easy for a beginner to digest. However, it is missing the different string requirement for subsequent inputs. I would add a variable `first` that controls the string of your input.
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
price = 0
first = True
while True:
if first:
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
first = False
else:
choice = input('Another item?: ')
if choice == 'nothing':
break
if choice in items.keys():
price += items[choice]
else:
print("Uh oh, I don't know about that item")
print('your result', price )
```
|
63,156,890
|
I'm really new to coding and after learning all the syntax for HTML and CSS I figured I'd move on to python but I'd actually learn how to use it to become a python programmer instead of just learning the syntax
So as one of my first small projects I figured id make a small piece of code that'd ask the user for some items they're buying then add the price of those items together to give them the price of their shopping list essentially, However, I couldn't get it working (p.s I'm really new so my code will probably look dumb)
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into
price = []
while items != 'nothing':
input('Another item?: ')
if choice in items:
the_choice = price[choice]
else:
print("Uh oh, I don't know about that item")
```
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63156890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14016707/"
] |
I recommend searching about the python basics and loops
This will make it
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
price = 0
while True:
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
if choice == 'nothing':
break
if choice in items.keys():
price += items[choice]
else:
print("Uh oh, I don't know about that item")
print('your result', price )
```
|
Is this what you were looking for?
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
a = input('Would you like to get another item? (yes/no) > ')
b = print("See you again!")
c = input('Another item? >')
#the list the purchased items would go into
price = []
if (choice == 'nothing'):
print(b)
quit()
else:
print(c)
if (c != items):
print("Sorry, I don't know that item")
print(a)
if (a == 'yes'):
input('what is it? > ')
else:
print(b)
quit(all)
```
if so you are welcome, if not can you please explain a little more to me?
|
63,156,890
|
I'm really new to coding and after learning all the syntax for HTML and CSS I figured I'd move on to python but I'd actually learn how to use it to become a python programmer instead of just learning the syntax
So as one of my first small projects I figured id make a small piece of code that'd ask the user for some items they're buying then add the price of those items together to give them the price of their shopping list essentially, However, I couldn't get it working (p.s I'm really new so my code will probably look dumb)
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into
price = []
while items != 'nothing':
input('Another item?: ')
if choice in items:
the_choice = price[choice]
else:
print("Uh oh, I don't know about that item")
```
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63156890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14016707/"
] |
The problem with your code -
```
if choice in items:
the_choice = price[choice]
```
In the above lines of code, what you are trying to do doesn't make sense with what you are trying to achieve. You are probably looking to add each item that user inputs into the `price` list. But you are instead assigning the value at choice index to `the_choice` variable which is wrong.
---
What you are trying to do can be done in the following manner -
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into.
# If user enters input not in items, it would add 0 into price
price = [items.get(choice,0)]
# The loop will keep running until user enters nothing and it stops looping
while True:
choice = input('Another item?: ')
if choice in items:
# Append price of each choice of items that user inputs
price.append(items[choice])
# Break whenever user enters nothing.
elif choice == 'nothing':
break
# On any other input, just print that you don't know about that item
else:
print("Uh oh, I don't know about that item")
# At last, printing the final cost of all the items that user selected
print('Your total cost of items is - ',sum(price))
```
**OUTPUT :**
```
Select your item(type 'nothing' to make it stop)
: milk
Another item?: bread
Another item?: butter
Another item?: nothing
Your total cost of items is - 47
```
Also, do note that you don't need to maintain the price list unless you are going to print the price list to the user. You could just keep a variable that would add up all the sum of price of items and print it at the last. Its up to you based on what you are trying to achieve with your code.
|
Is this what you want?
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
price = 0
while True:
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
if choice in items:
price += items[choice]
elif choice == 'nothing':
break
else:
print("Uh oh, I don't know about that item")
print('Your total price is: ',price)
```
|
63,156,890
|
I'm really new to coding and after learning all the syntax for HTML and CSS I figured I'd move on to python but I'd actually learn how to use it to become a python programmer instead of just learning the syntax
So as one of my first small projects I figured id make a small piece of code that'd ask the user for some items they're buying then add the price of those items together to give them the price of their shopping list essentially, However, I couldn't get it working (p.s I'm really new so my code will probably look dumb)
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into
price = []
while items != 'nothing':
input('Another item?: ')
if choice in items:
the_choice = price[choice]
else:
print("Uh oh, I don't know about that item")
```
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63156890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14016707/"
] |
The problem with your code -
```
if choice in items:
the_choice = price[choice]
```
In the above lines of code, what you are trying to do doesn't make sense with what you are trying to achieve. You are probably looking to add each item that user inputs into the `price` list. But you are instead assigning the value at choice index to `the_choice` variable which is wrong.
---
What you are trying to do can be done in the following manner -
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into.
# If user enters input not in items, it would add 0 into price
price = [items.get(choice,0)]
# The loop will keep running until user enters nothing and it stops looping
while True:
choice = input('Another item?: ')
if choice in items:
# Append price of each choice of items that user inputs
price.append(items[choice])
# Break whenever user enters nothing.
elif choice == 'nothing':
break
# On any other input, just print that you don't know about that item
else:
print("Uh oh, I don't know about that item")
# At last, printing the final cost of all the items that user selected
print('Your total cost of items is - ',sum(price))
```
**OUTPUT :**
```
Select your item(type 'nothing' to make it stop)
: milk
Another item?: bread
Another item?: butter
Another item?: nothing
Your total cost of items is - 47
```
Also, do note that you don't need to maintain the price list unless you are going to print the price list to the user. You could just keep a variable that would add up all the sum of price of items and print it at the last. Its up to you based on what you are trying to achieve with your code.
|
Code:
=====
```
# items and their prices
items = {
'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
users_items = [] # The list of purchased items
choice = None
while choice != 'nothing':
choice = input("Select your item(type 'nothing' to make it stop) : ") # Asking for the item
if choice in items.keys():
users_items.append((choice, items[choice]))
else:
print('Item not in item\'s list')
final_cost = sum(val for item, val in users_items)
final_items = [item for item, val in users_items]
print(f'Final sum of users items is: {final_cost}. Items {final_items}')
```
Output:
=======
```
Select your item(type 'nothing' to make it stop)
: banana
Select your item(type 'nothing' to make it stop)
: nothing
Item not in item's list
Final sum of users items is: 3. Items ['banana']
```
Explanation
===========
`users_items` is a list. When user types his choice, then program appends to list a tuple(item, price). After `nothing` the loop ends and results are printed. `final_cost` is the **the sum of 2nd elements of every tuple in the** `users_items`. `final_items` is **the list of 1st elements of every tuple in the** `users_items`.
|
63,156,890
|
I'm really new to coding and after learning all the syntax for HTML and CSS I figured I'd move on to python but I'd actually learn how to use it to become a python programmer instead of just learning the syntax
So as one of my first small projects I figured id make a small piece of code that'd ask the user for some items they're buying then add the price of those items together to give them the price of their shopping list essentially, However, I couldn't get it working (p.s I'm really new so my code will probably look dumb)
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into
price = []
while items != 'nothing':
input('Another item?: ')
if choice in items:
the_choice = price[choice]
else:
print("Uh oh, I don't know about that item")
```
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63156890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14016707/"
] |
The problem with your code -
```
if choice in items:
the_choice = price[choice]
```
In the above lines of code, what you are trying to do doesn't make sense with what you are trying to achieve. You are probably looking to add each item that user inputs into the `price` list. But you are instead assigning the value at choice index to `the_choice` variable which is wrong.
---
What you are trying to do can be done in the following manner -
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into.
# If user enters input not in items, it would add 0 into price
price = [items.get(choice,0)]
# The loop will keep running until user enters nothing and it stops looping
while True:
choice = input('Another item?: ')
if choice in items:
# Append price of each choice of items that user inputs
price.append(items[choice])
# Break whenever user enters nothing.
elif choice == 'nothing':
break
# On any other input, just print that you don't know about that item
else:
print("Uh oh, I don't know about that item")
# At last, printing the final cost of all the items that user selected
print('Your total cost of items is - ',sum(price))
```
**OUTPUT :**
```
Select your item(type 'nothing' to make it stop)
: milk
Another item?: bread
Another item?: butter
Another item?: nothing
Your total cost of items is - 47
```
Also, do note that you don't need to maintain the price list unless you are going to print the price list to the user. You could just keep a variable that would add up all the sum of price of items and print it at the last. Its up to you based on what you are trying to achieve with your code.
|
@Vasyl Yovdiy has the most straightforward answer that's easy for a beginner to digest. However, it is missing the different string requirement for subsequent inputs. I would add a variable `first` that controls the string of your input.
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
price = 0
first = True
while True:
if first:
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
first = False
else:
choice = input('Another item?: ')
if choice == 'nothing':
break
if choice in items.keys():
price += items[choice]
else:
print("Uh oh, I don't know about that item")
print('your result', price )
```
|
63,156,890
|
I'm really new to coding and after learning all the syntax for HTML and CSS I figured I'd move on to python but I'd actually learn how to use it to become a python programmer instead of just learning the syntax
So as one of my first small projects I figured id make a small piece of code that'd ask the user for some items they're buying then add the price of those items together to give them the price of their shopping list essentially, However, I couldn't get it working (p.s I'm really new so my code will probably look dumb)
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into
price = []
while items != 'nothing':
input('Another item?: ')
if choice in items:
the_choice = price[choice]
else:
print("Uh oh, I don't know about that item")
```
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63156890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14016707/"
] |
The problem with your code -
```
if choice in items:
the_choice = price[choice]
```
In the above lines of code, what you are trying to do doesn't make sense with what you are trying to achieve. You are probably looking to add each item that user inputs into the `price` list. But you are instead assigning the value at choice index to `the_choice` variable which is wrong.
---
What you are trying to do can be done in the following manner -
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
#the list the purchased items would go into.
# If user enters input not in items, it would add 0 into price
price = [items.get(choice,0)]
# The loop will keep running until user enters nothing and it stops looping
while True:
choice = input('Another item?: ')
if choice in items:
# Append price of each choice of items that user inputs
price.append(items[choice])
# Break whenever user enters nothing.
elif choice == 'nothing':
break
# On any other input, just print that you don't know about that item
else:
print("Uh oh, I don't know about that item")
# At last, printing the final cost of all the items that user selected
print('Your total cost of items is - ',sum(price))
```
**OUTPUT :**
```
Select your item(type 'nothing' to make it stop)
: milk
Another item?: bread
Another item?: butter
Another item?: nothing
Your total cost of items is - 47
```
Also, do note that you don't need to maintain the price list unless you are going to print the price list to the user. You could just keep a variable that would add up all the sum of price of items and print it at the last. Its up to you based on what you are trying to achieve with your code.
|
Is this what you were looking for?
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
#Asking for the item
choice = input("Select your item(type 'nothing' to make it stop) \n : ")
a = input('Would you like to get another item? (yes/no) > ')
b = print("See you again!")
c = input('Another item? >')
#the list the purchased items would go into
price = []
if (choice == 'nothing'):
print(b)
quit()
else:
print(c)
if (c != items):
print("Sorry, I don't know that item")
print(a)
if (a == 'yes'):
input('what is it? > ')
else:
print(b)
quit(all)
```
if so you are welcome, if not can you please explain a little more to me?
|
22,567,083
|
I'm trying to run this simple example I found [here](https://groups.google.com/forum/#!msg/pyqtgraph/haiJsGhxTaQ/sTtMa195dHsJ), on MacOS X with Anaconda python.
```
import pyqtgraph as pg
import time
plt = pg.plot()
def update(data):
plt.plot(data, clear=True)
class Thread(pg.QtCore.QThread):
newData = pg.QtCore.Signal(object)
def run(self):
while True:
data = pg.np.random.normal(size=100)
# do NOT plot data from here!
self.newData.emit(data)
time.sleep(0.05)
thread = Thread()
thread.newData.connect(update)
thread.start()
```
However I keep getting:
```
QThread: Destroyed while thread is still running
```
|
2014/03/21
|
[
"https://Stackoverflow.com/questions/22567083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2585497/"
] |
The `pyqtgraph.plot` method seems buggy to me (anyway, I wasn't able to get it to produce any useful output, but maybe I'm doing something wrong).
However, if I create a `PlotWidget` and set up the application "manually", it all works as expected:
```
import pyqtgraph as pg
import numpy as np
import time
app = pg.QtGui.QApplication([])
window = pg.QtGui.QMainWindow()
plot = pg.PlotWidget()
window.setCentralWidget(plot)
window.show()
def update(data):
plot.plot(data, clear=True)
class Thread(pg.QtCore.QThread):
newData = pg.QtCore.Signal(object)
def run(self):
while True:
data = pg.np.random.normal(size=100)
# do NOT plot data from here!
self.newData.emit(data)
time.sleep(0.05)
thread = Thread()
thread.newData.connect(update)
thread.start()
app.exec_()
```
|
When you call `QThread.start()`, that function returns immediately. What happens is,
1. Thread #1 - creates new thread, #2
2. Thread #2 is created
3. Thread #1 regains control and runs.
4. Thread #1 dies or `thread` variable is cleaned up by GC (garbage collector) - I'm assuming the 2nd scenario should not happen
To solve this, don't let the main thread die. Before it dies, clean up all threads.
<http://pyqt.sourceforge.net/Docs/PyQt4/qthread.html#wait>
>
> bool QThread.wait (self, int msecs = ULONG\_MAX)
>
>
> Blocks the thread until either of these conditions is met:
>
>
> * The thread associated with this QThread object has finished execution (i.e. when it returns from run()). This function will return
> true if the thread has finished. It also returns true if the thread
> has not been started yet.
> * time milliseconds has elapsed. If time is ULONG\_MAX (the default), then the wait will never timeout (the thread must return from run()).
> This function will return false if the wait timed out.
>
>
> This provides similar functionality to the POSIX pthread\_join()
> function.
>
>
>
So, add `thread.wait()` to your code.
NOTE: You will need to make sure that your thread quits. As is, it will never quit.
|
22,567,083
|
I'm trying to run this simple example I found [here](https://groups.google.com/forum/#!msg/pyqtgraph/haiJsGhxTaQ/sTtMa195dHsJ), on MacOS X with Anaconda python.
```
import pyqtgraph as pg
import time
plt = pg.plot()
def update(data):
plt.plot(data, clear=True)
class Thread(pg.QtCore.QThread):
newData = pg.QtCore.Signal(object)
def run(self):
while True:
data = pg.np.random.normal(size=100)
# do NOT plot data from here!
self.newData.emit(data)
time.sleep(0.05)
thread = Thread()
thread.newData.connect(update)
thread.start()
```
However I keep getting:
```
QThread: Destroyed while thread is still running
```
|
2014/03/21
|
[
"https://Stackoverflow.com/questions/22567083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2585497/"
] |
Your program is exiting immediately because you have given it nothing to do after it starts the thread. The error you see is because the thread is surprised that the main thread has exited without it.
Solution: add `QtGui.QApplication.exec_()` to the end of the script. Or, if you have PyQt (not PySide) you can run from an interactive python prompt instead.
|
When you call `QThread.start()`, that function returns immediately. What happens is,
1. Thread #1 - creates new thread, #2
2. Thread #2 is created
3. Thread #1 regains control and runs.
4. Thread #1 dies or `thread` variable is cleaned up by GC (garbage collector) - I'm assuming the 2nd scenario should not happen
To solve this, don't let the main thread die. Before it dies, clean up all threads.
<http://pyqt.sourceforge.net/Docs/PyQt4/qthread.html#wait>
>
> bool QThread.wait (self, int msecs = ULONG\_MAX)
>
>
> Blocks the thread until either of these conditions is met:
>
>
> * The thread associated with this QThread object has finished execution (i.e. when it returns from run()). This function will return
> true if the thread has finished. It also returns true if the thread
> has not been started yet.
> * time milliseconds has elapsed. If time is ULONG\_MAX (the default), then the wait will never timeout (the thread must return from run()).
> This function will return false if the wait timed out.
>
>
> This provides similar functionality to the POSIX pthread\_join()
> function.
>
>
>
So, add `thread.wait()` to your code.
NOTE: You will need to make sure that your thread quits. As is, it will never quit.
|
22,567,083
|
I'm trying to run this simple example I found [here](https://groups.google.com/forum/#!msg/pyqtgraph/haiJsGhxTaQ/sTtMa195dHsJ), on MacOS X with Anaconda python.
```
import pyqtgraph as pg
import time
plt = pg.plot()
def update(data):
plt.plot(data, clear=True)
class Thread(pg.QtCore.QThread):
newData = pg.QtCore.Signal(object)
def run(self):
while True:
data = pg.np.random.normal(size=100)
# do NOT plot data from here!
self.newData.emit(data)
time.sleep(0.05)
thread = Thread()
thread.newData.connect(update)
thread.start()
```
However I keep getting:
```
QThread: Destroyed while thread is still running
```
|
2014/03/21
|
[
"https://Stackoverflow.com/questions/22567083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2585497/"
] |
Your program is exiting immediately because you have given it nothing to do after it starts the thread. The error you see is because the thread is surprised that the main thread has exited without it.
Solution: add `QtGui.QApplication.exec_()` to the end of the script. Or, if you have PyQt (not PySide) you can run from an interactive python prompt instead.
|
The `pyqtgraph.plot` method seems buggy to me (anyway, I wasn't able to get it to produce any useful output, but maybe I'm doing something wrong).
However, if I create a `PlotWidget` and set up the application "manually", it all works as expected:
```
import pyqtgraph as pg
import numpy as np
import time
app = pg.QtGui.QApplication([])
window = pg.QtGui.QMainWindow()
plot = pg.PlotWidget()
window.setCentralWidget(plot)
window.show()
def update(data):
plot.plot(data, clear=True)
class Thread(pg.QtCore.QThread):
newData = pg.QtCore.Signal(object)
def run(self):
while True:
data = pg.np.random.normal(size=100)
# do NOT plot data from here!
self.newData.emit(data)
time.sleep(0.05)
thread = Thread()
thread.newData.connect(update)
thread.start()
app.exec_()
```
|
11,466,909
|
```
node helloworld.js alex
```
I want it to console.log() alex. How do I pass "alex" as an argument into the code?
In python ,it is `sys.argv[1]`
|
2012/07/13
|
[
"https://Stackoverflow.com/questions/11466909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179736/"
] |
You can access command line arguments using `process.argv` in node.js.
The array also includes the node command and the application file, so the first custom command line argument will have an index = 2.
```
process.argv[2] === 'alex'; // true
```
<http://nodejs.org/api/process.html#process_process_argv>
|
If your requirements are more complex and you can take advantage of a command line argument parser, there are several choices. Two that seem popular are
* <https://www.npmjs.org/package/minimist> (simple and minimal)
* <https://www.npmjs.org/package/nomnom> (option parser with generated usage and commands)
More options available at [How do I pass command line arguments?](https://stackoverflow.com/questions/4351521/how-to-pass-command-line-arguments-to-node-js)
|
55,400,056
|
I have two lists of dicts: `list1` and `list2`.
```
print(list1)
[{'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'baer', 'desc': 'bees', 'city': 2, 'ID': 1},
{'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2}]
print(list2)
[{'name': 'foo', 'desc': 'baz', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2}]
```
I need a list of tuples that will hold two paired dicts (one dict from each list) with the same `city` and `ID`.
I did it with double loop:
```
list_of_tuples = []
for i in list1:
for j in list2:
if i['ID'] == j['ID'] and i['city'] == j['city']:
list_of_tuples.append((i, j))
print(list_of_tuples)
[({'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'foo', 'desc': 'baz', 'city': 1, 'ID': 1}),
({'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 1, 'ID': 1}),
({'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1}),
({'name': 'baer', 'desc': 'bees', 'city': 2, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1}),
({'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2}),
({'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2}),
({'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2}),
({'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2})]
```
**Question:** How to do this in a more pythonic way (without loops)?
|
2019/03/28
|
[
"https://Stackoverflow.com/questions/55400056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10095977/"
] |
You can use [`itertools.product`](https://docs.python.org/3.7/library/itertools.html#itertools.product) and `filter`:
```
from itertools import product
list1 = [{'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'baer', 'desc': 'bees', 'city': 2, 'ID': 1},
{'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2}]
list2 = [{'name': 'foo', 'desc': 'baz', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2}]
def condition(x):
return x[0]['ID'] == x[1]['ID'] and x[0]['city'] == x[1]['city']
list_of_tuples = list(filter(condition, product(list1, list2)))
```
|
Having nested loops is not "not pythonic". However, you can achieve the same result with a list comprehension. I don't think it's more readable though:
```
[(i, j) for j in list2 for i in list1 if i['ID'] == j['ID'] and i['city'] == j['city']]
```
|
55,400,056
|
I have two lists of dicts: `list1` and `list2`.
```
print(list1)
[{'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'baer', 'desc': 'bees', 'city': 2, 'ID': 1},
{'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2}]
print(list2)
[{'name': 'foo', 'desc': 'baz', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2}]
```
I need a list of tuples that will hold two paired dicts (one dict from each list) with the same `city` and `ID`.
I did it with double loop:
```
list_of_tuples = []
for i in list1:
for j in list2:
if i['ID'] == j['ID'] and i['city'] == j['city']:
list_of_tuples.append((i, j))
print(list_of_tuples)
[({'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'foo', 'desc': 'baz', 'city': 1, 'ID': 1}),
({'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 1, 'ID': 1}),
({'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1}),
({'name': 'baer', 'desc': 'bees', 'city': 2, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1}),
({'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2}),
({'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2}),
({'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2}),
({'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2})]
```
**Question:** How to do this in a more pythonic way (without loops)?
|
2019/03/28
|
[
"https://Stackoverflow.com/questions/55400056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10095977/"
] |
This is a problem well suited for `pandas`. If you convert the lists to DataFrames, matching the records on `ID` and `city` is the same as an [inner join of the two DataFrames](https://stackoverflow.com/questions/53645882/pandas-merging-101).
```
import pandas as pd
# convert lists to DataFrames
df1 = pd.DataFrame(list1)
df2 = pd.DataFrame(list2)
# merge the two DataFrames
print(df1.merge(df2, on=["ID", "city"]))
# ID city desc_x name_x desc_y name_y
#0 1 1 bazv fooa baz foo
#1 1 1 bazv fooa bes bar
#2 1 2 besd bard bes bar
#3 1 2 bees baer bes bar
#4 2 1 bnbb aaaa bbb aaa
#5 2 1 bnbb aaaa ddd ccc
#6 2 1 dgdd cgcc bbb aaa
#7 2 1 dgdd cgcc ddd ccc
```
Now you have the matched records in each row. Since the `desc` and `name` columns were present in both (and not used for the merge), they get subscripted with `_x` and `_y` to differentiate between the two souce DataFrames.
You just need to reformat it to be in your desired output. You can achieve this using `to_dict` and a list comprehension:
```
list_of_tuples = [
(
{"name": r["name_x"], "desc": r["desc_x"], "city": r["city"], "ID": r["ID"]},
{"name": r["name_y"], "desc": r["desc_y"], "city": r["city"], "ID": r["ID"]}
) for r in df1.merge(df2, on=["ID", "city"]).to_dict(orient="records")
]
print(list_of_tuples)
#[({'ID': 1, 'city': 1, 'desc': 'bazv', 'name': 'fooa'},
# {'ID': 1, 'city': 1, 'desc': 'baz', 'name': 'foo'}),
# ({'ID': 1, 'city': 1, 'desc': 'bazv', 'name': 'fooa'},
# {'ID': 1, 'city': 1, 'desc': 'bes', 'name': 'bar'}),
# ({'ID': 1, 'city': 2, 'desc': 'besd', 'name': 'bard'},
# {'ID': 1, 'city': 2, 'desc': 'bes', 'name': 'bar'}),
# ({'ID': 1, 'city': 2, 'desc': 'bees', 'name': 'baer'},
# {'ID': 1, 'city': 2, 'desc': 'bes', 'name': 'bar'}),
# ({'ID': 2, 'city': 1, 'desc': 'bnbb', 'name': 'aaaa'},
# {'ID': 2, 'city': 1, 'desc': 'bbb', 'name': 'aaa'}),
# ({'ID': 2, 'city': 1, 'desc': 'bnbb', 'name': 'aaaa'},
# {'ID': 2, 'city': 1, 'desc': 'ddd', 'name': 'ccc'}),
# ({'ID': 2, 'city': 1, 'desc': 'dgdd', 'name': 'cgcc'},
# {'ID': 2, 'city': 1, 'desc': 'bbb', 'name': 'aaa'}),
# ({'ID': 2, 'city': 1, 'desc': 'dgdd', 'name': 'cgcc'},
# {'ID': 2, 'city': 1, 'desc': 'ddd', 'name': 'ccc'})]
```
|
Having nested loops is not "not pythonic". However, you can achieve the same result with a list comprehension. I don't think it's more readable though:
```
[(i, j) for j in list2 for i in list1 if i['ID'] == j['ID'] and i['city'] == j['city']]
```
|
55,400,056
|
I have two lists of dicts: `list1` and `list2`.
```
print(list1)
[{'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'baer', 'desc': 'bees', 'city': 2, 'ID': 1},
{'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2}]
print(list2)
[{'name': 'foo', 'desc': 'baz', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2}]
```
I need a list of tuples that will hold two paired dicts (one dict from each list) with the same `city` and `ID`.
I did it with double loop:
```
list_of_tuples = []
for i in list1:
for j in list2:
if i['ID'] == j['ID'] and i['city'] == j['city']:
list_of_tuples.append((i, j))
print(list_of_tuples)
[({'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'foo', 'desc': 'baz', 'city': 1, 'ID': 1}),
({'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 1, 'ID': 1}),
({'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1}),
({'name': 'baer', 'desc': 'bees', 'city': 2, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1}),
({'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2}),
({'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2}),
({'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2}),
({'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2})]
```
**Question:** How to do this in a more pythonic way (without loops)?
|
2019/03/28
|
[
"https://Stackoverflow.com/questions/55400056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10095977/"
] |
You can use [`itertools.product`](https://docs.python.org/3.7/library/itertools.html#itertools.product) and `filter`:
```
from itertools import product
list1 = [{'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'baer', 'desc': 'bees', 'city': 2, 'ID': 1},
{'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'cgcc', 'desc': 'dgdd', 'city': 1, 'ID': 2}]
list2 = [{'name': 'foo', 'desc': 'baz', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 1, 'ID': 1},
{'name': 'bar', 'desc': 'bes', 'city': 2, 'ID': 1},
{'name': 'aaa', 'desc': 'bbb', 'city': 1, 'ID': 2},
{'name': 'ccc', 'desc': 'ddd', 'city': 1, 'ID': 2}]
def condition(x):
return x[0]['ID'] == x[1]['ID'] and x[0]['city'] == x[1]['city']
list_of_tuples = list(filter(condition, product(list1, list2)))
```
|
This is a problem well suited for `pandas`. If you convert the lists to DataFrames, matching the records on `ID` and `city` is the same as an [inner join of the two DataFrames](https://stackoverflow.com/questions/53645882/pandas-merging-101).
```
import pandas as pd
# convert lists to DataFrames
df1 = pd.DataFrame(list1)
df2 = pd.DataFrame(list2)
# merge the two DataFrames
print(df1.merge(df2, on=["ID", "city"]))
# ID city desc_x name_x desc_y name_y
#0 1 1 bazv fooa baz foo
#1 1 1 bazv fooa bes bar
#2 1 2 besd bard bes bar
#3 1 2 bees baer bes bar
#4 2 1 bnbb aaaa bbb aaa
#5 2 1 bnbb aaaa ddd ccc
#6 2 1 dgdd cgcc bbb aaa
#7 2 1 dgdd cgcc ddd ccc
```
Now you have the matched records in each row. Since the `desc` and `name` columns were present in both (and not used for the merge), they get subscripted with `_x` and `_y` to differentiate between the two souce DataFrames.
You just need to reformat it to be in your desired output. You can achieve this using `to_dict` and a list comprehension:
```
list_of_tuples = [
(
{"name": r["name_x"], "desc": r["desc_x"], "city": r["city"], "ID": r["ID"]},
{"name": r["name_y"], "desc": r["desc_y"], "city": r["city"], "ID": r["ID"]}
) for r in df1.merge(df2, on=["ID", "city"]).to_dict(orient="records")
]
print(list_of_tuples)
#[({'ID': 1, 'city': 1, 'desc': 'bazv', 'name': 'fooa'},
# {'ID': 1, 'city': 1, 'desc': 'baz', 'name': 'foo'}),
# ({'ID': 1, 'city': 1, 'desc': 'bazv', 'name': 'fooa'},
# {'ID': 1, 'city': 1, 'desc': 'bes', 'name': 'bar'}),
# ({'ID': 1, 'city': 2, 'desc': 'besd', 'name': 'bard'},
# {'ID': 1, 'city': 2, 'desc': 'bes', 'name': 'bar'}),
# ({'ID': 1, 'city': 2, 'desc': 'bees', 'name': 'baer'},
# {'ID': 1, 'city': 2, 'desc': 'bes', 'name': 'bar'}),
# ({'ID': 2, 'city': 1, 'desc': 'bnbb', 'name': 'aaaa'},
# {'ID': 2, 'city': 1, 'desc': 'bbb', 'name': 'aaa'}),
# ({'ID': 2, 'city': 1, 'desc': 'bnbb', 'name': 'aaaa'},
# {'ID': 2, 'city': 1, 'desc': 'ddd', 'name': 'ccc'}),
# ({'ID': 2, 'city': 1, 'desc': 'dgdd', 'name': 'cgcc'},
# {'ID': 2, 'city': 1, 'desc': 'bbb', 'name': 'aaa'}),
# ({'ID': 2, 'city': 1, 'desc': 'dgdd', 'name': 'cgcc'},
# {'ID': 2, 'city': 1, 'desc': 'ddd', 'name': 'ccc'})]
```
|
3,824,373
|
I am quite new at python and regex so please bear with me.
I am trying to read in a file, match a particular name using a regex while ignoring the case, and store each time I find it. For example, if the file is composed of `Bill bill biLl biLL`, I need to store each variation in a dictionary or list.
Current code:
```
import re
import sys
import fileinput
if __name__ == '__main__':
print "flag"
pattern = re.compile("""([b][i][l][l])""")
for line in fileinput.input():
variation=set(pattern.search(line, re.I))
print variation.groupdict()
print "flag2"
```
When ran, the code will return an error: 'NoneType' cannot be iterated (or something along those lines).
So how do I store each variation?
Thanks in advance!
|
2010/09/29
|
[
"https://Stackoverflow.com/questions/3824373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461063/"
] |
I'd use findall:
```
re.findall(r'bill', open(filename).read(), re.I)
```
Easy as pie:
```
>>> s = 'fooBiLL bill BILL bIlL foo bar'
>>> import re
>>> re.findall(r'bill', s, re.I)
['BiLL', 'bill', 'BILL', 'bIlL']
```
|
I think that you want [re.findall](http://localhost/docs/python-2.7-docs-html/library/re.html#re.findall). This is of course available on the compiled regular expression as well. The particular error code that you are getting though, would seem to indicate that you are [not matching your pattern](http://localhost/docs/python-2.7-docs-html/library/re.html#re.search). try
```
pattern = re.compile("bill", re.IGNORE_CASE)
```
|
65,890,917
|
I would like to obtain a nested dictionary from a string, which can be split by delimiter, `:`.
```
s='A:B:C:D'
v=['some','object']
desired={'A':{'B':{'C':{'D':v}}}}
```
Is there a "pythonic" way to generate this?
|
2021/01/25
|
[
"https://Stackoverflow.com/questions/65890917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12844579/"
] |
Hmmm . . . You want the most recent value from the `tracker` table. Then compare that to the existing values and insert where there are differences:
```
INSERT INTO Tracker (customer_id, value, date_of_value)
SELECT v.customer_id, v.value, GETDATE()
FROM (SELECT v.*,
ROW_NUMBER() OVER (PARTITION BY v.customer_id ORDER BY v.value DESC) as seqnum
FROM values v
) v LEFT JOIN
Tracker t
ON v.customer_id = t.customer_id AND
v.value = t.value
WHERE v.seqnum = 1 AND t.customer_id IS NULL;
```
|
We can create a trigger on the main table to insert a new row into the tracker table:
```sql
CREATE TRIGGER trg_Tracking
ON MainTable
AFTER INSERT, UPDATE AS
IF (NOT UPDATE(value) OR NOT EXISTS
(SELECT customer_id, value FROM inserted
EXCEPT
SELECT customer_id, value FROM deleted))
RETURN; -- early bail-out if we can
INSERT Tracker (customerr_id, value, date_of_value)
SELECT customer_id, value, GETDATE()
FROM (
SELECT customer_id, value FROM inserted
EXCEPT --make sure to compare inserted and deleted values (AFTER INSERT has empty deleted values)
SELECT customer_id, value FROM deleted
) changed;
GO -- No BEGIN and END as the whole batch is the trigger
```
|
72,366,129
|
I want to reach a document, but I always get this error:
**FileNotFoundError: [Errno 44] No such file or directory: 'dbs/school/students.ini' )**
I've tried putting "/" or "./" before the dbs, but it doesn't work, so I want to know how can I reach that document, the dbs folder is in the same directory where I run the html.
The code I'm using works in python so I don't know why it doesn't work in PyScript
[Here is a picture of the folder](https://i.stack.imgur.com/Jb5Gr.png)
|
2022/05/24
|
[
"https://Stackoverflow.com/questions/72366129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19059715/"
] |
Probably you need to add the file to your paths in your html code like:
```
<py-env>
- paths:
- dbs/school/students.ini
</py-env>
```
This way it should be added to your python environment.
|
i had the same issue, the solution i found was to insert my file into a github public branch and get the link from my github file, the code is below:
```
from pyodide.http import open_url
url_content = open_url('https://raw.githubusercontent.com/')
```
to know more about it read
<https://pyodide.org/en/stable/usage/faq.html>
and see the videos from 1littlecoder about pyscript
<https://www.youtube.com/c/1littlecoder>
|
22,489,243
|
I'm writing tutorial about "advanced" regular expressions for Python,
and I cannot understand
```
lastindex
```
attribute. Why is it always 1 in the given examples:
<http://docs.python.org/2/library/re.html#re.MatchObject.lastindex>
I mean this example:
```
re.match('((ab))', 'ab').lastindex
```
Why is it 1? Second group is matching too.
|
2014/03/18
|
[
"https://Stackoverflow.com/questions/22489243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1377803/"
] |
`lastindex` is the index of the last group that matched. The examples in the documentation include one that uses 2 capturing groups:
```
(a)(b)
```
where `lastindex` is set to 2 as the last capturing group to match was `(b)`.
The attribute comes in handy when you have optional capturing groups; compare:
```
>>> re.match('(required)( optional)?', 'required').lastindex
1
>>> re.match('(required)( optional)?', 'required optional').lastindex
2
```
When you have *nested* groups, the outer group is the last to match. So with `((ab))` or `((a)(b))` the outer group is group 1 and the last to match.
|
In regex groups are captured using `()`. In python `re` the `lastindex` holds the last capturing group.
Lets see this small code example:
```
match = re.search("(\w+).+?(\d+).+?(\W+)", "input 123 ---")
if match:
print match.lastindex
```
In this example, the output will be 3 as I have used three `()` in my regex and it matched all of those.
For the above code, if you execute the following line in `if` block, it will output `123` as it is the second capture group.
```
print match.group(2)
```
|
12,059,852
|
I am new to python or coding , so please be patient with my question,
So here's my busy XML
```
<?xml version="1.0" encoding="utf-8"?>
<Total>
<ID>999</ID>
<Response>
<Detail>
<Nix>
<Check>pass</Check>
</Nix>
<MaxSegment>
<Status>V</Status>
<Input>
<Name>
<First>jack</First>
<Last>smiths</Last>
</Name>
<Address>
<StreetAddress1>100 rodeo dr</StreetAddress1>
<City>long beach</City>
<State>ca</State>
<ZipCode>90802</ZipCode>
</Address>
<DriverLicense>
<Number>123456789</Number>
<State>ca</State>
</DriverLicense>
<Contact>
<Email>x@me.com</Email>
<Phones>
<Home>0000000000</Home>
<Work>1111111111</Work>
</Phones>
</Contact>
</Input>
<Type>Regular</Type>
</MaxSegment>
</Detail>
</Response>
</Total>
```
what I am trying to do is extract these value into nice and clean table below :

Here's my code so far.. but I couldn't figure it out how to get the subchild :
```
import os
os.chdir('d:/py/xml/')
import xml.etree.ElementTree as ET
tree = ET.parse('xxml.xml')
root=tree.getroot()
x = root.tag
y = root.attrib
print(x,y)
#---PRINT ALL NODES---
for child in root:
print(child.tag, child.attrib)
```
Thank you in advance !
|
2012/08/21
|
[
"https://Stackoverflow.com/questions/12059852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/918460/"
] |
Figured it out, add the `UIPopoverController` delegate in addition to the `UISplitViewControllerDelegate`:
```c
//Sent when switching to portrait
- (void)splitViewController:(UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController:(UIPopoverController*)pc
{
...
self.popoverController = pc;
[self.popoverController setDelegate:self];
}
-(void)splitViewController:(UISplitViewController *)svc popoverController:(UIPopoverController *)pc willPresentViewController:(UIViewController *)aViewController
{
NSLog(@"SHOWING POPOVER");
}
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
NSLog(@"HIDING POPOVER");
}
```
|
When you get that first delegate notification, you're passed a reference to the UIPopoverController that will present the hidden view controller. Register as its delegate, then use the [`-popoverControllerDidDismissPopover:`](http://developer.apple.com/library/ios/documentation/uikit/reference/UIPopoverControllerDelegate_protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIPopoverControllerDelegate/popoverControllerDidDismissPopover%3a) delegate method from the UIPopoverControllerDelegate protocol.
|
50,107,263
|
I have the following dataframe:
```
0 1 2 3 4
0 1.JPG NaN NaN NaN NaN
1 2883 2957.0 3412.0 3340.0 miscellaneous
2 3517 3007.0 4062.0 3371.0 miscellaneous
3 5678 3158.0 6299.0 3423.0 miscellaneous
4 1627 3287.0 2149.0 3694.0 miscellaneous
5 2894 3272.0 3421.0 3664.0 miscellaneous
6 3525 3271.0 4064.0 3672.0 miscellaneous
7 4759 3337.0 5321.0 3640.0 miscellaneous
8 6141 3289.0 6664.0 3654.0 miscellaneous
9 1017 3598.0 1539.0 3979.0 miscellaneous
10 1624 3586.0 2155.0 3993.0 miscellaneous
11 2252 3612.0 2777.0 3967.0 miscellaneous
12 3211 3548.0 3735.0 3944.0 miscellaneous
13 6052 3616.0 6572.0 3983.0 miscellaneous
14 691 3911.0 1204.0 4223.0 miscellaneous
15 2.JPG NaN NaN NaN NaN
16 3.JPG NaN NaN NaN NaN
17 5384 2841.0 5963.0 3095.0 miscellaneous
18 5985 2797.0 6611.0 3080.0 miscellaneous
19 3512 3012.0 4025.0 3366.0 miscellaneous
20 5085 2974.0 5587.0 3367.0 miscellaneous
21 2593 3224.0 3148.0 3469.0 miscellaneous
22 1044 3630.0 1511.0 3928.0 miscellaneous
23 4764 3619.0 5283.0 3971.0 miscellaneous
24 5103 3613.0 5635.0 3928.0 miscellaneous
```
I want to split this data frame into multiple csv such that: First csv should be named 1.csv and have all data which is below 1.jpg and so on.
For example, exported CSV should be like:
1.csv
```
2883 2957 3412 3340 miscellaneous
3517 3007 4062 3371 miscellaneous
5678 3158 6299 3423 miscellaneous
1627 3287 2149 3694 miscellaneous
2894 3272 3421 3664 miscellaneous
3525 3271 4064 3672 miscellaneous
4759 3337 5321 3640 miscellaneous
6141 3289 6664 3654 miscellaneous
1017 3598 1539 3979 miscellaneous
1624 3586 2155 3993 miscellaneous
2252 3612 2777 3967 miscellaneous
3211 3548 3735 3944 miscellaneous
6052 3616 6572 3983 miscellaneous
691 3911 1204 4223 miscellaneous
```
2.csv (this csv should should be blank)
3.csv
```
5384 2841 5963 3095 miscellaneous
5985 2797 6611 3080 miscellaneous
3512 3012 4025 3366 miscellaneous
5085 2974 5587 3367 miscellaneous
2593 3224 3148 3469 miscellaneous
1044 3630 1511 3928 miscellaneous
4764 3619 5283 3971 miscellaneous
5103 3613 5635 3928 miscellaneous
```
How do I do this using python and pandas ?
|
2018/04/30
|
[
"https://Stackoverflow.com/questions/50107263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4663377/"
] |
You can use:
```
for n,g in df.assign(grouper = df['0'].where(df['1'].isnull())
.ffill().astype('category'))\
.dropna().groupby('grouper'):
g.drop('grouper', axis=1).to_csv(n+'.csv', header=None, index=False)
```
***Note:*** used astype('category') to pickup that group with no records
Output `!dir *.JPG.csv`
```
04/30/2018 03:43 PM 657 1.JPG.csv
04/30/2018 03:43 PM 0 2.JPG.csv
04/30/2018 03:43 PM 376 3.JPG.csv
```
List contents of 1.jpg.csv
```
2883,2957.0,3412.0,3340.0,miscellaneous
3517,3007.0,4062.0,3371.0,miscellaneous
5678,3158.0,6299.0,3423.0,miscellaneous
1627,3287.0,2149.0,3694.0,miscellaneous
2894,3272.0,3421.0,3664.0,miscellaneous
3525,3271.0,4064.0,3672.0,miscellaneous
4759,3337.0,5321.0,3640.0,miscellaneous
6141,3289.0,6664.0,3654.0,miscellaneous
1017,3598.0,1539.0,3979.0,miscellaneous
1624,3586.0,2155.0,3993.0,miscellaneous
2252,3612.0,2777.0,3967.0,miscellaneous
3211,3548.0,3735.0,3944.0,miscellaneous
6052,3616.0,6572.0,3983.0,miscellaneous
691,3911.0,1204.0,4223.0,miscellaneous
```
|
```
# program splits one big csv file into individiual image csv 's
import pandas as pd
import numpy as np
df = pd.read_csv('results.csv', header=None)
#df1 = df.replace(np.nan, '1', regex=True)
print(df)
for n,g in df.assign(grouper = df[0].where(df[1].isnull())
.ffill().astype('category'))\
.dropna().groupby('grouper'):
g.drop('grouper', axis=1).to_csv(n+'.csv',float_format="%.0f", header=None, index=False )
```
This produces the required result
|
36,243,814
|
I noticed this while playing around with graph\_tool. Some module attributes only seem to be available when run from ipython. The simplest example (example.py)
```
import graph_tool as gt
g = gt.Graph()
gt.draw.sfdp_layout(g)
```
Runs without error from ipython using `run example.y', but from the command line,`python example.py` yields
```
AttributeError: 'module' object has no attribute 'draw'
```
The same hold true for `ipython example.py`. I'm lost as to what would cause this. I would like to access the draw module but it seems like I can only do this via `from graph_tool.draw import *` Any help or explanation would be appreciated.
|
2016/03/27
|
[
"https://Stackoverflow.com/questions/36243814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1308706/"
] |
based on comments:
if you are attempting to create a database programmatically, you can't use a connection to an unborn database, so in this situation you must open a connection to `master` database, something like that:
```
"Server = localhost; Database = master; User Id = 123; Password = abc;"
```
|
```
String str;
SqlConnection myConn = new SqlConnection("Server=localhost;User Id = 123; Password = abc;database=master");
str = "CREATE DATABASE database1";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "Creation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
```
Please try this above code. Its working for me.Don't give database name before you create the database. Use database master for initialize the database connection.
|
2,125,612
|
I'm building my first python app on app-engine and wondering if I should use Django or not.
What are the strong points of each? If you have references that support your answer, please post them. Maybe we can make a wiki out of this question.
|
2010/01/24
|
[
"https://Stackoverflow.com/questions/2125612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16628/"
] |
Aral Balkan wrote [a really nice piece](http://aralbalkan.com/1313) addressing this very question. Its a year or so old, so take it with a grain of salt - I think that a lot more emphasis should be put on the awesomeness of django's Object-Relational-Model. Basically, IMHO, it all comes down to whether or not you have a preference for using DJango's object model (which I happen to).
|
If it's not a small project, I try to use Django. You can use the App Engine Patch (<http://code.google.com/p/app-engine-patch/>). However, the ORM cannot use Django's meaning your models.py will still be using GAE's Datastore.
One of the advantages of using Django on GAE is session management. GAE does not have a built-in session.
You won't be able to using most Django 3rd-party apps though especially those with model changes. I had to build my own tagging app for GAE.
|
72,297,725
|
On my OSX M1 Mac I have the following keyring setup which works with Google Artifact Repository to resolve dependencies when using python on the command line shell.
Refer to <https://cloud.google.com/artifact-registry/docs/python/store-python>
```
$ keyring --list-backends
keyring.backends.chainer.ChainerBackend (priority: 10)
keyring.backends.fail.Keyring (priority: 0)
keyring.backends.macOS.Keyring (priority: 5)
keyrings.gauth.GooglePythonAuth (priority: 9)
```
If I try to install the dependencies from within PyCharm it does not work automatically, it prompts for a user as can be seen. I expected it to resolve the dependencies automatically from my already authenticated account. How to get PyCharm to work with Google Artifact Repository?
[](https://i.stack.imgur.com/B1Gwc.png)
|
2022/05/19
|
[
"https://Stackoverflow.com/questions/72297725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78000/"
] |
Based on your description, I suppose you have successfully set up the Python virtual environment (venv) and installed all the dependencies via the terminal (Step 1-4 in <https://cloud.google.com/artifact-registry/docs/python/store-python>). And you want PyCharm also run your Python codes using that virtual environment.
Usually, PyCharm will create a new Python virtual environment or use the default Python interpreter on your machine when you first open a project. That is why you will have to install the dependencies again.
In order to make PyCharm run your project using the venv you have created earlier (through the command line), go to the Setting -> Project: your-project-name -> Python interpreter -> Add -> Choose Existing environment -> Hit ... -> Navigate to the the venv folder you created -> Select venv/bin/python.exe or venv/bin/python3.exe or venv/bin/python.
After that PyCharm will run your project using the existing virtual environment, and you don't have to install everything again. I am from Upwork, by the way.
|
It's basically the same as what you found already on your link but you missed the following site :)
1. Setup service account with `roles/artifactregistry.writer` rights
2. Create key file (json file with your credentials) using `gcloud iam service-accounts keys create FILE_NAME.json --iam-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com`
3. After this you can follow the following website. [Setting up authentication to Python package repositories](https://cloud.google.com/artifact-registry/docs/python/authentication)
|
12,790,065
|
When I use the python Sybase package, and do a cursor fetch(), one of the columns is a datetime - in the sequence returned, it has a DateTimeType object for this value.
I can find it is in the sybasect module but can't find any documentation for this datatype.
I would like to be able to convert it to a string output - similar to using strftime() with datetime objects.
Any info on this?
|
2012/10/08
|
[
"https://Stackoverflow.com/questions/12790065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133237/"
] |
I think this is what are you looking for
```
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from(array('org' => 'orgTable'),
array(
'orgid' => 'org.orgid',
'role' =>'org.role',
'userid' =>'user.userid',
'firstname' =>'user.firstname'
))
->join(array('user' => 'userTable'),
'org.userid = user.userid',array())
->where('org.orgid = ?',$generated_id);
```
|
Here is a `Zend_Db_Select` that returns the result you are looking for.
```
$select = $db->select()
->from(array('org' => 'orgTable'), array('orgid', 'role'))
->join(array('user' => 'userTable'), 'org.userid = user.userid', array('userid', 'firstname'))
->where('org.orgid = ?', 'generated-id');
```
You can use the array notation for table names to get the aliased names in the query.
Hope that helps.
|
12,790,065
|
When I use the python Sybase package, and do a cursor fetch(), one of the columns is a datetime - in the sequence returned, it has a DateTimeType object for this value.
I can find it is in the sybasect module but can't find any documentation for this datatype.
I would like to be able to convert it to a string output - similar to using strftime() with datetime objects.
Any info on this?
|
2012/10/08
|
[
"https://Stackoverflow.com/questions/12790065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133237/"
] |
I think this is what are you looking for
```
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from(array('org' => 'orgTable'),
array(
'orgid' => 'org.orgid',
'role' =>'org.role',
'userid' =>'user.userid',
'firstname' =>'user.firstname'
))
->join(array('user' => 'userTable'),
'org.userid = user.userid',array())
->where('org.orgid = ?',$generated_id);
```
|
In **zend framework 2** , the following code helps you what are you looking for
```
$generated_id = 1 ;
$select = new \Zend\Db\Sql\Select( array('org' =>'orgTable'));
$select->columns(array('orgid','role') )
->join( array('user' => 'userTable'),
'org.userid = user.userid',
array('userid','firstname')
)->where( array('org.orgid' => $generated_id ) );
```
if your adapter platform is mysql, then for printing sql
```
$mysqlPlatform = new \Zend\Db\Adapter\Platform\Mysql();
echo $select->getSqlString( $mysqlPlatform );
```
which print sql as
```
SELECT
`org`.`orgid` AS `orgid`,
`org`.`role` AS `role`,
`user`.`userid` AS `userid`,
`user`.`firstname` AS `firstname`
FROM
`orgTable` AS `org`
INNER JOIN `userTable` AS `user`
ON `org`.`userid` = `user`.`userid`
WHERE
`org`.`orgid` = '1'
```
|
36,331,946
|
I installed Linux Mint as Virtual Machine.
When I do:
```
python --version
```
I get:
```
Python 2.7.6
```
I installed seperate python folder acording to [this](http://www.experts-exchange.com/articles/18641/Upgrade-Python-2-7-6-to-Python-2-7-10-on-Linux-Mint-OS.html).
and When I do:
```
python2.7 --version
```
I get:
```
Python 2.7.11
```
Now, I want to work only on Python 2.7.11
I installed pip
and installed a package using pip with `pip install paypalrestsdk`
It was successfull:
[](https://i.stack.imgur.com/ZPOgo.png)
However when I run the script using this package I get:
[](https://i.stack.imgur.com/WMLIW.png)
i suspect that pip and the install were done on the `python 2.7.6` rather than the `python 2.7.11`
What can I do?
|
2016/03/31
|
[
"https://Stackoverflow.com/questions/36331946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1712099/"
] |
mPDF uses autosizing tables and this influences, among other things, the font-size as well. When outputting tables with mPDF you need to set:
```
<table style="overflow: wrap">
```
on every table according to this [answer](https://stackoverflow.com/questions/23760018/mpdf-font-size-not-working).
You can set font-size by `$mpdf->SetFontSize(6);` Here font-size is measured in point(pt). Or you can set default font-size using the mpdf function `SetDefaultFontSize()`. According to MPDF documentation, `SetDefaultFontSize()` is depracated but still available. The other alternative is to edit the mpdf default stylesheet(mpdf.css).
Hope this may help
|
kindly use
```
$mpdf->keep_table_proportions = false;
```
|
62,264,821
|
Here is my [python](/questions/tagged/python "show questions tagged 'python'") code:
```py
while exit:
serialnumber = int(input("serial number of product :"))
try:
if len(str(serialnumber)) == 6:
break
else:
print("serial number cant be used")
serialnumber = int(serialnumber)
break
except ValueError:
print("Invalid input")
print()
```
I have been trying to make a length check on the input so that it does not go over 6 characters.
I would also like my program to keep asking for input until it passes the check.
However, in my program, if the input fails the check then it will just display the serial number and it won't prompt the user again.
|
2020/06/08
|
[
"https://Stackoverflow.com/questions/62264821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13653559/"
] |
You don't need to do any math manually. Simply declare a `DIBSECTION` variable, and then pass a pointer to it to `GetObject()` along with `sizeof()` as the size of that variable, eg:
```
DIBSECTION dib;
GetObject(hBitmap, sizeof(dib), &dib);
```
|
I took out a piece of paper and added up everything myself.
A `DIBSECTION` contains 5 parts.
```
typedef struct tagDIBSECTION {
BITMAP dsBm;
BITMAPINFOHEADER dsBmih;
DWORD dsBitfields[3];
HANDLE dshSection;
DWORD dsOffset;
} DIBSECTION, *LPDIBSECTION, *PDIBSECTION;
```
So let's start with `BITMAP`.
```
typedef struct tagBITMAP {
LONG bmType;
LONG bmWidth;
LONG bmHeight;
LONG bmWidthBytes;
WORD bmPlanes;
WORD bmBitsPixel;
LPVOID bmBits;
} BITMAP, *PBITMAP, *NPBITMAP, *LPBITMAP;
```
A `LONG` is just an `int` which is 4 bytes. A `WORD` is a `unsigned short` which is 2 bytes. And `LPVOID` is a `ptr`.
`4+4+4+4+2+2` = `20`. But wait, a struct has to be aligned properly. So we need to test divisibility by `8` on 64-bit systems. 20 is not divisible by 8, so we add 4 bytes of padding to get `24`. Adding the `ptr` gives us `32`.
The size of the `BITMAPINFOHEADER` is 40 bytes. It's divisible by 8, so nothing fancy needed. We're at `72` now.
Back to the `DIBSECTION`. There's an array of `DWORD`s. And each `DWORD` is an `unsigned int`. Adding 12 to 72 gives us `84`.
Now there's a `handle`. A handle is basically a pointer, whose value can be 4 or 8 depending on 32 or 64 bit. Time to check if `84` is divisible by 8. It's not so we add 4 bytes of padding to get `88`. Then add the pointer to get `96`.
Finally there's the last `DWORD` and the total reaches `100` on a 64-bit system.
But what about `sizeof()`?????? Can't you just do `sizeof(DIBSECTION)`? After all magic numbers = bad. Ken White said in the comments that I didn't need to do any math. I disagree with this. First, as a programmer, it's essential to understand what is happening and why. Nothing could be more elementary than memory on a computer. Second, I only tagged the post as `winapi`. For the people reading this, if you scroll down on the `GetObject` page, the function is exported on `Gdi32.dll`. Any windows program has access to `Gdi32.dll`. Not every windows program has access to `sizeof()`. Third, it may be important for people who need to know the math to have the steps shown. Not everyone programs in a high level language. It might even be a question on an exam.
Perhaps the real question is if a struct of size 100 gets padded to 104 when memory is being granted on a 64-bit system.
|
62,563,923
|
This seems really basic but I can't seem to figure it out. I am working in a Pyspark Notebook on EMR and have taken a pyspark dataframe and converted it to a pandas dataframe using `toPandas()`.
Now, I would like to save this dataframe to the local environment using the following code:
```
movie_franchise_counts.to_csv('test.csv')
```
But I keep getting a permission error:
```
[Errno 13] Permission denied: 'test.csv'
Traceback (most recent call last):
File "/usr/local/lib64/python3.6/site-packages/pandas/core/generic.py", line 3204, in to_csv
formatter.save()
File "/usr/local/lib64/python3.6/site-packages/pandas/io/formats/csvs.py", line 188, in save
compression=dict(self.compression_args, method=self.compression),
File "/usr/local/lib64/python3.6/site-packages/pandas/io/common.py", line 428, in get_handle
f = open(path_or_buf, mode, encoding=encoding, newline="")
PermissionError: [Errno 13] Permission denied: 'test.csv'
```
Any help would be much appreciated.
|
2020/06/24
|
[
"https://Stackoverflow.com/questions/62563923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13136602/"
] |
Your not passing anything to updateSettings `google.script.run.updateSettings();`>
I would do it like this:
```
<input type = "button" value="Submit" onClick="google.script.run.updateSettings(this.parentNode);" />
```
I'm running this as a dialog and it runs okay now. I added values to the radio buttons and now the weekly one returns 'weekly' and the daily one returns 'daily' and the IDdrive returns a string.
gs:
```
function openFolderForm() { SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1').setHeight(525).setWidth(800), 'Export Settings');
}
function updateSettings(form) {
console.log(form)
var formQ1=form.IDdrive;
if (form.radioDaily == true) { var formQ2 = 1; } else { var formQ2 = 7}
}
function exportCSV() {
var changelogSheetName = "data";
var ss=SpreadsheetApp.getActive();
var sheets=ss.getSheets();
var tab=ss.getSheetByName('data');
var folder=DriveApp.getFolderById(formQ1);
}
```
html:
```
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<title><b>Output Folder</b></title>
</head>
<body>
<p>Enter the ID of your output folder. A Drive ID is made up by the characters after the last /folder/ in the URL</p>
<form>
<input type='text' name='IDdrive' id="IDdrive" style="width: 300px;"/><br />
<input type="radio" name="radio" id="radioDaily" value="daily"> <label for="radioDaily">Daily</label><br />
<input type="radio" name="radio" id="radioWeekly" value="weekly"> <label for="radioWeekly">Weekly</label><br />
<input type="button" value="Submit" class="action" onClick="google.script.run.updateSettings(this.parentNode);" />
<input type="button" value="Cancel" class="cancel" onClick="google.script.host.close();" />
</form>
</body>
</html>
```
|
Got it to work. The secret was needed to just JSON to properly store the form input criteria.
**CODE**
```
function updateSettings(formObject) {
var uiForm = SpreadsheetApp.getUi();
JSON.stringify(formObject);
var formText = formObject.formQ1;
var formRadio = formObject.formQ2;
if (formRadio == "Daily") { var frequency = 1; } else { var frequency = 7};
etc etc
```
**HTML**
```
<form id="myForm" onsubmit="event.preventDefault(); google.script.run.updateSettings(this); google.script.host.close();">
<div>
<input type='text' name='formQ1' id="formQ1" style="width: 300px;"/>
</div>
<div class="inline form-group">
<input type="radio" name="formQ2" id="formQ2" value="Daily" /> <label for="radioDaily">Daily</label>
</div>
<div>
<input type="radio" name="formQ2" id="formQ2" value="Weekly" /> <label for="radioWeekly">Weekly</label>
</div>
<br><br>
<div class="inline form-group">
<input type="submit" value="Submit" style="color:#4285F4"/>
<input type="button" value="Cancel" class="cancel" onClick="google.script.host.close();" />
```
|
72,688,811
|
I tried to implement the binary tree program in python. I want to add one more function to get the level of a specific node.
eg:-
```
10 # level 0
/ \
5 15 # level 1
/ \
3 7 # level 2
```
if we search the level of node 3, it should return
```
class BinaryTree:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data == data:
return
if self.data<data:
if self.left:
self.left.insert(data)
else:
self.left = BinaryTree(data)
else:
if self.right:
self.right.insert(data)
else:
self.right = BinaryTree(data)
def print_tree(self):
if self:
print(self.data)
if self.left:
self.left.print_tree()
elif self.right:
self.right.print_tree()
def get_level(self, data, level=0):
print(type(data))
level += 1
if self.data == data:
return level
elif self.left and self.right:
if self.left:
self.left.get_level(data)
elif self.right:
self.right.get_level(data)
return level
def in_order(self):
if self:
#left
in_order(self.left)
#root
print(self.data, '->')
#right
in_order(self.right)
```
This is my code for Binary tree. I need to add another function to this class which will tell the **level of a node** after giving the value
For example:
```
def get_level(node):
#some code
return level
get_level(10) # returns the level of the node 10
```
|
2022/06/20
|
[
"https://Stackoverflow.com/questions/72688811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14931124/"
] |
If by "simplify", you mean "shorten", then this is as good as it gets:
```
public get isUsersLimitReached(): boolean {
return !this.isAdmin && usersCount >= this.max_users;
}
```
Other than that, there's really not much to work with here.
|
A user limit is reached only if the user is not admin and count exceeds.
```
public get isUsersLimitReached(): boolean {
return !this.isAdmin && usersCount >= this.max_users;
}
```
|
67,775,753
|
This is extended question to [Can we send data from Google cloud storage to SFTP server using GCP Cloud function?](https://stackoverflow.com/questions/67772938/can-we-send-data-from-cloud-storage-to-sftp-server-using-gcp-cloud-function)
```py
with pysftp.Connection(host=myHostName, username=myUsername,
password=myPassword, cnopts=cnopts) as sftp:
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(filename) #source_blob_name
with sftp.open(remotepath, 'w+', 32768) as f:
blob.download_to_file(f)
```
The `W+`/`w` command is not truncating the previous file and throwing error. This is when there is already a file with same name in SFTP server existing! what should be the optimal solution to this?
The complete error code log is
```none
gcs-to-sftp
4wz44jq3oe2g
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/client.py", line 728, in download_blob_to_file
checksum=checksum,
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 986, in _do_download
response = download.consume(transport, timeout=timeout)
File "/env/local/lib/python3.7/site-packages/google/resumable_media/requests/download.py", line 168, in consume
self._process_response(result)
File "/env/local/lib/python3.7/site-packages/google/resumable_media/_download.py", line 186, in _process_response
response, _ACCEPTABLE_STATUS_CODES, self._get_status_code
File "/env/local/lib/python3.7/site-packages/google/resumable_media/_helpers.py", line 104, in require_status_code
*status_codes
google.resumable_media.common.InvalidResponse: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 449, in run_background_function
_function_handler.invoke_user_function(event_object)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 268, in invoke_user_function
return call_user_function(request_or_event)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 265, in call_user_function
event_context.Context(**request_or_event.context))
File "/user_code/main.py", line 20, in hello_sftp
copy_file_on_ftp(myHostName, myUsername, myPassword, bucket_name, filename)
File "/user_code/main.py", line 42, in copy_file_on_ftp
file_to_export.download_to_file(f)
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 1128, in download_to_file
checksum=checksum,
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/client.py", line 731, in download_blob_to_file
_raise_from_invalid_response(exc)
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 4100, in _raise_from_invalid_response
raise exceptions.from_http_status(response.status_code, message, response=response)
google.api_core.exceptions.NotFound: 404 GET https://storage.googleapis.com/download/storage/v1/b/sftp__test/o/test_file.csv?alt=media: No such object: sftp__test/test_file.csv: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)
```
|
2021/05/31
|
[
"https://Stackoverflow.com/questions/67775753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452168/"
] |
For google, there is a formula googlefinance. For yahoo, all datas are imported in the code source within a big json you can fetch by this way
```
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString)
```
you can then navigate through data to retrieve the informations you need.
|
See formula GOOGLEFINANCE in Google Sheets. It's not totally live (about 20 minutes delay) but for many purposes is enough. I use it mostly for currency exchange rates but there far more options:
<https://support.google.com/docs/answer/3093281?hl=en>
Yahoo Finance and most of live sites are protected against webscraping or use javascript (that makes parts generated by javascript impossible for import by formulasa like IMPORTHML, IMPORTXML, IMPORTDATA).
|
67,775,753
|
This is extended question to [Can we send data from Google cloud storage to SFTP server using GCP Cloud function?](https://stackoverflow.com/questions/67772938/can-we-send-data-from-cloud-storage-to-sftp-server-using-gcp-cloud-function)
```py
with pysftp.Connection(host=myHostName, username=myUsername,
password=myPassword, cnopts=cnopts) as sftp:
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(filename) #source_blob_name
with sftp.open(remotepath, 'w+', 32768) as f:
blob.download_to_file(f)
```
The `W+`/`w` command is not truncating the previous file and throwing error. This is when there is already a file with same name in SFTP server existing! what should be the optimal solution to this?
The complete error code log is
```none
gcs-to-sftp
4wz44jq3oe2g
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/client.py", line 728, in download_blob_to_file
checksum=checksum,
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 986, in _do_download
response = download.consume(transport, timeout=timeout)
File "/env/local/lib/python3.7/site-packages/google/resumable_media/requests/download.py", line 168, in consume
self._process_response(result)
File "/env/local/lib/python3.7/site-packages/google/resumable_media/_download.py", line 186, in _process_response
response, _ACCEPTABLE_STATUS_CODES, self._get_status_code
File "/env/local/lib/python3.7/site-packages/google/resumable_media/_helpers.py", line 104, in require_status_code
*status_codes
google.resumable_media.common.InvalidResponse: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 449, in run_background_function
_function_handler.invoke_user_function(event_object)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 268, in invoke_user_function
return call_user_function(request_or_event)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 265, in call_user_function
event_context.Context(**request_or_event.context))
File "/user_code/main.py", line 20, in hello_sftp
copy_file_on_ftp(myHostName, myUsername, myPassword, bucket_name, filename)
File "/user_code/main.py", line 42, in copy_file_on_ftp
file_to_export.download_to_file(f)
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 1128, in download_to_file
checksum=checksum,
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/client.py", line 731, in download_blob_to_file
_raise_from_invalid_response(exc)
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 4100, in _raise_from_invalid_response
raise exceptions.from_http_status(response.status_code, message, response=response)
google.api_core.exceptions.NotFound: 404 GET https://storage.googleapis.com/download/storage/v1/b/sftp__test/o/test_file.csv?alt=media: No such object: sftp__test/test_file.csv: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)
```
|
2021/05/31
|
[
"https://Stackoverflow.com/questions/67775753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452168/"
] |
For google, there is a formula googlefinance. For yahoo, all datas are imported in the code source within a big json you can fetch by this way
```
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString)
```
you can then navigate through data to retrieve the informations you need.
|
I also built a Google sheets add-on that allows you to access fundamental and realtime financial data for tens of thousands of global companies, ETFs and Cryptos. You can access fundamental information like revenue or cashflow from specific years. It's still in its early phases but you can check it out in the add-on store, it's called SheetsFinance (sheetsfinance.com)
Feel free to drop me a line and ask any more questions about it
|
67,775,753
|
This is extended question to [Can we send data from Google cloud storage to SFTP server using GCP Cloud function?](https://stackoverflow.com/questions/67772938/can-we-send-data-from-cloud-storage-to-sftp-server-using-gcp-cloud-function)
```py
with pysftp.Connection(host=myHostName, username=myUsername,
password=myPassword, cnopts=cnopts) as sftp:
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(filename) #source_blob_name
with sftp.open(remotepath, 'w+', 32768) as f:
blob.download_to_file(f)
```
The `W+`/`w` command is not truncating the previous file and throwing error. This is when there is already a file with same name in SFTP server existing! what should be the optimal solution to this?
The complete error code log is
```none
gcs-to-sftp
4wz44jq3oe2g
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/client.py", line 728, in download_blob_to_file
checksum=checksum,
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 986, in _do_download
response = download.consume(transport, timeout=timeout)
File "/env/local/lib/python3.7/site-packages/google/resumable_media/requests/download.py", line 168, in consume
self._process_response(result)
File "/env/local/lib/python3.7/site-packages/google/resumable_media/_download.py", line 186, in _process_response
response, _ACCEPTABLE_STATUS_CODES, self._get_status_code
File "/env/local/lib/python3.7/site-packages/google/resumable_media/_helpers.py", line 104, in require_status_code
*status_codes
google.resumable_media.common.InvalidResponse: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 449, in run_background_function
_function_handler.invoke_user_function(event_object)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 268, in invoke_user_function
return call_user_function(request_or_event)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 265, in call_user_function
event_context.Context(**request_or_event.context))
File "/user_code/main.py", line 20, in hello_sftp
copy_file_on_ftp(myHostName, myUsername, myPassword, bucket_name, filename)
File "/user_code/main.py", line 42, in copy_file_on_ftp
file_to_export.download_to_file(f)
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 1128, in download_to_file
checksum=checksum,
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/client.py", line 731, in download_blob_to_file
_raise_from_invalid_response(exc)
File "/env/local/lib/python3.7/site-packages/google/cloud/storage/blob.py", line 4100, in _raise_from_invalid_response
raise exceptions.from_http_status(response.status_code, message, response=response)
google.api_core.exceptions.NotFound: 404 GET https://storage.googleapis.com/download/storage/v1/b/sftp__test/o/test_file.csv?alt=media: No such object: sftp__test/test_file.csv: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)
```
|
2021/05/31
|
[
"https://Stackoverflow.com/questions/67775753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452168/"
] |
For google, there is a formula googlefinance. For yahoo, all datas are imported in the code source within a big json you can fetch by this way
```
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString)
```
you can then navigate through data to retrieve the informations you need.
|
Regarding cryptocurrency coins you can simply use
`=IMPORTDATA("https://cryptoprices.cc/BTC/")`
Google Finance only supports the very biggest coins (BTC, ETH), not much more.
Other services usually require fragile web page parsing which is difficult, error prone and not a long term solution.
From looking at some of your comments, you may be looking at something more complex and get a lot more data together. That will probably require access to paid services and some software programming to get it working together.
Google Sheets is not a scraping software, it can pull data from websites and do some limited parsing, but most websites protect against it and or may change over time. Trying to do what you want to do may be the best way to do it.
|
46,282,656
|
I have a test project that looks like this:
```
_ test_project
├- __init__.py
├- main.py
└- output.py
```
`__init__.py` is empty, and the other two files look like this:
```
# main.py
from . import output
```
and
```
# output.py
print("hello world")
```
I would like to import `output.py` just for the side effect, but I am getting this message instead:
```
(venv) $ python test_project/main.py
Traceback (most recent call last):
File "test_project/main.py", line 2, in <module>
from . import output
ImportError: cannot import name 'output'
```
What does the import statement in `main.py` have to be to just print "hello world"?
|
2017/09/18
|
[
"https://Stackoverflow.com/questions/46282656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5203563/"
] |
Relative imports can only be performed in a package. So, run the code as a package.
```
$ cd /pathabovetest_project
$ python -m test_project.main
```
|
Just do `import output`, that worked for me.
|
57,712,218
|
I try to use requests to get a url of file. It works well locally but it doesn't work with nameko.
I tried 3 libs of python3.7. But all has the same error.
import urllib.request,urllib3,requests
it works well locally like this:
```py
import requests
url = "https://www.python.org/static/img/python-logo.png"
r = requests.get(url)
print(r.content)
```
But it can't work with nameko:
```py
import requests
from nameko.web.handlers import http
@http("POST", "/import")
def testurl(self,request):
url = "https://www.python.org/static/img/python-logo.png"
r = requests.get(url)
print(r.content)
```
```py
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.7/site-packages/nameko/rpc.py", line 373, in __call__
return reply.result()
File "/usr/local/lib/python3.7/site-packages/nameko/rpc.py", line 331, in result
raise deserialize(error)
nameko.exceptions.RemoteError: Exception Error on testurl: Cause : wrap_socket() got an unexpected keyword argument '_context'
```
|
2019/08/29
|
[
"https://Stackoverflow.com/questions/57712218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11994979/"
] |
It is an eventlet bug. If it is possible you need to downgrade to Python 3.6.
<https://github.com/eventlet/eventlet/issues/526>
Nameko has a PR for this issue which is on pause until the above is fixed.
<https://github.com/nameko/nameko/pull/644>
|
I caught the same error with python 3.7, eventlet 0.25.2, requests 2.24.0.
It works fine with requests 2.23.0
|
6,918,719
|
Whenever I try to create a table using python and sqlite3, it gives me the following error:
```
Traceback (most recent call last)
File "directory.py", line 14, in <module>
'Children' TEXT, 'Other' TEXT, 'Masul' TEXT);''')
sqlite3.OperationalError: near ")": syntax error
```
The way I'm trying to create the table is:
```
conn.execute('''create table Jamaat
(id integer primary key,
Email TEXT,
LastName TEXT,
Address1 TEXT,
Apt TEXT,
Address2 TEXT,
City TEXT,
State TEXT,
Zip TEXT,
HomePhone TEXT,
FaxNumber TEXT,
Primary TEXT,
Spouse TEXT,
Children TEXT,
Other TEXT,
Masul TEXT);''')
conn.commit()
```
I'm using python 2.7 and trying to import a csv spreadsheet into sqlite3
Thanks in advance
EDIT: I've tried the code without the trailing comma and it still doesn't work...
|
2011/08/02
|
[
"https://Stackoverflow.com/questions/6918719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764746/"
] |
Often when you get this kind of error it is because you are using keywords as column (or table) names.
I see that you have a column called `primary`.
You will want to put backticks around it or rename it because [it is a keyword in SQLite](http://www.sqlite.org/lang_keywords.html); e.g.:
```
...
`Primary` TEXT,
...
```
|
You have a trailing "," before the closing parenthesis.
|
6,918,719
|
Whenever I try to create a table using python and sqlite3, it gives me the following error:
```
Traceback (most recent call last)
File "directory.py", line 14, in <module>
'Children' TEXT, 'Other' TEXT, 'Masul' TEXT);''')
sqlite3.OperationalError: near ")": syntax error
```
The way I'm trying to create the table is:
```
conn.execute('''create table Jamaat
(id integer primary key,
Email TEXT,
LastName TEXT,
Address1 TEXT,
Apt TEXT,
Address2 TEXT,
City TEXT,
State TEXT,
Zip TEXT,
HomePhone TEXT,
FaxNumber TEXT,
Primary TEXT,
Spouse TEXT,
Children TEXT,
Other TEXT,
Masul TEXT);''')
conn.commit()
```
I'm using python 2.7 and trying to import a csv spreadsheet into sqlite3
Thanks in advance
EDIT: I've tried the code without the trailing comma and it still doesn't work...
|
2011/08/02
|
[
"https://Stackoverflow.com/questions/6918719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764746/"
] |
Often when you get this kind of error it is because you are using keywords as column (or table) names.
I see that you have a column called `primary`.
You will want to put backticks around it or rename it because [it is a keyword in SQLite](http://www.sqlite.org/lang_keywords.html); e.g.:
```
...
`Primary` TEXT,
...
```
|
There's a missing `)` in your sample, and since the error is in your SQL you should probably include the actual execute statement not `...`.
But i'd say your error is a trailing `,` at the end of the list of your columns.
|
2,811,822
|
In other languages (ruby, python, ...) I can use `zip(list1, list2)` which works like this:
If `list1 is {1,2,3,4}` and `list2 is {a,b,c}`
then `zip(list1, list2)` would return: `{(1,a), (2,b), (3,c), (d,null)}`
Is such a method available in .NET's Linq extensions?
|
2010/05/11
|
[
"https://Stackoverflow.com/questions/2811822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545/"
] |
.NET 4 gives us a [`Zip`](http://msdn.microsoft.com/en-us/library/dd267698.aspx) method but it is not available in .NET 3.5. If you are curious, [Eric Lippert provides an implementation of `Zip`](http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx) that you may find useful.
|
neither implementation will fill in the missing values (or check that the lengths are the same) as the question asked.
here is an implementation that can:
```
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult> (this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector, bool checkLengths = true, bool fillMissing = false) {
if (first == null) { throw new ArgumentNullException("first");}
if (second == null) { throw new ArgumentNullException("second");}
if (selector == null) { throw new ArgumentNullException("selector");}
using (IEnumerator<TFirst> e1 = first.GetEnumerator()) {
using (IEnumerator<TSecond> e2 = second.GetEnumerator()) {
while (true) {
bool more1 = e1.MoveNext();
bool more2 = e2.MoveNext();
if( ! more1 || ! more2) { //one finished
if(checkLengths && ! fillMissing && (more1 || more2)) { //checking length && not filling in missing values && ones not finished
throw new Exception("Enumerables have different lengths (" + (more1 ? "first" : "second") +" is longer)");
}
//fill in missing values with default(Tx) if asked too
if (fillMissing) {
if ( more1 ) {
while ( e1.MoveNext() ) {
yield return selector(e1.Current, default(TSecond));
}
} else {
while ( e2.MoveNext() ) {
yield return selector(default(TFirst), e2.Current);
}
}
}
yield break;
}
yield return selector(e1.Current, e2.Current);
}
}
}
}
```
|
31,823,262
|
I just started python a few days ago and have been working on a calculator (not extremely basic, but also not advanced). The problem doesn't prevent code from running or anything, it is just a visual thing.
Output in the console looks like this (stuff in parenthesis is explaining what is happening and is not actually part of the output):
```
4 (user prompted for first number, press enter afterwards)
+ (user prompted for an operator, press enter afterwards
5 (user prompted for second number, press enter afterwards)
9.00000 (answer is printed)
Process finished with exit code 0
```
Basically what I want it to look like is this when I'm entering it into the console:
```
4+5
9.00000
```
I don't want it to start a newline after I enter a number or operator or whatever, it looks more like an actual calculator when it prints along one line. Is this possible to do and if so how? Btw I know `end=""` works with `print` but not with `input` since it doesn't accept arguments. Also I know the whole calculator thing is kind of redundant considering you can make calculations really easily in the python IDLE but I thought it was a good way for me to learn. Here is the entire code if you need it:
```
import math
while True:
try:
firstNumber = float(input())
break
except ValueError:
print("Please enter a number... ", end="")
while True:
operators = ['+', '-', '*', '/', '!', '^']
userOperator = str(input())
if userOperator in operators:
break
else:
print("Enter a valid operator... ", end="")
if userOperator == operators[4]:
answer = math.factorial(firstNumber)
print(answer)
pause = input()
raise SystemExit
while True:
try:
secondNumber = float(input())
break
except ValueError:
print("Please enter a number... ", end="")
if userOperator == operators[0]:
answer = firstNumber + secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[1]:
answer = firstNumber - secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[2]:
answer = firstNumber * secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[3]:
answer = firstNumber / secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[5]:
answer = firstNumber ** secondNumber
print('%.5f' % round(answer, 5))
pause = input()
raise SystemExit
```
|
2015/08/05
|
[
"https://Stackoverflow.com/questions/31823262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5166610/"
] |
Your problem is that you're asking for `input()` without specifying what you want. So if you take a look at the first one: `firstNumber = float(input())` It's executing properly, but you hit `enter` it gives an error which is only then you're specifying what you want.
Try replacing with these:
```
...
try
firstNumber = float(input("Please enter a number... "))
...
userOperator = str(input("Enter a valid operator... "))
...
secondNumber = float(input("Please enter a number... "))
```
Is that what you're looking for?
Using my method I suggested:
```
Please enter a number... 5
Enter a valid operator... +
Please enter a number... 6
11.00000
```
Using your method:
```
Please enter a number... 5
Enter a valid operator... +
Please enter a number... 6
11.00000
```
Extra newlines which is what I'm assuming you're referring to.
|
That's a [nice exercise](http://alfasin.com/2015/08/05/a-simple-calculator-in-python/), and as I wrote in the comments, I would ignore whitespaces, take the expression as a whole from the user and then parse it and calculate the result. Here's a small demo:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def calc(expr):
if is_number(expr):
return float(expr)
arr = expr.split('+')
if len(arr) > 1:
return sum(map(calc, arr))
arr = expr.split('-')
if len(arr) > 1:
return reduce(lambda x,y: x-y, map(calc, arr))
arr = expr.split('*')
if len(arr) > 1:
return reduce(lambda x,y: x*y, map(calc, arr), 1)
arr = expr.split('/')
if len(arr) > 1:
return reduce(lambda x,y: x/y, map(calc, arr))
print calc("3+4-2 *2/ 2") # 5
```
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
You're overthinking it
This part is trying to do too much
```
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
```
See how simple it really should be
```
def get_powerset (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = get_powerset(rem)
perm.extend(words)
for word in words:
perm.append(first+word)
return perm
if __name__=="__main__":
a = "ab"
mag = get_powerset(a)
print mag
```
Now you should be able to make the code look a lot nicer with a little refactoring
|
Here's a refactored iterative solution **without** the `itertools` module:
```
def powerset(s):
a = ['']
for i,c in enumerate(s):
for k in range(2**i):
a.append(a[k]+c)
return a
```
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
Is this what you want?
```
import itertools as it
def func(s):
for i in range(len(s)+1):
for combo in it.combinations(s,i):
yield "".join(combo)
print list(func("abc"))
```
|
Use [`powerset`](https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.powerset) from [`more_itertools`](https://github.com/erikrose/more-itertools):
```
>>> import more_itertools
>>> ["".join(p) for p in list(more_itertools.powerset("ab"))]
['', 'a', 'b', 'ab']
```
This `powerset` is a convenience function directly implemented from the `itertools` [recipes](https://docs.python.org/3/library/itertools.html#itertools-recipes).
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
There are a method for permutations:
```
>>> import itertools
>>> chars = "ABCD"
>>> perms = list(itertools.permutations(chars))
>>> print(perms)
[('A', 'B', 'C'),
('A', 'C', 'B'),
('B', 'A', 'C'),
('B', 'C', 'A'),
('C', 'A', 'B'),
('C', 'B', 'A')]
```
|
Use [`powerset`](https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.powerset) from [`more_itertools`](https://github.com/erikrose/more-itertools):
```
>>> import more_itertools
>>> ["".join(p) for p in list(more_itertools.powerset("ab"))]
['', 'a', 'b', 'ab']
```
This `powerset` is a convenience function directly implemented from the `itertools` [recipes](https://docs.python.org/3/library/itertools.html#itertools-recipes).
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
You're overthinking it
This part is trying to do too much
```
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
```
See how simple it really should be
```
def get_powerset (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = get_powerset(rem)
perm.extend(words)
for word in words:
perm.append(first+word)
return perm
if __name__=="__main__":
a = "ab"
mag = get_powerset(a)
print mag
```
Now you should be able to make the code look a lot nicer with a little refactoring
|
Use [`powerset`](https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.powerset) from [`more_itertools`](https://github.com/erikrose/more-itertools):
```
>>> import more_itertools
>>> ["".join(p) for p in list(more_itertools.powerset("ab"))]
['', 'a', 'b', 'ab']
```
This `powerset` is a convenience function directly implemented from the `itertools` [recipes](https://docs.python.org/3/library/itertools.html#itertools-recipes).
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
There are a method for permutations:
```
>>> import itertools
>>> chars = "ABCD"
>>> perms = list(itertools.permutations(chars))
>>> print(perms)
[('A', 'B', 'C'),
('A', 'C', 'B'),
('B', 'A', 'C'),
('B', 'C', 'A'),
('C', 'A', 'B'),
('C', 'B', 'A')]
```
|
Have you tried tracing through what your algorithm actually does?
```
getperm('ab'):
first, rem = 'a', 'b'
words = getperm('b')
first, rem = 'b', ''
words = getperm('')
words = ['']
for word in words:
for i in range(len(word)):
pass # only called on '', so doesn't matter
return []
words = []
for word in words:
pass # only called on [], so doesn't matter
```
So, there's no nuance of Python here; your algorithm returns the empty list in O(N) steps, and you've coded that algorithm properly in Python.
(Instead of tracing it by hand, of course, you can add some more useful print statements and see what each step is actually doing.)
It probably wasn't the algorithm you wanted, but you'll need to tell us what you were *trying* to do. Are you, e.g., porting some pseudocode from Hoare into Python? If so, what's the pseudocode?
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
Here's a refactored iterative solution **without** the `itertools` module:
```
def powerset(s):
a = ['']
for i,c in enumerate(s):
for k in range(2**i):
a.append(a[k]+c)
return a
```
|
Have you tried tracing through what your algorithm actually does?
```
getperm('ab'):
first, rem = 'a', 'b'
words = getperm('b')
first, rem = 'b', ''
words = getperm('')
words = ['']
for word in words:
for i in range(len(word)):
pass # only called on '', so doesn't matter
return []
words = []
for word in words:
pass # only called on [], so doesn't matter
```
So, there's no nuance of Python here; your algorithm returns the empty list in O(N) steps, and you've coded that algorithm properly in Python.
(Instead of tracing it by hand, of course, you can add some more useful print statements and see what each step is actually doing.)
It probably wasn't the algorithm you wanted, but you'll need to tell us what you were *trying* to do. Are you, e.g., porting some pseudocode from Hoare into Python? If so, what's the pseudocode?
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
You're overthinking it
This part is trying to do too much
```
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
```
See how simple it really should be
```
def get_powerset (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = get_powerset(rem)
perm.extend(words)
for word in words:
perm.append(first+word)
return perm
if __name__=="__main__":
a = "ab"
mag = get_powerset(a)
print mag
```
Now you should be able to make the code look a lot nicer with a little refactoring
|
Have you tried tracing through what your algorithm actually does?
```
getperm('ab'):
first, rem = 'a', 'b'
words = getperm('b')
first, rem = 'b', ''
words = getperm('')
words = ['']
for word in words:
for i in range(len(word)):
pass # only called on '', so doesn't matter
return []
words = []
for word in words:
pass # only called on [], so doesn't matter
```
So, there's no nuance of Python here; your algorithm returns the empty list in O(N) steps, and you've coded that algorithm properly in Python.
(Instead of tracing it by hand, of course, you can add some more useful print statements and see what each step is actually doing.)
It probably wasn't the algorithm you wanted, but you'll need to tell us what you were *trying* to do. Are you, e.g., porting some pseudocode from Hoare into Python? If so, what's the pseudocode?
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
Here's a refactored iterative solution **without** the `itertools` module:
```
def powerset(s):
a = ['']
for i,c in enumerate(s):
for k in range(2**i):
a.append(a[k]+c)
return a
```
|
Use [`powerset`](https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.powerset) from [`more_itertools`](https://github.com/erikrose/more-itertools):
```
>>> import more_itertools
>>> ["".join(p) for p in list(more_itertools.powerset("ab"))]
['', 'a', 'b', 'ab']
```
This `powerset` is a convenience function directly implemented from the `itertools` [recipes](https://docs.python.org/3/library/itertools.html#itertools-recipes).
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
Is this what you want?
```
import itertools as it
def func(s):
for i in range(len(s)+1):
for combo in it.combinations(s,i):
yield "".join(combo)
print list(func("abc"))
```
|
Have you tried tracing through what your algorithm actually does?
```
getperm('ab'):
first, rem = 'a', 'b'
words = getperm('b')
first, rem = 'b', ''
words = getperm('')
words = ['']
for word in words:
for i in range(len(word)):
pass # only called on '', so doesn't matter
return []
words = []
for word in words:
pass # only called on [], so doesn't matter
```
So, there's no nuance of Python here; your algorithm returns the empty list in O(N) steps, and you've coded that algorithm properly in Python.
(Instead of tracing it by hand, of course, you can add some more useful print statements and see what each step is actually doing.)
It probably wasn't the algorithm you wanted, but you'll need to tell us what you were *trying* to do. Are you, e.g., porting some pseudocode from Hoare into Python? If so, what's the pseudocode?
|
12,632,421
|
I'm trying to write python code to print the [powerset](/tags/powerset/info) of a string, but am running into some bugs. Here's what I've got:
```
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
```
My expected output would be:
```
['', 'a', 'b', 'ab']
```
My actual output is:
```
[]
```
Can anyone help me figure out what's going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok -- I'm going off the fifth edition of Cracking the coding interview
Thank you!
|
2012/09/28
|
[
"https://Stackoverflow.com/questions/12632421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390268/"
] |
Here's a refactored iterative solution **without** the `itertools` module:
```
def powerset(s):
a = ['']
for i,c in enumerate(s):
for k in range(2**i):
a.append(a[k]+c)
return a
```
|
There are a method for permutations:
```
>>> import itertools
>>> chars = "ABCD"
>>> perms = list(itertools.permutations(chars))
>>> print(perms)
[('A', 'B', 'C'),
('A', 'C', 'B'),
('B', 'A', 'C'),
('B', 'C', 'A'),
('C', 'A', 'B'),
('C', 'B', 'A')]
```
|
9,887,319
|
I am running a server with cherrypy and python script. Currently, there is a web page containing data of a list of people, which i need to get. The format of the web page is as follow:
```
www.url1.com, firstName_1, lastName_1
www.url2.com, firstName_2, lastName_2
www.url3.com, firstName_3, lastName_3
```
I wish to display the list of names on my own webpage, with each name hyperlinked to their corresponding website.
I have read the webpage into a list with the following method:
```
@cherrypy.expose
def receiveData(self):
""" Get a list, one per line, of currently known online addresses,
separated by commas.
"""
method = "whoonline"
fptr = urllib2.urlopen("%s/%s" % (masterServer, method))
data = fptr.readlines()
fptr.close()
return data
```
But I don't know how to break the list into a list of lists at where the comma are. The result should give each smaller list three elements; URL, First Name, and Last Name. So I was wondering if anyone could help.
Thank you in advance!
|
2012/03/27
|
[
"https://Stackoverflow.com/questions/9887319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008340/"
] |
You need the `split(',')` method on each string:
```
data = [ line.split(',') for line in fptr.readlines() ]
```
|
```
lists = []
for line in data:
lists.append([x.strip() for x in line.split(',')])
```
|
9,887,319
|
I am running a server with cherrypy and python script. Currently, there is a web page containing data of a list of people, which i need to get. The format of the web page is as follow:
```
www.url1.com, firstName_1, lastName_1
www.url2.com, firstName_2, lastName_2
www.url3.com, firstName_3, lastName_3
```
I wish to display the list of names on my own webpage, with each name hyperlinked to their corresponding website.
I have read the webpage into a list with the following method:
```
@cherrypy.expose
def receiveData(self):
""" Get a list, one per line, of currently known online addresses,
separated by commas.
"""
method = "whoonline"
fptr = urllib2.urlopen("%s/%s" % (masterServer, method))
data = fptr.readlines()
fptr.close()
return data
```
But I don't know how to break the list into a list of lists at where the comma are. The result should give each smaller list three elements; URL, First Name, and Last Name. So I was wondering if anyone could help.
Thank you in advance!
|
2012/03/27
|
[
"https://Stackoverflow.com/questions/9887319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008340/"
] |
You can iterate over fptr, no need to call `readlines()`
```
data = [line.split(', ') for line in fptr]
```
|
You need the `split(',')` method on each string:
```
data = [ line.split(',') for line in fptr.readlines() ]
```
|
9,887,319
|
I am running a server with cherrypy and python script. Currently, there is a web page containing data of a list of people, which i need to get. The format of the web page is as follow:
```
www.url1.com, firstName_1, lastName_1
www.url2.com, firstName_2, lastName_2
www.url3.com, firstName_3, lastName_3
```
I wish to display the list of names on my own webpage, with each name hyperlinked to their corresponding website.
I have read the webpage into a list with the following method:
```
@cherrypy.expose
def receiveData(self):
""" Get a list, one per line, of currently known online addresses,
separated by commas.
"""
method = "whoonline"
fptr = urllib2.urlopen("%s/%s" % (masterServer, method))
data = fptr.readlines()
fptr.close()
return data
```
But I don't know how to break the list into a list of lists at where the comma are. The result should give each smaller list three elements; URL, First Name, and Last Name. So I was wondering if anyone could help.
Thank you in advance!
|
2012/03/27
|
[
"https://Stackoverflow.com/questions/9887319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008340/"
] |
You need the `split(',')` method on each string:
```
data = [ line.split(',') for line in fptr.readlines() ]
```
|
If you data is a big 'ole string (potentially with leading or trailing spaces), do it this way:
```
lines=""" www.url1.com, firstName_1, lastName_1
www.url2.com, firstName_2 , lastName_2
www.url3.com, firstName_3, lastName_3 """
data=[]
for line in lines.split('\n'):
t=[e.strip() for e in line.split(',')]
data.append(t)
print data
```
Out:
```
[['www.url1.com', 'firstName_1', 'lastName_1'], ['www.url2.com', 'firstName_2',
'lastName_2'], ['www.url3.com', 'firstName_3', 'lastName_3']]
```
Notice the leading and trailing spaces are removed.
|
9,887,319
|
I am running a server with cherrypy and python script. Currently, there is a web page containing data of a list of people, which i need to get. The format of the web page is as follow:
```
www.url1.com, firstName_1, lastName_1
www.url2.com, firstName_2, lastName_2
www.url3.com, firstName_3, lastName_3
```
I wish to display the list of names on my own webpage, with each name hyperlinked to their corresponding website.
I have read the webpage into a list with the following method:
```
@cherrypy.expose
def receiveData(self):
""" Get a list, one per line, of currently known online addresses,
separated by commas.
"""
method = "whoonline"
fptr = urllib2.urlopen("%s/%s" % (masterServer, method))
data = fptr.readlines()
fptr.close()
return data
```
But I don't know how to break the list into a list of lists at where the comma are. The result should give each smaller list three elements; URL, First Name, and Last Name. So I was wondering if anyone could help.
Thank you in advance!
|
2012/03/27
|
[
"https://Stackoverflow.com/questions/9887319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008340/"
] |
You can iterate over fptr, no need to call `readlines()`
```
data = [line.split(', ') for line in fptr]
```
|
```
lists = []
for line in data:
lists.append([x.strip() for x in line.split(',')])
```
|
9,887,319
|
I am running a server with cherrypy and python script. Currently, there is a web page containing data of a list of people, which i need to get. The format of the web page is as follow:
```
www.url1.com, firstName_1, lastName_1
www.url2.com, firstName_2, lastName_2
www.url3.com, firstName_3, lastName_3
```
I wish to display the list of names on my own webpage, with each name hyperlinked to their corresponding website.
I have read the webpage into a list with the following method:
```
@cherrypy.expose
def receiveData(self):
""" Get a list, one per line, of currently known online addresses,
separated by commas.
"""
method = "whoonline"
fptr = urllib2.urlopen("%s/%s" % (masterServer, method))
data = fptr.readlines()
fptr.close()
return data
```
But I don't know how to break the list into a list of lists at where the comma are. The result should give each smaller list three elements; URL, First Name, and Last Name. So I was wondering if anyone could help.
Thank you in advance!
|
2012/03/27
|
[
"https://Stackoverflow.com/questions/9887319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008340/"
] |
You can iterate over fptr, no need to call `readlines()`
```
data = [line.split(', ') for line in fptr]
```
|
If you data is a big 'ole string (potentially with leading or trailing spaces), do it this way:
```
lines=""" www.url1.com, firstName_1, lastName_1
www.url2.com, firstName_2 , lastName_2
www.url3.com, firstName_3, lastName_3 """
data=[]
for line in lines.split('\n'):
t=[e.strip() for e in line.split(',')]
data.append(t)
print data
```
Out:
```
[['www.url1.com', 'firstName_1', 'lastName_1'], ['www.url2.com', 'firstName_2',
'lastName_2'], ['www.url3.com', 'firstName_3', 'lastName_3']]
```
Notice the leading and trailing spaces are removed.
|
46,188,797
|
I use a script to parce some sites and get news from there.
Each function in this script parse one site and return list of articles and then I want to combine them all in one big list.
If I parce site by site it takes to long and I desided to use multithreading.
I found a sample like this one in the bottom, but it seems not pithonic for me.
If I will add one more function to parse one more site, I will need to add each time the same block of code:
```
qN = Queue()
Thread(target=wrapper, args=(last_news_from_bar, qN)).start()
news_from_N = qN.get()
for new in news_from_N:
news.append(new)
```
Is there another solution to do this kind of stuff?
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
from queue import Queue
from threading import Thread
def wrapper(func, queue):
queue.put(func())
def last_news_from_bar():
...
return list_of_articles #[['title1', 'http://someurl1', '2017-09-13'],['title2', 'http://someurl2', '2017-09-13']]
def last_news_from_foo():
...
return list_of_articles
q1, q2 = Queue(), Queue()
Thread(target=wrapper, args=(last_news_from_bar, q1)).start()
Thread(target=wrapper, args=(last_news_from_foo, q2)).start()
news_from_bar = q1.get()
news_from_foo = q2.get()
all_news = []
for new in news_from_bar:
news.append(new)
for new in news_from_foo:
news.append(new)
print(all_news)
```
|
2017/09/13
|
[
"https://Stackoverflow.com/questions/46188797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6217484/"
] |
Solution without `Queue`:
```
NEWS = []
LOCK = Lock()
def gather_news(url):
while True:
news = news_from(url)
if not news: break
with LOCK:
NEWS.append(news)
if __name__ == '__main__':
T = []
for url in ['url1', 'url2', 'url3']:
t = Thread(target=gather_news, args=(url,))
t.start()
T.append(t)
# Wait until all Threads done
for t in T:
t.join()
print(NEWS)
```
|
All, that you should do, is using a single queue and extend your result array:
```
q1 = Queue()
Thread(target=wrapper, args=(last_news_from_bar, q1)).start()
Thread(target=wrapper, args=(last_news_from_foo, q1)).start()
all_news = []
all_news.extend(q1.get())
all_news.extend(q1.get())
print(all_news)
```
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
Since neighboring string constants are automatically concatenated, you can code it like this:
```
s = ("this is my really, really, really, really, really, really, "
"really long string that I'd like to shorten.")
```
Note no plus sign, and I added the extra comma and space that follows the formatting of your example.
Personally I don't like the backslashes, and I recall reading somewhere that its use is actually deprecated in favor of this form which is more explicit. Remember "Explicit is better than implicit."
I consider the backslash to be less clear and less useful because this is actually escaping the newline character. It's not possible to put a line end comment after it if one should be necessary. It is possible to do this with concatenated string constants:
```
s = ("this is my really, really, really, really, really, really, " # comments ok
"really long string that I'd like to shorten.")
```
---
I used a Google search of "python line length" which returns the PEP8 link as the first result, but also links to another good StackOverflow post on this topic: "[Why should Python PEP-8 specify a maximum line length of 79 characters?](https://stackoverflow.com/questions/88942/why-should-python-pep-8-specify-a-maximum-line-length-of-79-characters)"
Another good search phrase would be "python line continuation".
|
I've used textwrap.dedent in the past. It's a little cumbersome so I prefer line continuations now but if you really want the block indent, I think this is great.
Example Code (where the trim is to get rid of the first '\n' with a slice):
```
import textwrap as tw
x = """\
This is a yet another test.
This is only a test"""
print(tw.dedent(x))
```
Explanation:
dedent calculates the indentation based on the white space in the first line of text before a new line. If you wanted to tweak it, you could easily reimplement it using the `re` module.
This method has limitations in that very long lines may still be longer than you want in which case other methods that concatenate strings is more suitable.
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
If you must insert a long string literal and want flake8 to shut up, you can use it's [shutting up directives](http://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html). For example, in a testing routine I defined some fake CSV input. I found that splitting it over more lines that it had rows would be mightily confusing, so I decided to add a `# noqa: E501` as follows:
```
csv_test_content = """"STATION","DATE","SOURCE","LATITUDE","LONGITUDE","ELEVATION","NAME","REPORT_TYPE","CALL_SIGN","QUALITY_CONTROL","WND","CIG","VIS","TMP","DEW","SLP","AA1","AA2","AY1","AY2","GF1","MW1","REM"
"94733099999","2019-01-03T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","050,1,N,0010,1","22000,1,9,N","025000,1,9,9","+0260,1","+0210,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1","01,99,1,99,9,99,9,99999,9,99,9,99,9","01,1","SYN05294733 11/75 10502 10260 20210 60004 70100 333 70000="
"94733099999","2019-01-04T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","090,1,N,0021,1","22000,1,9,N","025000,1,9,9","+0378,1","+0172,1","99999,9","06,0000,9,1",,"0,1,02,1","0,1,02,1","03,99,1,99,9,99,9,99999,9,99,9,99,9","03,1","SYN04294733 11/75 30904 10378 20172 60001 70300="
"94733099999","2019-01-04T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","290,1,N,0057,1","99999,9,9,N","020000,1,9,9","+0339,1","+0201,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1",,"02,1","SYN05294733 11970 02911 10339 20201 60004 70200 333 70000="
"94733099999","2019-01-05T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","200,1,N,0026,1","99999,9,9,N","000100,1,9,9","+0209,1","+0193,1","99999,9","24,0004,3,1",,"1,1,02,1","1,1,02,1","08,99,1,99,9,99,9,99999,9,99,9,99,9","51,1","SYN05294733 11/01 82005 10209 20193 69944 75111 333 70004="
"94733099999","2019-01-08T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","070,1,N,0026,1","22000,1,9,N","025000,1,9,9","+0344,1","+0213,1","99999,9","06,0000,9,1",,"2,1,02,1","2,1,02,1","04,99,1,99,9,99,9,99999,9,99,9,99,9","02,1","SYN04294733 11/75 40705 10344 20213 60001 70222="
""" # noqa: E501
```
|
```
message = f"Variable : child({type(child)}) -> is not of"\
" type Node."
```
This syntax worked for me. Note the indentation of the second statement, it should be indented correctly.
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
These are all great answers, but I couldn't find an editor plugin that would help me with editing "implicitly concatenated" strings, so I wrote a package to make it easier on me.
On pip (install paragraphs) if whoever's wandering this old thread would like to check it out. Formats multi-line strings the way html does (compress whitespace, two newlines for a new paragraph, no worries about spaces between lines).
```
from paragraphs import par
class SuddenDeathError(Exception):
def __init__(self, cause: str) -> None:
self.cause = cause
def __str__(self):
return par(
f""" Y - e - e - e - es, Lord love you! Why should she die of
{self.cause}? She come through diphtheria right enough the year
before. I saw her with my own eyes. Fairly blue with it, she
was. They all thought she was dead; but my father he kept ladling
gin down her throat till she came to so sudden that she bit the bowl
off the spoon.
What call would a woman with that strength in her have to die of
{self.cause}? What become of her new straw hat that should have
come to me? Somebody pinched it; and what I say is, them as pinched
it done her in."""
)
raise SuddenDeathError("influenza")
```
becomes ...
```html
__main__.SuddenDeathError: Y - e - e - e - es, Lord love you! Why should she die of influenza? She come through diphtheria right enough the year before. I saw her with my own eyes. Fairly blue with it, she was. They all thought she was dead; but my father he kept ladling gin down her throat till she came to so sudden that she bit the bowl off the spoon.
What call would a woman with that strength in her have to die of influenza? What become of her new straw hat that should have come to me? Somebody pinched it; and what I say is, them as pinched it done her in.
```
Everything lines up easily with (Vim) 'gq'
|
Backslash:
```
s = "this is my really, really, really, really, really, really" + \
"really long string that I'd like to shorten."
```
or wrap in parens:
```
s = ("this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten.")
```
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
Since neighboring string constants are automatically concatenated, you can code it like this:
```
s = ("this is my really, really, really, really, really, really, "
"really long string that I'd like to shorten.")
```
Note no plus sign, and I added the extra comma and space that follows the formatting of your example.
Personally I don't like the backslashes, and I recall reading somewhere that its use is actually deprecated in favor of this form which is more explicit. Remember "Explicit is better than implicit."
I consider the backslash to be less clear and less useful because this is actually escaping the newline character. It's not possible to put a line end comment after it if one should be necessary. It is possible to do this with concatenated string constants:
```
s = ("this is my really, really, really, really, really, really, " # comments ok
"really long string that I'd like to shorten.")
```
---
I used a Google search of "python line length" which returns the PEP8 link as the first result, but also links to another good StackOverflow post on this topic: "[Why should Python PEP-8 specify a maximum line length of 79 characters?](https://stackoverflow.com/questions/88942/why-should-python-pep-8-specify-a-maximum-line-length-of-79-characters)"
Another good search phrase would be "python line continuation".
|
```
message = f"Variable : child({type(child)}) -> is not of"\
" type Node."
```
This syntax worked for me. Note the indentation of the second statement, it should be indented correctly.
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
Using **black** [https://github.com/psf/black] I format it like this.
```
help=f"""filters, lista de filtros para cargar las base de conocimiento.
Pueden mandarse solo algunos filtros ya que no son obligatorios,
por ejemplo, si no se manda sts, se cargarán todos las bases de todos los estados.""",
```
|
I've used textwrap.dedent in the past. It's a little cumbersome so I prefer line continuations now but if you really want the block indent, I think this is great.
Example Code (where the trim is to get rid of the first '\n' with a slice):
```
import textwrap as tw
x = """\
This is a yet another test.
This is only a test"""
print(tw.dedent(x))
```
Explanation:
dedent calculates the indentation based on the white space in the first line of text before a new line. If you wanted to tweak it, you could easily reimplement it using the `re` module.
This method has limitations in that very long lines may still be longer than you want in which case other methods that concatenate strings is more suitable.
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
Implicit concatenation might be the cleanest solution:
```
s = "this is my really, really, really, really, really, really," \
" really long string that I'd like to shorten."
```
**Edit** On reflection I agree that Todd's suggestion to use brackets rather than line continuation is better for all the reasons he gives. The only hesitation I have is that it's relatively easy to confuse bracketed strings with tuples.
|
I think the most important word in your question was "suggests".
Coding standards are funny things. Often the guidance they provide has a really good basis when it was written (e.g. most terminals being unable to show > 80 characters on a line), but over time they become functionally obsolete, but still rigidly adhered to. I guess what you need to do here is weigh up the relative merits of "breaking" that particular suggestion against the readability and mainatinability of your code.
Sorry this doesn't directly answer your question.
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
If you must insert a long string literal and want flake8 to shut up, you can use it's [shutting up directives](http://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html). For example, in a testing routine I defined some fake CSV input. I found that splitting it over more lines that it had rows would be mightily confusing, so I decided to add a `# noqa: E501` as follows:
```
csv_test_content = """"STATION","DATE","SOURCE","LATITUDE","LONGITUDE","ELEVATION","NAME","REPORT_TYPE","CALL_SIGN","QUALITY_CONTROL","WND","CIG","VIS","TMP","DEW","SLP","AA1","AA2","AY1","AY2","GF1","MW1","REM"
"94733099999","2019-01-03T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","050,1,N,0010,1","22000,1,9,N","025000,1,9,9","+0260,1","+0210,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1","01,99,1,99,9,99,9,99999,9,99,9,99,9","01,1","SYN05294733 11/75 10502 10260 20210 60004 70100 333 70000="
"94733099999","2019-01-04T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","090,1,N,0021,1","22000,1,9,N","025000,1,9,9","+0378,1","+0172,1","99999,9","06,0000,9,1",,"0,1,02,1","0,1,02,1","03,99,1,99,9,99,9,99999,9,99,9,99,9","03,1","SYN04294733 11/75 30904 10378 20172 60001 70300="
"94733099999","2019-01-04T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","290,1,N,0057,1","99999,9,9,N","020000,1,9,9","+0339,1","+0201,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1",,"02,1","SYN05294733 11970 02911 10339 20201 60004 70200 333 70000="
"94733099999","2019-01-05T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","200,1,N,0026,1","99999,9,9,N","000100,1,9,9","+0209,1","+0193,1","99999,9","24,0004,3,1",,"1,1,02,1","1,1,02,1","08,99,1,99,9,99,9,99999,9,99,9,99,9","51,1","SYN05294733 11/01 82005 10209 20193 69944 75111 333 70004="
"94733099999","2019-01-08T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","070,1,N,0026,1","22000,1,9,N","025000,1,9,9","+0344,1","+0213,1","99999,9","06,0000,9,1",,"2,1,02,1","2,1,02,1","04,99,1,99,9,99,9,99999,9,99,9,99,9","02,1","SYN04294733 11/75 40705 10344 20213 60001 70222="
""" # noqa: E501
```
|
I tend to use a couple of methods not mentioned here for specifying large strings, but these are for very specific scenarios. YMMV...
* Multi-line blobs of text, often with formatted tokens (not quite what you were asking, but still useful):
```
error_message = '''
I generally like to see how my helpful, sometimes multi-line error
messages will look against the left border.
'''.strip()
```
* Grow the variable piece-by-piece through whatever string interpolation method you prefer:
```
var = 'This is the start of a very,'
var = f'{var} very long string which could'
var = f'{var} contain a ridiculous number'
var = f'{var} of words.'
```
* Read it from a file. PEP-8 doesn't limit the length of strings in a file; just the lines of your code. :)
* Use brute-force or your editor to split the string into managaeble lines using newlines, and then remove all newlines. (Similar to the first technique I listed):
```
foo = '''
agreatbigstringthatyoudonotwanttohaveanyne
wlinesinbutforsomereasonyouneedtospecifyit
verbatimintheactualcodejustlikethis
'''.replace('\n', '')
```
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
Available options:
* **backslash**: `"foo" \ "bar"`
* **plus sign** followed by **backslash**: `"foo" + \ "bar"`
* **brackets**:
+ `("foo" "bar")`
+ **brackets** with **plus sign**: `("foo" + "bar")`
+ *PEP8, E502: the backslash is redundant between brackets*
Avoid
=====
Avoid brackets with comma: `("foo", "bar")` which defines a tuple.
---
```
>>> s = "a" \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
```
```
>>> s = "a" + \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
```
```
>>> s = ("a"
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
```
```
>>> s = ("a",
... "b")
>>> type(s)
<class 'tuple'>
```
```
>>> s = ("a" +
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>>
```
|
With a `\` you can expand statements to multiple lines:
```
s = "this is my really, really, really, really, really, really" + \
"really long string that I'd like to shorten."
```
should work.
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
You lost a space, and you probably need a line continuation character, ie. a `\`.
```
s = "this is my really, really, really, really, really, really" + \
" really long string that I'd like to shorten."
```
or even:
```
s = "this is my really, really, really, really, really, really" \
" really long string that I'd like to shorten."
```
Parens would also work instead of the line continuation, but you risk someone thinking you intended to have a tuple and had just forgotten a comma. Take for instance:
```
s = ("this is my really, really, really, really, really, really"
" really long string that I'd like to shorten.")
```
versus:
```
s = ("this is my really, really, really, really, really, really",
" really long string that I'd like to shorten.")
```
With Python's dynamic typing, the code may run either way, but produce incorrect results with the one you didn't intend.
|
I tend to use a couple of methods not mentioned here for specifying large strings, but these are for very specific scenarios. YMMV...
* Multi-line blobs of text, often with formatted tokens (not quite what you were asking, but still useful):
```
error_message = '''
I generally like to see how my helpful, sometimes multi-line error
messages will look against the left border.
'''.strip()
```
* Grow the variable piece-by-piece through whatever string interpolation method you prefer:
```
var = 'This is the start of a very,'
var = f'{var} very long string which could'
var = f'{var} contain a ridiculous number'
var = f'{var} of words.'
```
* Read it from a file. PEP-8 doesn't limit the length of strings in a file; just the lines of your code. :)
* Use brute-force or your editor to split the string into managaeble lines using newlines, and then remove all newlines. (Similar to the first technique I listed):
```
foo = '''
agreatbigstringthatyoudonotwanttohaveanyne
wlinesinbutforsomereasonyouneedtospecifyit
verbatimintheactualcodejustlikethis
'''.replace('\n', '')
```
|
1,874,592
|
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
```
How would I go about expanding this to the following line, i.e.
```
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
```
|
2009/12/09
|
[
"https://Stackoverflow.com/questions/1874592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154280/"
] |
Since neighboring string constants are automatically concatenated, you can code it like this:
```
s = ("this is my really, really, really, really, really, really, "
"really long string that I'd like to shorten.")
```
Note no plus sign, and I added the extra comma and space that follows the formatting of your example.
Personally I don't like the backslashes, and I recall reading somewhere that its use is actually deprecated in favor of this form which is more explicit. Remember "Explicit is better than implicit."
I consider the backslash to be less clear and less useful because this is actually escaping the newline character. It's not possible to put a line end comment after it if one should be necessary. It is possible to do this with concatenated string constants:
```
s = ("this is my really, really, really, really, really, really, " # comments ok
"really long string that I'd like to shorten.")
```
---
I used a Google search of "python line length" which returns the PEP8 link as the first result, but also links to another good StackOverflow post on this topic: "[Why should Python PEP-8 specify a maximum line length of 79 characters?](https://stackoverflow.com/questions/88942/why-should-python-pep-8-specify-a-maximum-line-length-of-79-characters)"
Another good search phrase would be "python line continuation".
|
I think the most important word in your question was "suggests".
Coding standards are funny things. Often the guidance they provide has a really good basis when it was written (e.g. most terminals being unable to show > 80 characters on a line), but over time they become functionally obsolete, but still rigidly adhered to. I guess what you need to do here is weigh up the relative merits of "breaking" that particular suggestion against the readability and mainatinability of your code.
Sorry this doesn't directly answer your question.
|
43,540,159
|
I am trying to build an executable out of my .py script using Pyinstaller. The problem is that it builds it using Python 2.7 instead of Python 3.5, so my executable won't even run.
```
cali@californiki-pc ~/Desktop $ pyinstaller --onefile Vocabulary.py
25 INFO: PyInstaller: 3.2.1
25 INFO: Python: 2.7.12
26 INFO: Platform: Linux-4.4.0-72-generic-x86_64-with-LinuxMint-18.1-serena
26 INFO: wrote /home/cali/Desktop/Vocabulary.spec
31 INFO: UPX is not available.
32 INFO: Extending PYTHONPATH with paths
['/home/cali/Desktop', '/home/cali/Desktop']
32 INFO: checking Analysis
33 INFO: Building Analysis because out00-Analysis.toc is non existent
33 INFO: Initializing module dependency graph...
34 INFO: Initializing module graph hooks...
139 INFO: running Analysis out00-Analysis.toc
160 INFO: Caching module hooks...
164 INFO: Analyzing /home/cali/Desktop/Vocabulary.py
246 INFO: Processing pre-safe import module hook _xmlplus
1991 INFO: Processing pre-find module path hook distutils
2209 INFO: Loading module hooks...
2209 INFO: Loading module hook "hook-distutils.py"...
2210 INFO: Loading module hook "hook-xml.py"...
2959 INFO: Loading module hook "hook-httplib.py"...
2960 INFO: Loading module hook "hook-encodings.py"...
3427 INFO: Looking for ctypes DLLs
3428 INFO: Analyzing run-time hooks ...
3435 INFO: Looking for dynamic libraries
3663 INFO: Looking for eggs
3663 INFO: Python library not in binary depedencies. Doing additional searching...
3707 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0
3710 INFO: Warnings written to /home/cali/Desktop/build/Vocabulary/warnVocabulary.txt
3768 INFO: checking PYZ
3768 INFO: Building PYZ because out00-PYZ.toc is non existent
3768 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz
4122 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz completed successfully.
4172 INFO: checking PKG
4172 INFO: Building PKG because out00-PKG.toc is non existent
4172 INFO: Building PKG (CArchive) out00-PKG.pkg
7322 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully.
7336 INFO: Bootloader /usr/local/lib/python2.7/dist-packages/PyInstaller/bootloader/Linux-64bit/run
7336 INFO: checking EXE
7336 INFO: Building EXE because out00-EXE.toc is non existent
7336 INFO: Building EXE from out00-EXE.toc
7337 INFO: Appending archive to ELF section in EXE /home/cali/Desktop/dist/Vocabulary
7352 INFO: Building EXE from out00-EXE.toc completed successfully.
```
How can I overcome the issue?
@EDIT:
I tried to install Pyinstaller using `pip3 install pyinstaller` as Claudio suggested, but I am getting:
```
cali@californiki-pc ~/Desktop $ pip3 install pyinstaller
Collecting pyinstaller
Using cached PyInstaller-3.2.1.tar.bz2
Collecting setuptools (from pyinstaller)
Using cached setuptools-35.0.1-py2.py3-none-any.whl
Collecting appdirs>=1.4.0 (from setuptools->pyinstaller)
Using cached appdirs-1.4.3-py2.py3-none-any.whl
Collecting packaging>=16.8 (from setuptools->pyinstaller)
Using cached packaging-16.8-py2.py3-none-any.whl
Collecting six>=1.6.0 (from setuptools->pyinstaller)
Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller)
Using cached pyparsing-2.2.0-py2.py3-none-any.whl
Building wheels for collected packages: pyinstaller
Running setup.py bdist_wheel for pyinstaller ... error
Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-42qpk7iy/pyinstaller/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpmmn5007ppip-wheel- --python-tag cp35:
usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: -c --help [cmd1 cmd2 ...]
or: -c --help-commands
or: -c cmd --help
error: invalid command 'bdist_wheel'
----------------------------------------
Failed building wheel for pyinstaller
Running setup.py clean for pyinstaller
Failed to build pyinstaller
Installing collected packages: appdirs, six, pyparsing, packaging, setuptools, pyinstaller
Running setup.py install for pyinstaller ... done
Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.2.0 setuptools-35.0.1 six-1.10.0
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
```
|
2017/04/21
|
[
"https://Stackoverflow.com/questions/43540159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
To overcome the problem you face install PyInstaller using:
>
> pip3 install pyinstaller
>
>
>
Then take care that you run the right one (there will then be two of them in different locations, one in the path of Python2.7 modules and one in the path of Python3.5 modules)
Just installed PyInstaller for Python 3.5 on my machine:
```
$ pip3 install pyinstaller
Collecting pyinstaller
Collecting setuptools (from pyinstaller)
Using cached setuptools-35.0.1-py2.py3-none-any.whl
Collecting six>=1.6.0 (from setuptools->pyinstaller)
Using cached six-1.10.0-py2.py3-none-any.whl
Collecting appdirs>=1.4.0 (from setuptools->pyinstaller)
Using cached appdirs-1.4.3-py2.py3-none-any.whl
Collecting packaging>=16.8 (from setuptools->pyinstaller)
Using cached packaging-16.8-py2.py3-none-any.whl
Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller)
Using cached pyparsing-2.2.0-py2.py3-none-any.whl
Installing collected packages: six, appdirs, pyparsing, packaging, setuptools, pyinstaller
Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.0.3 setuptools-20.7.0 six-1.10.0
```
It installs without problems ... Hmmm ...
Try:
```
sudo -H pip3 install setuptools --upgrade
```
(see for more [here](https://stackoverflow.com/questions/34819221/why-is-python-setup-py-saying-invalid-command-bdist-wheel-on-travis-ci) - you are not alone with this problem)
|
Just set an option -upx-dir in pyinstaller specifying your path for python 3.5. It can be the virtual environment too. For instance:
```
pyinstaller --upx-dir="$HOME/virtual-envs/<your-virtual-env>/lib/python3.5/site-packages/" <your-script>.py'
```
|
43,540,159
|
I am trying to build an executable out of my .py script using Pyinstaller. The problem is that it builds it using Python 2.7 instead of Python 3.5, so my executable won't even run.
```
cali@californiki-pc ~/Desktop $ pyinstaller --onefile Vocabulary.py
25 INFO: PyInstaller: 3.2.1
25 INFO: Python: 2.7.12
26 INFO: Platform: Linux-4.4.0-72-generic-x86_64-with-LinuxMint-18.1-serena
26 INFO: wrote /home/cali/Desktop/Vocabulary.spec
31 INFO: UPX is not available.
32 INFO: Extending PYTHONPATH with paths
['/home/cali/Desktop', '/home/cali/Desktop']
32 INFO: checking Analysis
33 INFO: Building Analysis because out00-Analysis.toc is non existent
33 INFO: Initializing module dependency graph...
34 INFO: Initializing module graph hooks...
139 INFO: running Analysis out00-Analysis.toc
160 INFO: Caching module hooks...
164 INFO: Analyzing /home/cali/Desktop/Vocabulary.py
246 INFO: Processing pre-safe import module hook _xmlplus
1991 INFO: Processing pre-find module path hook distutils
2209 INFO: Loading module hooks...
2209 INFO: Loading module hook "hook-distutils.py"...
2210 INFO: Loading module hook "hook-xml.py"...
2959 INFO: Loading module hook "hook-httplib.py"...
2960 INFO: Loading module hook "hook-encodings.py"...
3427 INFO: Looking for ctypes DLLs
3428 INFO: Analyzing run-time hooks ...
3435 INFO: Looking for dynamic libraries
3663 INFO: Looking for eggs
3663 INFO: Python library not in binary depedencies. Doing additional searching...
3707 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0
3710 INFO: Warnings written to /home/cali/Desktop/build/Vocabulary/warnVocabulary.txt
3768 INFO: checking PYZ
3768 INFO: Building PYZ because out00-PYZ.toc is non existent
3768 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz
4122 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz completed successfully.
4172 INFO: checking PKG
4172 INFO: Building PKG because out00-PKG.toc is non existent
4172 INFO: Building PKG (CArchive) out00-PKG.pkg
7322 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully.
7336 INFO: Bootloader /usr/local/lib/python2.7/dist-packages/PyInstaller/bootloader/Linux-64bit/run
7336 INFO: checking EXE
7336 INFO: Building EXE because out00-EXE.toc is non existent
7336 INFO: Building EXE from out00-EXE.toc
7337 INFO: Appending archive to ELF section in EXE /home/cali/Desktop/dist/Vocabulary
7352 INFO: Building EXE from out00-EXE.toc completed successfully.
```
How can I overcome the issue?
@EDIT:
I tried to install Pyinstaller using `pip3 install pyinstaller` as Claudio suggested, but I am getting:
```
cali@californiki-pc ~/Desktop $ pip3 install pyinstaller
Collecting pyinstaller
Using cached PyInstaller-3.2.1.tar.bz2
Collecting setuptools (from pyinstaller)
Using cached setuptools-35.0.1-py2.py3-none-any.whl
Collecting appdirs>=1.4.0 (from setuptools->pyinstaller)
Using cached appdirs-1.4.3-py2.py3-none-any.whl
Collecting packaging>=16.8 (from setuptools->pyinstaller)
Using cached packaging-16.8-py2.py3-none-any.whl
Collecting six>=1.6.0 (from setuptools->pyinstaller)
Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller)
Using cached pyparsing-2.2.0-py2.py3-none-any.whl
Building wheels for collected packages: pyinstaller
Running setup.py bdist_wheel for pyinstaller ... error
Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-42qpk7iy/pyinstaller/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpmmn5007ppip-wheel- --python-tag cp35:
usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: -c --help [cmd1 cmd2 ...]
or: -c --help-commands
or: -c cmd --help
error: invalid command 'bdist_wheel'
----------------------------------------
Failed building wheel for pyinstaller
Running setup.py clean for pyinstaller
Failed to build pyinstaller
Installing collected packages: appdirs, six, pyparsing, packaging, setuptools, pyinstaller
Running setup.py install for pyinstaller ... done
Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.2.0 setuptools-35.0.1 six-1.10.0
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
```
|
2017/04/21
|
[
"https://Stackoverflow.com/questions/43540159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Try:
```
py -3.5 -m PyInstaller Vocabulary.py --onefile
```
I think it is case sensitive
|
Just set an option -upx-dir in pyinstaller specifying your path for python 3.5. It can be the virtual environment too. For instance:
```
pyinstaller --upx-dir="$HOME/virtual-envs/<your-virtual-env>/lib/python3.5/site-packages/" <your-script>.py'
```
|
61,250,928
|
```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
```
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
|
2020/04/16
|
[
"https://Stackoverflow.com/questions/61250928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13111498/"
] |
Change the if statement:
```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
while True:
if 0 <= score <= 100:
break
score = int(input("Invalid score, please re-enter: "))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
```
---
Here, the `score` at the same time can't be less than 0 and greater than 100. So as you want to break of the score is between 0 and 100, we use `0 <= score <= 100` as the `break`ing condition.
Also the loops were reversed, since you won't get what you expected to.
|
try this one:
```
array = []
total = 0
num_of_students = int(input("How many students in your class: "))
print("\n")
for x in range(num_of_students):
score = int(input("Input score {} : ".format(x + 1)))
while True:
if score < 0 or score > 100:
score = int(input("Invalid score, please re-enter: "))
else:
array.append(score)
break
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/num_of_students))
```
|
61,250,928
|
```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
```
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
|
2020/04/16
|
[
"https://Stackoverflow.com/questions/61250928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13111498/"
] |
Change the if statement:
```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
while True:
if 0 <= score <= 100:
break
score = int(input("Invalid score, please re-enter: "))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
```
---
Here, the `score` at the same time can't be less than 0 and greater than 100. So as you want to break of the score is between 0 and 100, we use `0 <= score <= 100` as the `break`ing condition.
Also the loops were reversed, since you won't get what you expected to.
|
You could try something like this:
```
score = -1
first_time = True
while type(score) != int or score <= 0 or score >= 101 :
if first_time:
score = int(input("Input score: "))
first_time = False
else:
score = int(input("Invalid score, please re-enter: "))
array.append(score)
```
|
61,250,928
|
```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
```
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
|
2020/04/16
|
[
"https://Stackoverflow.com/questions/61250928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13111498/"
] |
Change the if statement:
```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
while True:
if 0 <= score <= 100:
break
score = int(input("Invalid score, please re-enter: "))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
```
---
Here, the `score` at the same time can't be less than 0 and greater than 100. So as you want to break of the score is between 0 and 100, we use `0 <= score <= 100` as the `break`ing condition.
Also the loops were reversed, since you won't get what you expected to.
|
I renamed some of your variables. You should always try to using self explanatory variable names. I am also using string interpolation (should be possible for Python +3.6) and comparison chaining.
```
score_list = []
total = 0
number_of_students = int(input("How many students in your class: "))
print("\n")
for student in range(number_of_students):
score_invalid = True
while score_invalid:
score_student = int(input(f"Input score {student + 1} : "))
if (0 <= score_student <= 100):
score_invalid = False
else:
score_invalid = True
if score_invalid:
print("Invalid score!\n")
score_list.append(score_student)
print("\n")
print(f"Maximum: {max(score_list)}")
print(f"Minimum: {min(score_list)}")
print(f"Average: {sum(score_list) / number_of_students}")
```
|
61,250,928
|
```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
```
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
|
2020/04/16
|
[
"https://Stackoverflow.com/questions/61250928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13111498/"
] |
try this one:
```
array = []
total = 0
num_of_students = int(input("How many students in your class: "))
print("\n")
for x in range(num_of_students):
score = int(input("Input score {} : ".format(x + 1)))
while True:
if score < 0 or score > 100:
score = int(input("Invalid score, please re-enter: "))
else:
array.append(score)
break
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/num_of_students))
```
|
You could try something like this:
```
score = -1
first_time = True
while type(score) != int or score <= 0 or score >= 101 :
if first_time:
score = int(input("Input score: "))
first_time = False
else:
score = int(input("Invalid score, please re-enter: "))
array.append(score)
```
|
61,250,928
|
```
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
```
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
|
2020/04/16
|
[
"https://Stackoverflow.com/questions/61250928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13111498/"
] |
I renamed some of your variables. You should always try to using self explanatory variable names. I am also using string interpolation (should be possible for Python +3.6) and comparison chaining.
```
score_list = []
total = 0
number_of_students = int(input("How many students in your class: "))
print("\n")
for student in range(number_of_students):
score_invalid = True
while score_invalid:
score_student = int(input(f"Input score {student + 1} : "))
if (0 <= score_student <= 100):
score_invalid = False
else:
score_invalid = True
if score_invalid:
print("Invalid score!\n")
score_list.append(score_student)
print("\n")
print(f"Maximum: {max(score_list)}")
print(f"Minimum: {min(score_list)}")
print(f"Average: {sum(score_list) / number_of_students}")
```
|
You could try something like this:
```
score = -1
first_time = True
while type(score) != int or score <= 0 or score >= 101 :
if first_time:
score = int(input("Input score: "))
first_time = False
else:
score = int(input("Invalid score, please re-enter: "))
array.append(score)
```
|
62,214,293
|
I usually start all my scripts with the shebang line
```
#!/usr/bin/env python
```
However our production server has Python 2 as the default `python`, while all of our new scripts and programs are being built under Python 3. To help keep people from accidentally running the script with the default Python 2, I am considering switching all my shebangs from now on to this;
```
#!/usr/bin/env python3
```
On our server, `python3` indeed points to Python 3, and our basic scripts will run correctly on it. However I am not clear if this is something specific to our installation, or if `python3` is *always* available if Python 3 is installed?
I know this probably will not help a user who runs `$ python myscript.py` when the default Python is loaded, but its better than nothing and is clear enough in letting a user who inspects the script realize they are using the wrong Python version. Though now I also realize that, with Python being on version 3.8, a Python 4 is imminent... at the same time, I am not sure I am ready to embed code in every single script to check if Python >= 3 is loaded...
|
2020/06/05
|
[
"https://Stackoverflow.com/questions/62214293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5359531/"
] |
Yes, this is a safe bet.
[PEP 394](https://www.python.org/dev/peps/pep-0394/) recommends Python 3 be available under the binary name `python3` and most Linux distributions follow this recommendation. In fact, this is the *only* name under which Python 3 has been available in most distributions (the only outlier being Arch Linux, but even that also provides a `python3` binary), and plans to make the ‘plain’ `python` binary also refer to Python 3 have only been made quite recently. The article [‘Revisiting PEP 394’](https://lwn.net/Articles/780737/) on LWN.net has more details.
|
I believe that a python 3 version only install's `python3` if there is already another version of python installed, no matter if it is a python 2 or python 3 version, because the standard `python` command would then not work properly for the new version of python.
But please correct me if I'm wrong!
|
38,811,966
|
I'm trying to create an exe for my python script using pyinstaller each time it runs into errors which can be found in a pastebin [here](http://pastebin.com/DJrZjVkv).
Also when I double click the exe file it shows this error:
>
> C:Users\Afro\AppData\Local\Temp\_MEI51322\VCRUNTIME140.dll is either not designed to run on windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support. Error status 0xc000007b
>
>
>
and then this:
>
> Error loading Python DLL:
> C:\Users\Afro\AppData\Local\Temp\_MEI51322\python35.dll(error code 193)
>
>
>
what's wrong, please?
|
2016/08/07
|
[
"https://Stackoverflow.com/questions/38811966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483094/"
] |
I was haunted with similar issue. It might be that in your case UPX is breaking vcruntime140.dll.
Solution to this is turning off UPX, so just add **--noupx** to your pyinstaller call.
```
pyinstaller --noupx --onedir --onefile --windowed get.py
```
Long explanation here: [UPX breaking vcruntime140.dll (64bit)](https://github.com/pyinstaller/pyinstaller/issues/1565)
|
In my case it was:
```
pyinstaller --clean --win-private-assemblies --noupx --onedir --onefile script.py
```
**--windowed** caused problems with wxWidgets
|
38,811,966
|
I'm trying to create an exe for my python script using pyinstaller each time it runs into errors which can be found in a pastebin [here](http://pastebin.com/DJrZjVkv).
Also when I double click the exe file it shows this error:
>
> C:Users\Afro\AppData\Local\Temp\_MEI51322\VCRUNTIME140.dll is either not designed to run on windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support. Error status 0xc000007b
>
>
>
and then this:
>
> Error loading Python DLL:
> C:\Users\Afro\AppData\Local\Temp\_MEI51322\python35.dll(error code 193)
>
>
>
what's wrong, please?
|
2016/08/07
|
[
"https://Stackoverflow.com/questions/38811966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483094/"
] |
I was haunted with similar issue. It might be that in your case UPX is breaking vcruntime140.dll.
Solution to this is turning off UPX, so just add **--noupx** to your pyinstaller call.
```
pyinstaller --noupx --onedir --onefile --windowed get.py
```
Long explanation here: [UPX breaking vcruntime140.dll (64bit)](https://github.com/pyinstaller/pyinstaller/issues/1565)
|
I have also met this issue, and the root cause is that I am using upx to compress the file size. The solution is to exclude files which should not be compressed by upx:
```
pyinstaller --onefile --console --upx-dir=/path/to/upx --upx-exclude=vcruntime140.dll --upx-exclude=python36.dll my_script.py
```
|
38,811,966
|
I'm trying to create an exe for my python script using pyinstaller each time it runs into errors which can be found in a pastebin [here](http://pastebin.com/DJrZjVkv).
Also when I double click the exe file it shows this error:
>
> C:Users\Afro\AppData\Local\Temp\_MEI51322\VCRUNTIME140.dll is either not designed to run on windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support. Error status 0xc000007b
>
>
>
and then this:
>
> Error loading Python DLL:
> C:\Users\Afro\AppData\Local\Temp\_MEI51322\python35.dll(error code 193)
>
>
>
what's wrong, please?
|
2016/08/07
|
[
"https://Stackoverflow.com/questions/38811966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483094/"
] |
I was haunted with similar issue. It might be that in your case UPX is breaking vcruntime140.dll.
Solution to this is turning off UPX, so just add **--noupx** to your pyinstaller call.
```
pyinstaller --noupx --onedir --onefile --windowed get.py
```
Long explanation here: [UPX breaking vcruntime140.dll (64bit)](https://github.com/pyinstaller/pyinstaller/issues/1565)
|
I tried with this version of Pyinstaller commands, Add this commands to a `.bat` file and execute the `.bat` file. It worked for me:
```
pyinstaller --log-level=WARN ^
--upx-dir <PATH_TO_UPX.exe_FILE> ^
--upx-exclude vcruntime140.dll ^
--upx-exclude ucrtbase.dll ^
--upx-exclude qwindows.dll ^
--upx-exclude libegl.dll ^
--name <NAME_OF_APPLICATION> ^
--onefile --windowed ^
<PY_DEPENDENT_FILES.py>
```
|
38,811,966
|
I'm trying to create an exe for my python script using pyinstaller each time it runs into errors which can be found in a pastebin [here](http://pastebin.com/DJrZjVkv).
Also when I double click the exe file it shows this error:
>
> C:Users\Afro\AppData\Local\Temp\_MEI51322\VCRUNTIME140.dll is either not designed to run on windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support. Error status 0xc000007b
>
>
>
and then this:
>
> Error loading Python DLL:
> C:\Users\Afro\AppData\Local\Temp\_MEI51322\python35.dll(error code 193)
>
>
>
what's wrong, please?
|
2016/08/07
|
[
"https://Stackoverflow.com/questions/38811966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483094/"
] |
I have also met this issue, and the root cause is that I am using upx to compress the file size. The solution is to exclude files which should not be compressed by upx:
```
pyinstaller --onefile --console --upx-dir=/path/to/upx --upx-exclude=vcruntime140.dll --upx-exclude=python36.dll my_script.py
```
|
In my case it was:
```
pyinstaller --clean --win-private-assemblies --noupx --onedir --onefile script.py
```
**--windowed** caused problems with wxWidgets
|
38,811,966
|
I'm trying to create an exe for my python script using pyinstaller each time it runs into errors which can be found in a pastebin [here](http://pastebin.com/DJrZjVkv).
Also when I double click the exe file it shows this error:
>
> C:Users\Afro\AppData\Local\Temp\_MEI51322\VCRUNTIME140.dll is either not designed to run on windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support. Error status 0xc000007b
>
>
>
and then this:
>
> Error loading Python DLL:
> C:\Users\Afro\AppData\Local\Temp\_MEI51322\python35.dll(error code 193)
>
>
>
what's wrong, please?
|
2016/08/07
|
[
"https://Stackoverflow.com/questions/38811966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483094/"
] |
I have also met this issue, and the root cause is that I am using upx to compress the file size. The solution is to exclude files which should not be compressed by upx:
```
pyinstaller --onefile --console --upx-dir=/path/to/upx --upx-exclude=vcruntime140.dll --upx-exclude=python36.dll my_script.py
```
|
I tried with this version of Pyinstaller commands, Add this commands to a `.bat` file and execute the `.bat` file. It worked for me:
```
pyinstaller --log-level=WARN ^
--upx-dir <PATH_TO_UPX.exe_FILE> ^
--upx-exclude vcruntime140.dll ^
--upx-exclude ucrtbase.dll ^
--upx-exclude qwindows.dll ^
--upx-exclude libegl.dll ^
--name <NAME_OF_APPLICATION> ^
--onefile --windowed ^
<PY_DEPENDENT_FILES.py>
```
|
45,628,653
|
I have written a small program in `tkinter` in `python 3.5`
I'm making executable out of it using `pyintaller`
I have included a custom icon to the window to replace default feather icon of tkinter
```
from tkinter import *
from tkinter import messagebox
import webbrowser
calculator = Tk()
calculator.title("TBE Calculator")
calculator.resizable(0, 0)
iconFile = 'calculator.ico'
calculator.iconbitmap(default=iconFile)
```
icon works fine when running `program.py` file directly
But when making it executable using
```
pyinstaller --onefile --windowed --icon=program.ico program.py
```
and running program.exe from dist directory, it gives error as
```
failed to execute script program
```
I also tried with
```
pyinstaller --onefile --windowed --icon=program.ico --add-data="calculator.ico;ico" program.py
```
But still same error.
**program.spec** file
```
# -*- mode: python -*-
block_cipher = None
a = Analysis(['program.py'],
pathex=['C:\\Users\\anuj\\PycharmProjects\\YouTubePlayer\\Program'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='calculator',
debug=False,
strip=False,
upx=True,
console=False , icon='program.ico')
```
Removing the line `calculator.iconbitmap(default=iconFile)` works fine but with default feather icon.
**How to include window icon file with .exe executable?**
|
2017/08/11
|
[
"https://Stackoverflow.com/questions/45628653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3719167/"
] |
Uninstall and re install the visual studio with azure service fabric tools resolved the problem.
|

I have install only runtime this way. Hope this will help you to install runtime only.
|
52,287,641
|
I have a the below `df1`:
```
Date Tickers Qty
01-01-2018 ABC 25
02-01-2018 BCD 25
02-01-2018 XYZ 31
05-01-2018 XYZ 25
```
and another `df2` as below
```
Date ABC BCD XYZ
01-01-2018 123 5 78
02-01-2018 125 7 79
03-01-2018 127 6 81
04-01-2018 126 7 82
05-01-2018 124 6 83
```
I want a resultant column in `df1` which is the product of the correct column and row in `df2` - getting the right ticker's rate on the given date and let the other dates have nan within `df1`
```
Date df1['Product']
01-01-2018 3075
02-01-2018 175
02-01-2018 2449
03-01-2018 nan
04-01-2018 nan
05-01-2018 2075
```
This seems like standard python operation, but I just am unable to achieve this without writing a loop - which is taking a very long time to execute:
I merged the above 2 tables on `Date` and then ran the below loop
```
for i in range(len(df1)):
try:
df1['Product'][i] = df1[df1['Ticker'][i]][i]
except ValueError:
df['Product'][i] = np.nan
```
Is there any better pythonic way of achieving this and not writing this loop pls?
|
2018/09/12
|
[
"https://Stackoverflow.com/questions/52287641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6577574/"
] |
Use:
```
df11 = df1.pivot('Date', 'Tickers','Qty')
df22 = df2.set_index('Date')
s = df22.mul(df11).bfill(axis=1).iloc[:, 0]
print (s)
Date
01-01-2018 3075.0
02-01-2018 175.0
03-01-2018 NaN
04-01-2018 NaN
05-01-2018 2075.0
Name: ABC, dtype: float64
```
Solution for add new column to `df1`:
```
df11 = df1.pivot('Date', 'Tickers','Qty')
df22 = df2.set_index('Date')
df = df1.join(df22.mul(df11).stack().rename('new'), on=['Date','Tickers'], how='left')
print (df)
Date Tickers Qty new
0 01-01-2018 ABC 25 3075.0
1 02-01-2018 BCD 25 175.0
2 05-01-2018 XYZ 25 2075.0
```
EDIT:
If pairs `Date`s with `Tickers` are duplicated, solution above is not possible use.
```
print (df1)
Date Tickers Qty
0 01-01-2018 ABC 25
1 01-01-2018 ABC 20 <-added duplicated pairs 01-01-2018 and ABC
2 02-01-2018 XYZ 31
3 02-01-2018 BCD 25
4 05-01-2018 XYZ 25
df3 = df1[['Date']].copy()
#add new values to column
df3['new'] = df2.set_index('Date').lookup(df1['Date'], df1['Tickers']) * df1['Qty']
#add missing values to duplicated Dates
df3 = df2[['Date']].drop_duplicates().merge(df3, how='left')
print (df3)
Date new
0 01-01-2018 3075.0
1 01-01-2018 2460.0
2 02-01-2018 2449.0
3 02-01-2018 175.0
4 03-01-2018 NaN
5 04-01-2018 NaN
6 05-01-2018 2075.0
```
|
you need to set 'Date' as index and multiply,
```
df1=df1.set_index('Date')
df2=df2.set_index('Date')
df3=(df2['ABC']*df1['Qty']).reset_index()
print(df3)
Date 0
0 01-01-2018 3075.0
1 02-01-2018 3125.0
2 03-01-2018 NaN
3 04-01-2018 NaN
4 05-01-2018 3100.0
```
|
55,514,933
|
am trying to write a loop that gets .json from an url via requests, then writes the .json to a .csv file. Then I need it to it over and over again until my list of names (.txt file) is finished(89 lines). I can't get it to go over the list, it just get the error:
```py
AttributeError: module 'response' has no attribute 'append'
```
I can´t find the issue, if I change 'response' to 'responses' I get also an error
```py
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
OSError: [Errno 22] Invalid argument: "listan-['A..
```
I can't seem to find a loop fitting for my purpose. Since I am a total beginner of python I hope I can get some help here and learn more.
My code so far.
```py
#Opens the file with pricelists
pricelists = []
with open('prislistor.txt', 'r') as f:
for i, line in enumerate(f):
pricelists.append(line.strip())
# build responses
responses = []
for pricelist in pricelists:
response.append(requests.get('https://api.example.com/3/prices/sublist/{}/'.format(pricelist), headers=headers))
#Format each response
fullData = []
for response in responses:
parsed = json.loads(response.text)
listan=(json.dumps(parsed, indent=4, sort_keys=True))
#Converts and creates a .csv file.
fullData.append(parsed['Prices'])
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
dw.writeheader()
for data in fullData:
dw = csv.DictWriter(outf, data[0].keys())
for row in data:
dw.writerow(row)
print ("The file list-{}.csv is created!".format(pricelists))
```
|
2019/04/04
|
[
"https://Stackoverflow.com/questions/55514933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6553605/"
] |
VS2019 also introduced new "enhanced" colors for .NET languages, for which there is a separate option to toggle on and off:
[](https://i.stack.imgur.com/IpRoV.png)
The same checkbox is listed for both C# and Basic (VB).
|
It is possible to change in `Options->Environment->Fonts and Colors`. There is a list with different `User Memebers - ...` and `User Tyeps - ...` that define these colors.
[](https://i.stack.imgur.com/D6XSR.png)
I have actually changed `User Members - Fields` and `User Members - Properties` to be same color as `User Member - Parameters`. It became much better, white and yellow did not work too well for me :)
Now it's almost like Visual Studio Code
|
55,514,933
|
am trying to write a loop that gets .json from an url via requests, then writes the .json to a .csv file. Then I need it to it over and over again until my list of names (.txt file) is finished(89 lines). I can't get it to go over the list, it just get the error:
```py
AttributeError: module 'response' has no attribute 'append'
```
I can´t find the issue, if I change 'response' to 'responses' I get also an error
```py
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
OSError: [Errno 22] Invalid argument: "listan-['A..
```
I can't seem to find a loop fitting for my purpose. Since I am a total beginner of python I hope I can get some help here and learn more.
My code so far.
```py
#Opens the file with pricelists
pricelists = []
with open('prislistor.txt', 'r') as f:
for i, line in enumerate(f):
pricelists.append(line.strip())
# build responses
responses = []
for pricelist in pricelists:
response.append(requests.get('https://api.example.com/3/prices/sublist/{}/'.format(pricelist), headers=headers))
#Format each response
fullData = []
for response in responses:
parsed = json.loads(response.text)
listan=(json.dumps(parsed, indent=4, sort_keys=True))
#Converts and creates a .csv file.
fullData.append(parsed['Prices'])
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
dw.writeheader()
for data in fullData:
dw = csv.DictWriter(outf, data[0].keys())
for row in data:
dw.writerow(row)
print ("The file list-{}.csv is created!".format(pricelists))
```
|
2019/04/04
|
[
"https://Stackoverflow.com/questions/55514933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6553605/"
] |
It is possible to change in `Options->Environment->Fonts and Colors`. There is a list with different `User Memebers - ...` and `User Tyeps - ...` that define these colors.
[](https://i.stack.imgur.com/D6XSR.png)
I have actually changed `User Members - Fields` and `User Members - Properties` to be same color as `User Member - Parameters`. It became much better, white and yellow did not work too well for me :)
Now it's almost like Visual Studio Code
|
If you are coding in C++ you probably have enhanced color activate. To deactivate go Tool-->Options and from the left menu select Text Editor-->C/C++-->View. Then go to the section "Miscellaneous" on the right and change "Color Scheme" from "Enhanced" to "Visual Studio 2017"
|
55,514,933
|
am trying to write a loop that gets .json from an url via requests, then writes the .json to a .csv file. Then I need it to it over and over again until my list of names (.txt file) is finished(89 lines). I can't get it to go over the list, it just get the error:
```py
AttributeError: module 'response' has no attribute 'append'
```
I can´t find the issue, if I change 'response' to 'responses' I get also an error
```py
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
OSError: [Errno 22] Invalid argument: "listan-['A..
```
I can't seem to find a loop fitting for my purpose. Since I am a total beginner of python I hope I can get some help here and learn more.
My code so far.
```py
#Opens the file with pricelists
pricelists = []
with open('prislistor.txt', 'r') as f:
for i, line in enumerate(f):
pricelists.append(line.strip())
# build responses
responses = []
for pricelist in pricelists:
response.append(requests.get('https://api.example.com/3/prices/sublist/{}/'.format(pricelist), headers=headers))
#Format each response
fullData = []
for response in responses:
parsed = json.loads(response.text)
listan=(json.dumps(parsed, indent=4, sort_keys=True))
#Converts and creates a .csv file.
fullData.append(parsed['Prices'])
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
dw.writeheader()
for data in fullData:
dw = csv.DictWriter(outf, data[0].keys())
for row in data:
dw.writerow(row)
print ("The file list-{}.csv is created!".format(pricelists))
```
|
2019/04/04
|
[
"https://Stackoverflow.com/questions/55514933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6553605/"
] |
Updated answer for 2020.
[](https://i.stack.imgur.com/kt09L.png)
Make sure this is set to 2019.
|
It is possible to change in `Options->Environment->Fonts and Colors`. There is a list with different `User Memebers - ...` and `User Tyeps - ...` that define these colors.
[](https://i.stack.imgur.com/D6XSR.png)
I have actually changed `User Members - Fields` and `User Members - Properties` to be same color as `User Member - Parameters`. It became much better, white and yellow did not work too well for me :)
Now it's almost like Visual Studio Code
|
55,514,933
|
am trying to write a loop that gets .json from an url via requests, then writes the .json to a .csv file. Then I need it to it over and over again until my list of names (.txt file) is finished(89 lines). I can't get it to go over the list, it just get the error:
```py
AttributeError: module 'response' has no attribute 'append'
```
I can´t find the issue, if I change 'response' to 'responses' I get also an error
```py
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
OSError: [Errno 22] Invalid argument: "listan-['A..
```
I can't seem to find a loop fitting for my purpose. Since I am a total beginner of python I hope I can get some help here and learn more.
My code so far.
```py
#Opens the file with pricelists
pricelists = []
with open('prislistor.txt', 'r') as f:
for i, line in enumerate(f):
pricelists.append(line.strip())
# build responses
responses = []
for pricelist in pricelists:
response.append(requests.get('https://api.example.com/3/prices/sublist/{}/'.format(pricelist), headers=headers))
#Format each response
fullData = []
for response in responses:
parsed = json.loads(response.text)
listan=(json.dumps(parsed, indent=4, sort_keys=True))
#Converts and creates a .csv file.
fullData.append(parsed['Prices'])
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
dw.writeheader()
for data in fullData:
dw = csv.DictWriter(outf, data[0].keys())
for row in data:
dw.writerow(row)
print ("The file list-{}.csv is created!".format(pricelists))
```
|
2019/04/04
|
[
"https://Stackoverflow.com/questions/55514933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6553605/"
] |
VS2019 also introduced new "enhanced" colors for .NET languages, for which there is a separate option to toggle on and off:
[](https://i.stack.imgur.com/IpRoV.png)
The same checkbox is listed for both C# and Basic (VB).
|
If you are coding in C++ you probably have enhanced color activate. To deactivate go Tool-->Options and from the left menu select Text Editor-->C/C++-->View. Then go to the section "Miscellaneous" on the right and change "Color Scheme" from "Enhanced" to "Visual Studio 2017"
|
55,514,933
|
am trying to write a loop that gets .json from an url via requests, then writes the .json to a .csv file. Then I need it to it over and over again until my list of names (.txt file) is finished(89 lines). I can't get it to go over the list, it just get the error:
```py
AttributeError: module 'response' has no attribute 'append'
```
I can´t find the issue, if I change 'response' to 'responses' I get also an error
```py
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
OSError: [Errno 22] Invalid argument: "listan-['A..
```
I can't seem to find a loop fitting for my purpose. Since I am a total beginner of python I hope I can get some help here and learn more.
My code so far.
```py
#Opens the file with pricelists
pricelists = []
with open('prislistor.txt', 'r') as f:
for i, line in enumerate(f):
pricelists.append(line.strip())
# build responses
responses = []
for pricelist in pricelists:
response.append(requests.get('https://api.example.com/3/prices/sublist/{}/'.format(pricelist), headers=headers))
#Format each response
fullData = []
for response in responses:
parsed = json.loads(response.text)
listan=(json.dumps(parsed, indent=4, sort_keys=True))
#Converts and creates a .csv file.
fullData.append(parsed['Prices'])
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
dw.writeheader()
for data in fullData:
dw = csv.DictWriter(outf, data[0].keys())
for row in data:
dw.writerow(row)
print ("The file list-{}.csv is created!".format(pricelists))
```
|
2019/04/04
|
[
"https://Stackoverflow.com/questions/55514933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6553605/"
] |
VS2019 also introduced new "enhanced" colors for .NET languages, for which there is a separate option to toggle on and off:
[](https://i.stack.imgur.com/IpRoV.png)
The same checkbox is listed for both C# and Basic (VB).
|
Updated answer for 2020.
[](https://i.stack.imgur.com/kt09L.png)
Make sure this is set to 2019.
|
55,514,933
|
am trying to write a loop that gets .json from an url via requests, then writes the .json to a .csv file. Then I need it to it over and over again until my list of names (.txt file) is finished(89 lines). I can't get it to go over the list, it just get the error:
```py
AttributeError: module 'response' has no attribute 'append'
```
I can´t find the issue, if I change 'response' to 'responses' I get also an error
```py
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
OSError: [Errno 22] Invalid argument: "listan-['A..
```
I can't seem to find a loop fitting for my purpose. Since I am a total beginner of python I hope I can get some help here and learn more.
My code so far.
```py
#Opens the file with pricelists
pricelists = []
with open('prislistor.txt', 'r') as f:
for i, line in enumerate(f):
pricelists.append(line.strip())
# build responses
responses = []
for pricelist in pricelists:
response.append(requests.get('https://api.example.com/3/prices/sublist/{}/'.format(pricelist), headers=headers))
#Format each response
fullData = []
for response in responses:
parsed = json.loads(response.text)
listan=(json.dumps(parsed, indent=4, sort_keys=True))
#Converts and creates a .csv file.
fullData.append(parsed['Prices'])
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
dw.writeheader()
for data in fullData:
dw = csv.DictWriter(outf, data[0].keys())
for row in data:
dw.writerow(row)
print ("The file list-{}.csv is created!".format(pricelists))
```
|
2019/04/04
|
[
"https://Stackoverflow.com/questions/55514933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6553605/"
] |
Updated answer for 2020.
[](https://i.stack.imgur.com/kt09L.png)
Make sure this is set to 2019.
|
If you are coding in C++ you probably have enhanced color activate. To deactivate go Tool-->Options and from the left menu select Text Editor-->C/C++-->View. Then go to the section "Miscellaneous" on the right and change "Color Scheme" from "Enhanced" to "Visual Studio 2017"
|
72,066,195
|
I want to insert zero at certain locations in an array, but the index position of the location exceeds the size of the array
I wanted that as the numbers get inserted one by one, size also gets increased in that process (of the array X), so till it reaches index 62, it will not produce that error.
```
import numpy as np
X = np.arange(0,57,1)
desired_location = [ 0, 1, 24, 25, 26, 27, 62, 63]
for i in desired_location:
X_new = np.insert(X,i,0)
print(X_new)
```
output
```
File "D:\python programming\random python files\untitled4.py", line 15, in <module>
X_new = np.insert(X,i,0)
File "<__array_function__ internals>", line 6, in insert
File "D:\spyder\pkgs\numpy\lib\function_base.py", line 4560, in insert
"size %i" % (obj, axis, N))
IndexError: index 62 is out of bounds for axis 0 with size 57
```
|
2022/04/30
|
[
"https://Stackoverflow.com/questions/72066195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18746410/"
] |
Make a copy of `X` into `X_new` so the array gets longer in loop as you desire.
```
X_new = X.copy()
for i in desired_location:
X_new = np.insert(X_new, i, 0)
```
|
how silly I was.
```
import numpy as np
X = np.arange(0,57,1)
desired_location = [ 0, 1, 24, 25, 26, 27, 62, 63]
for i in desired_location:
X = np.insert(X,i,0)
print(X)
```
|
72,066,195
|
I want to insert zero at certain locations in an array, but the index position of the location exceeds the size of the array
I wanted that as the numbers get inserted one by one, size also gets increased in that process (of the array X), so till it reaches index 62, it will not produce that error.
```
import numpy as np
X = np.arange(0,57,1)
desired_location = [ 0, 1, 24, 25, 26, 27, 62, 63]
for i in desired_location:
X_new = np.insert(X,i,0)
print(X_new)
```
output
```
File "D:\python programming\random python files\untitled4.py", line 15, in <module>
X_new = np.insert(X,i,0)
File "<__array_function__ internals>", line 6, in insert
File "D:\spyder\pkgs\numpy\lib\function_base.py", line 4560, in insert
"size %i" % (obj, axis, N))
IndexError: index 62 is out of bounds for axis 0 with size 57
```
|
2022/04/30
|
[
"https://Stackoverflow.com/questions/72066195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18746410/"
] |
Make a copy of `X` into `X_new` so the array gets longer in loop as you desire.
```
X_new = X.copy()
for i in desired_location:
X_new = np.insert(X_new, i, 0)
```
|
Converting `tolist()`, inserting and converting to `np.array` is an order of magnitude faster.
```
# %%timeit 10000 loops, best of 5: 117 µs per loop
X_new = X
for i in desired_location:
X_new = np.insert(X_new,i,0)
```
```
# %%timeit 100000 loops, best of 5: 4.18 µs per loop
X_new = X.tolist()
for i in desired_location:
X_new.insert(i, 0)
np.fromiter(X_new, dtype=X.dtype)
```
|
72,066,195
|
I want to insert zero at certain locations in an array, but the index position of the location exceeds the size of the array
I wanted that as the numbers get inserted one by one, size also gets increased in that process (of the array X), so till it reaches index 62, it will not produce that error.
```
import numpy as np
X = np.arange(0,57,1)
desired_location = [ 0, 1, 24, 25, 26, 27, 62, 63]
for i in desired_location:
X_new = np.insert(X,i,0)
print(X_new)
```
output
```
File "D:\python programming\random python files\untitled4.py", line 15, in <module>
X_new = np.insert(X,i,0)
File "<__array_function__ internals>", line 6, in insert
File "D:\spyder\pkgs\numpy\lib\function_base.py", line 4560, in insert
"size %i" % (obj, axis, N))
IndexError: index 62 is out of bounds for axis 0 with size 57
```
|
2022/04/30
|
[
"https://Stackoverflow.com/questions/72066195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18746410/"
] |
how silly I was.
```
import numpy as np
X = np.arange(0,57,1)
desired_location = [ 0, 1, 24, 25, 26, 27, 62, 63]
for i in desired_location:
X = np.insert(X,i,0)
print(X)
```
|
Converting `tolist()`, inserting and converting to `np.array` is an order of magnitude faster.
```
# %%timeit 10000 loops, best of 5: 117 µs per loop
X_new = X
for i in desired_location:
X_new = np.insert(X_new,i,0)
```
```
# %%timeit 100000 loops, best of 5: 4.18 µs per loop
X_new = X.tolist()
for i in desired_location:
X_new.insert(i, 0)
np.fromiter(X_new, dtype=X.dtype)
```
|
2,686,520
|
For what I've read I need Python-Dev, how do I install it on OSX?
I think the problem I have, is, my Xcode was not properly installed, and I don't have the paths where I should.
This previous question:
[Where is gcc on OSX? I have installed Xcode already](https://stackoverflow.com/questions/2685887/where-is-gcc-on-osx-i-have-installed-xcode-already)
Was about I couldn't find gcc, now I can't find Python.h
Should I just link my /Developer directory to somewhere else in /usr/ ???
This is my output:
```
$ sudo easy_install mercurial
Password:
Searching for mercurial
Reading http://pypi.python.org/simple/mercurial/
Reading http://www.selenic.com/mercurial
Best match: mercurial 1.5.1
Downloading http://mercurial.selenic.com/release/mercurial-1.5.1.tar.gz
Processing mercurial-1.5.1.tar.gz
Running mercurial-1.5.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-_7RaTq/mercurial-1.5.1/egg-dist-tmp-l7JP3u
mercurial/base85.c:12:20: error: Python.h: No such file or directory
...
```
Thanks in advance.
|
2010/04/21
|
[
"https://Stackoverflow.com/questions/2686520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
Might depend on what version of Mac OSX you have, I have it in these spots:
```
/Developer/SDKs/MacOSX10.5.sdk/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/Python.h
/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/Python.h
```
Also I believe the version of python that comes with Xcode is a custom build that plays well with xcode but you have to jump through some hoops if you use another dev environment.
|
Are you sure you want to build Mercurial from source? There are [binary packages available](https://www.mercurial-scm.org/downloads), including the nice [MacHg](http://jasonfharris.com/machg/) which comes with a bundled Mercurial.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.