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
|
|---|---|---|---|---|---|
65,390,129
|
I create a virtual environment; let's say test\_venv, and I activate it. All successful.
HOWEVER, the path of the Python Interpreter doesn't not change. I have illustrated the situation below.
For clarification, the python path SHOULD BE `~/Desktop/test_venv/bin/python`.
```
>>> python3 -m venv Desktop/test_venv
>>> source Desktop/test_venv/bin/activate
(test_venv) >>> which python
/usr/bin/python
```
|
2020/12/21
|
[
"https://Stackoverflow.com/questions/65390129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14392583/"
] |
#### *Please make sure to read Note #2.*
---
**This is what you should do if you don't want to create a new virtual environment**:
In `venv/bin` folder there are 3 files that store your venv path explicitly
and if the path is wrong they take the normal python path so you should change the path there to your new path.
change: `set -gx VIRTUAL_ENV "what/ever/path/you/need"` in `activate.fish`
change: `VIRTUAL_ENV="what/ever/path/you/need"` in `activate`
change: `setenv VIRTUAL_ENV "what/ever/path/you/need"` in `activate.csh`
**Note #1:**
the path is to `/venv` and not to `/venv/bin`
**Note #2:**
If you reached this page it means that you are probably **not following Python's best practice for a project structure**.
If you were, the process of creating a new virtual environment was just a matter of one command line.
Please consider using one of the following methods:
* add a [`requirements.txt`](https://pip.pypa.io/en/stable/user_guide/#requirements-files) to your project - *for very small projects.*
* [implement an `setup.py` script](https://docs.python.org/3/distutils/setupscript.html) - *for real projects.*
* use a tool like [Poetry](https://python-poetry.org/) - *just like the latter though somewhat user-friendlier for some tasks.*
Thanks you Khalaimov Dmitrii, I didn't thought it was because I moved the folder.
|
Check the value of VIRTUAL\_ENV in /venv/bin/activate . If you renamed your project directory or moved it, then the value may still be the old value. PyCharm doesn't update your venv files if you used PyCharm to rename the project. You can delete the venv and recreate a new one if the path is wrong, or try the answer that talks about where to change it.
|
55,378,150
|
I have a r Script with the code:
```
args = commandArgs(trailingOnly=TRUE)
myData <- read.csv(file=args[0])
```
I want to run this using a GUI and deliver a choosen csv file with this python code
```
from tkinter import filedialog
from tkinter import *
import subprocess
window = Tk()
window.geometry('500x200')
window.title("Wordcloud Creator")
lbl = Label(window, text="1. Please prepare a CSV (-Trennzeichen) file with the columns untgscod, berpos, SpezX3")
lbl.grid(column=0, row=0)
def runScript():
filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("csv files","*.csv"),("all files","*.*")))
subprocess.call(['Rscript', 'C:/Users/Name/Desktop/R-GUI/test.r', filename])
btn = Button(window, text="Select a file and start Cloud creation", command=runScript())
btn.grid(column=0, row=1)
window.mainloop()
```
But unfortunately this is not working. I get this error but do not know what is wrong.
```
File "c:\Users\name\.vscode\extensions\ms-python.python-2019.2.5558\pythonFiles\lib\python\ptvsd\_vendored\pydevd\_pydev_bundle\pydev_monkey.py", line 444, in new_CreateProcess
return getattr(_subprocess, original_name)(app_name, patch_arg_str_win(cmd_line), *args)
FileNotFoundError: [WinError 2] The system cannot find the file specified
```
I do not see why the file cannot be found.
|
2019/03/27
|
[
"https://Stackoverflow.com/questions/55378150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2377949/"
] |
With Java 8 streams:
```
List<Accout> accounts = accounts.values().stream()
.filter(account -> account.getBalance() > threshold)
.collect(Collectors.toList())
```
With `foreach`:
```
List<Account> accountsWithMinimum = new ArrayList<>();
for (Account acccount : accounts.values() ) {
if (account.balance > threshold) {
accountsWithMinimum.add(account);
}
}
```
The `values` method of the `Map` interface returns a `Collection` of the values stored in the map. You can also used `entrySet` to get the collection of key-value pairs, or `keySet` to get only the keys.
|
From information you provided best solution seems to be change data from HashMap to [LinkedHashMap](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html), that keep ordering.
If you take a close took to javadoc, you can find following part useful:
>
> his implementation spares its clients from the unspecified, generally
> chaotic ordering provided by HashMap (and Hashtable), without
> incurring the increased cost associated with TreeMap. It can be used
> to produce a copy of a map that has the same order as the original,
> regardless of the original map's implementation:
>
>
>
> ```
> void foo(Map m) {
> Map copy = new LinkedHashMap(m);
> ...
> }
>
> ```
>
> This technique is particularly useful if a module takes a map on
> input, copies it, and later returns results whose order is determined
> by that of the copy. (Clients generally appreciate having things
> returned in the same order they were presented.)
>
>
>
So the idea is to get in input the map, create a LinkedHashMap over it, iterate using forEach. Here an example with comments where you can start to elaborate on it
```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.test();
}
private void test() {
// your input
HashMap<Integer, Account> accounts = new HashMap<>();
accounts.put(0, new Account("first", 1));
accounts.put(1, new Account("second", 10));
accounts.put(2, new Account("third", 5));
// call your method
List<Account> result = getAccountsWithMinumum(accounts);
System.out.println(result.toString());
}
private List<Account> getAccountsWithMinumum(HashMap<Integer, Account> accounts) {
List<Account> result = new ArrayList<>();
// create linkedhashmap to get order
LinkedHashMap<Integer, Account> data = new LinkedHashMap<>(accounts);
// get entries
for (Entry<Integer, Account> entry : data.entrySet()) {
// print entry
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
// check account balanece on a value, for example 6 (use it as parameter!)
if (entry.getValue().balance < 6) {
// add to the result list
result.add(entry.getValue());
}
}
return result;
}
// your account class
private class Account {
public String name;
public int balance;
public Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
@Override
public String toString() {
return "[name=" + name + ", balance=" + balance + "]";
}
}
}
```
Your answer is a little bit difficult to answer because of lack of what Hashmap is exactly, in my case is
|
55,378,150
|
I have a r Script with the code:
```
args = commandArgs(trailingOnly=TRUE)
myData <- read.csv(file=args[0])
```
I want to run this using a GUI and deliver a choosen csv file with this python code
```
from tkinter import filedialog
from tkinter import *
import subprocess
window = Tk()
window.geometry('500x200')
window.title("Wordcloud Creator")
lbl = Label(window, text="1. Please prepare a CSV (-Trennzeichen) file with the columns untgscod, berpos, SpezX3")
lbl.grid(column=0, row=0)
def runScript():
filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("csv files","*.csv"),("all files","*.*")))
subprocess.call(['Rscript', 'C:/Users/Name/Desktop/R-GUI/test.r', filename])
btn = Button(window, text="Select a file and start Cloud creation", command=runScript())
btn.grid(column=0, row=1)
window.mainloop()
```
But unfortunately this is not working. I get this error but do not know what is wrong.
```
File "c:\Users\name\.vscode\extensions\ms-python.python-2019.2.5558\pythonFiles\lib\python\ptvsd\_vendored\pydevd\_pydev_bundle\pydev_monkey.py", line 444, in new_CreateProcess
return getattr(_subprocess, original_name)(app_name, patch_arg_str_win(cmd_line), *args)
FileNotFoundError: [WinError 2] The system cannot find the file specified
```
I do not see why the file cannot be found.
|
2019/03/27
|
[
"https://Stackoverflow.com/questions/55378150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2377949/"
] |
With Java 8 streams:
```
List<Accout> accounts = accounts.values().stream()
.filter(account -> account.getBalance() > threshold)
.collect(Collectors.toList())
```
With `foreach`:
```
List<Account> accountsWithMinimum = new ArrayList<>();
for (Account acccount : accounts.values() ) {
if (account.balance > threshold) {
accountsWithMinimum.add(account);
}
}
```
The `values` method of the `Map` interface returns a `Collection` of the values stored in the map. You can also used `entrySet` to get the collection of key-value pairs, or `keySet` to get only the keys.
|
The example you found predates the use of generics in Java. Any Map is these days actually a Map<K,V>, where K is the type (= the class) of the keys in the mapping, and V is the type (once again the java class) of the value objects the key values are mapped to. So the Map in your example (looking at what types the objects are cast to) would these days be written as Map<Integer,Integer>.
There are some distinct ways of iterating over the contents of a Map : iterating its entrySet(), iterating its keySet() or iterating its values().
The first results in objects of type Map.Entry (as in the example) from which you can subsequently retrieve both the key object and the value object.
The second results in objects of type K (type of the key) and will obviously give you only the key objects leaving you no access to the corresponding value object (except by using map.get(key) which is rather stupid given that you're already iterating and could have had the value object "for free").
The third results in objects of type V (type/class of the value objects), without access to the corresponding key, except if the map has been built using key objects from within the value objects.
Assuming your Account objects are the value objects, I'd guess you'd want to iterate over the values() and then check each returned object's getBalance().
Or you can use the more modern lambda-style syntax using streams, as has been sugested in other answers.
Was this the kind of "explanation" you were looking for ?
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
The [Markdown](https://pypi.org/project/Markdown/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) (now called *beautifulsoup4*) modules will help do what you describe.
Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text.
Your code might look something like this:
```
from bs4 import BeautifulSoup
from markdown import markdown
html = markdown(some_html_string)
text = ''.join(BeautifulSoup(html).findAll(text=True))
```
|
Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
The [Markdown](https://pypi.org/project/Markdown/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) (now called *beautifulsoup4*) modules will help do what you describe.
Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text.
Your code might look something like this:
```
from bs4 import BeautifulSoup
from markdown import markdown
html = markdown(some_html_string)
text = ''.join(BeautifulSoup(html).findAll(text=True))
```
|
Despite the fact that this is a very old question, I'd like to suggest a solution I came up with recently. This one neither uses BeautifulSoup nor has an overhead of converting to html and back.
The **markdown** module core class Markdown has a property **output\_formats** which is not configurable but otherwise patchable like almost anything in python is. This property is a dict mapping output format name to a rendering function. By default it has two output formats, 'html' and 'xhtml' correspondingly. With a little help it may have a plaintext rendering function which is easy to write:
```
from markdown import Markdown
from io import StringIO
def unmark_element(element, stream=None):
if stream is None:
stream = StringIO()
if element.text:
stream.write(element.text)
for sub in element:
unmark_element(sub, stream)
if element.tail:
stream.write(element.tail)
return stream.getvalue()
# patching Markdown
Markdown.output_formats["plain"] = unmark_element
__md = Markdown(output_format="plain")
__md.stripTopLevelTags = False
def unmark(text):
return __md.convert(text)
```
**unmark** function takes markdown text as an input and returns all the markdown characters stripped out.
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
The [Markdown](https://pypi.org/project/Markdown/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) (now called *beautifulsoup4*) modules will help do what you describe.
Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text.
Your code might look something like this:
```
from bs4 import BeautifulSoup
from markdown import markdown
html = markdown(some_html_string)
text = ''.join(BeautifulSoup(html).findAll(text=True))
```
|
This is similar to Jason's answer, but handles comments correctly.
```py
import markdown # pip install markdown
from bs4 import BeautifulSoup # pip install beautifulsoup4
def md_to_text(md):
html = markdown.markdown(md)
soup = BeautifulSoup(html, features='html.parser')
return soup.get_text()
def example():
md = '**A** [B](http://example.com) <!-- C -->'
text = md_to_text(md)
print(text)
# Output: A B
```
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
The [Markdown](https://pypi.org/project/Markdown/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) (now called *beautifulsoup4*) modules will help do what you describe.
Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text.
Your code might look something like this:
```
from bs4 import BeautifulSoup
from markdown import markdown
html = markdown(some_html_string)
text = ''.join(BeautifulSoup(html).findAll(text=True))
```
|
I came here while searching for a way to perform s.c. [GitLab Releases](https://docs.gitlab.com/ee/user/project/releases/) via [API call](https://docs.gitlab.com/ee/api/releases/). I hope this matches the use case of the original questioner.
I decoded markdown to plain text (including whitespaces in the form of `\n` etc.) in that way:
```
with open("release_note.md", 'r') as file:
release_note = file.read()
description = bytes(release_note, 'utf-8')
return description.decode("utf-8")
```
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
Despite the fact that this is a very old question, I'd like to suggest a solution I came up with recently. This one neither uses BeautifulSoup nor has an overhead of converting to html and back.
The **markdown** module core class Markdown has a property **output\_formats** which is not configurable but otherwise patchable like almost anything in python is. This property is a dict mapping output format name to a rendering function. By default it has two output formats, 'html' and 'xhtml' correspondingly. With a little help it may have a plaintext rendering function which is easy to write:
```
from markdown import Markdown
from io import StringIO
def unmark_element(element, stream=None):
if stream is None:
stream = StringIO()
if element.text:
stream.write(element.text)
for sub in element:
unmark_element(sub, stream)
if element.tail:
stream.write(element.tail)
return stream.getvalue()
# patching Markdown
Markdown.output_formats["plain"] = unmark_element
__md = Markdown(output_format="plain")
__md.stripTopLevelTags = False
def unmark(text):
return __md.convert(text)
```
**unmark** function takes markdown text as an input and returns all the markdown characters stripped out.
|
Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
This is similar to Jason's answer, but handles comments correctly.
```py
import markdown # pip install markdown
from bs4 import BeautifulSoup # pip install beautifulsoup4
def md_to_text(md):
html = markdown.markdown(md)
soup = BeautifulSoup(html, features='html.parser')
return soup.get_text()
def example():
md = '**A** [B](http://example.com) <!-- C -->'
text = md_to_text(md)
print(text)
# Output: A B
```
|
Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.
|
I came here while searching for a way to perform s.c. [GitLab Releases](https://docs.gitlab.com/ee/user/project/releases/) via [API call](https://docs.gitlab.com/ee/api/releases/). I hope this matches the use case of the original questioner.
I decoded markdown to plain text (including whitespaces in the form of `\n` etc.) in that way:
```
with open("release_note.md", 'r') as file:
release_note = file.read()
description = bytes(release_note, 'utf-8')
return description.decode("utf-8")
```
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
Despite the fact that this is a very old question, I'd like to suggest a solution I came up with recently. This one neither uses BeautifulSoup nor has an overhead of converting to html and back.
The **markdown** module core class Markdown has a property **output\_formats** which is not configurable but otherwise patchable like almost anything in python is. This property is a dict mapping output format name to a rendering function. By default it has two output formats, 'html' and 'xhtml' correspondingly. With a little help it may have a plaintext rendering function which is easy to write:
```
from markdown import Markdown
from io import StringIO
def unmark_element(element, stream=None):
if stream is None:
stream = StringIO()
if element.text:
stream.write(element.text)
for sub in element:
unmark_element(sub, stream)
if element.tail:
stream.write(element.tail)
return stream.getvalue()
# patching Markdown
Markdown.output_formats["plain"] = unmark_element
__md = Markdown(output_format="plain")
__md.stripTopLevelTags = False
def unmark(text):
return __md.convert(text)
```
**unmark** function takes markdown text as an input and returns all the markdown characters stripped out.
|
This is similar to Jason's answer, but handles comments correctly.
```py
import markdown # pip install markdown
from bs4 import BeautifulSoup # pip install beautifulsoup4
def md_to_text(md):
html = markdown.markdown(md)
soup = BeautifulSoup(html, features='html.parser')
return soup.get_text()
def example():
md = '**A** [B](http://example.com) <!-- C -->'
text = md_to_text(md)
print(text)
# Output: A B
```
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
Despite the fact that this is a very old question, I'd like to suggest a solution I came up with recently. This one neither uses BeautifulSoup nor has an overhead of converting to html and back.
The **markdown** module core class Markdown has a property **output\_formats** which is not configurable but otherwise patchable like almost anything in python is. This property is a dict mapping output format name to a rendering function. By default it has two output formats, 'html' and 'xhtml' correspondingly. With a little help it may have a plaintext rendering function which is easy to write:
```
from markdown import Markdown
from io import StringIO
def unmark_element(element, stream=None):
if stream is None:
stream = StringIO()
if element.text:
stream.write(element.text)
for sub in element:
unmark_element(sub, stream)
if element.tail:
stream.write(element.tail)
return stream.getvalue()
# patching Markdown
Markdown.output_formats["plain"] = unmark_element
__md = Markdown(output_format="plain")
__md.stripTopLevelTags = False
def unmark(text):
return __md.convert(text)
```
**unmark** function takes markdown text as an input and returns all the markdown characters stripped out.
|
I came here while searching for a way to perform s.c. [GitLab Releases](https://docs.gitlab.com/ee/user/project/releases/) via [API call](https://docs.gitlab.com/ee/api/releases/). I hope this matches the use case of the original questioner.
I decoded markdown to plain text (including whitespaces in the form of `\n` etc.) in that way:
```
with open("release_note.md", 'r') as file:
release_note = file.read()
description = bytes(release_note, 'utf-8')
return description.decode("utf-8")
```
|
761,824
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
2009/04/17
|
[
"https://Stackoverflow.com/questions/761824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
This is similar to Jason's answer, but handles comments correctly.
```py
import markdown # pip install markdown
from bs4 import BeautifulSoup # pip install beautifulsoup4
def md_to_text(md):
html = markdown.markdown(md)
soup = BeautifulSoup(html, features='html.parser')
return soup.get_text()
def example():
md = '**A** [B](http://example.com) <!-- C -->'
text = md_to_text(md)
print(text)
# Output: A B
```
|
I came here while searching for a way to perform s.c. [GitLab Releases](https://docs.gitlab.com/ee/user/project/releases/) via [API call](https://docs.gitlab.com/ee/api/releases/). I hope this matches the use case of the original questioner.
I decoded markdown to plain text (including whitespaces in the form of `\n` etc.) in that way:
```
with open("release_note.md", 'r') as file:
release_note = file.read()
description = bytes(release_note, 'utf-8')
return description.decode("utf-8")
```
|
53,264,593
|
I have been trying this code to get a random seed, but it always fails.
```
import string
import random
import time
import sys
from random import seed
possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:'
target = input("Enter text: ")
attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
attemptNext = ''
completed = False
generation = 0
while completed == False:
print(attemptThis)
attemptNext = ''
completed = True
for i in range(len(target)):
if attemptThis[i] != target[i]:
completed = False
attemptNext += random.choice(possibleCharacters)
else:
attemptNext += target[i]
generation += 1
attemptThis = attemptNext
time.sleep(0)
time.sleep(seed(1))
print("Operation completed in " + str(generation) + " different generations!")
```
The error is always as this one:
```
Traceback (most recent call last):
File "N:\ict python\python programs\demo\genration text.py", line 30, in <module>
time.sleep(seed(1))
TypeError: an integer is required (got type NoneType) at the end of it.
```
I have tried other functions - randint, pi and generating a random number and deciding by a random number.
Do I have to hardcode that number, or is there a way to make it generate a random delay?
|
2018/11/12
|
[
"https://Stackoverflow.com/questions/53264593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9199123/"
] |
The `random.seed()` function always returns `None` but `time.sleep()` needs a number (the number of seconds to sleep).
try `random.randint()` instead to generate a random integer:
```
import random
time.sleep(random.randint(1, 50))
```
|
Use also `random.randint(a, b)` function - to generate random integer number. `seed` function just initializes random numbers generator.
|
53,264,593
|
I have been trying this code to get a random seed, but it always fails.
```
import string
import random
import time
import sys
from random import seed
possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:'
target = input("Enter text: ")
attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
attemptNext = ''
completed = False
generation = 0
while completed == False:
print(attemptThis)
attemptNext = ''
completed = True
for i in range(len(target)):
if attemptThis[i] != target[i]:
completed = False
attemptNext += random.choice(possibleCharacters)
else:
attemptNext += target[i]
generation += 1
attemptThis = attemptNext
time.sleep(0)
time.sleep(seed(1))
print("Operation completed in " + str(generation) + " different generations!")
```
The error is always as this one:
```
Traceback (most recent call last):
File "N:\ict python\python programs\demo\genration text.py", line 30, in <module>
time.sleep(seed(1))
TypeError: an integer is required (got type NoneType) at the end of it.
```
I have tried other functions - randint, pi and generating a random number and deciding by a random number.
Do I have to hardcode that number, or is there a way to make it generate a random delay?
|
2018/11/12
|
[
"https://Stackoverflow.com/questions/53264593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9199123/"
] |
The `random.seed()` function always returns `None` but `time.sleep()` needs a number (the number of seconds to sleep).
try `random.randint()` instead to generate a random integer:
```
import random
time.sleep(random.randint(1, 50))
```
|
The type of seed is None and the time.sleep() expects an integer.
To send a random integer as a parameter for sleep you can try:
```
time.sleep(random.randint(1, 60))
```
You need to import randim libraby for this.
|
50,073,779
|
I am aware that [re.search(pattns,text)][1] in python method takes a regular expression pattern and a string and searches for that pattern within the string. If the search is successful, search() returns a match object or None otherwise.
My problem however is, am trying to implement this using OOP (class) i want to return a string representation of the results of the matches whether true or none
or any other form of representation(readable) not this **<\_\_main\_\_.Expression instance at 0x7f30d0a81440>** below are two example classes : Student and Epression. The one using **\_\_str\_\_(self)\_\_** works fine but i cannot figure out how to get the representation funtion for **re.search()**.
Please someone help me out.
```
import re
class Expression:
def __init__(self,patterns,text):
self.patterns = patterns
self.text = text
def __bool__(self):
# i want to get a readable representation from here
for pattern in self.patterns:
result = re.search(pattern,self.text)
return result
patterns = ['term1','term2','23','ghghg']
text = 'This is a string with term1 23 not ghghg the other'
reg = Expression(patterns,text)
print(reg)
class Student:
def __init__(self, name):
self.name = name
def __str__(self):
# string representation here works fine
result = self.name
return result
# Usage:
s1 = Student('john')
print(s1)
[1]: https://developers.google.com/edu/python/regular-expressions
```
|
2018/04/28
|
[
"https://Stackoverflow.com/questions/50073779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4209906/"
] |
The output of `re.search` returns a match object.
It tells you whether the regex matches the string.
You should identify the group to retrieve string from the match like so:
```
if result:
return result.group(0)
```
Replace `return result` in your code with above code snippet.
If you are not sure how [`group`](https://docs.python.org/2/library/re.html#re.MatchObject.group) works, here is an example from docs:
```
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0) # The entire match
'Isaac Newton'
>>> m.group(1) # The first parenthesized subgroup.
'Isaac'
>>> m.group(2) # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2) # Multiple arguments give us a tuple.
('Isaac', 'Newton')
```
|
First, there is a subtle *bug* in your code:
```
def __bool__(self):
for pattern in self.patterns:
result = re.search(pattern,self.text)
return result
```
As you return the result of the searched pattern at the end of the first iteration, others patterns are simply ignored.
You probaly want something like this:
```
def __bool__(self):
result = True
for pattern in self.patterns:
result = result or bool(re.search(pattern,self.text))
return result
```
---
About the representation, you may use `.group(0)`. This will return the matched string, rather than the `re.Match` obscur representation.
```
import re
s = re.search(r"ab", "okokabuyuihiab")
print(s.group(0))
# "ab"
```
And as you use a list of patterns, maybe use instead:
```
results = [re.search(pattern, seld.text) for pattern in self.patterns]
representation = [r.group(0) for r in results if r else None]
```
|
44,262,833
|
I am facing some error while using classes in python 2.7
My class definition is:
```
class Timer(object):
def __init__(self):
self.msg = ""
def start(self,msg):
self.msg = msg
self.start = time.time()
def stop(self):
t = time.time() - self.start
return self.msg, " => ", t, 'seconds'
```
On executing the following code.
```
timer = Timer()
timer.start("Function 1")
Some code
timer.stop()
timer.start('Function 2')
some code
timer.stop()
```
I am getting following error:
```
Function 1 => 0.01 seconds
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable
```
For the first call it worked as desired but for the second call, it gave an error. I am unable to figure out the cause of the error.
|
2017/05/30
|
[
"https://Stackoverflow.com/questions/44262833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450212/"
] |
When you write `self.start = time.time()`, you replace the function `start()` with a variable named `start`, which has a float value. The next time you write `timer.start()`, start is a float, and you are trying to call it as a function. Just replace the name `self.start` with something else.
|
I think the problem is that you are using the same name for a method and for an attribute.
I would refactor it like this:
```
class Timer(object):
def __init__(self):
self.msg = ""
self.start_time = None #I prefer to declare it but you can avoid this
def start(self,msg):
self.msg = msg
self.start_time = time.time()
def stop(self):
t = time.time() - self.start_time
return self.msg, " => ", t, 'seconds'
```
|
44,262,833
|
I am facing some error while using classes in python 2.7
My class definition is:
```
class Timer(object):
def __init__(self):
self.msg = ""
def start(self,msg):
self.msg = msg
self.start = time.time()
def stop(self):
t = time.time() - self.start
return self.msg, " => ", t, 'seconds'
```
On executing the following code.
```
timer = Timer()
timer.start("Function 1")
Some code
timer.stop()
timer.start('Function 2')
some code
timer.stop()
```
I am getting following error:
```
Function 1 => 0.01 seconds
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable
```
For the first call it worked as desired but for the second call, it gave an error. I am unable to figure out the cause of the error.
|
2017/05/30
|
[
"https://Stackoverflow.com/questions/44262833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450212/"
] |
When you write `self.start = time.time()`, you replace the function `start()` with a variable named `start`, which has a float value. The next time you write `timer.start()`, start is a float, and you are trying to call it as a function. Just replace the name `self.start` with something else.
|
I think now I understood your question and error, the following correct your issue:
```
import time
class Timer(object):
def __init__(self):
self.msg = ""
def start(self,msg):
self.msg = msg
self.start = time.time() # Here, your method name is the same has the variable name
```
If you rename the variable name, you have to remember to call first the start method so the start\_value variable exists:
```
import time
class Timer(object):
def __init__(self):
self.msg = ""
def start(self,msg):
self.msg = msg
self.start_value = time.time() #Is you change the variable name, the problem is solved
def stop(self):
t = time.time() - self.start_value
return self.msg, " => ", t, 'seconds'
a = Timer()
a.start("first call")
print a.stop()
>> ('first call', ' => ', 1.9073486328125e-06, 'seconds')
```
but if you don't call the method and just do:
```
a = Timer()
# a.start("first call") without it
print a.stop()
```
the variable `start` will never exist, wich throws to you the error:
```
AttributeError: 'Timer' object has no attribute 'start_value'
```
I hope that helps!
|
44,262,833
|
I am facing some error while using classes in python 2.7
My class definition is:
```
class Timer(object):
def __init__(self):
self.msg = ""
def start(self,msg):
self.msg = msg
self.start = time.time()
def stop(self):
t = time.time() - self.start
return self.msg, " => ", t, 'seconds'
```
On executing the following code.
```
timer = Timer()
timer.start("Function 1")
Some code
timer.stop()
timer.start('Function 2')
some code
timer.stop()
```
I am getting following error:
```
Function 1 => 0.01 seconds
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable
```
For the first call it worked as desired but for the second call, it gave an error. I am unable to figure out the cause of the error.
|
2017/05/30
|
[
"https://Stackoverflow.com/questions/44262833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450212/"
] |
I think the problem is that you are using the same name for a method and for an attribute.
I would refactor it like this:
```
class Timer(object):
def __init__(self):
self.msg = ""
self.start_time = None #I prefer to declare it but you can avoid this
def start(self,msg):
self.msg = msg
self.start_time = time.time()
def stop(self):
t = time.time() - self.start_time
return self.msg, " => ", t, 'seconds'
```
|
I think now I understood your question and error, the following correct your issue:
```
import time
class Timer(object):
def __init__(self):
self.msg = ""
def start(self,msg):
self.msg = msg
self.start = time.time() # Here, your method name is the same has the variable name
```
If you rename the variable name, you have to remember to call first the start method so the start\_value variable exists:
```
import time
class Timer(object):
def __init__(self):
self.msg = ""
def start(self,msg):
self.msg = msg
self.start_value = time.time() #Is you change the variable name, the problem is solved
def stop(self):
t = time.time() - self.start_value
return self.msg, " => ", t, 'seconds'
a = Timer()
a.start("first call")
print a.stop()
>> ('first call', ' => ', 1.9073486328125e-06, 'seconds')
```
but if you don't call the method and just do:
```
a = Timer()
# a.start("first call") without it
print a.stop()
```
the variable `start` will never exist, wich throws to you the error:
```
AttributeError: 'Timer' object has no attribute 'start_value'
```
I hope that helps!
|
52,743,872
|
I have been creating a game where an image moves according to player input with Keydown and Keyup methods. I want to add boundaries so that the user cannot move the image/character out of the display (I dont want a game over kind of thing if boundary is hit, just that the image/character wont be able to move past that boundary)
```
import pygame
pygame.init()#initiate pygame
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
display_width = 1200
display_height = 800
display = pygame.display.set_mode((display_width,display_height))
characterimg_left = pygame.image.load(r'/Users/ye57324/Desktop/Make/coding/python/characterimg_left.png')
characterimg_right = pygame.image.load(r'/Users/ye57324/Desktop/Make/coding/python/characterimg_right.png')
characterimg = characterimg_left
def soldier(x,y):
display.blit(characterimg, (x,y))
x = (display_width * 0.30)
y = (display_height * 0.2)
pygame.display.set_caption('No U')
clock = pygame.time.Clock()#game clock
flip_right = False
x_change = 0
y_change = 0
bg_x = 0
start = True
bg = pygame.image.load(r'/Users/ye57324/Desktop/Make/coding/python/bg.png').convert()
class player:
def __init__(self, x, y):
self.jumping = False
p = player(x, y)
while start:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
start = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change += -4
if flip_right == True:
characterimg = characterimg_left
flip_right = False
x += -150
elif event.key == pygame.K_RIGHT:
x_change += 4
if flip_right == False:
characterimg = characterimg_right
flip_right = True
x += 150
elif event.key == pygame.K_UP:
y_change += -4
elif event.key == pygame.K_DOWN:
y_change += 4
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change += 4
elif event.key == pygame.K_RIGHT:
x_change += -4
elif event.key == pygame.K_UP:
y_change += 4
elif event.key == pygame.K_DOWN:
y_change += -4
x += x_change
y += y_change
display.fill(white)
soldier(x,y)
pygame.display.update()
clock.tick(120)#fps
pygame.quit()
```
I have tried several times including switching to the key pressed method but they all failed. Help please, thank you.
|
2018/10/10
|
[
"https://Stackoverflow.com/questions/52743872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10366920/"
] |
**Root cause:**
Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare.
**Solution:**
Use exactly value of an item in the list with if else command to compare.
```
var arr = pm.response.json();
console.log(arr.length)
for (var i = 0; i < arr.length; i++)
{
if(arr[i].Verified === true){
pm.test("Verified should be true", function () {
pm.expect(arr[i].Verified).to.be.true;
});
}
if(arr[i].Verified === false){
pm.test("Verified should be false", function () {
pm.expect(arr[i].Verified).to.be.false;
});
}
}
```
Hope it help you.
|
You could also just do this:
```
pm.test('Check the response body properties', () => {
_.each(pm.response.json(), (item) => {
pm.expect(item.Verified).to.be.true
pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/)
})
})
```
The check will do a few things for you, it will iterate over the whole array and check that the `Verified` property is `true` and also check that the `VerifiedDate` is a string and matches the `YYYY-MM-DD` format, like in the example given in your question.
|
61,924,960
|
I am querying (via sqlalchemy) *my\_table* with a conditional on a column and then retrieve distinct values in another column. Quite simply
```
selection_1 = session.query(func.distinct(my_table.col2)).\
filter(my_table.col1 == value1)
```
I need to do this repeatedly to get distinct values from different columns from *my\_table*.
```
selection_2 = session.query(func.distinct(my_table.col3)).\
filter(my_table.col1 == value1).\
filter(my_table.col2 == value2)
selection_3 = session.query(func.distinct(my_table.col4)).\
filter(my_table.col1 == value1).\
filter(my_table.col2 == value2).\
filter(my_table.col3 == value3)
```
The above code works, but as I need to have 6 successive calls it's getting a bit out of hand. I have created a class to handle the method chaining:
```
class QueryProcessor:
def add_filter(self, my_table_col, value):
filter(my_table_col == value)
return self
def set_distinct_col(self, my_other_table_col):
self.my_other_table_col = my_other_table_col
return session.query(func.distinct(self.my_other_table_col))
```
Ideally I'd be able to use the class like
```
selection_1 = QueryProcessor().set_distinct_col(my_table.col2).add_filter(my_table.col1, value1)
selection_2 = selection_1.set_distinct_col(my_table.col3).add_filter(my_table.col2, value2)
selection_3 = selection_2.set_distinct_col(my_table.col4).add_filter(my_table.col3, value3)
```
but when I run
```
selection_1 = QueryProcessor().set_distinct_col(my_table.col2).add_filter(my_table.col1, value1)
```
I get the following error:
```
Traceback (most recent call last):
File " ... "
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-20-789b26eccbc5>", line 10, in <module>
selection_1 = QueryProcessor().set_distinct_col(my_table.col2).add_filter(my_table.col1, value1)
AttributeError: 'Query' object has no attribute 'add_filter'
```
Any help will be much welcomed.
|
2020/05/21
|
[
"https://Stackoverflow.com/questions/61924960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13583344/"
] |
You don't really need a special class for this. Your existing code
```
selection_2 = session.query(func.distinct(my_table.col3)).\
filter(my_table.col1 == value1).\
filter(my_table.col2 == value2)
```
works because `filter` is returning a *new* query based on the original query, but with an additional filter added to it. You can just iterate over the columns and their corresponding values, replacing each old query with its successor.
```
selection2 = session.query(func.distinct(my_table.col3))
for col, val in zip([my_table.col1, my_table.col2], [value1, value2]):
selection2 = selection2.filter(col == val)
selection_3 = session.query(func.distinct(my_table.col4))
for col, val in zip([mytable.col1, mytable.col2, mytable.col3],
[value1, value2, value3]):
selection_3 = selection_3.filter(col == val)
```
That said, the problem with your code is that `add_filter` doesn't actually call the query's `filter` method, or update the wrapped query.
```
class QueryProcessor:
def set_distinct_col(self, my_other_table_col):
self.query = session.query(func.distinct(self.my_other_table_col))
return self
def add_filter(self, my_table_col, value):
self.query = self.query.filter(my_table_col == value)
return self
```
This poses a problem, though: `set_distinct_col` creates a new query, so it doesn't really make sense in the following
```
selection_1 = QueryProcessor().set_distinct_col(my_table.col2).add_filter(my_table.col1, value1)
selection_2 = selection_1.set_distinct_col(my_table.col3).add_filter(my_table.col2, value2)
selection_3 = selection_2.set_distinct_col(my_table.col4).add_filter(my_table.col3, value3)
```
to call `set_distinct_col` on an existing instance. It can return either a new query or the existing one, but not both (at least, not if you want to do chaining).
Also, note that `selection_1` itself is not the query, but `selection_1.query`.
|
For your `add_filter()` function to work as intended, you need your `set_distinct_col()` function to return a reference to itself (*an instance of `QueryProcessor`*).
[`session.query()`](https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.query) returns a `Query` object which doesn't have an `add_filter()` method.
Query could have an `add_filter` method if you did something like `Query.add_filter = add_filter`, but that's a bad practice because it modifies the Query class, so I don't recommend doing it.
What you're doing is a better option. In order to have access to the query you create with the `set_distinct_col()` method, you need to store it as an instance variable.
Below, I have done this by storing the query in the instance variable `query` with
`self.query = session.query(func.distinct(self.my_other_table_col))`
Then, I changed the `add_filter()` method to return itself to allow for chaining more add\_filter() methods.
```
class QueryProcessor:
def add_filter(self, my_table_col, value):
self.query = self.query.filter(my_table_col == value)
return self
def set_distinct_col(self, my_other_table_col):
self.my_other_table_col = my_other_table_col
self.query = session.query(func.distinct(self.my_other_table_col))
return self
```
You should also know that you can use multiple filter conditions at a time, so you don't actually need to chain multiple filters together.
```
session.query(db.users).filter(or_(db.users.name=='Ryan', db.users.country=='England'))
```
or
```
session.query(db.users).filter((db.users.name=='Ryan') | (db.users.country=='England'))
```
[Difference between filter and filter\_by in SQLAlchemy](https://stackoverflow.com/questions/2128505/difference-between-filter-and-filter-by-in-sqlalchemy)
P.S. This code has not been tested
|
30,909,627
|
I am tried to create a slice in django template and get an attribute.
How can i do in django template something like this:
python code:
```
somelist[1].name
```
please help
|
2015/06/18
|
[
"https://Stackoverflow.com/questions/30909627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3520178/"
] |
If you are accessing a single element of a list, you don't need the `slice` filter, just use the dot notation.
```
{{ somelist.1.name }}
```
See [the docs](https://docs.djangoproject.com/en/1.8/ref/templates/language/#variables) for more info.
|
You can use the built-in tag [`slice`](https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#slice) with a combination of [`with`](https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#with):
```
{% with somelist|slice:"1" as item %}
{{ item.name }}
{% endwith %}
```
|
49,913,084
|
All,
I am trying to build a Docker image to run my python 2 App within an embedded system which has OS yocto. Since the embedded system has limited flash, I want to have a small Docker image. However, after I install all the python and other packages, I get an image with 730M, which is too big for me. I don't know how to compress the image. Please share your wisdom.
Thanks!!
My Dcokerfile is like below:
```
FROM *****/base-rootfs:yocto-2.1.1
RUN opkg update
RUN opkg install *****toolchain
RUN opkg install python-pip
RUN opkg install python-dev
RUN opkg install python
RUN pip install numpy
RUN pip install pandas
RUN pip install scipy
RUN pip install sklearn
COPY appa /opt/app/
RUN chmod 777 /opt/app/main.py
CMD ["python", "./opt/app/main.py"]
```
|
2018/04/19
|
[
"https://Stackoverflow.com/questions/49913084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1227199/"
] |
**Q:** How to reduce the size of my docker image?
**A:** There are a few ways you can do this. The most prominent thing I can immediately spot from your Dockerfile is that you are installing packages using individual `RUN` command.
While this can make your code look a bit cleaner but each `RUN` statement is an overhead in size because docker images are build from `layers`.
To docker, each `RUN` statement is like building a new `layer` from the previous one and wrapping it around the previous one.
I think you should see a drop in size if you reduce the amount of `layers` by bundling the packages into single installation command. Maybe try grouping the `pip` ones together and `opkg` into another.
|
You can use docker history command to see which layer is causing more disk space addition.
```
docker@default:~Example>> docker history {image-name}:{image-tag}
docker@default:~$ docker history mysql
IMAGE CREATED CREATED BY SIZE COMMENT
5195076672a7 5 weeks ago /bin/sh -c #(nop) CMD ["mysqld"] 0B
<missing> 5 weeks ago /bin/sh -c #(nop) EXPOSE 3306/tcp 0B
<missing> 5 weeks ago /bin/sh -c #(nop) ENTRYPOINT ["docker-entry⦠0B
<missing> 5 weeks ago /bin/sh -c ln -s usr/local/bin/docker-entryp⦠34B
<missing> 5 weeks ago /bin/sh -c #(nop) COPY file:05922d368ede3042⦠5.92kB
<missing> 5 weeks ago /bin/sh -c #(nop) VOLUME [/var/lib/mysql] 0B
<missing> 5 weeks ago /bin/sh -c { echo mysql-community-server m⦠256MB
<missing> 5 weeks ago /bin/sh -c echo "deb http://repo.mysql.com/a⦠56B
<missing> 5 weeks ago /bin/sh -c #(nop) ENV MYSQL_VERSION=5.7.21-⦠0B
<missing> 5 weeks ago /bin/sh -c #(nop) ENV MYSQL_MAJOR=5.7 0B
<missing> 5 weeks ago /bin/sh -c set -ex; key='A4A9406876FCBD3C45⦠23kB
<missing> 5 weeks ago /bin/sh -c apt-get update && apt-get install⦠44.7MB
<missing> 5 weeks ago /bin/sh -c mkdir /docker-entrypoint-initdb.d 0B
<missing> 5 weeks ago /bin/sh -c set -x && apt-get update && apt-⦠4.44MB
<missing> 5 weeks ago /bin/sh -c #(nop) ENV GOSU_VERSION=1.7 0B
<missing> 5 weeks ago /bin/sh -c apt-get update && apt-get install⦠10.2MB
<missing> 5 weeks ago /bin/sh -c groupadd -r mysql && useradd -r -⦠329kB
<missing> 5 weeks ago /bin/sh -c #(nop) CMD ["bash"] 0B
<missing> 5 weeks ago /bin/sh -c #(nop) ADD file:e3250bb9848f956bd⦠55.3MB
docker@default:~$
```
Based on output you can see and compare results with the real size of those packages and eventually drill down to what causing such a huge docker image ?
|
54,419,118
|
I am trying to extract table from a PPT using `python-pptx`, however, the I am not sure how do I that using `shape.table`.
```
from pptx import Presentation
prs = Presentation(path_to_presentation)
# text_runs will be populated with a list of strings,
# one for each text run in presentation
text_runs = []
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_table:
tbl = shape.table
rows = tbl.rows.count
cols = tbl.columns.count
```
I found a post [here](https://stackoverflow.com/questions/27843018/read-from-powerpoint-table-in-python) but the accepted solution does not work, giving error that `count` attribute is not available.
How do I modify the above code so I can get a table in a dataframe?
**EDIT**
Please see the image of the slide below
[](https://i.stack.imgur.com/ZQ3Us.png)
|
2019/01/29
|
[
"https://Stackoverflow.com/questions/54419118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479974/"
] |
This appears to work for me.
```
prs = Presentation((path_to_presentation))
# text_runs will be populated with a list of strings,
# one for each text run in presentation
text_runs = []
for slide in prs.slides:
for shape in slide.shapes:
if not shape.has_table:
continue
tbl = shape.table
row_count = len(tbl.rows)
col_count = len(tbl.columns)
for r in range(0, row_count):
for c in range(0, col_count):
cell = tbl.cell(r,c)
paragraphs = cell.text_frame.paragraphs
for paragraph in paragraphs:
for run in paragraph.runs:
text_runs.append(run.text)
print(text_runs)```
```
|
To read the values present inside ppt |
This code worked for me
```
slide = Deck.slides[1]
table = slide.shapes[1].table
for r in range(0,len(table.rows)):
for c in range(2,len(table.columns)):
cell_value = (table.cell(r,c)).text_frame.text
print(cell_value)
```
|
68,173,157
|
i have a List a
```
a = [["v1_0001.jpg","v1_00015.jpg","v1_0002.jpg"],["v2_0001.jpg","v2_0002.jpg","v2_00015.jpg"]]
```
i want to concatenate these list of list in one list and sort list by alphanumeric
While i am try to sort concatenation list
```
['v1_0001.jpg', 'v1_00015.jpg', 'v1_0002.jpg','v2_0001.jpg' 'v2_00015.jpg', 'v2_0002.jpg']
```
I got output like this
```
['v1_0001.jpg','v1_0002.jpg','v1_00015.jpg','v2_0001.jpg','v2_00015.jpg' 'v2_0002.jpg]
```
How to resolve this in python
|
2021/06/29
|
[
"https://Stackoverflow.com/questions/68173157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Use `chain` from `itertools`, as so -
```
from itertools import chain
a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]]
b = list(chain(*a))
print(b)
# [0, 15, 30, 45, 75, 105,0, 15, 30, 45, 75, 105]
```
|
Here is one way. You can do it with recursion
```
solution :
```
```
import itertools
a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]]
print(list(itertools.chain.from_iterable(a)))
```
|
68,173,157
|
i have a List a
```
a = [["v1_0001.jpg","v1_00015.jpg","v1_0002.jpg"],["v2_0001.jpg","v2_0002.jpg","v2_00015.jpg"]]
```
i want to concatenate these list of list in one list and sort list by alphanumeric
While i am try to sort concatenation list
```
['v1_0001.jpg', 'v1_00015.jpg', 'v1_0002.jpg','v2_0001.jpg' 'v2_00015.jpg', 'v2_0002.jpg']
```
I got output like this
```
['v1_0001.jpg','v1_0002.jpg','v1_00015.jpg','v2_0001.jpg','v2_00015.jpg' 'v2_0002.jpg]
```
How to resolve this in python
|
2021/06/29
|
[
"https://Stackoverflow.com/questions/68173157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Use `chain` from `itertools`, as so -
```
from itertools import chain
a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]]
b = list(chain(*a))
print(b)
# [0, 15, 30, 45, 75, 105,0, 15, 30, 45, 75, 105]
```
|
Maybe this is not the best to use in big lists but for understanding the logic might be good:
```
>>> a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]]
>>> b = [] # Creates an empty list
>>> for list_inside_a in a: # For every list in a
... b+= list_inside_a # Concatenates n-th list with b
...
>>> b
[0, 15, 30, 45, 75, 105, 0, 15, 30, 45, 75, 105]
```
|
37,090,675
|
I am working with canbus in python (Pcan basic api) and would like to make it easier to use.
Via the bus a lot of devices/modules are connected. They are all allowed to send data, if a collison would happen the lowest ID will win.
The data Is organized in frames with ID, SubID, hexvalues
To illustrate the problem I am trying to adress, imagine the amplitude of a signal.
To read the value a frame is send to
* QuestionID QuestionSUBID QuestionData
If there is no message with higher priority(=lowerID) the answer is written to the bus:
* AnswerID AnswerSubID AnswerData
Since any module/device is allowed to write to the bus, you don't know in advance which answer you will get next. Setting a value morks the same way, just with different IDs. So for the above example the amplitude would have:
1. 4 IDs and SubIds Associated with read/write question/answer
2. Additionally the lenght of the data has (0-8) has to be specified /stored.
3. Since the data is all hex values a parser has to be specified to obtain the human readable value (e.g Voltage in decimal representation)
To store this information I use nested dicts:
```
parameters = {'Parameter_1': {'Read': {'question_ID': ID,
'question_SUBID': SubID,
'question_Data': hex_value_list,
'answer_ID': ...,
'answer_subID': ...,
'answer_parser': function},
'Write': {'ID': ...,
'SubID': ...,
'parser' ...,
'answer_ID': ...,
'answer_subID': ...}},
'Parameter_2': ... }}
```
There are a lot of tools to show which value was set when, but for hardware control, the order in which paremeters are read are not relevant as long as they are up to date. Thus one part of a possible solution would be storing the whole traffic in a dict of dicts:
```
busdata = {'firstID' : {'first_subID': {'data': data,
'timestamp': timestamp},
'second_subID': {'data': data,
'timestamp': timestamp},
},
secondID': ...}
```
Due to the nature of the bus, I get a lot of answers other devices asked - the bus is quite full - these should not be dismissed since they might be the values I need next and there is no need to create additional traffic - I might use the timestamp with an expiry date, but I didn't think a lot about that so far.
This works, but is horrible to work with. In general I guess I will have about 300 parameters. The final goal is to controll the devices via a (pyqt) Gui, read some values like serial numbers but as well run measurement tasks.
So the big question is how to define a better datastructure that is easily accesible and understandable? I am looking forward to any suggestion on a clean design.
The main goal would be something like rid of the whole message based aproach.
**EDIT:** My goal is to get rid of the whole CAN specific message based aproach:
I assume I will need one thread for the communication, it should:
1. Read the buffer and update my variables
2. Send requests (messages) to obtain other values/variables
3. Send some values periodically
So from the gui I would like to be abled to:
1. get parameter by name --> send a string with parameter name
2. set parameter signal --> str(name), value(as displayedin the gui)
3. get values periodically --> name, interval, duration(10s or infinite)
The thread would have to:
1. Log all data on the bus for internal storage
2. Process requests by generating messages from name, value and read until result is obtained
3. Send periodical signals
I would like to have this design idependant of the actual hardware:
* The solution I thought of, is the above *parameters\_dict*
For internal storage I thought about the *bus\_data\_dict*
**Still I am not sure how to**:
1. Pass data from the bus thread to the gui (all values vs. new/requested value)
2. How to implement it with signals and slots in pyqt
3. Store data internally (dict of dicts or some new better idea)
4. If this design is a good choice
|
2016/05/07
|
[
"https://Stackoverflow.com/questions/37090675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Using the [python-can](https://bitbucket.org/hardbyte/python-can/) library will get you the networking thread - giving you a buffered queue of incoming messages. The library supports the PCAN interface among others.
Then you would create a middle-ware layer that converts and routes these `can.Message` types into pyqt signals. Think of this as a one to many source of events/signals.
I'd use another controller to be in charge of sending messages to the bus. It could have tasks like requesting periodic measurements from the bus, as well as on demand requests driven by the gui.
Regarding storing the data internally, it really depends on your programming style and the complexity. I have seen projects where each CAN message would have its own class.
Finally, queues are your friend!
|
```
class MySimpleCanBus:
def parse_message(self,raw_message):
return MyMessageClass._create(*struct.unpack(FRAME_FORMAT,msg))
def recieve_message(self,filter_data):
#code to recieve and parse a message(filtered by id)
raw = canbus.recv(FRAME_SIZE)
return self.parse_message(raw)
def send_message(msg_data):
# code to make sure the message can be sent and send the message
return self.recieve_message()
class MySpecificCanBus(MySimpleCanBus):
def get_measurement_reading():
msg_data = {} #code to request a measurement
return self.send_message(msg_data)
def get_device_id():
msg_data = {} # code to get device_id
return self.send_message(msg_data)
```
I probably dont understand your question properly ... maybe you could update it with additional details
|
37,090,675
|
I am working with canbus in python (Pcan basic api) and would like to make it easier to use.
Via the bus a lot of devices/modules are connected. They are all allowed to send data, if a collison would happen the lowest ID will win.
The data Is organized in frames with ID, SubID, hexvalues
To illustrate the problem I am trying to adress, imagine the amplitude of a signal.
To read the value a frame is send to
* QuestionID QuestionSUBID QuestionData
If there is no message with higher priority(=lowerID) the answer is written to the bus:
* AnswerID AnswerSubID AnswerData
Since any module/device is allowed to write to the bus, you don't know in advance which answer you will get next. Setting a value morks the same way, just with different IDs. So for the above example the amplitude would have:
1. 4 IDs and SubIds Associated with read/write question/answer
2. Additionally the lenght of the data has (0-8) has to be specified /stored.
3. Since the data is all hex values a parser has to be specified to obtain the human readable value (e.g Voltage in decimal representation)
To store this information I use nested dicts:
```
parameters = {'Parameter_1': {'Read': {'question_ID': ID,
'question_SUBID': SubID,
'question_Data': hex_value_list,
'answer_ID': ...,
'answer_subID': ...,
'answer_parser': function},
'Write': {'ID': ...,
'SubID': ...,
'parser' ...,
'answer_ID': ...,
'answer_subID': ...}},
'Parameter_2': ... }}
```
There are a lot of tools to show which value was set when, but for hardware control, the order in which paremeters are read are not relevant as long as they are up to date. Thus one part of a possible solution would be storing the whole traffic in a dict of dicts:
```
busdata = {'firstID' : {'first_subID': {'data': data,
'timestamp': timestamp},
'second_subID': {'data': data,
'timestamp': timestamp},
},
secondID': ...}
```
Due to the nature of the bus, I get a lot of answers other devices asked - the bus is quite full - these should not be dismissed since they might be the values I need next and there is no need to create additional traffic - I might use the timestamp with an expiry date, but I didn't think a lot about that so far.
This works, but is horrible to work with. In general I guess I will have about 300 parameters. The final goal is to controll the devices via a (pyqt) Gui, read some values like serial numbers but as well run measurement tasks.
So the big question is how to define a better datastructure that is easily accesible and understandable? I am looking forward to any suggestion on a clean design.
The main goal would be something like rid of the whole message based aproach.
**EDIT:** My goal is to get rid of the whole CAN specific message based aproach:
I assume I will need one thread for the communication, it should:
1. Read the buffer and update my variables
2. Send requests (messages) to obtain other values/variables
3. Send some values periodically
So from the gui I would like to be abled to:
1. get parameter by name --> send a string with parameter name
2. set parameter signal --> str(name), value(as displayedin the gui)
3. get values periodically --> name, interval, duration(10s or infinite)
The thread would have to:
1. Log all data on the bus for internal storage
2. Process requests by generating messages from name, value and read until result is obtained
3. Send periodical signals
I would like to have this design idependant of the actual hardware:
* The solution I thought of, is the above *parameters\_dict*
For internal storage I thought about the *bus\_data\_dict*
**Still I am not sure how to**:
1. Pass data from the bus thread to the gui (all values vs. new/requested value)
2. How to implement it with signals and slots in pyqt
3. Store data internally (dict of dicts or some new better idea)
4. If this design is a good choice
|
2016/05/07
|
[
"https://Stackoverflow.com/questions/37090675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Agree with @Hardbyte on the use of [python-can](https://pypi.python.org/pypi/python-can/). It's excellent.
As far as messaging between app layers, I've had a lot of luck with [Zero MQ](http://zeromq.org/bindings:python) -- you can set up your modules as event based, from the canbus message event all the way through to updating a UI or whatever.
For data storage / persistence, I'm dropping messages into SQLite, and in parallel (using [ZMQ Pub/Sub](http://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/patterns/pubsub.html) pattern) passing the data to an IoT hub (via [MQTT](https://www.eclipse.org/paho/clients/python/)).
|
```
class MySimpleCanBus:
def parse_message(self,raw_message):
return MyMessageClass._create(*struct.unpack(FRAME_FORMAT,msg))
def recieve_message(self,filter_data):
#code to recieve and parse a message(filtered by id)
raw = canbus.recv(FRAME_SIZE)
return self.parse_message(raw)
def send_message(msg_data):
# code to make sure the message can be sent and send the message
return self.recieve_message()
class MySpecificCanBus(MySimpleCanBus):
def get_measurement_reading():
msg_data = {} #code to request a measurement
return self.send_message(msg_data)
def get_device_id():
msg_data = {} # code to get device_id
return self.send_message(msg_data)
```
I probably dont understand your question properly ... maybe you could update it with additional details
|
37,090,675
|
I am working with canbus in python (Pcan basic api) and would like to make it easier to use.
Via the bus a lot of devices/modules are connected. They are all allowed to send data, if a collison would happen the lowest ID will win.
The data Is organized in frames with ID, SubID, hexvalues
To illustrate the problem I am trying to adress, imagine the amplitude of a signal.
To read the value a frame is send to
* QuestionID QuestionSUBID QuestionData
If there is no message with higher priority(=lowerID) the answer is written to the bus:
* AnswerID AnswerSubID AnswerData
Since any module/device is allowed to write to the bus, you don't know in advance which answer you will get next. Setting a value morks the same way, just with different IDs. So for the above example the amplitude would have:
1. 4 IDs and SubIds Associated with read/write question/answer
2. Additionally the lenght of the data has (0-8) has to be specified /stored.
3. Since the data is all hex values a parser has to be specified to obtain the human readable value (e.g Voltage in decimal representation)
To store this information I use nested dicts:
```
parameters = {'Parameter_1': {'Read': {'question_ID': ID,
'question_SUBID': SubID,
'question_Data': hex_value_list,
'answer_ID': ...,
'answer_subID': ...,
'answer_parser': function},
'Write': {'ID': ...,
'SubID': ...,
'parser' ...,
'answer_ID': ...,
'answer_subID': ...}},
'Parameter_2': ... }}
```
There are a lot of tools to show which value was set when, but for hardware control, the order in which paremeters are read are not relevant as long as they are up to date. Thus one part of a possible solution would be storing the whole traffic in a dict of dicts:
```
busdata = {'firstID' : {'first_subID': {'data': data,
'timestamp': timestamp},
'second_subID': {'data': data,
'timestamp': timestamp},
},
secondID': ...}
```
Due to the nature of the bus, I get a lot of answers other devices asked - the bus is quite full - these should not be dismissed since they might be the values I need next and there is no need to create additional traffic - I might use the timestamp with an expiry date, but I didn't think a lot about that so far.
This works, but is horrible to work with. In general I guess I will have about 300 parameters. The final goal is to controll the devices via a (pyqt) Gui, read some values like serial numbers but as well run measurement tasks.
So the big question is how to define a better datastructure that is easily accesible and understandable? I am looking forward to any suggestion on a clean design.
The main goal would be something like rid of the whole message based aproach.
**EDIT:** My goal is to get rid of the whole CAN specific message based aproach:
I assume I will need one thread for the communication, it should:
1. Read the buffer and update my variables
2. Send requests (messages) to obtain other values/variables
3. Send some values periodically
So from the gui I would like to be abled to:
1. get parameter by name --> send a string with parameter name
2. set parameter signal --> str(name), value(as displayedin the gui)
3. get values periodically --> name, interval, duration(10s or infinite)
The thread would have to:
1. Log all data on the bus for internal storage
2. Process requests by generating messages from name, value and read until result is obtained
3. Send periodical signals
I would like to have this design idependant of the actual hardware:
* The solution I thought of, is the above *parameters\_dict*
For internal storage I thought about the *bus\_data\_dict*
**Still I am not sure how to**:
1. Pass data from the bus thread to the gui (all values vs. new/requested value)
2. How to implement it with signals and slots in pyqt
3. Store data internally (dict of dicts or some new better idea)
4. If this design is a good choice
|
2016/05/07
|
[
"https://Stackoverflow.com/questions/37090675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Using the [python-can](https://bitbucket.org/hardbyte/python-can/) library will get you the networking thread - giving you a buffered queue of incoming messages. The library supports the PCAN interface among others.
Then you would create a middle-ware layer that converts and routes these `can.Message` types into pyqt signals. Think of this as a one to many source of events/signals.
I'd use another controller to be in charge of sending messages to the bus. It could have tasks like requesting periodic measurements from the bus, as well as on demand requests driven by the gui.
Regarding storing the data internally, it really depends on your programming style and the complexity. I have seen projects where each CAN message would have its own class.
Finally, queues are your friend!
|
Agree with @Hardbyte on the use of [python-can](https://pypi.python.org/pypi/python-can/). It's excellent.
As far as messaging between app layers, I've had a lot of luck with [Zero MQ](http://zeromq.org/bindings:python) -- you can set up your modules as event based, from the canbus message event all the way through to updating a UI or whatever.
For data storage / persistence, I'm dropping messages into SQLite, and in parallel (using [ZMQ Pub/Sub](http://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/patterns/pubsub.html) pattern) passing the data to an IoT hub (via [MQTT](https://www.eclipse.org/paho/clients/python/)).
|
41,033,115
|
I downloaded and installed datasheder using the below steps:
```
git clone https://github.com/bokeh/datashader.git
cd datashader
conda install -c bokeh --file requirements.txt
python setup.py install
```
After that, I have run the code using terminal like `python data.py, but no graph is displayed; nothin is being displayed.
I am not sure if I've follwed the right steps here, can somebody help me display the graphs? Here is my code:
```
import pandas as pd
import numpy as np
import xarray as xr
import datashader as ds
import datashader.glyphs
import datashader.transfer_functions as tf
from collections import OrderedDict
np.random.seed(1)
num=10000
dists = {cat: pd.DataFrame(dict(x=np.random.normal(x,s,num),
y=np.random.normal(y,s,num),
val=val,cat=cat))
for x,y,s,val,cat in
[(2,2,0.01,10,"d1"), (2,-2,0.1,20,"d2"), (-2,-2,0.5,30,"d3"), (-2,2,1.0,40,"d4"), (0,0,3,50,"d5")]}
df = pd.concat(dists,ignore_index=True)
df["cat"]=df["cat"].astype("category")
df.tail()
tf.shade(ds.Canvas().points(df,'x','y'))
glyph = ds.glyphs.Point('x', 'y')
canvas = ds.Canvas(plot_width=200, plot_height=200, x_range=(-8,8)y_range=(-8,8))
from datashader import reductions
reduction = reductions.count()
from datashader.core import bypixel
agg = bypixel(df, canvas, glyph, reduction)
agg
canvas.points(df, 'x', 'y', agg=reductions.count())
tf.shade(canvas.points(df,'x','y',agg=reductions.count()))
tf.shade(canvas.points(df,'x','y',agg=reductions.any()))
tf.shade(canvas.points(df,'x','y',agg=reductions.mean('y')))
tf.shade(50-canvas.points(df,'x','y',agg=reductions.mean('val')))
agg = canvas.points(df, 'x', 'y')
tf.shade(agg.where(agg>=np.percentile(agg,99)))
tf.shade(np.sin(agg))
aggc = canvas.points(df, 'x', 'y', ds.count_cat('cat'))
aggc
tf.shade(aggc.sel(cat='d3'))
agg_d3_d5=aggc.sel(cat=['d3', 'd5']).sum(dim='cat')
tf.shade(agg_d3_d5)
```
|
2016/12/08
|
[
"https://Stackoverflow.com/questions/41033115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7113481/"
] |
I haven't tried your code, but there is nothing in there that would actually display the image. Each shade() call creates an image in memory, but then nothing is done with it here. If you were in a Jupyter notebook environment and the shade() call were the last item in the cell, it would display automatically, but the regular Python prompt doesn't have such "rich display" support. So you can either save it to an image file on disk (using e.g. [utils/export\_image](https://github.com/bokeh/datashader/blob/0.4.0/datashader/utils.py#L124)), or you can assign the result of shade() to a variable and then pass that to a Bokeh or Matplotlib or other plot, as you prefer. But you have to do something with the image if you want to see it.
|
I was able to produce the plot one of the tf.shade in your code this way.
```
from datashader.utils import export_image
img = tf.shade(canvas.points(df,'x','y',agg=reductions.count()))
export_image(img=img, filename='test1', fmt=".png", export_path=".")
```
This is the plot in test1.png[](https://i.stack.imgur.com/mW0wA.png)
|
31,662,355
|
I am creating a simple GUI production calculator in python. I am using Tkinter and have a main frame with 10 tabs in it. I have created all the entries and functions do do the calculations we need and it all works. My problem is that i want these entries and labels on each tab line10 - line19. I could manually recreate the code for each tab but that does not seem very pythonic. What I am hoping for is to be able to put this code in a loop that will rename the variable names for each line and place the objects into the different tab frames by changing the argument in the grid methods. I hope I am being clear enough I am very new and hoping to get a good grasp of this language. I am hoping to be able to just reiterate this code with a different number at the end of all the variable names, would concatenation work?
here is my code.
```
from Tkinter import *
from ttk import *
import time
class supervisorcalc:
def __init__(self, master):
self.notebook = Notebook(master)
self.line10 = Frame(self.notebook);
self.notebook.add(self.line10, text="Line 10")
self.line11 = Frame(self.notebook);
self.notebook.add(self.line11, text="Line 11")
self.line12 = Frame(self.notebook);
self.notebook.add(self.line12, text="Line 12")
self.line13 = Frame(self.notebook);
self.notebook.add(self.line13, text="Line 13")
self.line14 = Frame(self.notebook);
self.notebook.add(self.line14, text="Line 14")
self.line15 = Frame(self.notebook);
self.notebook.add(self.line15, text="Line 15")
self.line16 = Frame(self.notebook);
self.notebook.add(self.line16, text="Line 16")
self.line17 = Frame(self.notebook);
self.notebook.add(self.line17, text="Line 17")
self.line18 = Frame(self.notebook);
self.notebook.add(self.line18, text="Line 18")
self.line19 = Frame(self.notebook);
self.notebook.add(self.line19, text="Line 19")
self.notebook.grid(row=0,column=0)
###functions###
def cyclecnt(*args):
cyclecount = int(self.cyccnt.get())
molds = int(self.vj.get())
cyccount = cyclecount * molds
self.cyc.set(cyccount)
return
def currentproduction(*args):
item = int(self.item.get())
case = int(self.case.get())
currprod = item * case
self.production.set(currprod)
return
def lostunits(*args):
cycle = int(self.cyc.get())
prod = int(self.production.get())
self.loss.set(cycle - prod)
return
def efficiency(*args):
lost = float(self.loss.get())
prod = float(self.production.get())
self.efficiency.set((lost/prod)*100)
return
def getSec(x):
l = x.split(':')
return int(l[0]) * 3600 + int(l[1]) * 60 + int(l[2])
def future_time_seconds(*args):
hrs = self.hour.get()
mins = self.minute.get()
return (int(hrs) * 3600) + (int(mins) * 60)
def time_difference_seconds(*args):
fseconds = future_time_seconds()
s = time.strftime('%I:%M:%S')
cursecs = getSec(s)
return fseconds - cursecs
def proj(*args):
ctime = float(self.cycletime.get())
prod = int(self.production.get())
loss = int(self.loss.get())
case = float(self.case.get())
molds = int(self.vj.get())
item = int(self.item.get())
seconds = time_difference_seconds()
pcycle = ((molds / ctime) * seconds)
projeff = float(self.peff.get()) / float(100)
pproduction = pcycle - (pcycle * projeff)
self.projectedprod.set(prod + pproduction)
projloss = loss + pcycle * projeff
self.ploss.set(projloss)
fcase = case + (pproduction / float(item))
self.fcase.set(fcase)
###line 19
self.ctlabelj = Label(self.line19, text = "Cycle Time:")
self.ctlabelj.grid(row=2, column=0)
self.cycletime = StringVar()
self.cycletime.trace('w', proj)
self.cycletimeentj = Entry(self.line19, textvariable=self.cycletime)
self.cycletimeentj.grid(row=2,column=1)
moldoptionsj = [1, 1, 2, 3, 4]
self.vj = IntVar()
self.vj.set(moldoptionsj[0])
self.headslabelj = Label(self.line19, text = "# of Molds:")
self.headslabelj.grid(row=3, column=0)
self.headcomboj = OptionMenu(self.line19, self.vj, *moldoptionsj)
self.headcomboj.grid(row=3,column=1)
self.vj.trace("w", cyclecnt)
self.cclabelj = Label(self.line19, text = "Cycle Count:")
self.cclabelj.grid(row=4, column=0)
self.cyccnt = StringVar()
self.cyclecountentj = Entry(self.line19, textvariable=self.cyccnt)
self.cyclecountentj.grid(row=4,column=1)
self.cyccnt.trace("w", cyclecnt)
self.ipcj = Label(self.line19, text = "Items/Case:")
self.ipcj.grid(row=5, column=0)
self.item = StringVar()
self.ipcentj = Entry(self.line19, textvariable=self.item)
self.ipcentj.grid(row=5,column=1)
self.item.trace("w", currentproduction)
self.currj = Label(self.line19, text = "Current Case #:")
self.currj.grid(row=6, column=0)
self.case = StringVar()
self.currentj = Entry(self.line19, textvariable=self.case)
self.currentj.grid(row=6,column=1)
self.case.trace("w", currentproduction)
self.ctimej = Label(self.line19, text = "Current Time:")
self.ctimej.grid(row=7, column=0, sticky='W')
self.clockj = Label(self.line19)
self.clockj.grid(row=7,column=1, sticky='w')
####futureztime###
self.futureframe = Frame(self.line19)
self.futureframe.grid(row=8, column=1)
self.futurej = Label(self.line19, text = "Future Projections time:")
self.futurej.grid(row=8, column=0, sticky='w')
self.hour = StringVar()
self.hour.trace('w', time_difference_seconds)
self.hour.trace('w', proj)
self.futureenthourj = Entry(self.futureframe, width=2, textvariable=self.hour)
self.futureenthourj.grid(row=0, column=0)
self.futurecolonj = Label(self.futureframe, text = ":")
self.futurecolonj.grid(row=0, column=1)
self.minute = StringVar()
self.minute.trace('w', time_difference_seconds)
self.minute.trace('w', proj)
self.futureentminj = Entry(self.futureframe, width=2, textvariable=self.minute)
self.futureentminj.grid(row=0, column=2)
####
self.cycleslabel = Label(self.line19, text = 'Cycle Total:')
self.cycleslabel.grid(row=2, column=2)
self.cyc = StringVar()
self.cyc.set("00000")
self.cyc.trace('w', lostunits)
self.cycles = Label(self.line19, foreground = 'green', background = 'black', text = "00000", textvariable = self.cyc)
self.cycles.grid(row=2, column=3)
self.currprodkeylabel = Label(self.line19, text = 'Current Production:')
self.currprodkeylabel.grid(row=3, column=2)
self.production = StringVar()
self.production.set('00000')
self.production.trace('w', lostunits)
self.production.trace('w', efficiency)
self.currentprod = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.production)
self.currentprod.grid(row=3, column=3)
self.prodprojkeylabel = Label(self.line19, text = 'Projected Production:')
self.prodprojkeylabel.grid(row=4, column=2)
self.projectedprod = StringVar()
self.projectedprod.set('00000')
self.prodproj = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.projectedprod )
self.prodproj.grid(row=4, column=3)
self.losskeylabel = Label(self.line19, text = 'Lost units:')
self.losskeylabel.grid(row=5, column=2)
self.loss = StringVar()
self.loss.set("0000")
self.loss.trace('w', efficiency)
self.lossprod = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.loss)
self.lossprod.grid(row=5, column=3)
self.plosskeylabel = Label(self.line19, text = 'Projected Lost units:')
self.plosskeylabel.grid(row=6, column=2)
self.ploss = StringVar()
self.ploss.set("0000")
self.plossprod = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.ploss)
self.plossprod.grid(row=6, column=3)
self.currefficiencykeylabel = Label(self.line19, text = 'Current efficiency %:')
self.currefficiencykeylabel.grid(row=7, column=2)
self.efficiency = StringVar()
self.efficiency.set("00.00")
self.currentefficiency = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.efficiency)
self.currentefficiency.grid(row=7, column=3)
self.futurecaselabel = Label(self.line19, text = 'Future case # projection:')
self.futurecaselabel.grid(row=8, column=2)
self.fcase = StringVar()
self.fcase.set("000.0")
self.futurecase = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.fcase)
self.futurecase.grid(row=8, column=3)
self.projefficiencylabel = Label(self.line19, text = "Efficiency Projection:")
self.projefficiencylabel.grid(row=9, column=2)
self.peff = StringVar()
self.peff.set(0.00)
self.peff.trace('w', proj)
self.projefficiency = Entry(self.line19, textvariable=self.peff)
self.projefficiency.grid(row=9,column=3)
def tick():
s = time.strftime('%I:%M:%S')
if s != self.clockj:
self.clockj.configure(text=s)
self.notebook.after(200, tick)
tick()
root = Tk()
root.wm_title("Hillside Plastics Production Calculator")
calc = supervisorcalc(root)
mainloop()
```
|
2015/07/27
|
[
"https://Stackoverflow.com/questions/31662355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5111347/"
] |
This can't be intentional, because it can't work. As you've seen, you can't create a table twice. You should delete one of the migrations, possibly merging from the one you delete into the other one.
The only differences are the taggings\_count field and the indexes. There isn't enough to go on here to say whether you need taggings\_count or which is the better index. If I had to guess, I'd say the index on the first was trying to create a covering index, for what that's worth.
|
Get use to it. This error will happen often in the future. Usually, it happens when your migration failed in the middle, and for example your table was created, but later creation of indexes failed. Then when you are trying to rerun the migration the table already exists, and migration fails.
There are several ways to deal with such situation:
1) you can drop the table or anything else that was partially created, and rerun.
2) you can edit that particular migration and comment out the table creation part while rerunning (then you can uncomment it).
I personally prefer the #2.
I had to say that this situation happens only for some databases. You will see it with MySQL, but will not see it with PostreSQL. It happens because PostreSQL fully rolls back changes for failed migration (including successfully created tables and such); and MySQL decides that changes in partially successful migration should not be rolled back.
|
31,662,355
|
I am creating a simple GUI production calculator in python. I am using Tkinter and have a main frame with 10 tabs in it. I have created all the entries and functions do do the calculations we need and it all works. My problem is that i want these entries and labels on each tab line10 - line19. I could manually recreate the code for each tab but that does not seem very pythonic. What I am hoping for is to be able to put this code in a loop that will rename the variable names for each line and place the objects into the different tab frames by changing the argument in the grid methods. I hope I am being clear enough I am very new and hoping to get a good grasp of this language. I am hoping to be able to just reiterate this code with a different number at the end of all the variable names, would concatenation work?
here is my code.
```
from Tkinter import *
from ttk import *
import time
class supervisorcalc:
def __init__(self, master):
self.notebook = Notebook(master)
self.line10 = Frame(self.notebook);
self.notebook.add(self.line10, text="Line 10")
self.line11 = Frame(self.notebook);
self.notebook.add(self.line11, text="Line 11")
self.line12 = Frame(self.notebook);
self.notebook.add(self.line12, text="Line 12")
self.line13 = Frame(self.notebook);
self.notebook.add(self.line13, text="Line 13")
self.line14 = Frame(self.notebook);
self.notebook.add(self.line14, text="Line 14")
self.line15 = Frame(self.notebook);
self.notebook.add(self.line15, text="Line 15")
self.line16 = Frame(self.notebook);
self.notebook.add(self.line16, text="Line 16")
self.line17 = Frame(self.notebook);
self.notebook.add(self.line17, text="Line 17")
self.line18 = Frame(self.notebook);
self.notebook.add(self.line18, text="Line 18")
self.line19 = Frame(self.notebook);
self.notebook.add(self.line19, text="Line 19")
self.notebook.grid(row=0,column=0)
###functions###
def cyclecnt(*args):
cyclecount = int(self.cyccnt.get())
molds = int(self.vj.get())
cyccount = cyclecount * molds
self.cyc.set(cyccount)
return
def currentproduction(*args):
item = int(self.item.get())
case = int(self.case.get())
currprod = item * case
self.production.set(currprod)
return
def lostunits(*args):
cycle = int(self.cyc.get())
prod = int(self.production.get())
self.loss.set(cycle - prod)
return
def efficiency(*args):
lost = float(self.loss.get())
prod = float(self.production.get())
self.efficiency.set((lost/prod)*100)
return
def getSec(x):
l = x.split(':')
return int(l[0]) * 3600 + int(l[1]) * 60 + int(l[2])
def future_time_seconds(*args):
hrs = self.hour.get()
mins = self.minute.get()
return (int(hrs) * 3600) + (int(mins) * 60)
def time_difference_seconds(*args):
fseconds = future_time_seconds()
s = time.strftime('%I:%M:%S')
cursecs = getSec(s)
return fseconds - cursecs
def proj(*args):
ctime = float(self.cycletime.get())
prod = int(self.production.get())
loss = int(self.loss.get())
case = float(self.case.get())
molds = int(self.vj.get())
item = int(self.item.get())
seconds = time_difference_seconds()
pcycle = ((molds / ctime) * seconds)
projeff = float(self.peff.get()) / float(100)
pproduction = pcycle - (pcycle * projeff)
self.projectedprod.set(prod + pproduction)
projloss = loss + pcycle * projeff
self.ploss.set(projloss)
fcase = case + (pproduction / float(item))
self.fcase.set(fcase)
###line 19
self.ctlabelj = Label(self.line19, text = "Cycle Time:")
self.ctlabelj.grid(row=2, column=0)
self.cycletime = StringVar()
self.cycletime.trace('w', proj)
self.cycletimeentj = Entry(self.line19, textvariable=self.cycletime)
self.cycletimeentj.grid(row=2,column=1)
moldoptionsj = [1, 1, 2, 3, 4]
self.vj = IntVar()
self.vj.set(moldoptionsj[0])
self.headslabelj = Label(self.line19, text = "# of Molds:")
self.headslabelj.grid(row=3, column=0)
self.headcomboj = OptionMenu(self.line19, self.vj, *moldoptionsj)
self.headcomboj.grid(row=3,column=1)
self.vj.trace("w", cyclecnt)
self.cclabelj = Label(self.line19, text = "Cycle Count:")
self.cclabelj.grid(row=4, column=0)
self.cyccnt = StringVar()
self.cyclecountentj = Entry(self.line19, textvariable=self.cyccnt)
self.cyclecountentj.grid(row=4,column=1)
self.cyccnt.trace("w", cyclecnt)
self.ipcj = Label(self.line19, text = "Items/Case:")
self.ipcj.grid(row=5, column=0)
self.item = StringVar()
self.ipcentj = Entry(self.line19, textvariable=self.item)
self.ipcentj.grid(row=5,column=1)
self.item.trace("w", currentproduction)
self.currj = Label(self.line19, text = "Current Case #:")
self.currj.grid(row=6, column=0)
self.case = StringVar()
self.currentj = Entry(self.line19, textvariable=self.case)
self.currentj.grid(row=6,column=1)
self.case.trace("w", currentproduction)
self.ctimej = Label(self.line19, text = "Current Time:")
self.ctimej.grid(row=7, column=0, sticky='W')
self.clockj = Label(self.line19)
self.clockj.grid(row=7,column=1, sticky='w')
####futureztime###
self.futureframe = Frame(self.line19)
self.futureframe.grid(row=8, column=1)
self.futurej = Label(self.line19, text = "Future Projections time:")
self.futurej.grid(row=8, column=0, sticky='w')
self.hour = StringVar()
self.hour.trace('w', time_difference_seconds)
self.hour.trace('w', proj)
self.futureenthourj = Entry(self.futureframe, width=2, textvariable=self.hour)
self.futureenthourj.grid(row=0, column=0)
self.futurecolonj = Label(self.futureframe, text = ":")
self.futurecolonj.grid(row=0, column=1)
self.minute = StringVar()
self.minute.trace('w', time_difference_seconds)
self.minute.trace('w', proj)
self.futureentminj = Entry(self.futureframe, width=2, textvariable=self.minute)
self.futureentminj.grid(row=0, column=2)
####
self.cycleslabel = Label(self.line19, text = 'Cycle Total:')
self.cycleslabel.grid(row=2, column=2)
self.cyc = StringVar()
self.cyc.set("00000")
self.cyc.trace('w', lostunits)
self.cycles = Label(self.line19, foreground = 'green', background = 'black', text = "00000", textvariable = self.cyc)
self.cycles.grid(row=2, column=3)
self.currprodkeylabel = Label(self.line19, text = 'Current Production:')
self.currprodkeylabel.grid(row=3, column=2)
self.production = StringVar()
self.production.set('00000')
self.production.trace('w', lostunits)
self.production.trace('w', efficiency)
self.currentprod = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.production)
self.currentprod.grid(row=3, column=3)
self.prodprojkeylabel = Label(self.line19, text = 'Projected Production:')
self.prodprojkeylabel.grid(row=4, column=2)
self.projectedprod = StringVar()
self.projectedprod.set('00000')
self.prodproj = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.projectedprod )
self.prodproj.grid(row=4, column=3)
self.losskeylabel = Label(self.line19, text = 'Lost units:')
self.losskeylabel.grid(row=5, column=2)
self.loss = StringVar()
self.loss.set("0000")
self.loss.trace('w', efficiency)
self.lossprod = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.loss)
self.lossprod.grid(row=5, column=3)
self.plosskeylabel = Label(self.line19, text = 'Projected Lost units:')
self.plosskeylabel.grid(row=6, column=2)
self.ploss = StringVar()
self.ploss.set("0000")
self.plossprod = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.ploss)
self.plossprod.grid(row=6, column=3)
self.currefficiencykeylabel = Label(self.line19, text = 'Current efficiency %:')
self.currefficiencykeylabel.grid(row=7, column=2)
self.efficiency = StringVar()
self.efficiency.set("00.00")
self.currentefficiency = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.efficiency)
self.currentefficiency.grid(row=7, column=3)
self.futurecaselabel = Label(self.line19, text = 'Future case # projection:')
self.futurecaselabel.grid(row=8, column=2)
self.fcase = StringVar()
self.fcase.set("000.0")
self.futurecase = Label(self.line19, foreground = 'green', background = 'black', textvariable=self.fcase)
self.futurecase.grid(row=8, column=3)
self.projefficiencylabel = Label(self.line19, text = "Efficiency Projection:")
self.projefficiencylabel.grid(row=9, column=2)
self.peff = StringVar()
self.peff.set(0.00)
self.peff.trace('w', proj)
self.projefficiency = Entry(self.line19, textvariable=self.peff)
self.projefficiency.grid(row=9,column=3)
def tick():
s = time.strftime('%I:%M:%S')
if s != self.clockj:
self.clockj.configure(text=s)
self.notebook.after(200, tick)
tick()
root = Tk()
root.wm_title("Hillside Plastics Production Calculator")
calc = supervisorcalc(root)
mainloop()
```
|
2015/07/27
|
[
"https://Stackoverflow.com/questions/31662355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5111347/"
] |
This can't be intentional, because it can't work. As you've seen, you can't create a table twice. You should delete one of the migrations, possibly merging from the one you delete into the other one.
The only differences are the taggings\_count field and the indexes. There isn't enough to go on here to say whether you need taggings\_count or which is the better index. If I had to guess, I'd say the index on the first was trying to create a covering index, for what that's worth.
|
ActsAsTaggable\* will sometimes install a duplicate migration (or near duplicate) when upgrading the gem. Is the db/schema.rb checked in to the repo? If so, the unchanged version (once you start migrating, it gets changed) will have the "right" settings and help you figure out which one to remove.
|
51,591,025
|
I have used Django 1.11.14, python 2.7 and win 7 to build a website which could let registered user to login.
however, when I log in, some page display login link again when it should be logout link.
main page
```html
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}<title>xxxxx</title>{% endblock %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Add additional CSS in static file -->
{% load static %}
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2">
{% block sidebar %}
<ul class="sidebar-nav">
<br>
<li><a href="{% url 'index' %}"><mark>Home</mark></a></li>
<br>
<li><a href="{% url 'FWs' %}"><mark>FW request</mark></a></li>
<br>
</ul>
<ul class="sidebar-nav">
{% if user.is_authenticated %}
<li>User: {{ user.get_username }}</li>
<li><a href="{% url 'my-applied' %}"><mark>My applied</mark></a></li>
<br>
<li><a href="{% url 'logout'%}?next={{request.path}}"><mark>Logout</mark></a></li>
{% else %}
<li><a href="{% url 'login'%}?next={{request.path}}"><mark>Login</mark></a></li>
{% endif %}
</ul>
{% if user.is_staff %}
<hr />
<ul class="sidebar-nav">
<li>Staff</li>
{% if perms.catalog.can_mark_returned %}
<li><a href="{% url 'all-applied' %}"><mark>All applied</mark></a></li>
{% endif %}
</ul>
{% endif %}
{% endblock %}
</div>
<div class="col-sm-10 ">
{% block content %}{% endblock %}
{% block pagination %}
{% if is_paginated %}
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
<a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</span>
</div>
{% endif %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
```
FW\_request
```html
{% extends "base_generic.html" %}
{% block content %}
<p style = "color:#FF0000";> XXx</p>
{% if FW_list %}
<ul>
{% for FWinst in FW_list %}
{% if FWinst.is_approved %}
<p style = "color:#008000";>xxxx</p>
<p></p>
<br>
{% endif %}
{% endfor %}
</ul>
{% else %}
<p>Nothing.</p>
{% endif %}
{% endblock %}
```
view.py
```
class LoanedFWsByUserListView(LoginRequiredMixin,generic.ListView, FormView):
model = XX
paginate_by = 10
template_name = 'FW_request.html'
def get(self, request):
form = xx[![enter image description here][1]][1]Form()
FW_list = FW.objects.all().order_by('approve_time').reverse()
return render_to_response(self.template_name, locals())
```
when I login to the mainpage, it is correct, but when I click other tab like My applied, although I am still in the status of login, it shows login on the page, where it should be logout
|
2018/07/30
|
[
"https://Stackoverflow.com/questions/51591025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9669628/"
] |
Instead of `render_to_response` you should use [`render`](https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#render) function. This make request available in template.
```
def get(self, request):
form = xx[![enter image description here][1]][1]Form()
FW_list = FW.objects.all().order_by('approve_time').reverse()
return render(self.request, self.template_name, locals())
```
|
You have missed the point of using class based views here. You should rarely, if ever, be defining `get` (or `post`). In this case you should only define `get_context_data` to add your FW\_list, and let the view handle creating the form and rendering the template.
```
def get_context_data(self, **kwargs):
kwargs['FW_list'] = FW.objects.all().order_by('approve_time').reverse()
return super().get_context_data(**kwargs)
```
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
It seems most others have not quite understood the gist of your post. I'll break it down for you:
CSS positiong is complex because it was designed by many different groups of people over a long period of time, with various versions, and legacy compatibility issues.
The first attempts were to keep things simple. Just provide basic styling. Colors, fonts, sizes, magins, etc.. They added floats to provide the basic "cutout" functionality where text wraps around an image. Float was not intended to be used as a major layout feature as it currently is used.
But people were not happy with that. They wanted columns, and grids, boxes, and shadows, and rounded corners, and all kinds of other stuff, which was added in various stages. All while trying to maintain compatibility with previous bad implementations.
HTML has suffered from two opposing factions warring it out. One side wanted simple (compared to existing SGML anyways) solutions, another side wanted rich applications. So CSS has this sort of schitzophrenic nature to it sometimes.
What's more, features were extended to do things they weren't initially intended to do. This made the existing implementations all very buggy.
So what does that mean for you, a mere human? It means you are stuck dealing with everyone elses dirty laundry. It means you have to deal with decade old implementation bugs. It means you either have to write different CSS for different browsers, or you have to limit yourself to a common "well supported" featureset, which means you can't take full advantage of what the latest CSS can do (nor can you use the features there were designed to add some sanity to the standard).
In my opinion, there is no better book for a "mere human" to undrstand CSS than this:
[http://www.amazon.com/Eric-Meyer-CSS-Mastering-Language/dp/073571245X](https://rads.stackoverflow.com/amzn/click/com/073571245X)
It's simple, concise, and gives you real world examples in a glossy "easy on the eyes" format, and lacking most of the nasty technical jargon. It is 10 years old, and doesn't cover any of the new stuff, but it should allow you to "grok" the way things work.
|
Have you checked out this great book? <http://shop.oreilly.com/product/9781565926226.do>
just kidding.
I don't think you need an entire resource devoted to this one question. It's rather simple once it clicks.
Think of CSS positioning as a way to position items either relatively to themsevels (wherever they fall on the page) or absolutely from on an X/Y coordinate.
You can position something relative and it will either move up or to the right with a positive number, or down and to the left with a negative number.
If you position an element absolutely it will remove itself from the layout altogether (the other elements will not recognize it as being on the screen) and then do one of two things. It will either:
1 - position itself from the top left of the page and either go up/down right/left as I mentioned before depending on whether the numbers are +/-.
2- if the PARENT element is either positioned `absolute` or `relative` it will position itself from the top left "corner" of the parent element, NOT the browser window.
Think of `z-index` as layers in photoshop. With 0 being the bottom (and newer browsers recognize negative z index for even more fun). and 100 as the top later (newer browsers recognize an infinite amount of numbers). The `z-index` only works with position: `relative` and `absolute`.
So if I position something absolute, and it happens to fall underneath another element, I can give it `z-index: 100` and it will position itself on top. Keep in mind that the element itself is a rectangle, and the height/width of the element may inhibit you from clicking on the element beneath. You can't do angles,circles, etc. with pure CSS.
Does that help?
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
There's more to the positioning that just the position property. You need to understand how floats work as well.
<http://coding.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/>
<http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/>
These two articles should get you going.
Read a bit on display properties as well, since they're likely to be one of the problematic areas in any given html/css.
|
Have you checked out this great book? <http://shop.oreilly.com/product/9781565926226.do>
just kidding.
I don't think you need an entire resource devoted to this one question. It's rather simple once it clicks.
Think of CSS positioning as a way to position items either relatively to themsevels (wherever they fall on the page) or absolutely from on an X/Y coordinate.
You can position something relative and it will either move up or to the right with a positive number, or down and to the left with a negative number.
If you position an element absolutely it will remove itself from the layout altogether (the other elements will not recognize it as being on the screen) and then do one of two things. It will either:
1 - position itself from the top left of the page and either go up/down right/left as I mentioned before depending on whether the numbers are +/-.
2- if the PARENT element is either positioned `absolute` or `relative` it will position itself from the top left "corner" of the parent element, NOT the browser window.
Think of `z-index` as layers in photoshop. With 0 being the bottom (and newer browsers recognize negative z index for even more fun). and 100 as the top later (newer browsers recognize an infinite amount of numbers). The `z-index` only works with position: `relative` and `absolute`.
So if I position something absolute, and it happens to fall underneath another element, I can give it `z-index: 100` and it will position itself on top. Keep in mind that the element itself is a rectangle, and the height/width of the element may inhibit you from clicking on the element beneath. You can't do angles,circles, etc. with pure CSS.
Does that help?
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
It seems most others have not quite understood the gist of your post. I'll break it down for you:
CSS positiong is complex because it was designed by many different groups of people over a long period of time, with various versions, and legacy compatibility issues.
The first attempts were to keep things simple. Just provide basic styling. Colors, fonts, sizes, magins, etc.. They added floats to provide the basic "cutout" functionality where text wraps around an image. Float was not intended to be used as a major layout feature as it currently is used.
But people were not happy with that. They wanted columns, and grids, boxes, and shadows, and rounded corners, and all kinds of other stuff, which was added in various stages. All while trying to maintain compatibility with previous bad implementations.
HTML has suffered from two opposing factions warring it out. One side wanted simple (compared to existing SGML anyways) solutions, another side wanted rich applications. So CSS has this sort of schitzophrenic nature to it sometimes.
What's more, features were extended to do things they weren't initially intended to do. This made the existing implementations all very buggy.
So what does that mean for you, a mere human? It means you are stuck dealing with everyone elses dirty laundry. It means you have to deal with decade old implementation bugs. It means you either have to write different CSS for different browsers, or you have to limit yourself to a common "well supported" featureset, which means you can't take full advantage of what the latest CSS can do (nor can you use the features there were designed to add some sanity to the standard).
In my opinion, there is no better book for a "mere human" to undrstand CSS than this:
[http://www.amazon.com/Eric-Meyer-CSS-Mastering-Language/dp/073571245X](https://rads.stackoverflow.com/amzn/click/com/073571245X)
It's simple, concise, and gives you real world examples in a glossy "easy on the eyes" format, and lacking most of the nasty technical jargon. It is 10 years old, and doesn't cover any of the new stuff, but it should allow you to "grok" the way things work.
|
These two courses from code academy should explain CSS positioning well:
[First](http://www.codecademy.com/courses/50358c84b87e8f0002022429), [Second](http://www.codecademy.com/courses/advanced-css-positioning).
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
Positioning is easy to understand:
`relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected.
`absolute` positioning -- Removes the item from the page flow. Other things render as if this weren't there, i.e. they fill in the space that this item took up. They are now positioned *absolutely to the nearest element with `position: relative` OR `position: absolute` set*. In many cases this means they are positioned absolute to the `body` tag.
You then position things with `top`, `right`, `bottom` and `left` in CSS.
If something has `absolute` positioning set:
* positioned relative to the *top left* of the page when using `top` and `left`. Positioned relative to the *bottom right* of the page when using `bottom` and `right`.
* its width/height can be controlled with a combination of `top / bottom` or `left / right`, e.g.: `top: 100px; bottom: 100px` will make an item that is `100% - 200px` of its parent's height (unless you specify a height too in which case `top` and `height` are used and `bottom` is ignored).
|
this link is mainly about z-index but IMO it does a pretty good job of explaining how things are positioned on a page
<http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/>
This link is more focused on positioning but it is important to understand the z axis in order to understand the rest of the positioning puzzle
<http://kilianvalkhof.com/2008/css-xhtml/understanding-css-positioning-part-1/>
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
Positioning is easy to understand:
`relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected.
`absolute` positioning -- Removes the item from the page flow. Other things render as if this weren't there, i.e. they fill in the space that this item took up. They are now positioned *absolutely to the nearest element with `position: relative` OR `position: absolute` set*. In many cases this means they are positioned absolute to the `body` tag.
You then position things with `top`, `right`, `bottom` and `left` in CSS.
If something has `absolute` positioning set:
* positioned relative to the *top left* of the page when using `top` and `left`. Positioned relative to the *bottom right* of the page when using `bottom` and `right`.
* its width/height can be controlled with a combination of `top / bottom` or `left / right`, e.g.: `top: 100px; bottom: 100px` will make an item that is `100% - 200px` of its parent's height (unless you specify a height too in which case `top` and `height` are used and `bottom` is ignored).
|
These two courses from code academy should explain CSS positioning well:
[First](http://www.codecademy.com/courses/50358c84b87e8f0002022429), [Second](http://www.codecademy.com/courses/advanced-css-positioning).
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
Positioning is easy to understand:
`relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected.
`absolute` positioning -- Removes the item from the page flow. Other things render as if this weren't there, i.e. they fill in the space that this item took up. They are now positioned *absolutely to the nearest element with `position: relative` OR `position: absolute` set*. In many cases this means they are positioned absolute to the `body` tag.
You then position things with `top`, `right`, `bottom` and `left` in CSS.
If something has `absolute` positioning set:
* positioned relative to the *top left* of the page when using `top` and `left`. Positioned relative to the *bottom right* of the page when using `bottom` and `right`.
* its width/height can be controlled with a combination of `top / bottom` or `left / right`, e.g.: `top: 100px; bottom: 100px` will make an item that is `100% - 200px` of its parent's height (unless you specify a height too in which case `top` and `height` are used and `bottom` is ignored).
|
Have you checked out this great book? <http://shop.oreilly.com/product/9781565926226.do>
just kidding.
I don't think you need an entire resource devoted to this one question. It's rather simple once it clicks.
Think of CSS positioning as a way to position items either relatively to themsevels (wherever they fall on the page) or absolutely from on an X/Y coordinate.
You can position something relative and it will either move up or to the right with a positive number, or down and to the left with a negative number.
If you position an element absolutely it will remove itself from the layout altogether (the other elements will not recognize it as being on the screen) and then do one of two things. It will either:
1 - position itself from the top left of the page and either go up/down right/left as I mentioned before depending on whether the numbers are +/-.
2- if the PARENT element is either positioned `absolute` or `relative` it will position itself from the top left "corner" of the parent element, NOT the browser window.
Think of `z-index` as layers in photoshop. With 0 being the bottom (and newer browsers recognize negative z index for even more fun). and 100 as the top later (newer browsers recognize an infinite amount of numbers). The `z-index` only works with position: `relative` and `absolute`.
So if I position something absolute, and it happens to fall underneath another element, I can give it `z-index: 100` and it will position itself on top. Keep in mind that the element itself is a rectangle, and the height/width of the element may inhibit you from clicking on the element beneath. You can't do angles,circles, etc. with pure CSS.
Does that help?
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
Positioning is easy to understand:
`relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected.
`absolute` positioning -- Removes the item from the page flow. Other things render as if this weren't there, i.e. they fill in the space that this item took up. They are now positioned *absolutely to the nearest element with `position: relative` OR `position: absolute` set*. In many cases this means they are positioned absolute to the `body` tag.
You then position things with `top`, `right`, `bottom` and `left` in CSS.
If something has `absolute` positioning set:
* positioned relative to the *top left* of the page when using `top` and `left`. Positioned relative to the *bottom right* of the page when using `bottom` and `right`.
* its width/height can be controlled with a combination of `top / bottom` or `left / right`, e.g.: `top: 100px; bottom: 100px` will make an item that is `100% - 200px` of its parent's height (unless you specify a height too in which case `top` and `height` are used and `bottom` is ignored).
|
There's more to the positioning that just the position property. You need to understand how floats work as well.
<http://coding.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/>
<http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/>
These two articles should get you going.
Read a bit on display properties as well, since they're likely to be one of the problematic areas in any given html/css.
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
There's more to the positioning that just the position property. You need to understand how floats work as well.
<http://coding.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/>
<http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/>
These two articles should get you going.
Read a bit on display properties as well, since they're likely to be one of the problematic areas in any given html/css.
|
this link is mainly about z-index but IMO it does a pretty good job of explaining how things are positioned on a page
<http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/>
This link is more focused on positioning but it is important to understand the z axis in order to understand the rest of the positioning puzzle
<http://kilianvalkhof.com/2008/css-xhtml/understanding-css-positioning-part-1/>
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
It seems most others have not quite understood the gist of your post. I'll break it down for you:
CSS positiong is complex because it was designed by many different groups of people over a long period of time, with various versions, and legacy compatibility issues.
The first attempts were to keep things simple. Just provide basic styling. Colors, fonts, sizes, magins, etc.. They added floats to provide the basic "cutout" functionality where text wraps around an image. Float was not intended to be used as a major layout feature as it currently is used.
But people were not happy with that. They wanted columns, and grids, boxes, and shadows, and rounded corners, and all kinds of other stuff, which was added in various stages. All while trying to maintain compatibility with previous bad implementations.
HTML has suffered from two opposing factions warring it out. One side wanted simple (compared to existing SGML anyways) solutions, another side wanted rich applications. So CSS has this sort of schitzophrenic nature to it sometimes.
What's more, features were extended to do things they weren't initially intended to do. This made the existing implementations all very buggy.
So what does that mean for you, a mere human? It means you are stuck dealing with everyone elses dirty laundry. It means you have to deal with decade old implementation bugs. It means you either have to write different CSS for different browsers, or you have to limit yourself to a common "well supported" featureset, which means you can't take full advantage of what the latest CSS can do (nor can you use the features there were designed to add some sanity to the standard).
In my opinion, there is no better book for a "mere human" to undrstand CSS than this:
[http://www.amazon.com/Eric-Meyer-CSS-Mastering-Language/dp/073571245X](https://rads.stackoverflow.com/amzn/click/com/073571245X)
It's simple, concise, and gives you real world examples in a glossy "easy on the eyes" format, and lacking most of the nasty technical jargon. It is 10 years old, and doesn't cover any of the new stuff, but it should allow you to "grok" the way things work.
|
this link is mainly about z-index but IMO it does a pretty good job of explaining how things are positioned on a page
<http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/>
This link is more focused on positioning but it is important to understand the z axis in order to understand the rest of the positioning puzzle
<http://kilianvalkhof.com/2008/css-xhtml/understanding-css-positioning-part-1/>
|
9,072,175
|
fellow earthians.
I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself.
The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish.
Then, that if you want to put something to the left of something else (crazy idea, right?), *all* you have to do is to set it to float to the left provided you set the "relative" flag on its parent block which has to have a grand-father node with the "absolute" flag set to true so that it's positionned relatively to an other container that may-or-not contain anything, have a position, a size, or not, depending on the browser, the size of other stuff, and possibly the phases of the moon. (CSS experts are advised not to take the previous paragraph seriously. I'm pretty sure someone will point out that my rant is not valid, or w3c-compliant - and that it only applies to the swedish beta version of IE6)
Joking apart, I'm looking for any resource that explains the root causes of all the crazyness behind layout in CSS. In essence, something that would be to CSS what Crockford's articles are to Javascript.
In this spirit, let me point out that I'm not looking for css libraries or grid frameworks like blueprint, or for CSS extension languages like lesscss. I've been using those to ease my sufferings, but I'm afraid it would be like telling someone to "just use jQuery" when they say they can't wrap their mind around prototype inheritence in JS.
If all you can point me to is <http://shop.oreilly.com/product/9781565926226.do> , I guess I'll consider myself doomed.
Thanks in advance.
EDIT : I probably should not have talked about "positioning" (thanks to all who've explained again that 'position:relative' does not mean 'relative to your container' and that 'position:absolute' means relative to something. I've never been so close to making a monty python script out of a SO questions). I think I meant layout in general (positioning + floats + baselines + all the nonsense required to put stuff on a straight line).
Also please excuse the ranting tone, I'm trying to pour some humour into frustration. I would use zen techniques to calm down if I could, but this only reminds me of
[this](http://www.csszengarden.com/).
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9072175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77804/"
] |
It seems most others have not quite understood the gist of your post. I'll break it down for you:
CSS positiong is complex because it was designed by many different groups of people over a long period of time, with various versions, and legacy compatibility issues.
The first attempts were to keep things simple. Just provide basic styling. Colors, fonts, sizes, magins, etc.. They added floats to provide the basic "cutout" functionality where text wraps around an image. Float was not intended to be used as a major layout feature as it currently is used.
But people were not happy with that. They wanted columns, and grids, boxes, and shadows, and rounded corners, and all kinds of other stuff, which was added in various stages. All while trying to maintain compatibility with previous bad implementations.
HTML has suffered from two opposing factions warring it out. One side wanted simple (compared to existing SGML anyways) solutions, another side wanted rich applications. So CSS has this sort of schitzophrenic nature to it sometimes.
What's more, features were extended to do things they weren't initially intended to do. This made the existing implementations all very buggy.
So what does that mean for you, a mere human? It means you are stuck dealing with everyone elses dirty laundry. It means you have to deal with decade old implementation bugs. It means you either have to write different CSS for different browsers, or you have to limit yourself to a common "well supported" featureset, which means you can't take full advantage of what the latest CSS can do (nor can you use the features there were designed to add some sanity to the standard).
In my opinion, there is no better book for a "mere human" to undrstand CSS than this:
[http://www.amazon.com/Eric-Meyer-CSS-Mastering-Language/dp/073571245X](https://rads.stackoverflow.com/amzn/click/com/073571245X)
It's simple, concise, and gives you real world examples in a glossy "easy on the eyes" format, and lacking most of the nasty technical jargon. It is 10 years old, and doesn't cover any of the new stuff, but it should allow you to "grok" the way things work.
|
Positioning is easy to understand:
`relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected.
`absolute` positioning -- Removes the item from the page flow. Other things render as if this weren't there, i.e. they fill in the space that this item took up. They are now positioned *absolutely to the nearest element with `position: relative` OR `position: absolute` set*. In many cases this means they are positioned absolute to the `body` tag.
You then position things with `top`, `right`, `bottom` and `left` in CSS.
If something has `absolute` positioning set:
* positioned relative to the *top left* of the page when using `top` and `left`. Positioned relative to the *bottom right* of the page when using `bottom` and `right`.
* its width/height can be controlled with a combination of `top / bottom` or `left / right`, e.g.: `top: 100px; bottom: 100px` will make an item that is `100% - 200px` of its parent's height (unless you specify a height too in which case `top` and `height` are used and `bottom` is ignored).
|
25,237,039
|
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error.
>
> Traceback (most recent call last):
>
> File "score.py", line 30, in
>
> model = (cPickle.load(file))
>
> File "/usr/local/python2.7/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/sandbox/cuda/type.py", line 485, in CudaNdarray\_unpickler
>
> return cuda.CudaNdarray(npa)
>
> AttributeError: ("'NoneType' object has no attribute 'CudaNdarray'", , (array([[ 0.011515 , 0.01171047, 0.10408644, ..., -0.0343636 ,
>
> 0.04944979, -0.06583775],
>
> [-0.03771918, 0.080524 , -0.10609912, ..., 0.11019105,
>
> -0.0570752 , 0.02100536],
>
> [-0.03628891, -0.07109226, -0.00932018, ..., 0.04316209,
>
> 0.02817888, 0.05785328],
>
> ...,
>
> [ 0.0703947 , -0.00172865, -0.05942701, ..., -0.00999349,
>
> 0.01624184, 0.09832744],
>
> [-0.09029484, -0.11509365, -0.07193922, ..., 0.10658887,
>
> 0.17730837, 0.01104965],
>
> [ 0.06659461, -0.02492988, 0.02271739, ..., -0.0646857 ,
>
> 0.03879852, 0.08779807]], dtype=float32),))
>
>
>
I checked for that cudaNdarray package in my local machine and it is not installed, but still i am able to unpickle them. But in the server, i am unable to. How do i make them to run on a server which doesnt have a GPU?
|
2014/08/11
|
[
"https://Stackoverflow.com/questions/25237039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1505986/"
] |
There is a script in pylearn2 which may do what you need:
`pylearn2/scripts/gpu_pkl_to_cpu_pkl.py`
|
This works for me. Note: this doesn't work unless the following environment variable is set: `export THEANO_FLAGS='device=cpu'`
```
import os
from pylearn2.utils import serial
import pylearn2.config.yaml_parse as yaml_parse
if __name__=="__main__":
_, in_path, out_path = sys.argv
os.environ['THEANO_FLAGS']="device=cpu"
model = serial.load(in_path)
model2 = yaml_parse.load(model.yaml_src)
model2.set_param_values(model.get_param_values())
serial.save(out_path, model2)
```
|
25,237,039
|
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error.
>
> Traceback (most recent call last):
>
> File "score.py", line 30, in
>
> model = (cPickle.load(file))
>
> File "/usr/local/python2.7/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/sandbox/cuda/type.py", line 485, in CudaNdarray\_unpickler
>
> return cuda.CudaNdarray(npa)
>
> AttributeError: ("'NoneType' object has no attribute 'CudaNdarray'", , (array([[ 0.011515 , 0.01171047, 0.10408644, ..., -0.0343636 ,
>
> 0.04944979, -0.06583775],
>
> [-0.03771918, 0.080524 , -0.10609912, ..., 0.11019105,
>
> -0.0570752 , 0.02100536],
>
> [-0.03628891, -0.07109226, -0.00932018, ..., 0.04316209,
>
> 0.02817888, 0.05785328],
>
> ...,
>
> [ 0.0703947 , -0.00172865, -0.05942701, ..., -0.00999349,
>
> 0.01624184, 0.09832744],
>
> [-0.09029484, -0.11509365, -0.07193922, ..., 0.10658887,
>
> 0.17730837, 0.01104965],
>
> [ 0.06659461, -0.02492988, 0.02271739, ..., -0.0646857 ,
>
> 0.03879852, 0.08779807]], dtype=float32),))
>
>
>
I checked for that cudaNdarray package in my local machine and it is not installed, but still i am able to unpickle them. But in the server, i am unable to. How do i make them to run on a server which doesnt have a GPU?
|
2014/08/11
|
[
"https://Stackoverflow.com/questions/25237039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1505986/"
] |
There is a script in pylearn2 which may do what you need:
`pylearn2/scripts/gpu_pkl_to_cpu_pkl.py`
|
I solved this problem by just saving the parameters W & b, but not the whole model. You can save the parameters use this:<http://deeplearning.net/software/theano/tutorial/loading_and_saving.html?highlight=saving%20load#robust-serialization>
This can save the CudaNdarray to numpy array. Then you need to read the params by numpy.load(), and finally convert the numpy array to tensorSharedVariable use theano.shared().
|
25,237,039
|
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error.
>
> Traceback (most recent call last):
>
> File "score.py", line 30, in
>
> model = (cPickle.load(file))
>
> File "/usr/local/python2.7/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/sandbox/cuda/type.py", line 485, in CudaNdarray\_unpickler
>
> return cuda.CudaNdarray(npa)
>
> AttributeError: ("'NoneType' object has no attribute 'CudaNdarray'", , (array([[ 0.011515 , 0.01171047, 0.10408644, ..., -0.0343636 ,
>
> 0.04944979, -0.06583775],
>
> [-0.03771918, 0.080524 , -0.10609912, ..., 0.11019105,
>
> -0.0570752 , 0.02100536],
>
> [-0.03628891, -0.07109226, -0.00932018, ..., 0.04316209,
>
> 0.02817888, 0.05785328],
>
> ...,
>
> [ 0.0703947 , -0.00172865, -0.05942701, ..., -0.00999349,
>
> 0.01624184, 0.09832744],
>
> [-0.09029484, -0.11509365, -0.07193922, ..., 0.10658887,
>
> 0.17730837, 0.01104965],
>
> [ 0.06659461, -0.02492988, 0.02271739, ..., -0.0646857 ,
>
> 0.03879852, 0.08779807]], dtype=float32),))
>
>
>
I checked for that cudaNdarray package in my local machine and it is not installed, but still i am able to unpickle them. But in the server, i am unable to. How do i make them to run on a server which doesnt have a GPU?
|
2014/08/11
|
[
"https://Stackoverflow.com/questions/25237039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1505986/"
] |
The related Theano code is [here](https://github.com/Theano/Theano/blob/master/theano/sandbox/cuda/type.py).
From there, it looks like there is an option `config.experimental.unpickle_gpu_on_cpu` which you could set and which would make `CudaNdarray_unpickler` return the underlying raw Numpy array.
|
This works for me. Note: this doesn't work unless the following environment variable is set: `export THEANO_FLAGS='device=cpu'`
```
import os
from pylearn2.utils import serial
import pylearn2.config.yaml_parse as yaml_parse
if __name__=="__main__":
_, in_path, out_path = sys.argv
os.environ['THEANO_FLAGS']="device=cpu"
model = serial.load(in_path)
model2 = yaml_parse.load(model.yaml_src)
model2.set_param_values(model.get_param_values())
serial.save(out_path, model2)
```
|
25,237,039
|
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error.
>
> Traceback (most recent call last):
>
> File "score.py", line 30, in
>
> model = (cPickle.load(file))
>
> File "/usr/local/python2.7/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/sandbox/cuda/type.py", line 485, in CudaNdarray\_unpickler
>
> return cuda.CudaNdarray(npa)
>
> AttributeError: ("'NoneType' object has no attribute 'CudaNdarray'", , (array([[ 0.011515 , 0.01171047, 0.10408644, ..., -0.0343636 ,
>
> 0.04944979, -0.06583775],
>
> [-0.03771918, 0.080524 , -0.10609912, ..., 0.11019105,
>
> -0.0570752 , 0.02100536],
>
> [-0.03628891, -0.07109226, -0.00932018, ..., 0.04316209,
>
> 0.02817888, 0.05785328],
>
> ...,
>
> [ 0.0703947 , -0.00172865, -0.05942701, ..., -0.00999349,
>
> 0.01624184, 0.09832744],
>
> [-0.09029484, -0.11509365, -0.07193922, ..., 0.10658887,
>
> 0.17730837, 0.01104965],
>
> [ 0.06659461, -0.02492988, 0.02271739, ..., -0.0646857 ,
>
> 0.03879852, 0.08779807]], dtype=float32),))
>
>
>
I checked for that cudaNdarray package in my local machine and it is not installed, but still i am able to unpickle them. But in the server, i am unable to. How do i make them to run on a server which doesnt have a GPU?
|
2014/08/11
|
[
"https://Stackoverflow.com/questions/25237039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1505986/"
] |
The related Theano code is [here](https://github.com/Theano/Theano/blob/master/theano/sandbox/cuda/type.py).
From there, it looks like there is an option `config.experimental.unpickle_gpu_on_cpu` which you could set and which would make `CudaNdarray_unpickler` return the underlying raw Numpy array.
|
I solved this problem by just saving the parameters W & b, but not the whole model. You can save the parameters use this:<http://deeplearning.net/software/theano/tutorial/loading_and_saving.html?highlight=saving%20load#robust-serialization>
This can save the CudaNdarray to numpy array. Then you need to read the params by numpy.load(), and finally convert the numpy array to tensorSharedVariable use theano.shared().
|
25,237,039
|
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error.
>
> Traceback (most recent call last):
>
> File "score.py", line 30, in
>
> model = (cPickle.load(file))
>
> File "/usr/local/python2.7/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/sandbox/cuda/type.py", line 485, in CudaNdarray\_unpickler
>
> return cuda.CudaNdarray(npa)
>
> AttributeError: ("'NoneType' object has no attribute 'CudaNdarray'", , (array([[ 0.011515 , 0.01171047, 0.10408644, ..., -0.0343636 ,
>
> 0.04944979, -0.06583775],
>
> [-0.03771918, 0.080524 , -0.10609912, ..., 0.11019105,
>
> -0.0570752 , 0.02100536],
>
> [-0.03628891, -0.07109226, -0.00932018, ..., 0.04316209,
>
> 0.02817888, 0.05785328],
>
> ...,
>
> [ 0.0703947 , -0.00172865, -0.05942701, ..., -0.00999349,
>
> 0.01624184, 0.09832744],
>
> [-0.09029484, -0.11509365, -0.07193922, ..., 0.10658887,
>
> 0.17730837, 0.01104965],
>
> [ 0.06659461, -0.02492988, 0.02271739, ..., -0.0646857 ,
>
> 0.03879852, 0.08779807]], dtype=float32),))
>
>
>
I checked for that cudaNdarray package in my local machine and it is not installed, but still i am able to unpickle them. But in the server, i am unable to. How do i make them to run on a server which doesnt have a GPU?
|
2014/08/11
|
[
"https://Stackoverflow.com/questions/25237039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1505986/"
] |
This works for me. Note: this doesn't work unless the following environment variable is set: `export THEANO_FLAGS='device=cpu'`
```
import os
from pylearn2.utils import serial
import pylearn2.config.yaml_parse as yaml_parse
if __name__=="__main__":
_, in_path, out_path = sys.argv
os.environ['THEANO_FLAGS']="device=cpu"
model = serial.load(in_path)
model2 = yaml_parse.load(model.yaml_src)
model2.set_param_values(model.get_param_values())
serial.save(out_path, model2)
```
|
I solved this problem by just saving the parameters W & b, but not the whole model. You can save the parameters use this:<http://deeplearning.net/software/theano/tutorial/loading_and_saving.html?highlight=saving%20load#robust-serialization>
This can save the CudaNdarray to numpy array. Then you need to read the params by numpy.load(), and finally convert the numpy array to tensorSharedVariable use theano.shared().
|
33,157,597
|
I am trying to install rasterio into my python environment and am getting the following errors. I can do
```
conda install rasterio
```
No error comes up on the install but I come up with the following error when I try to import
```
from rasterio._base import eval_window, window_shape, window_index
ImportError: DLL load failed: The specified module could not be found.
```
if I try
```
pip install rasterio
```
it errors when installing with this:
```
rasterio/_base.c(263) : fatal error C1083: Cannot open include file:'cpl_conv.h': No such file or directory
error: command 'C:\\Users\\Rdebbout\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2
----------------------------------------
Failed building wheel for rasterio
```
I have the same problems with trying to import the fiona module. How and/or where do DLLs get loaded? I'm in the dark on this one and would appreciate any help or direction as to how to troubleshoot this problem.
I am using the 64-bit version of spyder on windows 7.
|
2015/10/15
|
[
"https://Stackoverflow.com/questions/33157597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4812453/"
] |
I would suggest trying the ioos anaconda recipe (<https://anaconda.org/ioos/rasterio>).
`conda install -c https://conda.anaconda.org/ioos rasterio`.
I have run into the same DLL issue you are seeing when trying to install more recent versions of rasterio using the standard anaconda version.
|
I had the same issue. A reinstall solved it.
```
conda install -f rasterio
```
|
33,157,597
|
I am trying to install rasterio into my python environment and am getting the following errors. I can do
```
conda install rasterio
```
No error comes up on the install but I come up with the following error when I try to import
```
from rasterio._base import eval_window, window_shape, window_index
ImportError: DLL load failed: The specified module could not be found.
```
if I try
```
pip install rasterio
```
it errors when installing with this:
```
rasterio/_base.c(263) : fatal error C1083: Cannot open include file:'cpl_conv.h': No such file or directory
error: command 'C:\\Users\\Rdebbout\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2
----------------------------------------
Failed building wheel for rasterio
```
I have the same problems with trying to import the fiona module. How and/or where do DLLs get loaded? I'm in the dark on this one and would appreciate any help or direction as to how to troubleshoot this problem.
I am using the 64-bit version of spyder on windows 7.
|
2015/10/15
|
[
"https://Stackoverflow.com/questions/33157597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4812453/"
] |
I would suggest trying the ioos anaconda recipe (<https://anaconda.org/ioos/rasterio>).
`conda install -c https://conda.anaconda.org/ioos rasterio`.
I have run into the same DLL issue you are seeing when trying to install more recent versions of rasterio using the standard anaconda version.
|
If you're still having the issue. you can create a new conda enviroment using:
```
conda create -n envname
```
After that install using: `conda install -c conda-forge/label/dev rasterio`
|
33,157,597
|
I am trying to install rasterio into my python environment and am getting the following errors. I can do
```
conda install rasterio
```
No error comes up on the install but I come up with the following error when I try to import
```
from rasterio._base import eval_window, window_shape, window_index
ImportError: DLL load failed: The specified module could not be found.
```
if I try
```
pip install rasterio
```
it errors when installing with this:
```
rasterio/_base.c(263) : fatal error C1083: Cannot open include file:'cpl_conv.h': No such file or directory
error: command 'C:\\Users\\Rdebbout\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2
----------------------------------------
Failed building wheel for rasterio
```
I have the same problems with trying to import the fiona module. How and/or where do DLLs get loaded? I'm in the dark on this one and would appreciate any help or direction as to how to troubleshoot this problem.
I am using the 64-bit version of spyder on windows 7.
|
2015/10/15
|
[
"https://Stackoverflow.com/questions/33157597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4812453/"
] |
I had the same issue. A reinstall solved it.
```
conda install -f rasterio
```
|
If you're still having the issue. you can create a new conda enviroment using:
```
conda create -n envname
```
After that install using: `conda install -c conda-forge/label/dev rasterio`
|
1,575,971
|
I'm making a stupid little game that saves your score in a highscores.txt file.
My problem is sorting the lines. Here's what I have so far.
Maybe an alphanumeric sorter for python would help? Thanks.
```
import os.path
import string
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name
f = open("highscores.txt", "r+")
words = f.readlines()
print words
main()
```
|
2009/10/16
|
[
"https://Stackoverflow.com/questions/1575971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190983/"
] |
after `words = f.readlines()`, try something like:
```
headers = words.pop(0)
def myway(aline):
i = 0
while aline[i].isdigit():
i += 1
score = int(aline[:i])
return score
words.sort(key=myway, reverse=True)
words.insert(0, headers)
```
The key (;-) idea is to make a function that returns the "sorting key" from each item (here, a line). I'm trying to write it in the simplest possible way: see how many leading digits there are, then turn them all into an int, and return that.
|
Doing a simple string sort on your
```
new_score = str(score) + ".........." + name
```
items isn't going to work since, for example str(1000) < str(500). In other words, 1000 will come before 500 in an alphanumeric sort.
Alex's answer is good in that it demonstrates the use of a sort key function, but here is another solution which is a bit simpler and has the added advantage of visuallaly aligning the high score displays.
What you need to do is right align your numbers in a fixed field of the maximum size of the scores, thus (assuming 5 digits max and ver < 3.0):
```
new_score = "%5d........%s" % (score, name)
```
or for Python ver 3.x:
```
new_score = "{0:5d}........{1}".format(score, name)
```
For each new\_score append it to the words list (you could use a better name here) and sort it reversed before printing. Or you could use the bisect.insort library function rather than doing a list.append.
Also, a more Pythonic form than
```
if file_exists == False:
```
is:
```
if not file_exists:
```
|
1,575,971
|
I'm making a stupid little game that saves your score in a highscores.txt file.
My problem is sorting the lines. Here's what I have so far.
Maybe an alphanumeric sorter for python would help? Thanks.
```
import os.path
import string
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name
f = open("highscores.txt", "r+")
words = f.readlines()
print words
main()
```
|
2009/10/16
|
[
"https://Stackoverflow.com/questions/1575971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190983/"
] |
after `words = f.readlines()`, try something like:
```
headers = words.pop(0)
def myway(aline):
i = 0
while aline[i].isdigit():
i += 1
score = int(aline[:i])
return score
words.sort(key=myway, reverse=True)
words.insert(0, headers)
```
The key (;-) idea is to make a function that returns the "sorting key" from each item (here, a line). I'm trying to write it in the simplest possible way: see how many leading digits there are, then turn them all into an int, and return that.
|
I guess something went wrong when you pasted from Alex's answer, so here is your code with a sort in there
```
import os.path
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name +"\n"
f = open("highscores.txt", "r+")
words = f.readlines()
headers = words.pop(0)
def anotherway(aline):
score=""
for c in aline:
if c.isdigit():
score+=c
else:
break
return int(score)
words.append(new_score)
words.sort(key=anotherway, reverse=True)
words.insert(0, headers)
print "".join(words)
main()
```
|
1,575,971
|
I'm making a stupid little game that saves your score in a highscores.txt file.
My problem is sorting the lines. Here's what I have so far.
Maybe an alphanumeric sorter for python would help? Thanks.
```
import os.path
import string
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name
f = open("highscores.txt", "r+")
words = f.readlines()
print words
main()
```
|
2009/10/16
|
[
"https://Stackoverflow.com/questions/1575971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190983/"
] |
after `words = f.readlines()`, try something like:
```
headers = words.pop(0)
def myway(aline):
i = 0
while aline[i].isdigit():
i += 1
score = int(aline[:i])
return score
words.sort(key=myway, reverse=True)
words.insert(0, headers)
```
The key (;-) idea is to make a function that returns the "sorting key" from each item (here, a line). I'm trying to write it in the simplest possible way: see how many leading digits there are, then turn them all into an int, and return that.
|
I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON.
```
import simplejson as json # Python 2.x
# import json # Python 3.x
d = {}
d["version"] = 1
d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]]
s = json.dumps(d)
print s
# prints:
# {"version": 1, "highscores": [[100, "Steve"], [200, "Ken"], [400, "Denise"]]}
d2 = json.loads(s)
for score, name in sorted(d2["highscores"], reverse=True):
print "%5d\t%s" % (score, name)
# prints:
# 400 Denise
# 200 Ken
# 100 Steve
```
Using JSON will keep you from having to write your own parser to recover data from saved files such as high score tables. You can just tuck everything into a dictionary and trivially get it all back.
Note that I tucked in a version number, the version number of your high score save format. If you ever change the save format of your data, having a version number in there will be a very good thing.
|
1,575,971
|
I'm making a stupid little game that saves your score in a highscores.txt file.
My problem is sorting the lines. Here's what I have so far.
Maybe an alphanumeric sorter for python would help? Thanks.
```
import os.path
import string
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name
f = open("highscores.txt", "r+")
words = f.readlines()
print words
main()
```
|
2009/10/16
|
[
"https://Stackoverflow.com/questions/1575971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190983/"
] |
after `words = f.readlines()`, try something like:
```
headers = words.pop(0)
def myway(aline):
i = 0
while aline[i].isdigit():
i += 1
score = int(aline[:i])
return score
words.sort(key=myway, reverse=True)
words.insert(0, headers)
```
The key (;-) idea is to make a function that returns the "sorting key" from each item (here, a line). I'm trying to write it in the simplest possible way: see how many leading digits there are, then turn them all into an int, and return that.
|
What you want is probably what's generally known as a "Natural Sort". Searching for "natural sort python" gives many results, but there's some good discussion on [ASPN](http://code.activestate.com/recipes/285264/).
|
1,575,971
|
I'm making a stupid little game that saves your score in a highscores.txt file.
My problem is sorting the lines. Here's what I have so far.
Maybe an alphanumeric sorter for python would help? Thanks.
```
import os.path
import string
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name
f = open("highscores.txt", "r+")
words = f.readlines()
print words
main()
```
|
2009/10/16
|
[
"https://Stackoverflow.com/questions/1575971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190983/"
] |
I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON.
```
import simplejson as json # Python 2.x
# import json # Python 3.x
d = {}
d["version"] = 1
d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]]
s = json.dumps(d)
print s
# prints:
# {"version": 1, "highscores": [[100, "Steve"], [200, "Ken"], [400, "Denise"]]}
d2 = json.loads(s)
for score, name in sorted(d2["highscores"], reverse=True):
print "%5d\t%s" % (score, name)
# prints:
# 400 Denise
# 200 Ken
# 100 Steve
```
Using JSON will keep you from having to write your own parser to recover data from saved files such as high score tables. You can just tuck everything into a dictionary and trivially get it all back.
Note that I tucked in a version number, the version number of your high score save format. If you ever change the save format of your data, having a version number in there will be a very good thing.
|
Doing a simple string sort on your
```
new_score = str(score) + ".........." + name
```
items isn't going to work since, for example str(1000) < str(500). In other words, 1000 will come before 500 in an alphanumeric sort.
Alex's answer is good in that it demonstrates the use of a sort key function, but here is another solution which is a bit simpler and has the added advantage of visuallaly aligning the high score displays.
What you need to do is right align your numbers in a fixed field of the maximum size of the scores, thus (assuming 5 digits max and ver < 3.0):
```
new_score = "%5d........%s" % (score, name)
```
or for Python ver 3.x:
```
new_score = "{0:5d}........{1}".format(score, name)
```
For each new\_score append it to the words list (you could use a better name here) and sort it reversed before printing. Or you could use the bisect.insort library function rather than doing a list.append.
Also, a more Pythonic form than
```
if file_exists == False:
```
is:
```
if not file_exists:
```
|
1,575,971
|
I'm making a stupid little game that saves your score in a highscores.txt file.
My problem is sorting the lines. Here's what I have so far.
Maybe an alphanumeric sorter for python would help? Thanks.
```
import os.path
import string
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name
f = open("highscores.txt", "r+")
words = f.readlines()
print words
main()
```
|
2009/10/16
|
[
"https://Stackoverflow.com/questions/1575971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190983/"
] |
I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON.
```
import simplejson as json # Python 2.x
# import json # Python 3.x
d = {}
d["version"] = 1
d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]]
s = json.dumps(d)
print s
# prints:
# {"version": 1, "highscores": [[100, "Steve"], [200, "Ken"], [400, "Denise"]]}
d2 = json.loads(s)
for score, name in sorted(d2["highscores"], reverse=True):
print "%5d\t%s" % (score, name)
# prints:
# 400 Denise
# 200 Ken
# 100 Steve
```
Using JSON will keep you from having to write your own parser to recover data from saved files such as high score tables. You can just tuck everything into a dictionary and trivially get it all back.
Note that I tucked in a version number, the version number of your high score save format. If you ever change the save format of your data, having a version number in there will be a very good thing.
|
I guess something went wrong when you pasted from Alex's answer, so here is your code with a sort in there
```
import os.path
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name +"\n"
f = open("highscores.txt", "r+")
words = f.readlines()
headers = words.pop(0)
def anotherway(aline):
score=""
for c in aline:
if c.isdigit():
score+=c
else:
break
return int(score)
words.append(new_score)
words.sort(key=anotherway, reverse=True)
words.insert(0, headers)
print "".join(words)
main()
```
|
1,575,971
|
I'm making a stupid little game that saves your score in a highscores.txt file.
My problem is sorting the lines. Here's what I have so far.
Maybe an alphanumeric sorter for python would help? Thanks.
```
import os.path
import string
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name
f = open("highscores.txt", "r+")
words = f.readlines()
print words
main()
```
|
2009/10/16
|
[
"https://Stackoverflow.com/questions/1575971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190983/"
] |
I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON.
```
import simplejson as json # Python 2.x
# import json # Python 3.x
d = {}
d["version"] = 1
d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]]
s = json.dumps(d)
print s
# prints:
# {"version": 1, "highscores": [[100, "Steve"], [200, "Ken"], [400, "Denise"]]}
d2 = json.loads(s)
for score, name in sorted(d2["highscores"], reverse=True):
print "%5d\t%s" % (score, name)
# prints:
# 400 Denise
# 200 Ken
# 100 Steve
```
Using JSON will keep you from having to write your own parser to recover data from saved files such as high score tables. You can just tuck everything into a dictionary and trivially get it all back.
Note that I tucked in a version number, the version number of your high score save format. If you ever change the save format of your data, having a version number in there will be a very good thing.
|
What you want is probably what's generally known as a "Natural Sort". Searching for "natural sort python" gives many results, but there's some good discussion on [ASPN](http://code.activestate.com/recipes/285264/).
|
26,645,502
|
The code is self-explained...
```
$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:18)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib.request as req
>>> url = 'http://bangladeshbrands.com/342560550782-44083.html'
>>> res = req.urlopen(url)
>>> html = res.read()
>>> type(html)
<class 'bytes'>
>>> html = html.decode('utf-8') # bytes -> str
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 66081: invalid start byte
```
|
2014/10/30
|
[
"https://Stackoverflow.com/questions/26645502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/907044/"
] |
You need to give the dataset name and table name
I am going to give you code which is work on my Machine Correctly
```
Dim ds As New DataSet
Dim dt As New DataTable
Dim RpDs1 As New Microsoft.Reporting.WinForms.ReportDataSource
Dim SQL As String = "select * from mfcount"
Dim da As New OleDbDataAdapter(SQL, My.Settings.trialConnectionString)
da.Fill(ds, "mfcount")
dt = ds.Tables(0)
ReportViewer1.Reset()
ReportViewer1.LocalReport.DataSources.Clear()
RpDs1.Name = "trialDataSet4_MFCount"
RpDs1.Value = dt
ReportViewer1.ProcessingMode = WinForms.ProcessingMode.Local
ReportViewer1.LocalReport.DataSources.Add(RpDs1)
Dim path = New DirectoryInfo(Application.StartupPath).Parent.Parent.Parent.FullName
ReportViewer1.LocalReport.ReportEmbeddedResource = Application.StartupPath & "\Report\" & "ADDRESSReport.rdlc"
ReportViewer1.LocalReport.ReportPath = Application.StartupPath & "\Report\" & "ADDRESSReport.rdlc"
ReportViewer1.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.PageWidth
ReportViewer1.RefreshReport()
```
This code will help you..
|
thanks basuraj kumbhar for your help to solve this problem. Here is the working codes for MyCql connection Report in vb.net
```
Dim ds As New DataSet
Dim dt As New DataTable
Dim RpDs1 As New Microsoft.Reporting.WinForms.ReportDataSource
Dim SQL As String = "select * from tb_course"
Dim da As New MySqlDataAdapter(SQL, con)
da.Fill(ds, "tb_course")
dt = ds.Tables(0)
ReportViewer1.Reset()
ReportViewer1.LocalReport.DataSources.Clear()
RpDs1.Name = "DataSet1"
RpDs1.Value = dt
ReportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Local
ReportViewer1.LocalReport.ReportPath = System.Environment.CurrentDirectory + "\Report1.rdlc"
ReportViewer1.LocalReport.DataSources.Clear()
ReportViewer1.LocalReport.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", ds.Tables(0)))
ReportViewer1.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.PageWidth
ReportViewer1.RefreshReport()
```
|
38,703,423
|
I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this:
```
$python GetHostID.py serverName.com
```
the last part is what I am wanting to pass on as a variable to socket.gethostbyaddr("") module. this is the code that I have so far. can someone help me figure out how to put that variable into the (" "). I think the "" is creating problems with using a simple variable name as it is trying to treat it as a string of text as appose to a variable name.
here is the code I have in my script:
```
#!/bin/python
#
import sys, os
import optparse
import socket
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyaddr(remoteServer)
socket.gethostbyaddr('remoteServer')[0]
os.getenv('remoteServer')
print (remoteServerIP)
```
any help would be welcome. I have been racking my brain over this...
thanks
|
2016/08/01
|
[
"https://Stackoverflow.com/questions/38703423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6664141/"
] |
The command line arguments are available as the list `sys.argv`, whose first element is the path to the program. There are a number of libraries you can use (argparse, optparse, etc.) to analyse the command line, but for your simple application you could do something like this:
```
import sys
import sys, os
import optparse
import socket
remoteServer = sys.argv[1]
remoteServerIP = socket.gethostbyaddr(remoteServer)
print (remoteServerIP)
```
Running this program with the command line
```
$ python GetHostID.py holdenweb.com
```
gives the output
```
('web105.webfaction.com', [], ['108.59.9.144'])
```
|
os.getenv('remoteserver') does not use the variable remoteserver as an argument. Instead it uses a string 'remoteserver'.
Also, are you trying to take input as a command line argument? Or are you trying to take it as user input? Your problem description and implementation differ here. The easiest way would be to run your script using
```
python GetHostID.py
```
and then in your code include
```
remoteServer = raw_input().strip().split()
```
to get the input you want for remoteserver.
|
38,703,423
|
I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this:
```
$python GetHostID.py serverName.com
```
the last part is what I am wanting to pass on as a variable to socket.gethostbyaddr("") module. this is the code that I have so far. can someone help me figure out how to put that variable into the (" "). I think the "" is creating problems with using a simple variable name as it is trying to treat it as a string of text as appose to a variable name.
here is the code I have in my script:
```
#!/bin/python
#
import sys, os
import optparse
import socket
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyaddr(remoteServer)
socket.gethostbyaddr('remoteServer')[0]
os.getenv('remoteServer')
print (remoteServerIP)
```
any help would be welcome. I have been racking my brain over this...
thanks
|
2016/08/01
|
[
"https://Stackoverflow.com/questions/38703423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6664141/"
] |
The command line arguments are available as the list `sys.argv`, whose first element is the path to the program. There are a number of libraries you can use (argparse, optparse, etc.) to analyse the command line, but for your simple application you could do something like this:
```
import sys
import sys, os
import optparse
import socket
remoteServer = sys.argv[1]
remoteServerIP = socket.gethostbyaddr(remoteServer)
print (remoteServerIP)
```
Running this program with the command line
```
$ python GetHostID.py holdenweb.com
```
gives the output
```
('web105.webfaction.com', [], ['108.59.9.144'])
```
|
you can use [sys.argv](https://docs.python.org/3/library/sys.html#sys.argv)
for
```
$python GetHostID.py serverName.com
```
`sys.argv` would be
```
['GetHostID.py', 'serverName.com']
```
but for being friendly to the user have a look at the [argparse Tutorial](https://docs.python.org/3/howto/argparse.html)
|
38,703,423
|
I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this:
```
$python GetHostID.py serverName.com
```
the last part is what I am wanting to pass on as a variable to socket.gethostbyaddr("") module. this is the code that I have so far. can someone help me figure out how to put that variable into the (" "). I think the "" is creating problems with using a simple variable name as it is trying to treat it as a string of text as appose to a variable name.
here is the code I have in my script:
```
#!/bin/python
#
import sys, os
import optparse
import socket
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyaddr(remoteServer)
socket.gethostbyaddr('remoteServer')[0]
os.getenv('remoteServer')
print (remoteServerIP)
```
any help would be welcome. I have been racking my brain over this...
thanks
|
2016/08/01
|
[
"https://Stackoverflow.com/questions/38703423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6664141/"
] |
The command line arguments are available as the list `sys.argv`, whose first element is the path to the program. There are a number of libraries you can use (argparse, optparse, etc.) to analyse the command line, but for your simple application you could do something like this:
```
import sys
import sys, os
import optparse
import socket
remoteServer = sys.argv[1]
remoteServerIP = socket.gethostbyaddr(remoteServer)
print (remoteServerIP)
```
Running this program with the command line
```
$ python GetHostID.py holdenweb.com
```
gives the output
```
('web105.webfaction.com', [], ['108.59.9.144'])
```
|
In Python 2, `input` reads text *and evaluates it as a Python expression in the current context*. This is almost never what you want; you want `raw_input` instead. However, in Python 3, `input` does what `raw_input` did in version 2, and `raw_input` is not available.
So, if you need your code to work in *both* Python 2 and 3, you should do something like this after your imports block:
```
# Apply Python 3 semantics to input() if running under v2.
try:
input = raw_input
def raw_input(*a, **k):
raise NameError('use input()')
except NameError:
pass
```
This has no effect in Python 3, but in v2 it replaces the stock `input` with `raw_input`, and `raw_input` with a function that always throws an exception (so you notice if you accidentally use `raw_input`).
If you find yourself needing to smooth over *lots* of differences between v2 and v3, the [python-future](http://python-future.org/) library will probably make your life easier.
|
38,897,842
|
I have an app running on AWS and I need to save every "event" in a file.
An "event" happens, for instance, when a user logs in to the app. When that happens I need to save this information on a file (presumably I would need to save a time stamp and the session id)
I expect to have a lot of events (of the order of a million per month) and I was wondering what would be the best way to do this.
I thought of writing on S3, but I think I can't append to existing files.
Another option would be to redirect the "event" to the standard output, but would not be the smartest solution.
Any ideas? Also, this needs to be done in python.
|
2016/08/11
|
[
"https://Stackoverflow.com/questions/38897842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863713/"
] |
The `.*` in the lookaheads checks for the letter presence not only in the adjacent word, but later in the string. Use `[a-zA-Z]*`:
```
echo "hello 123 worLD" | grep -oP "\\b(?=[A-Za-z]*[a-z])(?=[A-Za-z]*[A-Z])[a-zA-Z]+"
```
See the [demo online](https://ideone.com/aGaXTA)
I also added a word boundary `\b` at the start so that the lookahead check was only performed after a word boundary.
|
**Answer:**
```
echo "hello 123 worLD" | grep -oP "\b(?=[A-Z]+[a-z]|[a-z]+[A-Z])[a-zA-Z]*"
```
Demo: <https://ideone.com/HjLH5o>
**Explanation:**
First check if word starts with one or more uppercase letters followed by one lowercase letters or vice versa followed by any number of lowercase and uppercase letters in any order.
**Performance:**
[This solution](https://regex101.com/r/bC8vT6/5) takes 31 steps to reach the match on the provided test string, while the [accepted solution](https://regex101.com/r/bC8vT6/1) takes 47 steps.
|
3,124,229
|
I'm trying to take a screenshot of the entire screen with C and GTK. I don't want to make a call to an external application for speed reasons. I've found Python code for this ([Take a screenshot via a python script. [Linux]](https://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux/782768#782768)); I just need to figure out how to do that in C.
|
2010/06/26
|
[
"https://Stackoverflow.com/questions/3124229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287750/"
] |
After looking at the GNOME-Screenshot code and a Python example, I came up with this:
```
GdkPixbuf * get_screenshot(){
GdkPixbuf *screenshot;
GdkWindow *root_window;
gint x_orig, y_orig;
gint width, height;
root_window = gdk_get_default_root_window ();
gdk_drawable_get_size (root_window, &width, &height);
gdk_window_get_origin (root_window, &x_orig, &y_orig);
screenshot = gdk_pixbuf_get_from_drawable (NULL, root_window, NULL,
x_orig, y_orig, 0, 0, width, height);
return screenshot;
}
```
Which seems to work perfectly. Thanks!
|
9 years passed and as mentioned above API is removed.
As far as I understand, currently the bare minimum to do this at Linux is:
```
GdkWindow * root;
GdkPixbuf * screenshot;
gint x, y, width, height;
root = gdk_get_default_root_window ();
gdk_window_get_geometry (root, &x, &y, &width, &height);
screenshot = gdk_pixbuf_get_from_window (root, x, y, width, height);
// gdk_pixbuf_save...
```
This is very slightly tested and may fail. Further reading is in gnome-screenshooter [repo](https://gitlab.gnome.org/GNOME/gnome-screenshot)
|
6,457,102
|
I'm trying to load ~2GB of text files (approx 35K files) in my python script. I'm getting a memory error around a third of the way through on page.read(). I'
```
for f in files:
page = open(f)
pageContent = page.read().replace('\n', '')
page.close()
cFile_list.append(pageContent)
```
I've never dealt with objects or processes of this size in python. I checked some of other Python MemoryError related threads but I couldn't get anything to fix my scenario. Hopefully there is something out there that can help me out.
|
2011/06/23
|
[
"https://Stackoverflow.com/questions/6457102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812575/"
] |
You are trying to load too much into memory at once. This can be because of the process size limit (especially on a 32 bit OS), or because you don't have enough RAM.
A 64 bit OS (and 64 bit Python) would be able to do this ok given enough RAM, but maybe you can simply change the way your program is working so not every page is in RAM at once.
What is cFile\_list used for? Do you really need all the pages in memory at the same time?
|
Consider using generators, if possible in your case:
```
file_list = []
for file_ in files:
file_list.append(line.replace('\n', '') for line in open(file_))
```
file\_list now is a list of iterators which is more memory-efficient than reading the whole contents of each file into a string. As soon es you need the whole string of a particular file, you can do
```
string_ = ''.join(file_list[i])
```
Note, however, that iterating over file\_list is only possible once due to the nature of iterators in Python.
See <http://www.python.org/dev/peps/pep-0289/> for more details on generators.
|
6,457,102
|
I'm trying to load ~2GB of text files (approx 35K files) in my python script. I'm getting a memory error around a third of the way through on page.read(). I'
```
for f in files:
page = open(f)
pageContent = page.read().replace('\n', '')
page.close()
cFile_list.append(pageContent)
```
I've never dealt with objects or processes of this size in python. I checked some of other Python MemoryError related threads but I couldn't get anything to fix my scenario. Hopefully there is something out there that can help me out.
|
2011/06/23
|
[
"https://Stackoverflow.com/questions/6457102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812575/"
] |
You are trying to load too much into memory at once. This can be because of the process size limit (especially on a 32 bit OS), or because you don't have enough RAM.
A 64 bit OS (and 64 bit Python) would be able to do this ok given enough RAM, but maybe you can simply change the way your program is working so not every page is in RAM at once.
What is cFile\_list used for? Do you really need all the pages in memory at the same time?
|
This is not effective way to read whole file in memory.
Right way - get used to indexes.
Firstly you need to complete dictionary with start position of each line (key is line number, and value – cumulated length of previous lines).
```
t = open(file,’r’)
dict_pos = {}
kolvo = 0
length = 0
for each in t:
dict_pos[kolvo] = length
length = length+len(each)
kolvo = kolvo+1
```
and ultimately, aim function:
```
def give_line(line_number):
t.seek(dict_pos.get(line_number))
line = t.readline()
return line
```
t.seek(line\_number) – command that execute pruning of file up to line inception. So, if you next commit readline – you obtain your target line.
Using such approach (directly to handle to necessary position of file without running through the whole file) you are saving significant part of time and can handle huge files.
|
6,457,102
|
I'm trying to load ~2GB of text files (approx 35K files) in my python script. I'm getting a memory error around a third of the way through on page.read(). I'
```
for f in files:
page = open(f)
pageContent = page.read().replace('\n', '')
page.close()
cFile_list.append(pageContent)
```
I've never dealt with objects or processes of this size in python. I checked some of other Python MemoryError related threads but I couldn't get anything to fix my scenario. Hopefully there is something out there that can help me out.
|
2011/06/23
|
[
"https://Stackoverflow.com/questions/6457102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812575/"
] |
Consider using generators, if possible in your case:
```
file_list = []
for file_ in files:
file_list.append(line.replace('\n', '') for line in open(file_))
```
file\_list now is a list of iterators which is more memory-efficient than reading the whole contents of each file into a string. As soon es you need the whole string of a particular file, you can do
```
string_ = ''.join(file_list[i])
```
Note, however, that iterating over file\_list is only possible once due to the nature of iterators in Python.
See <http://www.python.org/dev/peps/pep-0289/> for more details on generators.
|
This is not effective way to read whole file in memory.
Right way - get used to indexes.
Firstly you need to complete dictionary with start position of each line (key is line number, and value – cumulated length of previous lines).
```
t = open(file,’r’)
dict_pos = {}
kolvo = 0
length = 0
for each in t:
dict_pos[kolvo] = length
length = length+len(each)
kolvo = kolvo+1
```
and ultimately, aim function:
```
def give_line(line_number):
t.seek(dict_pos.get(line_number))
line = t.readline()
return line
```
t.seek(line\_number) – command that execute pruning of file up to line inception. So, if you next commit readline – you obtain your target line.
Using such approach (directly to handle to necessary position of file without running through the whole file) you are saving significant part of time and can handle huge files.
|
70,623,704
|
The following code:
```
from typing import Union
def process(actions: Union[list[str], list[int]]) -> None:
for pos, action in enumerate(actions):
act(action)
def act(action: Union[str, int]) -> None:
print(action)
```
generates a mypy error: `Argument 1 to "act" has incompatible type "object"; expected "Union[str, int]"`
However when removing the enumerate function the typing is fine:
```
from typing import Union
def process(actions: Union[list[str], list[int]]) -> None:
for action in actions:
act(action)
def act(action: Union[str, int]) -> None:
print(action)
```
Does anyone know what the enumerate function is doing to effect the types?
This is python 3.9 and mypy 0.921
|
2022/01/07
|
[
"https://Stackoverflow.com/questions/70623704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3139441/"
] |
`enumerate.__next__` needs more context than is available to have a return type more specific than `Tuple[int, Any]`, so I believe `mypy` itself would need to be modified to make the inference that `enumerate(actions)` produces `Tuple[int,Union[str,int]]` values.
Until that happens, you can explicitly cast the value of `action` before passing it to `act`.
```
from typing import Union, cast
StrOrInt = Union[str, int]
def process(actions: Union[list[str], list[int]]) -> None:
for pos, action in enumerate(actions):
act(cast(StrOrInt, action))
def act(action: Union[str, int]) -> None:
print(action)
```
You can also make `process` generic (which now that I've thought of it, is probably a better idea, as it avoids the overhead of calling `cast` at runtime).
```
from typing import Union, cast, Iterable, TypeVar
T = TypeVar("T", str, int)
def process(actions: Iterable[T]) -> None:
for pos, action in enumerate(actions):
act(action)
def act(action: T) -> None:
print(action)
```
Here, `T` is not a union of types, but a single concrete type whose identity is fixed by the call to `process`. `Iterable[T]` is either `Iterable[str]` or `Iterable[int]`, depending on which type you pass to `process`. That fixes `T` for the rest of the call to `process`, which every call to `act` must take the same type of argument.
An `Iterable[str]` or an `Iterable[int]` is a valid argument, binding `T` to `int` or `str` in the process. Now `enumerate.__next__` apparently *can* have a specific return type `Tuple[int, T]`.
|
I don't know how it's affecting the types. I do know that using len() can work the same way. It is slower but if it solves the problem it might be worth it. Sorry that it's not much help
|
70,623,704
|
The following code:
```
from typing import Union
def process(actions: Union[list[str], list[int]]) -> None:
for pos, action in enumerate(actions):
act(action)
def act(action: Union[str, int]) -> None:
print(action)
```
generates a mypy error: `Argument 1 to "act" has incompatible type "object"; expected "Union[str, int]"`
However when removing the enumerate function the typing is fine:
```
from typing import Union
def process(actions: Union[list[str], list[int]]) -> None:
for action in actions:
act(action)
def act(action: Union[str, int]) -> None:
print(action)
```
Does anyone know what the enumerate function is doing to effect the types?
This is python 3.9 and mypy 0.921
|
2022/01/07
|
[
"https://Stackoverflow.com/questions/70623704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3139441/"
] |
`enumerate.__next__` needs more context than is available to have a return type more specific than `Tuple[int, Any]`, so I believe `mypy` itself would need to be modified to make the inference that `enumerate(actions)` produces `Tuple[int,Union[str,int]]` values.
Until that happens, you can explicitly cast the value of `action` before passing it to `act`.
```
from typing import Union, cast
StrOrInt = Union[str, int]
def process(actions: Union[list[str], list[int]]) -> None:
for pos, action in enumerate(actions):
act(cast(StrOrInt, action))
def act(action: Union[str, int]) -> None:
print(action)
```
You can also make `process` generic (which now that I've thought of it, is probably a better idea, as it avoids the overhead of calling `cast` at runtime).
```
from typing import Union, cast, Iterable, TypeVar
T = TypeVar("T", str, int)
def process(actions: Iterable[T]) -> None:
for pos, action in enumerate(actions):
act(action)
def act(action: T) -> None:
print(action)
```
Here, `T` is not a union of types, but a single concrete type whose identity is fixed by the call to `process`. `Iterable[T]` is either `Iterable[str]` or `Iterable[int]`, depending on which type you pass to `process`. That fixes `T` for the rest of the call to `process`, which every call to `act` must take the same type of argument.
An `Iterable[str]` or an `Iterable[int]` is a valid argument, binding `T` to `int` or `str` in the process. Now `enumerate.__next__` apparently *can* have a specific return type `Tuple[int, T]`.
|
Seems like mypy isn't able to infer the type and generalizes to object. Might be worth opening an issue at their side. As a workaround you could annotate 'action'. This would remove the error. Does it work if you import the (legacy) `List` from `typing`?
|
53,715,925
|
Greetings for the past week (or more) I've been struggling with a problem.
**Scenario:**
I am developing an app which will allow an expert to create a recipe using a provided image of something to be used as a base. The recipe consists of areas of interests. The program's purpose is to allow non experts to use it, providing images similar to that original and the software cross checks these different areas of interest from the Recipe image to the Provided image.
One use-case scenario could be banknotes. The expert would select an area on an a good picture of a banknote that is genuine, and then the user would provide the software with images of banknotes that need to be checked. So illumination, as well as capturing device could be different.
I don't want you guys to delve into the nature of comparing banknotes, that's another monster to tackle and I got it covered for the most part.
**My Problem:**
Initially I [shrink](https://stackoverflow.com/questions/44650888/resize-an-image-without-distortion-opencv) one of the two pictures to the size of the smaller one.
So now we are dealing with pictures having the same size. (I actually perform the shrinking to the areas of interest and not the whole picture, but that shouldn't matter.)
I have tried and used different methodologies compare these parts but each one had it's limitations due to the nature of the images. Illumination might be different, provided image might have some sort of contamination etc.
**What have I tried:**
*Simple image similarity comparison using [RGB](https://rosettacode.org/wiki/Percentage_difference_between_images) difference.*
Problem is provided image could be totally different but colours could be similar. So I would get high percentages on "totally" different banknotes.
*SSIM on RGB Images.*
Would give really low percentage of similarity on all channels.
*SSIM after using sobel filter.*
Again low percentage of similarity.
I used SSIM from both [Scikit](http://scikit-image.org/docs/dev/auto_examples/transform/plot_ssim.html) in python and [SSIM from OpenCV](https://docs.opencv.org/2.4/doc/tutorials/gpu/gpu-basics-similarity/gpu-basics-similarity.html)
*Feature matching with [Flann](https://docs.opencv.org/2.4/doc/tutorials/features2d/feature_flann_matcher/feature_flann_matcher.html)*.
Couldn't find a good way to use detected matches to extract a similarity.
Basically I am guessing that I need to use various methods and algorithms to achieve the best result. My gut tells me that I will need to combine RGB comparison results with a methodology that will:
* Perform some form of edge detection like sobel.
* Compare the results based on shape matching or something similar.
I am an image analysis newbie and I also tried to find a way to compare, the sobel products of the provided images, using [mean and std calculations](https://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html#void%20meanStdDev(InputArray%20src,%20OutputArray%20mean,%20OutputArray%20stddev,%20InputArray%20mask)) from openCV, however I either did it wrong, or the results I got were useless anyway. I calculated the [eucledian distance](https://stackoverflow.com/questions/23105777/opencv-euclidean-distance-between-two-vectors) between the vectors that resulted from mean and std calculation, however I could not use the results mainly because I couldn't see how they related between images.
I am not providing code I used, firslty because I scrapped some of it, and secondly because I am not looking for a code solution but a methodology or some direction to study-material. (I've read shitload of papers already).
Finally I am not trying to detect similar images, but given two images, extract the similarity between them, trying to bypass small differences created by illumination or paper distortion etc.
Finally I would like to say that I tested all the methods by providing the same image twice and I would get 100% similarity, so I didn't totally fuck it up.
Is what I am trying even possible without some sort of training sets to teach the software what are the acceptable variants of the image? (Again I have no idea if that even makes sense :D )
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53715925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4789509/"
] |
Your `DirectView` class must inherit from a `View` class in Django in order to use [`as_view`](https://docs.djangoproject.com/en/2.1/ref/class-based-views/base/#django.views.generic.base.View.as_view).
```
from django.views.generic import View
class DirectView(mixins.CreateModelMixin, View):
```
If you're using the rest framework, maybe the inheritance you need here is [`CreateAPIView`](https://www.django-rest-framework.org/api-guide/generic-views/#createapiview) or [`GenericAPIView`](https://www.django-rest-framework.org/api-guide/generic-views/#genericapiview) (with `CreateModelMixin`) which is the API equivalent of the `View` class mentioned above.
|
If we are looking into the [source code of **`mixins.CreateModelMixin`**](https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py#L14), we could see it's inherited from [**`object`**](https://stackoverflow.com/questions/4015417/python-class-inherits-object) (***builtin type***) and hence it's independent of any kind of inheritance other than ***builtin type***.
Apart from that, **Mixin** classes are special kind of multiple inheritance. You could read more about Mixins [here](https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful). In short, Mixins provides additional functionality to the class (kind of *helper class*).
---
**So, What's the solution to this problem?**
**Solution - 1 : Use `CreateAPIView`**
Since you are trying to extend the functionality of `CreateModelMixin`, it's highly recomended to use this DRF builtin view as,
```
**from rest\_framework import generics**
class DirectView(**generics.CreateAPIView**):
serializer_class = DirectSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
```
---
**Reference**
1. [What is a mixin, and why are they useful?](https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful)
2. [Python class inherits object](https://stackoverflow.com/questions/4015417/python-class-inherits-object)
|
69,108,130
|
I am trying to build a voice assistant. I am facing a problem with the playsound library. Please view my code snippet.
```
def respond(output):
"""
function to respond to user questions
"""
num=0
print(output)
num += 1
response=gTTS(text=output, lang='en')
file = str(num)+".mp3"
response.save(file)
play(file, True) #playsound import playsound as play
if __name__=='__main__':
respond("Hi! I am Zoya, your personal assistant")
```
My audio file is getting generated, however at the line play(file,True) it is throwing the following error.
```
---------------------------------------------------------------------------
CalledProcessError Traceback (most recent call last)
<ipython-input-52-be0c0a53e7e6> in <module>()
1 if __name__=='__main__':
----> 2 respond("Hi! I am Zoya, your personal assistant")
3
4 while(1):
5 respond("How can I help you?")
6 frames
/usr/lib/python3.7/subprocess.py in check_call(*popenargs, **kwargs)
361 if cmd is None:
362 cmd = popenargs[0]
--> 363 raise CalledProcessError(retcode, cmd)
364 return 0
365
CalledProcessError: Command '['/usr/bin/python3', '/usr/local/lib/python3.7/dist-packages/playsound.py', '1.mp3']' returned non-zero exit status 1.
```
How do I resolve the issue?
I would also like to mention that I am working on google colab.
|
2021/09/08
|
[
"https://Stackoverflow.com/questions/69108130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16863358/"
] |
Query
* lookup with it self, join only with the type that the id=3 has.
* empty join results => different type so they are filtered out
[Test code here](https://mongoplayground.net/p/KnKpOBZYJy7)
```js
db.collection.aggregate([
{
"$lookup": {
"from": "collection",
"let": {
"type": "$type"
},
"pipeline": [
{
"$match": {
"$expr": {
"$and": [
{
"$eq": [
"$_id",
"3"
]
},
{
"$eq": [
"$$type",
"$type"
]
}
]
}
}
}
],
"as": "joined"
}
},
{
"$match": {
"$expr": {
"$ne": [
"$joined",
[]
]
}
}
},
{
"$unset": [
"joined"
]
}
])
```
|
You're basically mixing two separate queries:
1. Get an item by ID - returns a **single** item
2. Get a list of items, that have the same type as the type of the first item - returns a **list of items**
Because of the difference of the queries, there's no super straightforward way to do so. Surely you can use [$aggregate](https://docs.mongodb.com/manual/aggregation/) to do the trick, but logic wise you'd still query quite a bit from the database, and you'd have to dig deeper to optimize it properly.
As long as you're not querying tens of millions of records, I'd suggest you do the two queries one after another, for the sake of simplicity.
|
18,600,200
|
in python here is my multiprocessing setup. I subclassed the Process method and gave it
a queue and some other fields for pickling/data purposes.
This strategy works about 95% of the time, the other 5% for an unknown reason the queue just hangs and it never finishes (it's common that 3 of the 4 cores finish their jobs and the last one takes forever so I have to just kill the job).
I am aware that queue's have a fixed size in python, or they will hang. My queue only stores one character strings... the id of the processor, so it can't be that.
Here is the exact line where my code halts:
```
res = self._recv()
```
Does anyone have ideas? The formal code is below.
Thank you.
```
from multiprocessing import Process, Queue
from multiprocessing import cpu_count as num_cores
import codecs, cPickle
class Processor(Process):
def __init__(self, queue, elements, process_num):
super(Processor, self).__init__()
self.queue = queue
self.elements = elements
self.id = process_num
def job(self):
ddd = []
for l in self.elements:
obj = ... heavy computation ...
dd = {}
dd['data'] = obj.data
dd['meta'] = obj.meta
ddd.append(dd)
cPickle.dump(ddd, codecs.open(
urljoin(TOPDIR, self.id+'.txt'), 'w'))
return self.id
def run(self):
self.queue.put(self.job())
if __name__=='__main__':
processes = []
for i in range(0, num_cores()):
q = Queue()
p = Processor(q, divided_work(), process_num=str(i))
processes.append((p, q))
p.start()
for val in processes:
val[0].join()
key = val[1].get()
storage = urljoin(TOPDIR, key+'.txt')
ddd = cPickle.load(codecs.open(storage , 'r'))
.. unpack ddd process data ...
```
|
2013/09/03
|
[
"https://Stackoverflow.com/questions/18600200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1660802/"
] |
Do a `time.sleep(0.001)` at the beginning of your `run()` method.
|
From my experience
```
time.sleep(0.001)
```
Is by far not long enough.
I had a similar problem. It seems to happen if you call `get()` or `put()` on a queue "too early". I guess it somehow fails to initialize quick enough. Not entirely sure, but I'm speculating that it might have something to do with the ways a queue might use the underlying operating system to pass messages. It started happening to me after I started using BeautifulSoup and lxml and it affected totally unrelated code.
My solution is a little big ugly but it's simple and it works:
```
import time
def run(self):
error = True
while error:
self.queue.put(self.job())
error = False
except EOFError:
print "EOFError. retrying..."
time.sleep(1)
```
On my machine it usually retries twice during application start-up and afterwards never again. You need to do that inside of sender AND receiver since this error will occur on both sides.
|
46,373,433
|
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string.
```
def protein(array):
ligand = ''
for i in range(array):
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
```
The following is the input and error code:
```
protein(1, 6, 8)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-a33f3d5c265e> in <module>()
----> 1 protein(1, 6, 8)
TypeError: protein() takes 1 positional argument but 3 were given
```
For single inputs, I get the wrong output:
```
protein(1)
Out[45]: ''
protein(6)
Out[46]: 'NO+'
```
If any further clarification is needed, let me know, thanks
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46373433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8658260/"
] |
You probably want `def protein(*array):` This allows you to give in any number of arguments. You also must use `for i in array:` instead of `for i in range(array):`
|
If you call it like `protein(1, 6, 8)` you are **not** passing it a tuple: you pass it **three parameters**. Since you defined `protein` with *one* parameter: `array`, that errors.
You can use arbitrary parameters, by using `*args`. But nevertheless this function is still not very elegant nor is it efficient: it will take *O(n2)* to calculate the string.
A more declarative and efficient approach is probably to use a dictionary and perform lookups that are then `''.join`ed together:
```
translate = {1: 'NO+', 6: 'F-', 8: 'NO+'}
def protein(*array):
return ''.join(translate[x] for x in array)
```
In case you want to *ignore* values you pass that are not in the dictionary (for instance ignore `7` in `protein(1,7,6,8)`, you can replace `[x]` with `.get(x, '')`:
```
translate = {1: 'NO+', 6: 'F-', 8: 'NO+'}
def protein(*array):
return ''.join(translate.get(x, '') for x in array)
```
|
46,373,433
|
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string.
```
def protein(array):
ligand = ''
for i in range(array):
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
```
The following is the input and error code:
```
protein(1, 6, 8)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-a33f3d5c265e> in <module>()
----> 1 protein(1, 6, 8)
TypeError: protein() takes 1 positional argument but 3 were given
```
For single inputs, I get the wrong output:
```
protein(1)
Out[45]: ''
protein(6)
Out[46]: 'NO+'
```
If any further clarification is needed, let me know, thanks
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46373433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8658260/"
] |
You probably want `def protein(*array):` This allows you to give in any number of arguments. You also must use `for i in array:` instead of `for i in range(array):`
|
You don't give a list to the protein function. You need to do something like:
```
num_list = [1, 6, 8]
protein(num_list)
```
Or directly:
```
protein([1, 6, 8])
```
Also, you need to fix the for loop after that. At last:
```
def protein(array):
ligand = ''
for i in array:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
print(protein([1, 3, 5]))
```
Output:
```
NO+
```
range() starts from zero(0).
|
46,373,433
|
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string.
```
def protein(array):
ligand = ''
for i in range(array):
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
```
The following is the input and error code:
```
protein(1, 6, 8)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-a33f3d5c265e> in <module>()
----> 1 protein(1, 6, 8)
TypeError: protein() takes 1 positional argument but 3 were given
```
For single inputs, I get the wrong output:
```
protein(1)
Out[45]: ''
protein(6)
Out[46]: 'NO+'
```
If any further clarification is needed, let me know, thanks
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46373433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8658260/"
] |
You probably want `def protein(*array):` This allows you to give in any number of arguments. You also must use `for i in array:` instead of `for i in range(array):`
|
1) replace 'range(array)' by 'array'
2) put list or tuple in argument when calling the function and not multiple numbers.
```
In [2]: def protein(array):
ligand = ''
for i in array:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
In [3]: protein((1, 6, 8))
Out[3]: 'NO+F-NO+'
```
|
46,373,433
|
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string.
```
def protein(array):
ligand = ''
for i in range(array):
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
```
The following is the input and error code:
```
protein(1, 6, 8)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-a33f3d5c265e> in <module>()
----> 1 protein(1, 6, 8)
TypeError: protein() takes 1 positional argument but 3 were given
```
For single inputs, I get the wrong output:
```
protein(1)
Out[45]: ''
protein(6)
Out[46]: 'NO+'
```
If any further clarification is needed, let me know, thanks
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46373433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8658260/"
] |
First, you need `*args` as the argument, to accept an arbitrary number of arguments as in your example.
Once you do that, you simply iterate over `args`. The rest of your code is OK, if not entirely idiomatic.
```
def protein(*args):
ligand = ''
for i in args:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
```
A better solution is to set up a mapping from integers to ions(?), then map and join.
```
def protein(*args):
d = {1: 'NO+', 6: 'F-', 8: 'NO+'}
return ''.join(d.get(i, '') for i in args)
```
Returning the empty string for a non-existing index is effectively the same as not appending to the result.
|
If you call it like `protein(1, 6, 8)` you are **not** passing it a tuple: you pass it **three parameters**. Since you defined `protein` with *one* parameter: `array`, that errors.
You can use arbitrary parameters, by using `*args`. But nevertheless this function is still not very elegant nor is it efficient: it will take *O(n2)* to calculate the string.
A more declarative and efficient approach is probably to use a dictionary and perform lookups that are then `''.join`ed together:
```
translate = {1: 'NO+', 6: 'F-', 8: 'NO+'}
def protein(*array):
return ''.join(translate[x] for x in array)
```
In case you want to *ignore* values you pass that are not in the dictionary (for instance ignore `7` in `protein(1,7,6,8)`, you can replace `[x]` with `.get(x, '')`:
```
translate = {1: 'NO+', 6: 'F-', 8: 'NO+'}
def protein(*array):
return ''.join(translate.get(x, '') for x in array)
```
|
46,373,433
|
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string.
```
def protein(array):
ligand = ''
for i in range(array):
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
```
The following is the input and error code:
```
protein(1, 6, 8)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-a33f3d5c265e> in <module>()
----> 1 protein(1, 6, 8)
TypeError: protein() takes 1 positional argument but 3 were given
```
For single inputs, I get the wrong output:
```
protein(1)
Out[45]: ''
protein(6)
Out[46]: 'NO+'
```
If any further clarification is needed, let me know, thanks
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46373433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8658260/"
] |
First, you need `*args` as the argument, to accept an arbitrary number of arguments as in your example.
Once you do that, you simply iterate over `args`. The rest of your code is OK, if not entirely idiomatic.
```
def protein(*args):
ligand = ''
for i in args:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
```
A better solution is to set up a mapping from integers to ions(?), then map and join.
```
def protein(*args):
d = {1: 'NO+', 6: 'F-', 8: 'NO+'}
return ''.join(d.get(i, '') for i in args)
```
Returning the empty string for a non-existing index is effectively the same as not appending to the result.
|
You don't give a list to the protein function. You need to do something like:
```
num_list = [1, 6, 8]
protein(num_list)
```
Or directly:
```
protein([1, 6, 8])
```
Also, you need to fix the for loop after that. At last:
```
def protein(array):
ligand = ''
for i in array:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
print(protein([1, 3, 5]))
```
Output:
```
NO+
```
range() starts from zero(0).
|
46,373,433
|
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string.
```
def protein(array):
ligand = ''
for i in range(array):
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
```
The following is the input and error code:
```
protein(1, 6, 8)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-a33f3d5c265e> in <module>()
----> 1 protein(1, 6, 8)
TypeError: protein() takes 1 positional argument but 3 were given
```
For single inputs, I get the wrong output:
```
protein(1)
Out[45]: ''
protein(6)
Out[46]: 'NO+'
```
If any further clarification is needed, let me know, thanks
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46373433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8658260/"
] |
First, you need `*args` as the argument, to accept an arbitrary number of arguments as in your example.
Once you do that, you simply iterate over `args`. The rest of your code is OK, if not entirely idiomatic.
```
def protein(*args):
ligand = ''
for i in args:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
```
A better solution is to set up a mapping from integers to ions(?), then map and join.
```
def protein(*args):
d = {1: 'NO+', 6: 'F-', 8: 'NO+'}
return ''.join(d.get(i, '') for i in args)
```
Returning the empty string for a non-existing index is effectively the same as not appending to the result.
|
1) replace 'range(array)' by 'array'
2) put list or tuple in argument when calling the function and not multiple numbers.
```
In [2]: def protein(array):
ligand = ''
for i in array:
if i == 1:
ligand = ligand + 'NO+'
if i == 6:
ligand = ligand + 'F-'
if i == 8:
ligand = ligand + 'NO+'
return ligand
In [3]: protein((1, 6, 8))
Out[3]: 'NO+F-NO+'
```
|
55,253,980
|
How to debug the code written in python in container using azure dev spaces for kubernetes ?
|
2019/03/20
|
[
"https://Stackoverflow.com/questions/55253980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8267052/"
] |
Debugging should be similar just like we have it in Dot net core.In dot net , we used to debug something like this
**Setting and using breakpoints for debugging**
If Visual Studio 2017 is still connected to your dev space, click the stop button. Open Controllers/HomeController.cs and click somewhere on line 20 to put your cursor there. To set a breakpoint hit F9 or click Debug then Toggle Breakpoint. To start your service in debugging mode in your dev space, hit F5 or click Debug then Start Debugging.
Open your service in a browser and notice no message is displayed. Return to Visual Studio 2017 and observe line 20 is highlighted. The breakpoint you set has paused the service at line 20. To resume the service, hit F5 or click Debug then Continue. Return to your browser and notice the message is now displayed.
While running your service in Kubernetes with a debugger attached, you have full access to debug information such as the call stack, local variables, and exception information.
Remove the breakpoint by putting your cursor on line 20 in Controllers/HomeController.cs and hitting F9.
Try something like this and see if it works.
Here is an article which explains debugging python code in visual studio 2017
<https://learn.microsoft.com/en-us/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-04-debugging?view=vs-2017>
Hope it helps.
|
Currently debugging in Azure Dev Spaces only lists Node.js, .NET Core, and Java as officially supported. The documentation for how to debug these 3 types of environments was written pretty recently (Quickstarts published on 7/7/2019). I am assuming that a guide for Python should be on the way shortly, but I have been unable to find any published timeline for this.
|
73,565,617
|
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number?
thought this could be done with if statements, but it's simply too long and I wonder if there's a better way.
(I'm programming in python btw)
|
2022/09/01
|
[
"https://Stackoverflow.com/questions/73565617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19517516/"
] |
You can use list comprehension for that :
```
myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN',
'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR',
'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA']
result = [el.split(',') for el in myList]
print(result)
```
output:
```
[['BUD'], ['CDG'], ['DEL'], ['DOH'], ['DSM', 'ORD'], ['EWR', 'HND'], ['EWR', 'HND', 'ICN'], ['EWR', 'HND', 'JFK'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWY', 'LHR'], ['EWY', 'LHR', 'SFO', 'DSM'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI', 'LGA']]
```
|
```
myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN',
'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR',
'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA']
nested_list = [[element] for element in myList]
```
output :
```
[['BUD'], ['CDG'], ['DEL'], ['DOH'], ['DSM,ORD'], ['EWR,HND'], ['EWR,HND,ICN'], ['EWR,HND,JFK'], ['EWR,HND,JFK,LGA'], ['EWR,HND,JFK,LGA'], ['EWY,LHR'], ['EWY,LHR,SFO,DSM'], ['EWY,LHR,SFO,DSM,ORD,BGI'], ['EWY,LHR,SFO,DSM,ORD,BGI,LGA']]
```
|
73,565,617
|
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number?
thought this could be done with if statements, but it's simply too long and I wonder if there's a better way.
(I'm programming in python btw)
|
2022/09/01
|
[
"https://Stackoverflow.com/questions/73565617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19517516/"
] |
You can use list comprehension for that :
```
myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN',
'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR',
'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA']
result = [el.split(',') for el in myList]
print(result)
```
output:
```
[['BUD'], ['CDG'], ['DEL'], ['DOH'], ['DSM', 'ORD'], ['EWR', 'HND'], ['EWR', 'HND', 'ICN'], ['EWR', 'HND', 'JFK'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWY', 'LHR'], ['EWY', 'LHR', 'SFO', 'DSM'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI', 'LGA']]
```
|
This group each element in order they appear.
`new_list = [data_list[i:i+1] for i in range(0, len(data_list), 1)]`
you can change integar value like if you want to group in form of 5 elements, replace 1 with 5.
.
|
73,565,617
|
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number?
thought this could be done with if statements, but it's simply too long and I wonder if there's a better way.
(I'm programming in python btw)
|
2022/09/01
|
[
"https://Stackoverflow.com/questions/73565617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19517516/"
] |
You can use list comprehension for that :
```
myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN',
'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR',
'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA']
result = [el.split(',') for el in myList]
print(result)
```
output:
```
[['BUD'], ['CDG'], ['DEL'], ['DOH'], ['DSM', 'ORD'], ['EWR', 'HND'], ['EWR', 'HND', 'ICN'], ['EWR', 'HND', 'JFK'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWY', 'LHR'], ['EWY', 'LHR', 'SFO', 'DSM'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI', 'LGA']]
```
|
```
li = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA', 'EWY,LHR,SFO,SAN', 'HND,ICN', 'ICN', 'ICN,JFK', 'ICN,JFK,LGA', 'ICN,JFK,LGA', 'LGA', 'LGA', 'LHR,SFO', 'LHR,SFO,DSM,ORD', 'LHR,SFO,SAN', 'LHR,SFO,SAN,EWY', 'ORD,BGI', 'SAN', 'SAN,EWY,LHR', 'SAN,EWY,LHR,SFO,DSM', 'SAN,EWY,LHR,SFO,DSM,ORD,BGI', 'SAN,EWY,LHR,SFO,DSM,ORD,BGI,LGA', 'SAN,EWY,LHR,SFO,DSM,ORD,BGI,LGA', 'SFO,DSM', 'SFO,DSM,ORD,BGI', 'SFO,SAN', 'SFO,SAN,EWY,LHR', 'SIN,CDG,BUD', 'TLV,DEL,DOH']
op = list(map(lambda x: x.split(','), li))
print(op)
```
Output:
```
[['BUD'], ['CDG'], ['DEL'], ['DOH'], ['DSM', 'ORD'], ['EWR', 'HND'], ['EWR', 'HND', 'ICN'], ['EWR', 'HND', 'JFK'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWY', 'LHR'], ['EWY', 'LHR', 'SFO', 'DSM'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI', 'LGA'], ['EWY', 'LHR', 'SFO', 'SAN'], ['HND', 'ICN'], ['ICN'], ['ICN', 'JFK'], ['ICN', 'JFK', 'LGA'], ['ICN', 'JFK', 'LGA'], ['LGA'], ['LGA'], ['LHR', 'SFO'], ['LHR', 'SFO', 'DSM', 'ORD'], ['LHR', 'SFO', 'SAN'], ['LHR', 'SFO', 'SAN', 'EWY'], ['ORD', 'BGI'], ['SAN'], ['SAN', 'EWY', 'LHR'], ['SAN', 'EWY', 'LHR', 'SFO', 'DSM'], ['SAN', 'EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI'], ['SAN', 'EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI', 'LGA'], ['SAN', 'EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI', 'LGA'], ['SFO', 'DSM'], ['SFO', 'DSM', 'ORD', 'BGI'], ['SFO', 'SAN'], ['SFO', 'SAN', 'EWY', 'LHR'], ['SIN', 'CDG', 'BUD'], ['TLV', 'DEL', 'DOH']]
```
|
73,565,617
|
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number?
thought this could be done with if statements, but it's simply too long and I wonder if there's a better way.
(I'm programming in python btw)
|
2022/09/01
|
[
"https://Stackoverflow.com/questions/73565617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19517516/"
] |
This group each element in order they appear.
`new_list = [data_list[i:i+1] for i in range(0, len(data_list), 1)]`
you can change integar value like if you want to group in form of 5 elements, replace 1 with 5.
.
|
```
myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN',
'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR',
'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA']
nested_list = [[element] for element in myList]
```
output :
```
[['BUD'], ['CDG'], ['DEL'], ['DOH'], ['DSM,ORD'], ['EWR,HND'], ['EWR,HND,ICN'], ['EWR,HND,JFK'], ['EWR,HND,JFK,LGA'], ['EWR,HND,JFK,LGA'], ['EWY,LHR'], ['EWY,LHR,SFO,DSM'], ['EWY,LHR,SFO,DSM,ORD,BGI'], ['EWY,LHR,SFO,DSM,ORD,BGI,LGA']]
```
|
73,565,617
|
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number?
thought this could be done with if statements, but it's simply too long and I wonder if there's a better way.
(I'm programming in python btw)
|
2022/09/01
|
[
"https://Stackoverflow.com/questions/73565617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19517516/"
] |
```
li = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA', 'EWY,LHR,SFO,SAN', 'HND,ICN', 'ICN', 'ICN,JFK', 'ICN,JFK,LGA', 'ICN,JFK,LGA', 'LGA', 'LGA', 'LHR,SFO', 'LHR,SFO,DSM,ORD', 'LHR,SFO,SAN', 'LHR,SFO,SAN,EWY', 'ORD,BGI', 'SAN', 'SAN,EWY,LHR', 'SAN,EWY,LHR,SFO,DSM', 'SAN,EWY,LHR,SFO,DSM,ORD,BGI', 'SAN,EWY,LHR,SFO,DSM,ORD,BGI,LGA', 'SAN,EWY,LHR,SFO,DSM,ORD,BGI,LGA', 'SFO,DSM', 'SFO,DSM,ORD,BGI', 'SFO,SAN', 'SFO,SAN,EWY,LHR', 'SIN,CDG,BUD', 'TLV,DEL,DOH']
op = list(map(lambda x: x.split(','), li))
print(op)
```
Output:
```
[['BUD'], ['CDG'], ['DEL'], ['DOH'], ['DSM', 'ORD'], ['EWR', 'HND'], ['EWR', 'HND', 'ICN'], ['EWR', 'HND', 'JFK'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWR', 'HND', 'JFK', 'LGA'], ['EWY', 'LHR'], ['EWY', 'LHR', 'SFO', 'DSM'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI'], ['EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI', 'LGA'], ['EWY', 'LHR', 'SFO', 'SAN'], ['HND', 'ICN'], ['ICN'], ['ICN', 'JFK'], ['ICN', 'JFK', 'LGA'], ['ICN', 'JFK', 'LGA'], ['LGA'], ['LGA'], ['LHR', 'SFO'], ['LHR', 'SFO', 'DSM', 'ORD'], ['LHR', 'SFO', 'SAN'], ['LHR', 'SFO', 'SAN', 'EWY'], ['ORD', 'BGI'], ['SAN'], ['SAN', 'EWY', 'LHR'], ['SAN', 'EWY', 'LHR', 'SFO', 'DSM'], ['SAN', 'EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI'], ['SAN', 'EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI', 'LGA'], ['SAN', 'EWY', 'LHR', 'SFO', 'DSM', 'ORD', 'BGI', 'LGA'], ['SFO', 'DSM'], ['SFO', 'DSM', 'ORD', 'BGI'], ['SFO', 'SAN'], ['SFO', 'SAN', 'EWY', 'LHR'], ['SIN', 'CDG', 'BUD'], ['TLV', 'DEL', 'DOH']]
```
|
```
myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN',
'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR',
'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA']
nested_list = [[element] for element in myList]
```
output :
```
[['BUD'], ['CDG'], ['DEL'], ['DOH'], ['DSM,ORD'], ['EWR,HND'], ['EWR,HND,ICN'], ['EWR,HND,JFK'], ['EWR,HND,JFK,LGA'], ['EWR,HND,JFK,LGA'], ['EWY,LHR'], ['EWY,LHR,SFO,DSM'], ['EWY,LHR,SFO,DSM,ORD,BGI'], ['EWY,LHR,SFO,DSM,ORD,BGI,LGA']]
```
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
This same issue happened to me when I had more than one API function in the module and tried to wrap each function with 2 decorators:
1. @app.route()
2. My custom @exception\_handler decorator
I got this same exception because I tried to wrap more than one function with those two decorators:
```
@app.route("/path1")
@exception_handler
def func1():
pass
@app.route("/path2")
@exception_handler
def func2():
pass
```
Specifically, it is caused by trying to register a few functions with the name **wrapper**:
```
def exception_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
error_code = getattr(e, "code", 500)
logger.exception("Service exception: %s", e)
r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code})
return Response(r, status=error_code, mimetype='application/json')
return wrapper
```
Changing the name of the function solved it for me (**wrapper.\_\_name\_\_ = func.\_\_name\_\_**):
```
def exception_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
error_code = getattr(e, "code", 500)
logger.exception("Service exception: %s", e)
r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code})
return Response(r, status=error_code, mimetype='application/json')
# Renaming the function name:
wrapper.__name__ = func.__name__
return wrapper
```
Then, decorating more than one endpoint worked.
|
In case you are using flask on python notebook, you need to restart kernel everytime you make changes in code
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
If you think you have unique endpoint names and still this error is given then probably you are facing [issue](https://github.com/pallets/flask/issues/796). Same was the case with me.
This issue is with flask 0.10 in case you have same version then do following to get rid of this:
```
sudo pip uninstall flask
sudo pip install flask=0.9
```
|
This is issue for me was from an (breaking) update to **flask-jwt-extended (version 4.x.x and up)** used in a basic api I wrote a year ago and am now incorporating into a project.
@jwt\_required to @jwt\_required()
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
I would just like to add to this a more 'template' type solution.
```
def func_name(f):
def wrap(*args, **kwargs):
if condition:
pass
else:
whatever you want
return f(*args, **kwargs)
wrap.__name__ = f.__name__
return wrap
```
would just like to add a really interesting article "Demystifying Decorators" I found recently: <https://sumit-ghosh.com/articles/demystifying-decorators-python/>
|
Your view names need to be unique even if they are pointing to the same view method, or you can add from functools import wraps and use @wraps
<https://docs.python.org/2/library/functools.html>
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
Adding `@wraps(f)` above the wrapper function solved my issue.
```
def list_ownership(f):
@wraps(f)
def decorator(*args,**kwargs):
return f(args,kwargs)
return decorator
```
|
I'm working on a similar problem and I managed to get rid of it by returning the wrapper funcion, which wasn't being done before:
```
def decorator_func(func_to_decorate):
def wrapper_func():
return func_to_decorate
return wrapper_func # I wasn't returning wrapper func!
```
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
For users that use @app.route it is better to use the key-argument `endpoint` rather then chaning the value of `__name__` like [Roei Bahumi](https://stackoverflow.com/a/42254713/5019818) stated. Taking his example will be:
```
@app.route("/path1", endpoint='func1')
@exception_handler
def func1():
pass
@app.route("/path2", endpoint='func2')
@exception_handler
def func2():
pass
```
|
I'm working on a similar problem and I managed to get rid of it by returning the wrapper funcion, which wasn't being done before:
```
def decorator_func(func_to_decorate):
def wrapper_func():
return func_to_decorate
return wrapper_func # I wasn't returning wrapper func!
```
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
For users that use @app.route it is better to use the key-argument `endpoint` rather then chaning the value of `__name__` like [Roei Bahumi](https://stackoverflow.com/a/42254713/5019818) stated. Taking his example will be:
```
@app.route("/path1", endpoint='func1')
@exception_handler
def func1():
pass
@app.route("/path2", endpoint='func2')
@exception_handler
def func2():
pass
```
|
Flask requires you to associate a single 'view function' with an 'endpoint'. You are calling `Main.as_view('main')` twice which creates two different functions (exactly the same functionality but different in memory signature). Short story, you should simply do
```
main_view_func = Main.as_view('main')
app.add_url_rule('/',
view_func=main_view_func,
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=main_view_func,
methods=["GET"])
```
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
For users that use @app.route it is better to use the key-argument `endpoint` rather then chaning the value of `__name__` like [Roei Bahumi](https://stackoverflow.com/a/42254713/5019818) stated. Taking his example will be:
```
@app.route("/path1", endpoint='func1')
@exception_handler
def func1():
pass
@app.route("/path2", endpoint='func2')
@exception_handler
def func2():
pass
```
|
This can happen also when you have identical function names on different routes.
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
This same issue happened to me when I had more than one API function in the module and tried to wrap each function with 2 decorators:
1. @app.route()
2. My custom @exception\_handler decorator
I got this same exception because I tried to wrap more than one function with those two decorators:
```
@app.route("/path1")
@exception_handler
def func1():
pass
@app.route("/path2")
@exception_handler
def func2():
pass
```
Specifically, it is caused by trying to register a few functions with the name **wrapper**:
```
def exception_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
error_code = getattr(e, "code", 500)
logger.exception("Service exception: %s", e)
r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code})
return Response(r, status=error_code, mimetype='application/json')
return wrapper
```
Changing the name of the function solved it for me (**wrapper.\_\_name\_\_ = func.\_\_name\_\_**):
```
def exception_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
error_code = getattr(e, "code", 500)
logger.exception("Service exception: %s", e)
r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code})
return Response(r, status=error_code, mimetype='application/json')
# Renaming the function name:
wrapper.__name__ = func.__name__
return wrapper
```
Then, decorating more than one endpoint worked.
|
There is a fix for Flask issue #570 introduced recenty (flask 0.10) that causes this exception to be raised.
See <https://github.com/mitsuhiko/flask/issues/796>
So if you go to flask/app.py and comment out the 4 lines 948..951, this may help until the issue is resovled fully in a new version.
The diff of that change is here: <http://github.com/mitsuhiko/flask/commit/661ee54bc2bc1ea0763ac9c226f8e14bb0beb5b1>
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
This can happen also when you have identical function names on different routes.
|
There is a fix for Flask issue #570 introduced recenty (flask 0.10) that causes this exception to be raised.
See <https://github.com/mitsuhiko/flask/issues/796>
So if you go to flask/app.py and comment out the 4 lines 948..951, this may help until the issue is resovled fully in a new version.
The diff of that change is here: <http://github.com/mitsuhiko/flask/commit/661ee54bc2bc1ea0763ac9c226f8e14bb0beb5b1>
|
17,256,602
|
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["GET"])
```
Traceback:
```
Traceback (most recent call last):
File "demo.py", line 20, in <module> methods=["GET"])
File ".../python2.6/site-packages/flask/app.py",
line 62, in wrapper_func return f(self, *args, **kwargs)
File ".../python2.6/site-packages/flask/app.py",
line 984, in add_url_rule 'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint
function: main
```
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17256602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016434/"
] |
Flask requires you to associate a single 'view function' with an 'endpoint'. You are calling `Main.as_view('main')` twice which creates two different functions (exactly the same functionality but different in memory signature). Short story, you should simply do
```
main_view_func = Main.as_view('main')
app.add_url_rule('/',
view_func=main_view_func,
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=main_view_func,
methods=["GET"])
```
|
If you think you have unique endpoint names and still this error is given then probably you are facing [issue](https://github.com/pallets/flask/issues/796). Same was the case with me.
This issue is with flask 0.10 in case you have same version then do following to get rid of this:
```
sudo pip uninstall flask
sudo pip install flask=0.9
```
|
28,418,677
|
i just began playing with python 3 and got a little stuck. I have this code:
```
person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel']
for item in person:
opinion = input("What do you think about "+person[0]+"? ")
print(person[0]+" is a "+opinion+"")
```
And i do not know how to make it ask about each of the persons in the list. I know person[0] is not good, but i do not know what to put there.
EDIT:
I tried fixing it with a loop:
```
person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel']
i = 0
while i<5:
opinion = input("What do you think about "+person[i]+"? ")
print(person[i]+" is a "+opinion+"")
i += 1
```
And it works, but after it runs out of people on the list and i keep replying, i get an error. There has to be a better way
|
2015/02/09
|
[
"https://Stackoverflow.com/questions/28418677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3025008/"
] |
You are assigning `item` to each value in `person`, use that variable.
```
for item in person:
opinion = input("What do you think about "+item+"? ")
print(item+" is a "+opinion+"")
```
When you called `person[0]`, you were setting it to the first value in `person` **every time**, which is not what you want.
|
What about
```
for item in person
opinion = input("What do you think about "+item+"? ")
print(item+" is a "+opinion+"")
```
And even better, if you want to make it more verbose:
```
# List with "s" to make it plural
persons = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel']
# List item without the "s"
for person in persons
opinion = input("What do you think about " + person + "? ")
print(person + " is a " + opinion + "")
```
|
28,418,677
|
i just began playing with python 3 and got a little stuck. I have this code:
```
person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel']
for item in person:
opinion = input("What do you think about "+person[0]+"? ")
print(person[0]+" is a "+opinion+"")
```
And i do not know how to make it ask about each of the persons in the list. I know person[0] is not good, but i do not know what to put there.
EDIT:
I tried fixing it with a loop:
```
person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel']
i = 0
while i<5:
opinion = input("What do you think about "+person[i]+"? ")
print(person[i]+" is a "+opinion+"")
i += 1
```
And it works, but after it runs out of people on the list and i keep replying, i get an error. There has to be a better way
|
2015/02/09
|
[
"https://Stackoverflow.com/questions/28418677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3025008/"
] |
Notice that when you are running your `for` loop, `item` will be whichever person you have in question. Thus, replace `person[0]` with `item` and you will ask about each person as required, like so:
```
for item in person:
opinion = input("What do you think about "+item+"? ")
print(item+" is a "+opinion+"")
```
|
What about
```
for item in person
opinion = input("What do you think about "+item+"? ")
print(item+" is a "+opinion+"")
```
And even better, if you want to make it more verbose:
```
# List with "s" to make it plural
persons = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel']
# List item without the "s"
for person in persons
opinion = input("What do you think about " + person + "? ")
print(person + " is a " + opinion + "")
```
|
28,418,677
|
i just began playing with python 3 and got a little stuck. I have this code:
```
person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel']
for item in person:
opinion = input("What do you think about "+person[0]+"? ")
print(person[0]+" is a "+opinion+"")
```
And i do not know how to make it ask about each of the persons in the list. I know person[0] is not good, but i do not know what to put there.
EDIT:
I tried fixing it with a loop:
```
person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel']
i = 0
while i<5:
opinion = input("What do you think about "+person[i]+"? ")
print(person[i]+" is a "+opinion+"")
i += 1
```
And it works, but after it runs out of people on the list and i keep replying, i get an error. There has to be a better way
|
2015/02/09
|
[
"https://Stackoverflow.com/questions/28418677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3025008/"
] |
Notice that when you are running your `for` loop, `item` will be whichever person you have in question. Thus, replace `person[0]` with `item` and you will ask about each person as required, like so:
```
for item in person:
opinion = input("What do you think about "+item+"? ")
print(item+" is a "+opinion+"")
```
|
You are assigning `item` to each value in `person`, use that variable.
```
for item in person:
opinion = input("What do you think about "+item+"? ")
print(item+" is a "+opinion+"")
```
When you called `person[0]`, you were setting it to the first value in `person` **every time**, which is not what you want.
|
45,654,850
|
I would like to do a stuff like this in c++ :
```
for (int i = 0, i < 3; ++i)
{
const auto& author = {"pierre", "paul", "jean"}[i];
const auto& age = {12, 45, 43}[i];
const auto& object = {o1, o2, o3}[i];
print({"even", "without", "identifier"}[i]);
...
}
```
Does everyone know how to do this kind of trick ? I do it a lot in python.
It helps me to factorize code nicely.
|
2017/08/12
|
[
"https://Stackoverflow.com/questions/45654850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443456/"
] |
Looks like you should have used a vector of your custom class with `author`, `age`, `object` and `whatever` attributes, put it in a vector and do range for-loop over it - that would be idiomatic in C++:
```
struct foo
{
std::string author;
int age;
object_t object;
whatever_t whatever;
};
std::vector<foo> foos = { /* contents */ };
for(auto const& foo : foos)
{
// do stuff
}
```
If you really want to, you can do:
```
const auto author = std::vector<std::string>{"pierre", "paul", "jean"}[i];
// ^ not a reference
```
but I'm not sure how well this will be optimised. You could also declare those vectors before the loop and keep the references.
|
Creating an object like `{"pierre", "paul", "jean"}` results in a initializer list. Initializer list does not have any [] operator [Why doesn't `std::initializer\_list` provide a subscript operator?](https://stackoverflow.com/questions/17787394/why-doesnt-stdinitializer-list-provide-a-subscript-operator). So you should convert to `const auto& author = (std::vector<std::string>{"pierre", "paul", "jean"})[i];`. Also the reference symbol should not be there as you are creating a temporary object and you are storing a reference to a temporary.
|
22,703,333
|
I'm working in python, trying to write a code that makes the Fibonacci sequence and return the results as a list. How would I go about doing so? I was able to write a code to return the set of values not as a list, but I'm unsure how I would go about writing a code to return a list.
(Here's the code I have to return just the values, just not as a list)
```
def fibo1(par):
var1 = 0
var2 = 1
while var2 < par:
print var2
var3 = var1 + var2
var1 = var2
var2 = var3
def main():
number = int(raw_input("What is the number? "))
return (fibo1(number))
main()
```
|
2014/03/28
|
[
"https://Stackoverflow.com/questions/22703333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471046/"
] |
The `string` class is in the namespace `std`. You can remove the scoping for `std::`.
You'd do best to include it inside the main function, so names don't colide if you use a library that uses the name string or `cout`, or such.
```
#include <iostream>
#include <string>
int main()
{
using namespace std;
string a;
cin >> a;
cout << a << endl;
return 0;
}
```
|
`string` is in `std` namespace, it's only valid to use `std::string` rather than `string` (the same for `std::cin`, `std::vector` etc). However, in practice, some compilers may let a program using `string` etc without `std::` prefix compile, which makes some programmers think it's OK to omit `std::`, but it's not in standard C++.
So it's best to use:
```
#include <iostream>
#include <string>
int main()
{
std::string a;
std::cin >> a;
std::cout << a << std::endl;
return 0;
}
```
Note that it's NOT a good idea to use `using namespace std;` (though it's legal), especially NOT put it in a header.
If you are tired of typing all the `std::`, declare all the names with namespace you **use** is one option:
```
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
string a;
cin >> a;
cout << a << endl;
return 0;
}
```
|
841,096
|
I've recently hit a wall in a project I'm working on which uses PyQt. I have a QTreeView hooked up to a QAbstractItemModel which typically has thousands of nodes in it. So far, it works alright, but I realized today that selecting a lot of nodes is very slow. After some digging, it turns out that QAbstractItemModel.parent() is called way too often. I created minimal code to reproduce the problem:
```
#!/usr/bin/env python
import sys
import cProfile
import pstats
from PyQt4.QtCore import Qt, QAbstractItemModel, QVariant, QModelIndex
from PyQt4.QtGui import QApplication, QTreeView
# 200 root nodes with 10 subnodes each
class TreeNode(object):
def __init__(self, parent, row, text):
self.parent = parent
self.row = row
self.text = text
if parent is None: # root node, create subnodes
self.children = [TreeNode(self, i, unicode(i)) for i in range(10)]
else:
self.children = []
class TreeModel(QAbstractItemModel):
def __init__(self):
QAbstractItemModel.__init__(self)
self.nodes = [TreeNode(None, i, unicode(i)) for i in range(200)]
def index(self, row, column, parent):
if not self.nodes:
return QModelIndex()
if not parent.isValid():
return self.createIndex(row, column, self.nodes[row])
node = parent.internalPointer()
return self.createIndex(row, column, node.children[row])
def parent(self, index):
if not index.isValid():
return QModelIndex()
node = index.internalPointer()
if node.parent is None:
return QModelIndex()
else:
return self.createIndex(node.parent.row, 0, node.parent)
def columnCount(self, parent):
return 1
def rowCount(self, parent):
if not parent.isValid():
return len(self.nodes)
node = parent.internalPointer()
return len(node.children)
def data(self, index, role):
if not index.isValid():
return QVariant()
node = index.internalPointer()
if role == Qt.DisplayRole:
return QVariant(node.text)
return QVariant()
app = QApplication(sys.argv)
treemodel = TreeModel()
treeview = QTreeView()
treeview.setSelectionMode(QTreeView.ExtendedSelection)
treeview.setSelectionBehavior(QTreeView.SelectRows)
treeview.setModel(treemodel)
treeview.expandAll()
treeview.show()
cProfile.run('app.exec_()', 'profdata')
p = pstats.Stats('profdata')
p.sort_stats('time').print_stats()
```
To reproduce the problem, just run the code (which does profiling) and select all nodes in the tree widget (either through shift selection or Cmd-A). When you quit the app, the profiling stats will show something like:
```
Fri May 8 20:04:26 2009 profdata
628377 function calls in 6.210 CPU seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
1 4.788 4.788 6.210 6.210 {built-in method exec_}
136585 0.861 0.000 1.182 0.000 /Users/hsoft/Desktop/slow_selection.py:34(parent)
142123 0.217 0.000 0.217 0.000 {built-in method createIndex}
17519 0.148 0.000 0.164 0.000 /Users/hsoft/Desktop/slow_selection.py:52(data)
162198 0.094 0.000 0.094 0.000 {built-in method isValid}
8000 0.055 0.000 0.076 0.000 /Users/hsoft/Desktop/slow_selection.py:26(index)
161357 0.047 0.000 0.047 0.000 {built-in method internalPointer}
94 0.000 0.000 0.000 0.000 /Users/hsoft/Desktop/slow_selection.py:46(rowCount)
404 0.000 0.000 0.000 0.000 /Users/hsoft/Desktop/slow_selection.py:43(columnCount)
94 0.000 0.000 0.000 0.000 {len}
1 0.000 0.000 6.210 6.210 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
```
The weird part in this data is how often parent() is called: 136k times for 2k nodes! Anyone has a clue why?
|
2009/05/08
|
[
"https://Stackoverflow.com/questions/841096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103667/"
] |
Try calling `setUniformRowHeights(true)` for your tree view:
<https://doc.qt.io/qt-4.8/qtreeview.html#uniformRowHeights-prop>
Also, there's a C++ tool called modeltest from qt labs. I'm not sure if there is something for python though:
<https://wiki.qt.io/Model_Test>
|
I converted your very nice example code to PyQt5 and ran under Qt5.2 and can confirm that the numbers are still similar, i.e. inexplicably huge numbers of calls. Here for example is the top part of the report for start, cmd-A to select all, scroll one page, quit:
```
ncalls tottime percall cumtime percall filename:lineno(function)
1 14.880 14.880 15.669 15.669 {built-in method exec_}
196712 0.542 0.000 0.703 0.000 /Users/dcortes1/Desktop/scratch/treeview.py:36(parent)
185296 0.104 0.000 0.104 0.000 {built-in method createIndex}
20910 0.050 0.000 0.056 0.000 /Users/dcortes1/Desktop/scratch/treeview.py:54(data)
225252 0.036 0.000 0.036 0.000 {built-in method isValid}
224110 0.034 0.000 0.034 0.000 {built-in method internalPointer}
7110 0.020 0.000 0.027 0.000 /Users/dcortes1/Desktop/scratch/treeview.py:28(index)
```
And while the counts are really excessive (and I have no explanation), notice the cumtime values aren't so big. Also those functions could be recoded to run faster; for example in index(), is "if not self.nodes" ever true? Similarly, notice the counts for parent() and createIndex() are almost the same, hence index.isValid() is true much more often than not (reasonable, as end-nodes are much more numerous than parent nodes). Recoding to handle that case first would cut the parent() cumtime further. Edit: on second thought, such optimizations are "rearranging the deck chairs on the titanic".
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.