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 |
|---|---|---|---|---|---|
6,738,987 | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding ... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6738987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614953/"
] | It can be done in pure Python with this incredibly clever module:
<https://pypi.python.org/pypi/forbiddenfruit>
For example:
```
import functools
import ctypes
import __builtin__
import operator
class PyObject(ctypes.Structure):
pass
Py_ssize_t = hasattr(ctypes.pythonapi, 'Py_InitModule4_64') and ctypes.c_int6... | The best you can do appears to be deriving a class from the built-in type. For example:
```
class mylist(list):
def myfunc(self, x):
self.append(x)
test = mylist([1,2,3,4])
test.myfunc(99)
```
(You could even name it "list" so as to get the same constructor, if you wanted.) However, you cannot directly ... |
6,738,987 | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding ... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6738987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614953/"
] | It can be done in pure Python with this incredibly clever module:
<https://pypi.python.org/pypi/forbiddenfruit>
For example:
```
import functools
import ctypes
import __builtin__
import operator
class PyObject(ctypes.Structure):
pass
Py_ssize_t = hasattr(ctypes.pythonapi, 'Py_InitModule4_64') and ctypes.c_int6... | Nope, you gotta subclass!
```
>>> import string
>>> class MyString(str):
... def disemvowel(self):
... return MyString(string.translate(self, None, "aeiou"))
...
>>> s = MyString("this is only a test")
>>> s.disemvowel()
'ths s nly tst'
```
---
Or more specific to your example
```
>>> class MyList(li... |
18,038,492 | I have a PHP script that needs to take one command-line argument. I need to call this script from inside my python script.
```
Popen('php simplepush.php "Here's the argument"', shell=True, cwd="/home/ubuntu/web/firestopapp.com/app")
```
^That works. However, I want to pass a variable in the Python script inste... | 2013/08/04 | [
"https://Stackoverflow.com/questions/18038492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2476581/"
] | You will not be able to get the JSON in controller. In ASP.NET Web API pipeline, binding happens before the action method executes. Media formatter would have read the request body JSON (which is a read-once stream) and emptied the contents by the time the execution comes to your action method. But if you read the JSON... | You can't get the parsed JSON, but you can get the content and parse it yourself. Try this:
```
public async Task PostCustomer(Customer customer)
{
var json = Newtonsoft.Json.JsonConvert.DeserializeObject(await this.Request.Content.ReadAsStringAsync());
///You can deserialize to any object you need or simply ... |
18,038,492 | I have a PHP script that needs to take one command-line argument. I need to call this script from inside my python script.
```
Popen('php simplepush.php "Here's the argument"', shell=True, cwd="/home/ubuntu/web/firestopapp.com/app")
```
^That works. However, I want to pass a variable in the Python script inste... | 2013/08/04 | [
"https://Stackoverflow.com/questions/18038492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2476581/"
] | You will not be able to get the JSON in controller. In ASP.NET Web API pipeline, binding happens before the action method executes. Media formatter would have read the request body JSON (which is a read-once stream) and emptied the contents by the time the execution comes to your action method. But if you read the JSON... | I was trying to do something very similar, but wasn't able to find a way to inject a handler directly into Web API in the proper place. It seems delegated message handlers fall between the deserialize/serialize step and the routing step (something they don't show you in all those Web API pipeline diagrams).
However I ... |
40,445,390 | I have a list composed by tuples.
Each tuple is in the following tuple format: (String, Integer).
I want to merge the tuples that have the same head (String) as follows:
```
[("Foo", 2), ("Bar", 4), ("Foo", 2), ("Bar", 4), ("Foo", 2)]
```
should become:
```
[("Foo", 6), ("Bar",8)].
```
What is a good python alg... | 2016/11/06 | [
"https://Stackoverflow.com/questions/40445390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4383494/"
] | How about collecting the sums in a [`defaultdict`](https://docs.python.org/3.6/library/collections.html#collections.defaultdict)?
```
from collections import defaultdict
d = defaultdict(int)
for (key, value) in items:
d[key] += value
```
And then turn them back to a list of tuples:
```
list(d.items())
```
The... | ```
d = {}
map(lambda (x,y):d.setdefault(x,[]).append(y),a)
print [(k,sum(v)) for k,v in d.items()]
``` |
40,445,390 | I have a list composed by tuples.
Each tuple is in the following tuple format: (String, Integer).
I want to merge the tuples that have the same head (String) as follows:
```
[("Foo", 2), ("Bar", 4), ("Foo", 2), ("Bar", 4), ("Foo", 2)]
```
should become:
```
[("Foo", 6), ("Bar",8)].
```
What is a good python alg... | 2016/11/06 | [
"https://Stackoverflow.com/questions/40445390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4383494/"
] | How about collecting the sums in a [`defaultdict`](https://docs.python.org/3.6/library/collections.html#collections.defaultdict)?
```
from collections import defaultdict
d = defaultdict(int)
for (key, value) in items:
d[key] += value
```
And then turn them back to a list of tuples:
```
list(d.items())
```
The... | You can try this:
```
from collections import defaultdict
my_list = [("Foo", 2), ("Bar", 4), ("Foo", 2), ("Bar", 4), ("Foo", 2)]
d = defaultdict(list)
for tup in my_list:
key, value = tup[0], tup[1]
d[key].append(value)
lst = [(key, sum(value)) for key, value in d.items()]
result = sorted(lst, key = lambd... |
17,581,418 | I'm trying to build OpenCV with MSYS / MinGW so I can use the cv2 module in python.
I'm on Windows 7 64-bit and using 32 bit Python 2.7. Building OpenCV works, but I cannot seem to use it without getting an "ImportError: DLL load failed: The specified module could not be found." after importing cv2. I've been debuggin... | 2013/07/10 | [
"https://Stackoverflow.com/questions/17581418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887074/"
] | I feel really stupid. The dlls were in "C:\Program Files (x86)\bin" not "C:\Program Files (x86)\lib" It seems to work now. | Just to make sure other users can be helped with this answer:
Imagine you have compiled OpenCV and have several \*.dll and the cv2.pyd file.
You need to copy those files to 'DLLs' folder within the python directory.
Then import the module to check wether it is ok.
I have also copied the \*.lib files into the appropr... |
17,581,418 | I'm trying to build OpenCV with MSYS / MinGW so I can use the cv2 module in python.
I'm on Windows 7 64-bit and using 32 bit Python 2.7. Building OpenCV works, but I cannot seem to use it without getting an "ImportError: DLL load failed: The specified module could not be found." after importing cv2. I've been debuggin... | 2013/07/10 | [
"https://Stackoverflow.com/questions/17581418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887074/"
] | I feel really stupid. The dlls were in "C:\Program Files (x86)\bin" not "C:\Program Files (x86)\lib" It seems to work now. | This post helped me a lot. The answer I found was to make sure the compiled bin files were part of my PATH variable.
My CMAKE\_INSTALL\_PREFIX was C:\opencv\src\build\install
and adding C:\opencv\src\build\install\x86\vc11\bin to my PATH variable made cv2 start working. |
17,581,418 | I'm trying to build OpenCV with MSYS / MinGW so I can use the cv2 module in python.
I'm on Windows 7 64-bit and using 32 bit Python 2.7. Building OpenCV works, but I cannot seem to use it without getting an "ImportError: DLL load failed: The specified module could not be found." after importing cv2. I've been debuggin... | 2013/07/10 | [
"https://Stackoverflow.com/questions/17581418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887074/"
] | This post helped me a lot. The answer I found was to make sure the compiled bin files were part of my PATH variable.
My CMAKE\_INSTALL\_PREFIX was C:\opencv\src\build\install
and adding C:\opencv\src\build\install\x86\vc11\bin to my PATH variable made cv2 start working. | Just to make sure other users can be helped with this answer:
Imagine you have compiled OpenCV and have several \*.dll and the cv2.pyd file.
You need to copy those files to 'DLLs' folder within the python directory.
Then import the module to check wether it is ok.
I have also copied the \*.lib files into the appropr... |
28,677,012 | the code:
```
import os
from time import *
import socket
import time
global diskspace
#####################
#display temp
#uses shell script to find out temp then uses python to display it
#python uses os module to run line of shell script
os.system("cat /sys/class/thermal/thermal_zone0/temp > sysTemp")
temp = op... | 2015/02/23 | [
"https://Stackoverflow.com/questions/28677012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3910964/"
] | You have few options:
1. Initialize arrays in constructor MesssageParsingTest using syntax : `firstMessage{0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10}`
in initializer list.
2. Create static const array containing your message, and either copy it to member variable using memcpy... | You can use a temporary buffer and then copy into you member as this:
```
void MessageParsingTest::setUp() {
unsigned char tmp[1500] = {0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10};
memcpy(firstMessage, tmp, 1500);
}
``` |
28,677,012 | the code:
```
import os
from time import *
import socket
import time
global diskspace
#####################
#display temp
#uses shell script to find out temp then uses python to display it
#python uses os module to run line of shell script
os.system("cat /sys/class/thermal/thermal_zone0/temp > sysTemp")
temp = op... | 2015/02/23 | [
"https://Stackoverflow.com/questions/28677012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3910964/"
] | You have few options:
1. Initialize arrays in constructor MesssageParsingTest using syntax : `firstMessage{0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10}`
in initializer list.
2. Create static const array containing your message, and either copy it to member variable using memcpy... | Here is one way to do it.
```
void MessageParsingTest::setUp()
{
unsigned char x[] = {0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10};
::memcpy(firstMessage, x, sizeof(x));
}
```
If you are using C++11, you can also initialize the firstMessage in the class member initia... |
28,677,012 | the code:
```
import os
from time import *
import socket
import time
global diskspace
#####################
#display temp
#uses shell script to find out temp then uses python to display it
#python uses os module to run line of shell script
os.system("cat /sys/class/thermal/thermal_zone0/temp > sysTemp")
temp = op... | 2015/02/23 | [
"https://Stackoverflow.com/questions/28677012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3910964/"
] | Here is one way to do it.
```
void MessageParsingTest::setUp()
{
unsigned char x[] = {0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10};
::memcpy(firstMessage, x, sizeof(x));
}
```
If you are using C++11, you can also initialize the firstMessage in the class member initia... | You can use a temporary buffer and then copy into you member as this:
```
void MessageParsingTest::setUp() {
unsigned char tmp[1500] = {0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10};
memcpy(firstMessage, tmp, 1500);
}
``` |
26,746,127 | I'm in an interactive Python 2.7 Terminal (Terminal default output is "utf-8"). I have a string from the internet, lets call it `a`
```
>>> a
u'M\xfcssen'
>>> a[1]
u'\xfc'
```
I wonder why its value is not `ü` so I try
```
>>> print(a)
Müssen
>>> print(a[1])
ü
```
which works as intended.
So my first question is... | 2014/11/04 | [
"https://Stackoverflow.com/questions/26746127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/620053/"
] | Can you try this
```
updateToServer: function(e) {
e.preventDefault();
var id = e.target.getAttribute('data-id');
var file = this.collection.get(id);
var data = {};
$(e.target).serializeArray().map(function(x) {data[x.name] = x.value;});
this.$el.modal('hide');
setTimeout(function(... | This was not at all what I suspected, and I hadn't given enough information in the question without realizing it. The line in my code that triggered the exception was `file.save()`, but the actual exception was happening inside Backgrid.
I provide a form to allow users to update models from the collection displayed in... |
26,504,852 | On `python/flask/gunicorn/heroku` stack, I need to set an environment variable based on the content of another env variable.
For background, I run a python/Flask app on heroku.
I communicate with an addon via a environment variable that contains credentials and url.
The library I use to communicate with the addon need... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26504852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1827442/"
] | you could also set the enviroment variables at run time as such
```
gunicorn -b 0.0.0.0:5000 -e env_var1=enviroment1 -e env_var2=environment2
``` | OK, so the answer (via Kenneth R, Heroku) is to set the environment before running gunicorn. I.e. write a Procfile like
```
web: sh appstarter.sh
```
which calls a wrapper (shell, python, ..) that sets up the environment variable and then runs the gunicorn command, like for example
appstarter.sh:
```
export LIB_EN... |
26,504,852 | On `python/flask/gunicorn/heroku` stack, I need to set an environment variable based on the content of another env variable.
For background, I run a python/Flask app on heroku.
I communicate with an addon via a environment variable that contains credentials and url.
The library I use to communicate with the addon need... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26504852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1827442/"
] | OK, so the answer (via Kenneth R, Heroku) is to set the environment before running gunicorn. I.e. write a Procfile like
```
web: sh appstarter.sh
```
which calls a wrapper (shell, python, ..) that sets up the environment variable and then runs the gunicorn command, like for example
appstarter.sh:
```
export LIB_EN... | Set environment variable (key=value).
Pass variables to the execution environment. Ex.:
$ gunicorn -b 127.0.0.1:8000 --env FOO=1 test:app
and test for the foo variable environment in your application.
from: <http://docs.gunicorn.org/en/stable/settings.html> |
26,504,852 | On `python/flask/gunicorn/heroku` stack, I need to set an environment variable based on the content of another env variable.
For background, I run a python/Flask app on heroku.
I communicate with an addon via a environment variable that contains credentials and url.
The library I use to communicate with the addon need... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26504852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1827442/"
] | you could also set the enviroment variables at run time as such
```
gunicorn -b 0.0.0.0:5000 -e env_var1=enviroment1 -e env_var2=environment2
``` | Set environment variable (key=value).
Pass variables to the execution environment. Ex.:
$ gunicorn -b 127.0.0.1:8000 --env FOO=1 test:app
and test for the foo variable environment in your application.
from: <http://docs.gunicorn.org/en/stable/settings.html> |
14,592,879 | I cannot run any script by pressing F5 or selecting run from the menus in IDLE. It stopped working suddenly. No errors are coughed up. IDLE simply does nothing at all.
Tried reinstalling python to no effect.
Cannot run even the simplest script.
Thank you for any help or suggestions you have.
Running Python 2.6.5 on... | 2013/01/29 | [
"https://Stackoverflow.com/questions/14592879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2022926/"
] | I am using a Dell laptop, and ran into this issue. I found that if I pressed Function + F5, the program would run.
On my laptop keyboard, functions key items are in blue (main functions in white). The Esc (escape) key has a blue lock with 'Fn' on it. I pressed Esc + F5, and it unlocked my function keys. I can now run ... | Your function keys are locked,I think so.
Function keys can be unlocked by fn key + esc.
Then f5 will work without any issue. |
6,080,930 | I have a problem setting up a Virtualenv on my web host server (to install python modules later on)
So far I tried this using SSH-access:
```
wget http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.5.2.tar.gz
tar xzf virtualenv-1.5.2.tar.gz
~/usr/lib/python2.4 virtualenv-1.5.2/virtualenv.py ~/data/env
... | 2011/05/21 | [
"https://Stackoverflow.com/questions/6080930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/763840/"
] | Same in Ruby.
```
require 'lib/yourlibrary.rb'
```
Or:
```
$LOAD_PATH << File.expand_path(File.dirname(FILE) + “/../lib”))
require 'yourlibrary.rb'
``` | To include a gem in your project, you could download the module and place it in the same folder as your code and then do a 'require'. You can also download the module with Rubygems copy, or you can download the module from it's project page. |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | In the Model's `__str__` method, you are returning a value which is `null`.
For example:
```py
class X(models.Model):
name = models.CharField(_('Name'), null=True, blank=True,
max_length=150)
date_of_birth = models.DateField(_('Date of birth'), null=True, blank=True)
street = models.CharField(_('Stre... | You probably have some null value in your table. Enter to mysql and delete null value in table. |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | Method [\_\_str\_\_](http://docs.python.org/reference/datamodel.html#object.__str__) should return string, not print.
```
def __str__(self):
return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)
``` | In the Model's `__str__` method, you are returning a value which is `null`.
For example:
```py
class X(models.Model):
name = models.CharField(_('Name'), null=True, blank=True,
max_length=150)
date_of_birth = models.DateField(_('Date of birth'), null=True, blank=True)
street = models.CharField(_('Stre... |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | In the Model's `__str__` method, you are returning a value which is `null`.
For example:
```py
class X(models.Model):
name = models.CharField(_('Name'), null=True, blank=True,
max_length=150)
date_of_birth = models.DateField(_('Date of birth'), null=True, blank=True)
street = models.CharField(_('Stre... | Just Try this:
```
def __str__(self):
return f'Memo={self.memo}, Tag={self.tags}'
``` |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | The problem that you are facing is :
TypeError : **str** returned non-string (type NoneType)
Here you have to understand the **str** function's working:
the **str** fucntion,although is mostly used to print values but actually is designed to return a string,not to print one.
In your class **str** function is calling t... | Just Try this:
```
def __str__(self):
return f'Memo={self.memo}, Tag={self.tags}'
``` |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | Method [\_\_str\_\_](http://docs.python.org/reference/datamodel.html#object.__str__) should return string, not print.
```
def __str__(self):
return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)
``` | The problem that you are facing is :
TypeError : **str** returned non-string (type NoneType)
Here you have to understand the **str** function's working:
the **str** fucntion,although is mostly used to print values but actually is designed to return a string,not to print one.
In your class **str** function is calling t... |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | In the Model's `__str__` method, you are returning a value which is `null`.
For example:
```py
class X(models.Model):
name = models.CharField(_('Name'), null=True, blank=True,
max_length=150)
date_of_birth = models.DateField(_('Date of birth'), null=True, blank=True)
street = models.CharField(_('Stre... | I Had the same problem, in my case, was because i was returned a digit:
```
def __str__(self):
return self.code
```
str is waiting for a str, not another.
now work good with:
```
def __str__(self):
return self.name
```
where name is a STRING. |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | You can also surround the output with str(). I had this same problem because my model had the following (as a simplified example):
```
def __str__(self):
return self.pressid
```
Where pressid was an IntegerField type object. Django (and python in general) expects a string for a **str** function, so returning an ... | In the Model's `__str__` method, you are returning a value which is `null`.
For example:
```py
class X(models.Model):
name = models.CharField(_('Name'), null=True, blank=True,
max_length=150)
date_of_birth = models.DateField(_('Date of birth'), null=True, blank=True)
street = models.CharField(_('Stre... |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | You can also surround the output with str(). I had this same problem because my model had the following (as a simplified example):
```
def __str__(self):
return self.pressid
```
Where pressid was an IntegerField type object. Django (and python in general) expects a string for a **str** function, so returning an ... | Just Try this:
```
def __str__(self):
return f'Memo={self.memo}, Tag={self.tags}'
``` |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | Method [\_\_str\_\_](http://docs.python.org/reference/datamodel.html#object.__str__) should return string, not print.
```
def __str__(self):
return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)
``` | You can also surround the output with str(). I had this same problem because my model had the following (as a simplified example):
```
def __str__(self):
return self.pressid
```
Where pressid was an IntegerField type object. Django (and python in general) expects a string for a **str** function, so returning an ... |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | Method [\_\_str\_\_](http://docs.python.org/reference/datamodel.html#object.__str__) should return string, not print.
```
def __str__(self):
return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)
``` | You probably have some null value in your table. Enter to mysql and delete null value in table. |
48,375,937 | I am new to python and web-scraping. I am trying to scrape a website (link is the url). I am getting an error as "'NoneType' object is not iterable", with the last line of below code. Could anyone point what could have gone wrong?
```
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
url ... | 2018/01/22 | [
"https://Stackoverflow.com/questions/48375937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9238871/"
] | a bit late, but for any one else stumbling upon this.
```
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.someMethod = functions.https.onRequest((req, res) => {
var stuff = [];
var db = admin.firestore();
d... | Thanks to [Ruan's answer](https://stackoverflow.com/a/49516133/2162226), here's an example for `onCall(..)` variation:
```
exports.fireGetColors = functions.https.onCall((data, context) => {
return new Promise((resolve, reject) => {
var colors = {};
var db = admin.firestore();
db.collect... |
48,375,937 | I am new to python and web-scraping. I am trying to scrape a website (link is the url). I am getting an error as "'NoneType' object is not iterable", with the last line of below code. Could anyone point what could have gone wrong?
```
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
url ... | 2018/01/22 | [
"https://Stackoverflow.com/questions/48375937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9238871/"
] | a bit late, but for any one else stumbling upon this.
```
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.someMethod = functions.https.onRequest((req, res) => {
var stuff = [];
var db = admin.firestore();
d... | In 2022, I am trying to do this thing in "Modular" way as what firebase has for version >= 9. Using typescript too as an addition :). Thanks to [Ruan](https://stackoverflow.com/users/1713519/ruan) for the inspiration.
So, here is how I made it ( similar to the following ):
```
import * as functions from "firebase-fun... |
48,375,937 | I am new to python and web-scraping. I am trying to scrape a website (link is the url). I am getting an error as "'NoneType' object is not iterable", with the last line of below code. Could anyone point what could have gone wrong?
```
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
url ... | 2018/01/22 | [
"https://Stackoverflow.com/questions/48375937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9238871/"
] | Thanks to [Ruan's answer](https://stackoverflow.com/a/49516133/2162226), here's an example for `onCall(..)` variation:
```
exports.fireGetColors = functions.https.onCall((data, context) => {
return new Promise((resolve, reject) => {
var colors = {};
var db = admin.firestore();
db.collect... | In 2022, I am trying to do this thing in "Modular" way as what firebase has for version >= 9. Using typescript too as an addition :). Thanks to [Ruan](https://stackoverflow.com/users/1713519/ruan) for the inspiration.
So, here is how I made it ( similar to the following ):
```
import * as functions from "firebase-fun... |
68,584,934 | I want to append to a csv file, some data from redshift tables, using the `pandas` module in python. From python, I can successfully connect and retrieve rows from redshift tables using the `psycopg2` module. Now, I am storing datewise data on the csv. So I need to first create a new date column in the csv, then append... | 2021/07/30 | [
"https://Stackoverflow.com/questions/68584934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15948815/"
] | I solved the problem with the following:
./tsconfig.json
```
{
"compilerOptions": {
"isolatedModules": true,
...
},
"exclude": ["cypress/**/*"]
}
```
./cypress/tsconfig.json
```
{
"extends": "../tsconfig.json",
"compilerOptions": {
"isolatedModules": false
},
"include": [
"../node_mod... | It seems to be a known issue of type conflicts between cypress and jest. Most accounts have detected that the problem started occurring from cypress v10.x onward.
The *following links* corroborate the OP's own answer, suggesting the exclusion of `cypress.config.ts` from `tsconfig.json`. It may or may not be a workarou... |
68,584,934 | I want to append to a csv file, some data from redshift tables, using the `pandas` module in python. From python, I can successfully connect and retrieve rows from redshift tables using the `psycopg2` module. Now, I am storing datewise data on the csv. So I need to first create a new date column in the csv, then append... | 2021/07/30 | [
"https://Stackoverflow.com/questions/68584934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15948815/"
] | I solved the problem with the following:
./tsconfig.json
```
{
"compilerOptions": {
"isolatedModules": true,
...
},
"exclude": ["cypress/**/*"]
}
```
./cypress/tsconfig.json
```
{
"extends": "../tsconfig.json",
"compilerOptions": {
"isolatedModules": false
},
"include": [
"../node_mod... | In my case, it was enough to exclude solely the Cypress configuration file name in the project's `tsconfig.json`. Didn't need "isolatedModules" flag. Example:
```
"exclude": [
...
"cypress.config.ts",
...
]
```
Worked with webpack, jest, react-testing-library with extensions and Cypress stack.
Note:... |
67,662,674 | My Input JSON data:
```
{
"data": [
{
"config": "current",
"id": "0"
},
{
"config": "current",
"id": "1"
},
{
"config": "current",
"id": "2"
},
{
"config": "current",
... | 2021/05/23 | [
"https://Stackoverflow.com/questions/67662674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11882985/"
] | Assuming you already know [how to parse JSON](https://stackoverflow.com/q/7771011/4518341), you can do this:
```
d = {
"data": [
{"config": "current", "id": "0"},
{"config": "current", "id": "1"},
{"config": "current", "id": "2"},
{"config": "current", "id": "3"},
{"config":... | ```
jsn = {
"data": [
{"config": "current", "id": "0"},
{"config": "current", "id": "1"},
{"config": "current", "id": "2"},
{"config": "current", "id": "3"},
{"config": "previous", "id": "4",},
{"config": "previous", "id": "5"},
{"config": "current", "id": "6"... |
51,937,449 | For my Coursework which I am desperately struggling with I have tried to set my inputs into a dictionary and then use this to format and print the string so that it is displayed as shown below.
>
>
> ```
> Surname, Forename Payroll Department Salary
>
> ```
>
> The name should be displayed using the format... | 2018/08/20 | [
"https://Stackoverflow.com/questions/51937449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10251613/"
] | While it would be simple to make a print function to print the way you want:
```
a = ('Surname', 'Forename', 'Payroll', 'Department', 'Salary')
def printer(tup):
print_string = str("(")
pad = 24
print_string += ", ".join(tup[:2]).ljust(pad)
print_string += ", ".join(tup[2:4]).ljust(pad)... | Why do you need this? Printing a tuple with spacing is impossible to my knowledge, but I'm sure theres another way to achieve what you're looking for. Aside from that, there is a kind of work around, although you aren't printing a tuple, to say.
```
indexs = {
payroll = 0,
dept = 1,
salary = 2,
name = ... |
67,967,272 | I am trying to program a calculator using python. It does not let me run the code because this error tells that:
ValueError: could not convert string to float: ''
This code was working but suddenly this error showed up.
Could anyone help me with telling what I should change or add.
This is the part of the code where th... | 2021/06/14 | [
"https://Stackoverflow.com/questions/67967272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15274509/"
] | As per Lombok documentation (<https://projectlombok.org/api/lombok/AllArgsConstructor.html>):
>
> An all-args constructor requires one argument for every field in the class.
>
>
>
Obviously you haven't provided id as a constructor argument. | If you still need some constructor having not all attributes you can use `lombok.NonNull` & `@RequiredArgsConstrutor`. Simplified example:
```
@AllArgsConstructor
@NoArgsConstructor
@RequiredArgsConstructor
public class Booking {
private Long id;
@lombok.NonNull
private Date startDate;
}
```
will provid... |
63,245,187 | I am just starting to get the concept of what [Prometheus](https://prometheus.io/docs/prometheus/latest/getting_started/) is, and I have done a couple of examples already.
I can understand how Prometheus monitors some data, even the one generated by itself and also some data related to a python application for example.... | 2020/08/04 | [
"https://Stackoverflow.com/questions/63245187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4451521/"
] | Short answer: No. If you actually have text files with data you want to analyze I'd suggest you to write the data to another TMDB (InfluxDB for example) or a plain old SQL database and then connect it with Grafana. Also take a look at PowerBI. I prefer it for data that is scoped more towards business analytics than mon... | While it is impossible to import historical data to Prometheus, such data can be imported to Prometheus-like systems such as VictoriaMetrics. See [these docs](https://victoriametrics.github.io/#how-to-import-time-series-data) for details. |
69,647,562 | Why does initializing the array `arr` work when it is done as a list comprehension (I think that is what the following example is --not sure), but not when each array location is initialized individually?
For example, this works:
(a)
```
arr=[]
arr=[0 for i in range(5)]
```
but (b),
```
arr=[]
arr[0]=0
arr[1]=0
... | 2021/10/20 | [
"https://Stackoverflow.com/questions/69647562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242713/"
] | Firstly, there is no point in declaring a variable if you rebind it later anyway:
```
arr = [] # <-- this line is entirely pointless
arr = [0 for i in range(5)]
```
Secondly, the two expressions
```
[0 for i in range(5)]
[0] * 5
```
**create** a new `list` object, whereas
```
arr[0] = 0
```
mutates an existin... | It doesn't pre-allocate. It's basically just appending in a loop, just in nice form (syntactic sugar).
Why it doesn't pre-allocate? Because to pre-allocate, we would need to know the length of the iterable, which may be a generator and it would use it up. And also, comprehension can have an if clause, limiting what ev... |
69,647,562 | Why does initializing the array `arr` work when it is done as a list comprehension (I think that is what the following example is --not sure), but not when each array location is initialized individually?
For example, this works:
(a)
```
arr=[]
arr=[0 for i in range(5)]
```
but (b),
```
arr=[]
arr[0]=0
arr[1]=0
... | 2021/10/20 | [
"https://Stackoverflow.com/questions/69647562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242713/"
] | Firstly, there is no point in declaring a variable if you rebind it later anyway:
```
arr = [] # <-- this line is entirely pointless
arr = [0 for i in range(5)]
```
Secondly, the two expressions
```
[0 for i in range(5)]
[0] * 5
```
**create** a new `list` object, whereas
```
arr[0] = 0
```
mutates an existin... | >
> I don't see how (a) preallocates the array dimension "ahead of time".
>
>
>
It doesn't. This:
```
arr=[]
arr=[0 for i in range(5)]
```
creates an empty array (I think it's more accurately called a *list* but I'm not a strong Python person) and stores it in `arr`, then creates an entirely new unrelated arra... |
15,213,428 | Recently I was going through the "Using Python App Engine with Google Cloud SQL" tutorial on Google Developers Academy website. However, I stumbled upon on the first part of the exercise "Building an application with a local MySQL instance". I could not connect the sample code (main.py) to my local MySQL instance. Wond... | 2013/03/04 | [
"https://Stackoverflow.com/questions/15213428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2130139/"
] | The answer is to use `add_action('edit_link','save_data')` and `add_option('name_of_option')` instead of `add_post_meta` view full results here [MetaBox Links](https://gist.github.com/davidchase/df9adeb1e03b88691899) | After some experiments, I figured out how to save data from custom metabox in link manager into db as post meta key/value (wp\_postmeta).
If someone needs, here is a working example:
```
action( 'add_meta_boxes', 'add_link_date' );
function add_link_date()
{
add_meta_box( 'link-date-meta-box', 'Link Date', 'link_d... |
50,876,292 | Given its link, I'd like to capture an online video (say from YouTube) for further processing **without downloading it on the disk**. What I mean by this is that I'd like to load it directly to memory whenever possible. According to these links:
<http://answers.opencv.org/question/24012/reading-video-stream-from-ip-... | 2018/06/15 | [
"https://Stackoverflow.com/questions/50876292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | You can achieve this by using `youtube-dl` and `ffmpeg`:
* Install the latest version of [`youtube-dl`](https://rg3.github.io/youtube-dl/download.html).
* Then do `sudo pip install --upgrade youtube_dl`
* Build `ffmpeg` with HTTPS support. You can do this by [turning on the `--enable-gnutls` option](https://askubuntu.... | Using pafy you can have a more elegant solution:
```
import cv2
import pafy
url = "https://www.youtube.com/watch?v=NKpuX_yzdYs"
video = pafy.new(url)
best = video.getbest(preftype="mp4")
capture = cv2.VideoCapture()
capture.open(best.url)
success,image = capture.read()
while success:
cv2.imshow('frame', image)... |
50,876,292 | Given its link, I'd like to capture an online video (say from YouTube) for further processing **without downloading it on the disk**. What I mean by this is that I'd like to load it directly to memory whenever possible. According to these links:
<http://answers.opencv.org/question/24012/reading-video-stream-from-ip-... | 2018/06/15 | [
"https://Stackoverflow.com/questions/50876292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | You can achieve this by using `youtube-dl` and `ffmpeg`:
* Install the latest version of [`youtube-dl`](https://rg3.github.io/youtube-dl/download.html).
* Then do `sudo pip install --upgrade youtube_dl`
* Build `ffmpeg` with HTTPS support. You can do this by [turning on the `--enable-gnutls` option](https://askubuntu.... | First of all Update [`youtube-dl`](https://rg3.github.io/youtube-dl/download.html) using the command `pip install -U youtube-dl`
Then use my [`VidGear`](https://github.com/abhiTronix/vidgear) Python Library, then automates the pipelining of YouTube Video using its URL address only. Here's a complete python example:
#... |
50,876,292 | Given its link, I'd like to capture an online video (say from YouTube) for further processing **without downloading it on the disk**. What I mean by this is that I'd like to load it directly to memory whenever possible. According to these links:
<http://answers.opencv.org/question/24012/reading-video-stream-from-ip-... | 2018/06/15 | [
"https://Stackoverflow.com/questions/50876292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | You can achieve this by using `youtube-dl` and `ffmpeg`:
* Install the latest version of [`youtube-dl`](https://rg3.github.io/youtube-dl/download.html).
* Then do `sudo pip install --upgrade youtube_dl`
* Build `ffmpeg` with HTTPS support. You can do this by [turning on the `--enable-gnutls` option](https://askubuntu.... | I want to highlight the issue I faced while running was a open-cv version problem, I was using OpenCV 3.4.x and the video feed was exiting before being read into the while loop, so, i upgraded my open cv to "opencv-contrib-python== 4.2.0.34". |
50,876,292 | Given its link, I'd like to capture an online video (say from YouTube) for further processing **without downloading it on the disk**. What I mean by this is that I'd like to load it directly to memory whenever possible. According to these links:
<http://answers.opencv.org/question/24012/reading-video-stream-from-ip-... | 2018/06/15 | [
"https://Stackoverflow.com/questions/50876292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | First of all Update [`youtube-dl`](https://rg3.github.io/youtube-dl/download.html) using the command `pip install -U youtube-dl`
Then use my [`VidGear`](https://github.com/abhiTronix/vidgear) Python Library, then automates the pipelining of YouTube Video using its URL address only. Here's a complete python example:
#... | Using pafy you can have a more elegant solution:
```
import cv2
import pafy
url = "https://www.youtube.com/watch?v=NKpuX_yzdYs"
video = pafy.new(url)
best = video.getbest(preftype="mp4")
capture = cv2.VideoCapture()
capture.open(best.url)
success,image = capture.read()
while success:
cv2.imshow('frame', image)... |
50,876,292 | Given its link, I'd like to capture an online video (say from YouTube) for further processing **without downloading it on the disk**. What I mean by this is that I'd like to load it directly to memory whenever possible. According to these links:
<http://answers.opencv.org/question/24012/reading-video-stream-from-ip-... | 2018/06/15 | [
"https://Stackoverflow.com/questions/50876292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | First of all Update [`youtube-dl`](https://rg3.github.io/youtube-dl/download.html) using the command `pip install -U youtube-dl`
Then use my [`VidGear`](https://github.com/abhiTronix/vidgear) Python Library, then automates the pipelining of YouTube Video using its URL address only. Here's a complete python example:
#... | I want to highlight the issue I faced while running was a open-cv version problem, I was using OpenCV 3.4.x and the video feed was exiting before being read into the while loop, so, i upgraded my open cv to "opencv-contrib-python== 4.2.0.34". |
27,321,523 | I have a Raspberry Pi that I use as a multi-purpose 24/7 device for DLNA, CIFS, VPN etc. Now I bought a TellStick, that is a USB device that can send 433MHz radio commands to wireless power switches, dimmers etc. The manufacturer offers sources and tools for linux, which is really great, btw.
Using a special command (... | 2014/12/05 | [
"https://Stackoverflow.com/questions/27321523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1901272/"
] | While your question is too "opinion-like", there's an almost instant solution:
[nginx - How to run a shell script on every request?](https://stackoverflow.com/questions/22891148/nginx-how-to-run-a-shell-script-on-every-request)
But since you're talking about R-Pi, maybe you will find Python builtin [CGIHTTPServer](ht... | Here a full & working RealLife™ perl's example
----------------------------------------------
...using [Dancer](https://metacpan.org/pod/Dancer)
```
# cpan Dancer
$ dancer -a MyApp
$ cd MyApp
$ cat ./lib/MyApp.pm # need to be edited, see bellow
$ bin/app.pl
```
Now you can call the URL
```
http://127.0.0.1:3000/sw... |
73,479,698 | I am trying to build a Docker image but when I build it, I get the error message : 'E: Unable to locate package libxcb-util1'.
Here is my Dockerfile :
```
`# $DEL_BEGIN`
FROM python:3.9.7-buster
WORKDIR /prod
COPY design_interface design_interface
COPY requirements.txt requirements.txt
COPY setup.py setup.py
RUN pip... | 2022/08/24 | [
"https://Stackoverflow.com/questions/73479698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19739078/"
] | Updating gradle solves the problem.
There are different ways to update the gradle, as explained in their official website: <https://gradle.org/install/>
*Assuming that you are a windows user*:
Downloading binary files of gradle and extracting the folder to the directory "c:/gradle" is enough.
* Download binary file... | To fix the issue, I've reverted to `cordova-android` version `9.1.0`. I've no idea, as of now, why `cordova-android` version `10` points to `gradle`, which as of now isn't possible to download... |
66,797,173 | I am using transformers pipeline to perform sentiment analysis on sample texts from 6 different languages. I tested the code in my local Jupyterhub and it worked fine. But when I wrap it in a flask application and create a docker image out of it, the execution is hanging at the pipeline inference line and its taking fo... | 2021/03/25 | [
"https://Stackoverflow.com/questions/66797173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10422855/"
] | I was having a similar issue. It seems that starting the app somehow polutes the memory of transformers models. Probably something to do with how Flask does threading but no idea why. What fixed it for me was doing the things that are causing trouble (loading the models) in a different thread.
```
import threading
de... | Flask uses port 5000. In creating a docker image, it's important to make sure that the port is set up this way. Replace the last line with the following:
```
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
```
Be also sure to `import os` at the top
Lastly, in `Dockerfile`, add
```
EXPOSE 5000
CMD [... |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | Maybe you could try [Markdown](http://www.freewisdom.org/projects/python-markdown/) instead, and convert it to HTML on the fly? | You don't necessarily need something complex - for instance, here's a ~150 line library to generate HTML in a functional manner:
<http://github.com/Yelp/PushmasterApp/blob/master/pushmaster/taglib.py>
(Full disclosure, I work with the person who originally wrote that version, and I also use it myself.) |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | Maybe you could try [Markdown](http://www.freewisdom.org/projects/python-markdown/) instead, and convert it to HTML on the fly? | Why would a templating engine necessarily be overkill? You don't need the whole web framework just to use the templating engine (at least, for most templating engines). [Mako](http://www.makotemplates.org/) for example can be used stand-alone just fine, and I often use it to generate html files (reports from a db and s... |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | Maybe you could try [Markdown](http://www.freewisdom.org/projects/python-markdown/) instead, and convert it to HTML on the fly? | i recommend having a look at [shpaml](http://shpaml.webfactional.com/) |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | Maybe you could try [Markdown](http://www.freewisdom.org/projects/python-markdown/) instead, and convert it to HTML on the fly? | If you have just some simple static HTML files. Then why not use string templates like so.
```
import string
TEMPLATE_FORMAT = """
<html>
<head><title>Trial</title></head>
<body>
<div class="myclass">$my_div_data</div>
</body>
"""
my_div_data = "some_data_to_display_in_HTML"
TEMPLATE = string.Template(TEMPLATE... |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | Maybe you could try [Markdown](http://www.freewisdom.org/projects/python-markdown/) instead, and convert it to HTML on the fly? | ElementTree can produce html with some limitations. I'd write it like this:
```
from xml.etree.ElementTree import ElementTree, Element, SubElement
import sys
html = Element('html')
head = SubElement(html, 'head')
style = SubElement(head, 'link')
style.attrib = {'rel': 'stylesheet', 'href': 'style.css', 'type': 'tex... |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | You don't necessarily need something complex - for instance, here's a ~150 line library to generate HTML in a functional manner:
<http://github.com/Yelp/PushmasterApp/blob/master/pushmaster/taglib.py>
(Full disclosure, I work with the person who originally wrote that version, and I also use it myself.) | i recommend having a look at [shpaml](http://shpaml.webfactional.com/) |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | Why would a templating engine necessarily be overkill? You don't need the whole web framework just to use the templating engine (at least, for most templating engines). [Mako](http://www.makotemplates.org/) for example can be used stand-alone just fine, and I often use it to generate html files (reports from a db and s... | i recommend having a look at [shpaml](http://shpaml.webfactional.com/) |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | If you have just some simple static HTML files. Then why not use string templates like so.
```
import string
TEMPLATE_FORMAT = """
<html>
<head><title>Trial</title></head>
<body>
<div class="myclass">$my_div_data</div>
</body>
"""
my_div_data = "some_data_to_display_in_HTML"
TEMPLATE = string.Template(TEMPLATE... | i recommend having a look at [shpaml](http://shpaml.webfactional.com/) |
3,887,393 | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to ou... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3887393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] | ElementTree can produce html with some limitations. I'd write it like this:
```
from xml.etree.ElementTree import ElementTree, Element, SubElement
import sys
html = Element('html')
head = SubElement(html, 'head')
style = SubElement(head, 'link')
style.attrib = {'rel': 'stylesheet', 'href': 'style.css', 'type': 'tex... | i recommend having a look at [shpaml](http://shpaml.webfactional.com/) |
6,699,201 | What would I have to do to make a Python application I am writing open up a web page in the default browser? It doesn't need to be told what the webpage is or anything, it'll be opening one that I've already chosen.
I found some documentation [here](http://docs.python.org/library/webbrowser.html) but I always get a sy... | 2011/07/14 | [
"https://Stackoverflow.com/questions/6699201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841843/"
] | The URL needs to be in a string.
```
webbrowser.open('http://www.google.com/')
``` | Have a look at the `webbrowser` module. |
64,082,288 | I masked a *sorted* 1-D numpy array using the method below (which follows a solution proposed [here](https://stackoverflow.com/questions/64076440/accessing-a-large-numpy-array-while-preserving-its-order)):
```
def get_from_sorted(sorted,idx):
mask = np.zeros(sorted.shape, bool)
mask[idx] = True
return s... | 2020/09/26 | [
"https://Stackoverflow.com/questions/64082288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815653/"
] | I believe your goal as follows.
* Your question has the following 2 questions.
1. You want to know the method for creating new Google Document including the text data.
2. You want to know the method for adding more text data to the existing Google Document.
* You want to achieve this using Drive API with googleapis ... | From the [Media Uploads example](https://github.com/googleapis/google-api-nodejs-client#media-uploads) for `[email protected]`, you can create a Google Document with a given title and content inside a given folder with
```
const drive = google.drive({ version: 'v3', auth });
const filename = '<filename>';
const paren... |
57,358,927 | I would like to use the twilight or twilight\_shifted colormap in my 2.7 python build, but it seems to be python 3 only? Is there some way to manually add it? | 2019/08/05 | [
"https://Stackoverflow.com/questions/57358927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1608765/"
] | `twilight` was added in matplotlib v3.0 which is python 3 only. But we can find where it was added in the source code are re-engineer it.
In the code below, you just need to grab the data used for `twilight` from the matplotlib source on github, by following this [link](https://github.com/matplotlib/matplotlib/blob/f2... | You can create a new custom colormap as shown in this [tutorial](https://matplotlib.org/3.1.0/tutorials/colors/colormap-manipulation.html).
The data for the "twilight" and "twilight\_shifted" colormaps is [here](https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/_cm_listed.py). |
57,358,927 | I would like to use the twilight or twilight\_shifted colormap in my 2.7 python build, but it seems to be python 3 only? Is there some way to manually add it? | 2019/08/05 | [
"https://Stackoverflow.com/questions/57358927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1608765/"
] | `twilight` was added in matplotlib v3.0 which is python 3 only. But we can find where it was added in the source code are re-engineer it.
In the code below, you just need to grab the data used for `twilight` from the matplotlib source on github, by following this [link](https://github.com/matplotlib/matplotlib/blob/f2... | You can take the [`_cm_listed.py`](https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/_cm_listed.py) file from the current version and copy it to your matplotlib 2.2.3 folder. Since the file is version agnostic, this should directly give you the additional colormaps. |
65,579,018 | **What I intend to do :**
I have an excel file with Voltage and Current data which I would like to extract from a specific sheet say 'IV\_RAW'. The values are only from 4th row and are in columns D and E.
Lets say the values look like this:
| V(voltage) | I(Current) |
| --- | --- |
| 47 | 1 |
| 46 | 2 |
| 45 | 3 |
| ... | 2021/01/05 | [
"https://Stackoverflow.com/questions/65579018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14944185/"
] | The following uses `pandas` which you should definitly take a look at. with `sheet_name` you set the sheet\_name, `header` is the row index of the header (starting at 0, so Row 4 -> 3), `usecols` defines the columns using A1 notation.
The last line filters the dataframe. If I understand correctly, then you want Voltag... | you can try this,
```
import openpyxl
tWorkbook = openpyxl.load_workbook("YOUR_FILEPATH")
tDataBase = tWorkbook.active
voltageVal= "D4"
currentVal= "E4"
V = tDataBase[voltageVal].value
I = tDataBase[currentVal].value
``` |
65,579,018 | **What I intend to do :**
I have an excel file with Voltage and Current data which I would like to extract from a specific sheet say 'IV\_RAW'. The values are only from 4th row and are in columns D and E.
Lets say the values look like this:
| V(voltage) | I(Current) |
| --- | --- |
| 47 | 1 |
| 46 | 2 |
| 45 | 3 |
| ... | 2021/01/05 | [
"https://Stackoverflow.com/questions/65579018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14944185/"
] | The following uses `pandas` which you should definitly take a look at. with `sheet_name` you set the sheet\_name, `header` is the row index of the header (starting at 0, so Row 4 -> 3), `usecols` defines the columns using A1 notation.
The last line filters the dataframe. If I understand correctly, then you want Voltag... | Building on from your example, you can use the following example to get what you need
```
from openpyxl import load_workbook
wb = load_workbook(filepath,data_only=True) #load the file using its full path
ws = wb["Sheet1"] #theactiveworksheet
#to extract the voltage and current data:
data = ws.iter_rows(min_col=4, ... |
65,579,018 | **What I intend to do :**
I have an excel file with Voltage and Current data which I would like to extract from a specific sheet say 'IV\_RAW'. The values are only from 4th row and are in columns D and E.
Lets say the values look like this:
| V(voltage) | I(Current) |
| --- | --- |
| 47 | 1 |
| 46 | 2 |
| 45 | 3 |
| ... | 2021/01/05 | [
"https://Stackoverflow.com/questions/65579018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14944185/"
] | Building on from your example, you can use the following example to get what you need
```
from openpyxl import load_workbook
wb = load_workbook(filepath,data_only=True) #load the file using its full path
ws = wb["Sheet1"] #theactiveworksheet
#to extract the voltage and current data:
data = ws.iter_rows(min_col=4, ... | you can try this,
```
import openpyxl
tWorkbook = openpyxl.load_workbook("YOUR_FILEPATH")
tDataBase = tWorkbook.active
voltageVal= "D4"
currentVal= "E4"
V = tDataBase[voltageVal].value
I = tDataBase[currentVal].value
``` |
26,513,125 | I have some django view handler functions which are structured like this
```
def view1(request):
# Check for authorization
if not isAuthorized(request):
return HttpResponse('Foo error', status=401)
return HttpResponse('view1 data')
def view2(request):
# Check for authorization
if not isAuthorized(req... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26513125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20392/"
] | The line `int ans = tmp->next;` appears to be the source of the problem. This is attempting to take the `next` pointer in the node, convert it to an `int`, and return it. What you (almost certainly) want is to retrieve the data from the node and return that, with something like `int ans = tmp->num;`.
Of course, that's... | First, you are trying to delete `tmp` node, but top node still exist and value has to be returned as ans or top->next or in this situation top->num. Why do you initialize node `tmp` in the function when node `tmp` is a parameter? Why should node \* &top be in the function parameters instead of `tmp`.
value = top->num ... |
26,513,125 | I have some django view handler functions which are structured like this
```
def view1(request):
# Check for authorization
if not isAuthorized(request):
return HttpResponse('Foo error', status=401)
return HttpResponse('view1 data')
def view2(request):
# Check for authorization
if not isAuthorized(req... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26513125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20392/"
] | Usually such a function throws an exception if the stack is empty or it has undefined behaviour. I used return value 0 in case when the stack is empty.
```
int pop( Node * &top )
{
int value = 0;
if ( top )
{
value = top->num;
Node *tmp = top;
top = top->next;
delete tmp;
... | First, you are trying to delete `tmp` node, but top node still exist and value has to be returned as ans or top->next or in this situation top->num. Why do you initialize node `tmp` in the function when node `tmp` is a parameter? Why should node \* &top be in the function parameters instead of `tmp`.
value = top->num ... |
26,513,125 | I have some django view handler functions which are structured like this
```
def view1(request):
# Check for authorization
if not isAuthorized(request):
return HttpResponse('Foo error', status=401)
return HttpResponse('view1 data')
def view2(request):
# Check for authorization
if not isAuthorized(req... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26513125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20392/"
] | As mentioned in my [comment](https://stackoverflow.com/questions/26513124/pop-function-on-linked-list-stack/26513670#comment41656530_26513124) you should split this up to two separate functions. One to get the value, and another one to pop (remove) the `Node`
```
void pop(Node*& top) { // Note the reference. You want ... | First, you are trying to delete `tmp` node, but top node still exist and value has to be returned as ans or top->next or in this situation top->num. Why do you initialize node `tmp` in the function when node `tmp` is a parameter? Why should node \* &top be in the function parameters instead of `tmp`.
value = top->num ... |
56,439,798 | I have a camera running on rtsp link. I want to write python code to check if the camera is live or dead. Similar to using curl to check http if url is working or not. What is a similar command can one use to check rtsp url status?
I have tried using openRTSP on terminal and I want to use it as python script
openRTSP... | 2019/06/04 | [
"https://Stackoverflow.com/questions/56439798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6006820/"
] | You can call FFMPEG to extract a snapshot. If successful stream is accessible.
Test this functionality (exctracting snapshot from rtsp) with <https://videonow.live/broadcast-ip-camera-or-stream/> per tutorial at <https://broadcastlivevideo.com/publish-ip-camera-stream-to-website/>.
Command to extract should be someth... | You can use the `opencv_python` module to play rtsp stream.
Sample codes:
```
import cv2
cap=cv2.VideoCapture("rtsp://admin:admin123@test_url_here")
ret,frame = cap.read()
while ret:
ret,frame = cap.read()
cv2.imshow("frame",frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindo... |
27,466,862 | There's something wrong with my OSX system and python that no amount of googling has fixed. I've uninstalled all traces of python except the system python package with OSX that I'm not supposed to uninstall, and then started afresh with a new python from python.org, and installed pip.
Now...not sure if this particula... | 2014/12/14 | [
"https://Stackoverflow.com/questions/27466862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119779/"
] | `sudo` overrides your `export`. It's the same Python (as you can easily tell from the version information it prints) but it runs with a different (system default) `PYTHONPATH`.
This is one of the jobs of `sudo`; it sanitizes the environment to safe defaults. You may be able to tweak this, but the real question is, wha... | What do you get when you compare the output of `which pip` and `sudo which pip`?
On my system I get different outputs. If you do, I'm not sure how to fix that, but you could try to force the sudo'd python to look in the correct directory:
```
import sys
sys.path.insert(0, '/lib/python2.7/site-packages/')
import pip
... |
21,783,840 | I have a CSV file that has numerous data points included in each row, despite belonging to the same column. Something similar to this:
```
A, B, C, X, Y, Z
```
Now, what I would like to do is to reformat the file such that the resulting CSV is:
```
A, B, C
X, Y, Z
```
I'm not too sure how to go about this / expre... | 2014/02/14 | [
"https://Stackoverflow.com/questions/21783840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2179795/"
] | Just write two rows to an output [`csv.writer()` object](http://docs.python.org/2/library/csv.html#csv.writer):
```
with open(inputfilename, 'rb') as infh, open(outputfilename, 'wb') as outfh:
reader = csv.reader(infh)
writer = csv.writer(outfh)
for row in reader:
writer.writerows([row[:3], row[3:... | You could probably use python's [CSV module](http://docs.python.org/2/library/csv.html)
Example:
```
#!/usr/bin/env python
import csv
with open("input.csv", "r") as input_file, open("output.csv", "w+"):
input_csv, output_csv = csv.reader(input_file), csv.writer(output_file);
for row in input_csv:
out... |
21,783,840 | I have a CSV file that has numerous data points included in each row, despite belonging to the same column. Something similar to this:
```
A, B, C, X, Y, Z
```
Now, what I would like to do is to reformat the file such that the resulting CSV is:
```
A, B, C
X, Y, Z
```
I'm not too sure how to go about this / expre... | 2014/02/14 | [
"https://Stackoverflow.com/questions/21783840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2179795/"
] | Just write two rows to an output [`csv.writer()` object](http://docs.python.org/2/library/csv.html#csv.writer):
```
with open(inputfilename, 'rb') as infh, open(outputfilename, 'wb') as outfh:
reader = csv.reader(infh)
writer = csv.writer(outfh)
for row in reader:
writer.writerows([row[:3], row[3:... | *This solution is for Python 3. For Python 2, see [Martijn Pieters's answer](https://stackoverflow.com/a/21784082/1970751) (differs in the way files are opened).*
Python has a module to [read](http://docs.python.org/3.3/library/csv.html?highlight=csv.writer#csv.reader) and [write](http://docs.python.org/3.3/library/cs... |
21,783,840 | I have a CSV file that has numerous data points included in each row, despite belonging to the same column. Something similar to this:
```
A, B, C, X, Y, Z
```
Now, what I would like to do is to reformat the file such that the resulting CSV is:
```
A, B, C
X, Y, Z
```
I'm not too sure how to go about this / expre... | 2014/02/14 | [
"https://Stackoverflow.com/questions/21783840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2179795/"
] | You could probably use python's [CSV module](http://docs.python.org/2/library/csv.html)
Example:
```
#!/usr/bin/env python
import csv
with open("input.csv", "r") as input_file, open("output.csv", "w+"):
input_csv, output_csv = csv.reader(input_file), csv.writer(output_file);
for row in input_csv:
out... | *This solution is for Python 3. For Python 2, see [Martijn Pieters's answer](https://stackoverflow.com/a/21784082/1970751) (differs in the way files are opened).*
Python has a module to [read](http://docs.python.org/3.3/library/csv.html?highlight=csv.writer#csv.reader) and [write](http://docs.python.org/3.3/library/cs... |
74,304,917 | I'm having trouble trying to find the parameters of a gaussian curve fit.
The site <https://mycurvefit.com/> provides a good answer fairly quickly. However, my implementation with python's curve\_fit(), from the scipy.optimize library, is not providing good results (even when inputting the answers).
For instance, the... | 2022/11/03 | [
"https://Stackoverflow.com/questions/74304917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14703689/"
] | One way to do it is using window functions. The first one ([**`lag`**](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.lag.html#pyspark.sql.functions.lag)) marks the row if it is different than the previous. The second ([**`sum`**](https://spark.apache.org/docs/latest/api... | Use window functions. get ranks per group of blocks and through away any rows that rank higher than 1. Code below
```
(df.withColumn('index', row_number().over(Window.partitionBy().orderBy('ID','Block')))#create an index to reorder after comps
.withColumn('BlockRank', rank().over(Window.partitionBy('Block').orderBy('... |
63,574,704 | I have the following `Dockerfile`:
```
# beginning of the the docker ...
ARG SIGNAL_ID
CMD python ./my_repo/my_main.py --signal_id $SIGNAL_ID
```
I also have a `docker-compose.yml` with all the needed information for the service
```
version: '3'
services:
my_app:
build: .
# additional info ...
```
How would... | 2020/08/25 | [
"https://Stackoverflow.com/questions/63574704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9253013/"
] | You can convert an integral value to its decimal representation with [`std::to_string`](https://en.cppreference.com/w/cpp/string/basic_string/to_string):
```
std::string const dec = std::to_string(num);
```
If you have a character array, say `char a[4]`, you can copy the data there element-wise:
```
for (std::size_... | a way is decomposing the number in hundred, tens and units... modulo can help and log10 will be useful too:
this is going to be a nice work around if you arent allowed to convert to string
here an example:
```
int value = 256;
int myArray[3];
auto m = static_cast<int>(ceil(log10(value)));
for(int i =0; i < m; ++i)
{... |
63,574,704 | I have the following `Dockerfile`:
```
# beginning of the the docker ...
ARG SIGNAL_ID
CMD python ./my_repo/my_main.py --signal_id $SIGNAL_ID
```
I also have a `docker-compose.yml` with all the needed information for the service
```
version: '3'
services:
my_app:
build: .
# additional info ...
```
How would... | 2020/08/25 | [
"https://Stackoverflow.com/questions/63574704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9253013/"
] | C++17 has [`std::to_chars`](https://en.cppreference.com/w/cpp/utility/to_chars) for this purpose:
```
char a[10];
if (auto const result = std::to_chars(a, a + sizeof a - 1, 256); result.ec != std::errc()) {
// An error occurred.
} else {
*result.ptr = '\0';
}
``` | a way is decomposing the number in hundred, tens and units... modulo can help and log10 will be useful too:
this is going to be a nice work around if you arent allowed to convert to string
here an example:
```
int value = 256;
int myArray[3];
auto m = static_cast<int>(ceil(log10(value)));
for(int i =0; i < m; ++i)
{... |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | you can do this, but it works backwards. you implement `__float__()` in your new type and then `sin()` will work with your class.
in other words, you don't adapt sine to work on other types; you adapt those types so that they work with sine.
this is better because it forces consistency. if there is no obvious mapping... | Typically the answer to questions like this is "you don't" or "use duck typing". Can you provide a little more detail about what you want to do? Have you looked at the remainder of the protocol methods for numeric types?
<http://docs.python.org/reference/datamodel.html#emulating-numeric-types> |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | If you want the return type of `math.sin()` to be your user-defined type, you appear to be out of luck. Python's `math` library is basically a thin wrapper around a fast native IEEE 754 floating point math library. If you want to be internally consistent and duck-typed, you can at least put the extensibility shim that ... | Typically the answer to questions like this is "you don't" or "use duck typing". Can you provide a little more detail about what you want to do? Have you looked at the remainder of the protocol methods for numeric types?
<http://docs.python.org/reference/datamodel.html#emulating-numeric-types> |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | Define your own versions in a module. This is what's done in cmath for complex number and in numpy for arrays. | Typically the answer to questions like this is "you don't" or "use duck typing". Can you provide a little more detail about what you want to do? Have you looked at the remainder of the protocol methods for numeric types?
<http://docs.python.org/reference/datamodel.html#emulating-numeric-types> |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | you can do this, but it works backwards. you implement `__float__()` in your new type and then `sin()` will work with your class.
in other words, you don't adapt sine to work on other types; you adapt those types so that they work with sine.
this is better because it forces consistency. if there is no obvious mapping... | Ideally, you will derive your user-defined numeric types from a native Python type, and the math functions will just work. When that isn't possible, perhaps you can define `__int__()` or `__float__()` or `__complex__()` or `__long__()` on the object so it knows how to convert itself to a type the math functions can han... |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | If you want the return type of `math.sin()` to be your user-defined type, you appear to be out of luck. Python's `math` library is basically a thin wrapper around a fast native IEEE 754 floating point math library. If you want to be internally consistent and duck-typed, you can at least put the extensibility shim that ... | Ideally, you will derive your user-defined numeric types from a native Python type, and the math functions will just work. When that isn't possible, perhaps you can define `__int__()` or `__float__()` or `__complex__()` or `__long__()` on the object so it knows how to convert itself to a type the math functions can han... |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | Define your own versions in a module. This is what's done in cmath for complex number and in numpy for arrays. | Ideally, you will derive your user-defined numeric types from a native Python type, and the math functions will just work. When that isn't possible, perhaps you can define `__int__()` or `__float__()` or `__complex__()` or `__long__()` on the object so it knows how to convert itself to a type the math functions can han... |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | you can do this, but it works backwards. you implement `__float__()` in your new type and then `sin()` will work with your class.
in other words, you don't adapt sine to work on other types; you adapt those types so that they work with sine.
this is better because it forces consistency. if there is no obvious mapping... | If you want the return type of `math.sin()` to be your user-defined type, you appear to be out of luck. Python's `math` library is basically a thin wrapper around a fast native IEEE 754 floating point math library. If you want to be internally consistent and duck-typed, you can at least put the extensibility shim that ... |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | you can do this, but it works backwards. you implement `__float__()` in your new type and then `sin()` will work with your class.
in other words, you don't adapt sine to work on other types; you adapt those types so that they work with sine.
this is better because it forces consistency. if there is no obvious mapping... | Define your own versions in a module. This is what's done in cmath for complex number and in numpy for arrays. |
7,151,776 | *Edit: Let me try to reword and improve my question. The old version is attached at the bottom.*
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
```
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
```
I... | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172531/"
] | If you want the return type of `math.sin()` to be your user-defined type, you appear to be out of luck. Python's `math` library is basically a thin wrapper around a fast native IEEE 754 floating point math library. If you want to be internally consistent and duck-typed, you can at least put the extensibility shim that ... | Define your own versions in a module. This is what's done in cmath for complex number and in numpy for arrays. |
66,583,626 | In plotly I can create a histogram as e.g. [in this example code from the documentation](https://plotly.com/python/histograms/):
```
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.show()
```
which results to:
[`, this:
[](https://i.stack.imgur.com/8ksQb.png)
And reading off the chart those values wo... | In the same Plotly Histogram documentation, there's a section called [Accessing the counts yaxis values](https://plotly.com/python/histograms/#accessing-the-counts-yaxis-values), and it explains that the y values are calculated by the JavaScript in the browser when the figure renders so you can't access it in the figur... |
66,583,626 | In plotly I can create a histogram as e.g. [in this example code from the documentation](https://plotly.com/python/histograms/):
```
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.show()
```
which results to:
[, and it explains that the y values are calculated by the JavaScript in the browser when the figure renders so you can't access it in the figur... | After making some proofs, I came to the conclusion that you can get histogram values in y axis by using groupby. You can generate your own dataframe with total\_bill values and count for each one of the values like this:
```
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.sho... |
66,583,626 | In plotly I can create a histogram as e.g. [in this example code from the documentation](https://plotly.com/python/histograms/):
```
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.show()
```
which results to:
[`, this:
[](https://i.stack.imgur.com/8ksQb.png)
And reading off the chart those values wo... | After making some proofs, I came to the conclusion that you can get histogram values in y axis by using groupby. You can generate your own dataframe with total\_bill values and count for each one of the values like this:
```
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.sho... |
14,251,877 | I worked out a code that make sense to me but not python since I'm new to python.
Check my code here:
```
checksum_algos = ['md5','sha1']
for filename in ["%smanifest-%s.txt" % (prefix for prefix in ['', 'tag'], a for a in checksum_algos)]:
f = os.path.join(self.path, filename)
if isfile(f):
yield f
```
... | 2013/01/10 | [
"https://Stackoverflow.com/questions/14251877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/921082/"
] | You're overthinking it.
```
for filename in ("%smanifest-%s.txt" % (prefix, a)
for prefix in ['', 'tag'] for a in checksum_algos):
``` | Or you need [`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product):
```
>>> import itertools
>>> [i for i in itertools.product(('', 'tag'), ('sha', 'md5'))]
[('', 'sha'), ('', 'md5'), ('tag', 'sha'), ('tag', 'md5')]
``` |
14,251,877 | I worked out a code that make sense to me but not python since I'm new to python.
Check my code here:
```
checksum_algos = ['md5','sha1']
for filename in ["%smanifest-%s.txt" % (prefix for prefix in ['', 'tag'], a for a in checksum_algos)]:
f = os.path.join(self.path, filename)
if isfile(f):
yield f
```
... | 2013/01/10 | [
"https://Stackoverflow.com/questions/14251877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/921082/"
] | You're overthinking it.
```
for filename in ("%smanifest-%s.txt" % (prefix, a)
for prefix in ['', 'tag'] for a in checksum_algos):
``` | Using new style string formatting and `itertools`:
```
from itertools import product
["{0}manifest-{1}.txt".format(i,e) for i,e in product(*(tags,checksum_algos))]
```
**out:**
```
['manifest-md5.txt',
'manifest-sha1.txt',
'tagmanifest-md5.txt',
'tagmanifest-sha1.txt']
``` |
62,601,766 | I am trying to use SIFT for feature detection with Python, but it is no longer part of OpenCV **or** OpenCV contrib.
With OpenCV opencv-contrib-python (both versions 4.2.0.34, the latest as of this question), I get:
```
>>> import cv2
>>> cv2.SIFT_create()
Traceback (most recent call last):
File "<stdin>", line 1, ... | 2020/06/26 | [
"https://Stackoverflow.com/questions/62601766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8605685/"
] | The patent for SIFT expired this Mar 2020. But the opencv might not be updated by moving the SIFT to free open source collection.
See this issue: <https://github.com/skvark/opencv-python/issues/126>
To rebuild with the non-free components:
```
git clone --recursive https://github.com/skvark/opencv-python.git
cd open... | From [the issue](https://github.com/skvark/opencv-python/issues/126):
to rebuild with the non-free components:
```
git clone --recursive https://github.com/skvark/opencv-python.git
cd opencv-python
export CMAKE_ARGS="-DOPENCV_ENABLE_NONFREE=ON"
python setup.py bdist_wheel
``` |
46,016,131 | ```
I have a list of tuples `data`:
data =[(array([[2, 1, 3]]), array([1])),
(array([[2, 1, 2]]), array([1])),
(array([[4, 4, 4]]), array([0])),
(array([[4, 1, 1]]), array([0])),
(array([[4, 4, 3]]), array([0]))]
```
For simplicity's sake, this list here only has 5 tuples.
When I run the following code, it seem... | 2017/09/02 | [
"https://Stackoverflow.com/questions/46016131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6802252/"
] | In the first two cases you're looping through `list`, in the last one you're accessing `tuple`
Not sure what you want to achieve, but instead of `data[0]`, `data[:1]` would work. | If your data looks like this:
```
data =[([[2, 1, 3]], [1]),
([[2, 1, 2]], [1]),
([[4, 4, 4]]), [0]),
([[4, 1, 1]], [0]),
([[4, 4, 3]], [0])]
for [a], b in data:
print a, b
```
Output:
```
[2, 1, 3] [1]
[2, 1, 2] [1]
[4, 4, 4] [0]
[4, 1, 1] [0]
[4, 4, 3] [0]
``` |
1,239,538 | I've been trying to use [suds](https://fedorahosted.org/suds/wiki) for Python to call a SOAP WSDL. I just need to call the service programmatically and write the output XML document. However suds automatically parses this data into it's own pythonic data format. I've been looking through [the examples](https://fedoraho... | 2009/08/06 | [
"https://Stackoverflow.com/questions/1239538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54283/"
] | At this early stage in suds development, the easiest way to get to the raw XML content is not what one would expect.
The examples on the site show us with something like this:
```
client = Client(url)
result = client.service.Invoke(subm)
```
however, the result is a pre-parsed object that is great for access by Pyt... | You could take a look at a library such as [soaplib](http://wiki.github.com/jkp/soaplib): its a really nice way to consume (and serve) SOAP webservices in Python. The latest version has some code to dynamically generate Python bindings either dynamically (at runtime) or statically (run a script against some WSDL).
[d... |
65,514,398 | I have a radar chart. Need to change the grid from circle-form to pentagon-form. Currently, I have this output:
[](https://i.stack.imgur.com/mDLeM.jpg)
Whereas I expect smth like this:
[. The working code for your example would be
```py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from ... |
6,259,623 | >
> **Possible Duplicate:**
>
> [How does Python compare string and int?](https://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int)
>
>
>
An intern was just asking me to help debug code that looked something like this:
```
widths = [image.width for image in images]
widths.append(374)... | 2011/06/07 | [
"https://Stackoverflow.com/questions/6259623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | Python 2.x compares *every* built-in type to every other. From the [docs](http://docs.python.org/library/stdtypes.html#comparisons):
>
> Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a ... | When comparing values of incompatible types in python 2.x, the ordering will be arbitrary but consistent. This is to allow you to put values of different types in a sorted collection.
In CPython 2.x any string will always be higher than any integer, but as I said that's arbitrary. The actual ordering does not matter, ... |
6,259,623 | >
> **Possible Duplicate:**
>
> [How does Python compare string and int?](https://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int)
>
>
>
An intern was just asking me to help debug code that looked something like this:
```
widths = [image.width for image in images]
widths.append(374)... | 2011/06/07 | [
"https://Stackoverflow.com/questions/6259623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | Python 2.x compares *every* built-in type to every other. From the [docs](http://docs.python.org/library/stdtypes.html#comparisons):
>
> Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a ... | From [the documentation](http://docs.python.org/reference/expressions.html#notin):
>
> Most other objects of built-in types
> compare unequal unless they are the
> same object; the choice whether one
> object is considered smaller or larger
> than another one is made arbitrarily
> but consistently within one exe... |
6,259,623 | >
> **Possible Duplicate:**
>
> [How does Python compare string and int?](https://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int)
>
>
>
An intern was just asking me to help debug code that looked something like this:
```
widths = [image.width for image in images]
widths.append(374)... | 2011/06/07 | [
"https://Stackoverflow.com/questions/6259623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | When comparing values of incompatible types in python 2.x, the ordering will be arbitrary but consistent. This is to allow you to put values of different types in a sorted collection.
In CPython 2.x any string will always be higher than any integer, but as I said that's arbitrary. The actual ordering does not matter, ... | From [the documentation](http://docs.python.org/reference/expressions.html#notin):
>
> Most other objects of built-in types
> compare unequal unless they are the
> same object; the choice whether one
> object is considered smaller or larger
> than another one is made arbitrarily
> but consistently within one exe... |
27,914,648 | I am using geopy to geocode some addresses and I want to catch the timeout errors and print them out so I can do some quality control on the input. I am putting the geocode request in a try/catch but it's not working. Any ideas on what I need to do?
Here is my code:
```
try:
location = geolocator.geocode(my_addres... | 2015/01/13 | [
"https://Stackoverflow.com/questions/27914648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860317/"
] | Try this:
```
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
my_address = '1600 Pennsylvania Avenue NW Washington, DC 20500'
geolocator = Nominatim()
try:
location = geolocator.geocode(my_address)
print(location.latitude, location.longitude)
except GeocoderTimedOut as e:
pri... | You may be experiencing this problem because you tried to request this address multiple times and they temporarily blocked you or slowed you down because of their [usage policy](https://operations.osmfoundation.org/policies/nominatim/). It states no more requests than one per second and that you should cache your resul... |
27,914,648 | I am using geopy to geocode some addresses and I want to catch the timeout errors and print them out so I can do some quality control on the input. I am putting the geocode request in a try/catch but it's not working. Any ideas on what I need to do?
Here is my code:
```
try:
location = geolocator.geocode(my_addres... | 2015/01/13 | [
"https://Stackoverflow.com/questions/27914648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860317/"
] | Try this:
```
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
my_address = '1600 Pennsylvania Avenue NW Washington, DC 20500'
geolocator = Nominatim()
try:
location = geolocator.geocode(my_address)
print(location.latitude, location.longitude)
except GeocoderTimedOut as e:
pri... | I dealt with the Same Problem for so many days this is my code:
```
geolocator = Nominatim(user_agent="ny_explorer")
location = geolocator.geocode(address_venue)
```
**ERROR**
Service timed out
solution: Add a new attribute that declares the timeout:
```
location = geolocator.geocode(address_venue,timeout=10000)
... |
51,963,377 | I am trying to write a discriminator that evaluates patches of an image.
Therefore I generate 32x32 non-overlapping patches from the input and then concatenate them on a new axis.
The reason I am using a time-distributed layer is that at the end, the discriminator should evaluate the whole image as true or fake. Thus,... | 2018/08/22 | [
"https://Stackoverflow.com/questions/51963377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4880918/"
] | You need to put your cropping operations in a function and then use that function in a `Lambda` layer:
```
def my_cropping(a):
cropping_list = []
n_patches = 256/32
for x in range(256//32):
for y in range(256//32):
cropping_list += [
K.expand_dims(
Croppin... | I ran into the same issue and it solved indeed by wrapping a Lambda layer around the tensor as @today proposed.
Thanks for that hint, it pointed me in the right direction. I wanted to turn a vector into a diagonal matrix to
I wanted to concatenate a vector with a square image and by turning the vector in a diag matr... |
820,671 | I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:
```
class MyClass( object ) :
m = None # my attribute
__slots__ = ( "m" ) # ensure that object has no _m etc
a = MyClass() # create one
a.m = "?... | 2009/05/04 | [
"https://Stackoverflow.com/questions/820671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69882/"
] | When you declare instance variables using `__slots__`, Python creates a [descriptor object](https://docs.python.org/2/howto/descriptor.html) as a class variable with the same name. In your case, this descriptor is overwritten by the class variable `m` that you are defining at the following line:
```
m = None # my at... | `__slots__` works with instance variables, whereas what you have there is a class variable. This is how you should be doing it:
```
class MyClass( object ) :
__slots__ = ( "m", )
def __init__(self):
self.m = None
a = MyClass()
a.m = "?" # No error
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.