qid
int64 469
74.7M
| question
stringlengths 36
37.8k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 5
31.5k
| response_k
stringlengths 10
31.6k
|
---|---|---|---|---|---|
41,850,558 | I have a model called "document-detail-sample" and when you call it with a GET, something like this, **GET** `https://url/document-detail-sample/` then you get every "document-detail-sample".
Inside the model is the id. So, if you want every Id, you could just "iterate" on the list and ask for the id. Easy.
But... the front-end Developers don't want to do it :D they say it's too much work...
So, I gotta return the id list. :D
I was thinking something like **GET** `https://url/document-detail-sample/id-list`
But I don't know how to return just a list. I read [this post](https://stackoverflow.com/questions/27647871/django-python-how-to-get-a-list-of-ids-from-a-list-of-objects) and I know how to get the id\_list in the backend. But I don't know what should I implement to just return a list in that url...
the view that I have it's pretty easy:
```
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
```
and the url is so:
```
router.register(r'document-detail-sample', DocumentDetailSampleViewSet)
```
so:
**1**- is a good Idea do it with an url like `.../document-detail-sample/id-list"` ?
**2**- if yes, how can I do it?
**3**- if not, what should I do then? | 2017/01/25 | [
"https://Stackoverflow.com/questions/41850558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050960/"
] | You could use `@list_route` decorator
```
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
@list_route()
def id_list(self, request):
q = self.get_queryset().values('id')
return Response(list(q))
```
This decorator allows you provide additional endpoint with the same name as a method. `/document-detail-sample/id_list/`
[reference to docs about extra actions in a viewset](http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing) | Assuming you don't need pagination, just override the `list` method like so
```
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
def list(self, request):
return Response(self.get_queryset().values_list("id", flat=True))
``` |
14,585,722 | Suppose you have a python function, as so:
```
def foo(spam, eggs, ham):
pass
```
You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`).
Is it possible to get the same kind of functionality with argparse? I have a couple of positional arguments with keywords, and I don't want to define all of them when using just one. | 2013/01/29 | [
"https://Stackoverflow.com/questions/14585722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731881/"
] | You can do something like this:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--foo',dest='foo',default=None)
parser.add_argument('bar',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--bar',dest='bar',default=None)
parser.add_argument('baz',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--baz',dest='baz',default=None)
print parser.parse_args()
```
which works mostly as you describe:
```
temp $ python test.py 1 2 --baz=3
Namespace(bar='2', baz='3', foo='1')
temp $ python test.py --baz=3
Namespace(bar=None, baz='3', foo=None)
temp $ python test.py --foo=2 --baz=3
Namespace(bar=None, baz='3', foo='2')
temp $ python test.py 1 2 3
Namespace(bar='2', baz='3', foo='1')
```
python would give you an error for the next one in the function call analogy, but argparse will allow it:
```
temp $ python test.py 1 2 3 --foo=27.5
Namespace(bar='2', baz='3', foo='27.5')
```
You could probably work around that by using [mutually exclusive groupings](http://docs.python.org/2.7/library/argparse.html#mutual-exclusion) | I believe this is what you are looking for [Argparse defaults](http://docs.python.org/dev/library/argparse.html#default) |
14,585,722 | Suppose you have a python function, as so:
```
def foo(spam, eggs, ham):
pass
```
You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`).
Is it possible to get the same kind of functionality with argparse? I have a couple of positional arguments with keywords, and I don't want to define all of them when using just one. | 2013/01/29 | [
"https://Stackoverflow.com/questions/14585722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731881/"
] | You can also use this module: [docopt](https://github.com/docopt/docopt) | I believe this is what you are looking for [Argparse defaults](http://docs.python.org/dev/library/argparse.html#default) |
14,585,722 | Suppose you have a python function, as so:
```
def foo(spam, eggs, ham):
pass
```
You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`).
Is it possible to get the same kind of functionality with argparse? I have a couple of positional arguments with keywords, and I don't want to define all of them when using just one. | 2013/01/29 | [
"https://Stackoverflow.com/questions/14585722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731881/"
] | You can do something like this:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--foo',dest='foo',default=None)
parser.add_argument('bar',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--bar',dest='bar',default=None)
parser.add_argument('baz',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--baz',dest='baz',default=None)
print parser.parse_args()
```
which works mostly as you describe:
```
temp $ python test.py 1 2 --baz=3
Namespace(bar='2', baz='3', foo='1')
temp $ python test.py --baz=3
Namespace(bar=None, baz='3', foo=None)
temp $ python test.py --foo=2 --baz=3
Namespace(bar=None, baz='3', foo='2')
temp $ python test.py 1 2 3
Namespace(bar='2', baz='3', foo='1')
```
python would give you an error for the next one in the function call analogy, but argparse will allow it:
```
temp $ python test.py 1 2 3 --foo=27.5
Namespace(bar='2', baz='3', foo='27.5')
```
You could probably work around that by using [mutually exclusive groupings](http://docs.python.org/2.7/library/argparse.html#mutual-exclusion) | You can also use this module: [docopt](https://github.com/docopt/docopt) |
72,950,868 | I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis.
For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park".
I found a similar question and solution but it is in Python ([How to add a missing closing parenthesis to a string in Python?](https://stackoverflow.com/questions/67400960/how-to-add-a-missing-closing-parenthesis-to-a-string-in-python)). I have tried to modify the code to be used in R but to no avail. Can someone help me with this please?
I have tried modifying the original python solution as R doesn't recognise the "r" and "\" has been replaced by "\\" but this solution doesn't work properly and does not capture the string preceded before the bracket I would like to add:
```
text = "The dog walked (ABC in the park"
str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\)')
text
```
The python solution that works is as follows:
```
text = "The dog walked (ABC in the park"
text = re.sub(r'(\([A-Z]+(?!\))\b)', r"\1)", text)
print(text)
``` | 2022/07/12 | [
"https://Stackoverflow.com/questions/72950868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533566/"
] | Try this
```
stringr::str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\0\\)')
```
* output
```
"The dog walked (ABC) in the park"
``` | Not a one liner, but it does the trick and is (hopefully!) intuitive.
```
library(stringr)
add_brackets = function(text) {
brackets = str_extract(text, "\\([:alpha:]+") # finds the open bracket and any following letters
brackets_new = paste0(brackets, ")") # adds in the closing brackets
str_replace(text, paste0("\\", brackets), brackets_new) # replaces the unclosed string with the closed one
}
```
```
> add_brackets(text)
[1] "The dog walked (ABC) in the park"
``` |
72,950,868 | I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis.
For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park".
I found a similar question and solution but it is in Python ([How to add a missing closing parenthesis to a string in Python?](https://stackoverflow.com/questions/67400960/how-to-add-a-missing-closing-parenthesis-to-a-string-in-python)). I have tried to modify the code to be used in R but to no avail. Can someone help me with this please?
I have tried modifying the original python solution as R doesn't recognise the "r" and "\" has been replaced by "\\" but this solution doesn't work properly and does not capture the string preceded before the bracket I would like to add:
```
text = "The dog walked (ABC in the park"
str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\)')
text
```
The python solution that works is as follows:
```
text = "The dog walked (ABC in the park"
text = re.sub(r'(\([A-Z]+(?!\))\b)', r"\1)", text)
print(text)
``` | 2022/07/12 | [
"https://Stackoverflow.com/questions/72950868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533566/"
] | Try this
```
stringr::str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\0\\)')
```
* output
```
"The dog walked (ABC) in the park"
``` | You might also use gsub, and first use the word boundary and then the negative lookahead.
In the replacement use the first capture group followed by `)`
```
text = "The dog walked (ABC in the park"
gsub('(\\([A-Z]+)\\b(?!\\))', '\\1\\)', text, perl=T)
```
Output
```
[1] "The dog walked (ABC) in the park"
``` |
72,950,868 | I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis.
For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park".
I found a similar question and solution but it is in Python ([How to add a missing closing parenthesis to a string in Python?](https://stackoverflow.com/questions/67400960/how-to-add-a-missing-closing-parenthesis-to-a-string-in-python)). I have tried to modify the code to be used in R but to no avail. Can someone help me with this please?
I have tried modifying the original python solution as R doesn't recognise the "r" and "\" has been replaced by "\\" but this solution doesn't work properly and does not capture the string preceded before the bracket I would like to add:
```
text = "The dog walked (ABC in the park"
str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\)')
text
```
The python solution that works is as follows:
```
text = "The dog walked (ABC in the park"
text = re.sub(r'(\([A-Z]+(?!\))\b)', r"\1)", text)
print(text)
``` | 2022/07/12 | [
"https://Stackoverflow.com/questions/72950868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533566/"
] | You might also use gsub, and first use the word boundary and then the negative lookahead.
In the replacement use the first capture group followed by `)`
```
text = "The dog walked (ABC in the park"
gsub('(\\([A-Z]+)\\b(?!\\))', '\\1\\)', text, perl=T)
```
Output
```
[1] "The dog walked (ABC) in the park"
``` | Not a one liner, but it does the trick and is (hopefully!) intuitive.
```
library(stringr)
add_brackets = function(text) {
brackets = str_extract(text, "\\([:alpha:]+") # finds the open bracket and any following letters
brackets_new = paste0(brackets, ")") # adds in the closing brackets
str_replace(text, paste0("\\", brackets), brackets_new) # replaces the unclosed string with the closed one
}
```
```
> add_brackets(text)
[1] "The dog walked (ABC) in the park"
``` |
67,609,973 | I chose to use Python 3.8.1 Azure ML in Azure Machine learning studio, but when i run the command
`!python train.py`, it uses python Anconda 3.6.9, when i downloaded python 3.8 and run the command `!python38 train.py` in the same dir as before, the response was `python3.8: can't open file` .
Any idea?
Also Python 3 in azure, is always busy, without anything running from my side.
Thank you. | 2021/05/19 | [
"https://Stackoverflow.com/questions/67609973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14915505/"
] | You should try adding a new Python 3.8 Kernel. Here and instructions how to add a new Kernel: <https://learn.microsoft.com/en-us/azure/machine-learning/how-to-access-terminal#add-new-kernels> | Yeah I understand your pain point, and I agree that calling bash commands in a notebook cell should execute in the same conda environment as the one associated with the selected kernel of the notebook. I think this is bug, I'll flag it to the notebook feature team, but I encourage you to open a priority support ticket if you want to ensure that your problem is addressed! |
58,483,706 | I am new to python and trying my hands on certain problems. I have a situation where I have 2 dataframe which I want to combine to achieve my desired dataframe.
I have tried .merge and .join, both of which was not able to get my desired outbcome.
let us suppose I have the below scenario:
```
lt = list(['a','b','c','d','a','b','a','b'])
df = pd.DataFrame(columns = lt)
data = [[10,11,12,12], [15,14,12,10]]
df1 = pd.DataFrame(data, columns = ['a','b','c','d'])
```
I want df and df1 to be combined and get desired dataframe as df2 as:
```
a b c d a b a b
0 10 11 12 12 10 11 10 11
1 15 14 12 10 15 14 15 14
``` | 2019/10/21 | [
"https://Stackoverflow.com/questions/58483706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11378087/"
] | If you don't mind the order of the columns changing, this is just a right join. The only caveat is that those are performed on rows rather than columns, so you need to transpose first:
```py
In [44]: df.T.join(df1.T, how='right').T
Out[44]:
a a a b b b c d
0 10 10 10 11 11 11 12 12
1 15 15 15 14 14 14 12 10
``` | Use [`concat()`](https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html)
```py
pd.concat([df, df1], axis=0, join='inner', sort=False)
a b c d a b a b
0 10 11 12 12 10 11 10 11
1 15 14 12 10 15 14 15 14
``` |
58,483,706 | I am new to python and trying my hands on certain problems. I have a situation where I have 2 dataframe which I want to combine to achieve my desired dataframe.
I have tried .merge and .join, both of which was not able to get my desired outbcome.
let us suppose I have the below scenario:
```
lt = list(['a','b','c','d','a','b','a','b'])
df = pd.DataFrame(columns = lt)
data = [[10,11,12,12], [15,14,12,10]]
df1 = pd.DataFrame(data, columns = ['a','b','c','d'])
```
I want df and df1 to be combined and get desired dataframe as df2 as:
```
a b c d a b a b
0 10 11 12 12 10 11 10 11
1 15 14 12 10 15 14 15 14
``` | 2019/10/21 | [
"https://Stackoverflow.com/questions/58483706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11378087/"
] | What you can do is to use the columns of `df` and select the corresponding columns in `df1`, like so:
```py
lt = list(['a','b','c','d','a','b','a','b'])
df = pd.DataFrame(columns = lt)
data = [[10,11,12,12], [15,14,12,10]]
df1 = pd.DataFrame(data, columns = ['a','b','c','d'])
df2 = df1[df.columns]
print(df2)
```
prints:
```
a b c d a b a b
0 10 11 12 12 10 11 10 11
1 15 14 12 10 15 14 15 14
``` | Use [`concat()`](https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html)
```py
pd.concat([df, df1], axis=0, join='inner', sort=False)
a b c d a b a b
0 10 11 12 12 10 11 10 11
1 15 14 12 10 15 14 15 14
``` |
14,187,973 | Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static))
Lets concider following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
```
In Python 3 there is no `instancemethod` anymore, everything is function, so the answer related to Python 2 will not work anymore.
As I told, everything is function, so we can call `A.f(0)`, but of course we cannot call `A.f()` (argument missmatch). But if we make an instance `a=A()` and we call `a.f()` Python passes to the function `A.f` the `self` as first argument. Calling `a.g()` prevents from sending it or captures the `self` - so there have to be a way to test if this is staticmethod or not.
So can we check in Python3 if a method was declared as `static` or not? | 2013/01/06 | [
"https://Stackoverflow.com/questions/14187973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889902/"
] | ```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
print(type(A.__dict__['g']))
print(type(A.g))
<class 'staticmethod'>
<class 'function'>
``` | I needed this solution and wrote the following based on the answer from @root
```
def is_method_static(cls, method_name):
# http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static
for c in cls.mro():
if method_name in c.__dict__:
return isinstance(c.__dict__[method_name], staticmethod)
raise RuntimeError("Unable to find %s in %s" % (method_name, cls.__name__))
``` |
14,187,973 | Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static))
Lets concider following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
```
In Python 3 there is no `instancemethod` anymore, everything is function, so the answer related to Python 2 will not work anymore.
As I told, everything is function, so we can call `A.f(0)`, but of course we cannot call `A.f()` (argument missmatch). But if we make an instance `a=A()` and we call `a.f()` Python passes to the function `A.f` the `self` as first argument. Calling `a.g()` prevents from sending it or captures the `self` - so there have to be a way to test if this is staticmethod or not.
So can we check in Python3 if a method was declared as `static` or not? | 2013/01/06 | [
"https://Stackoverflow.com/questions/14187973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889902/"
] | ```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
print(type(A.__dict__['g']))
print(type(A.g))
<class 'staticmethod'>
<class 'function'>
``` | For Python 3.2 or newer, use [`inspect.getattr_static()`](https://docs.python.org/3/library/inspect.html#inspect.getattr_static) to retrieve the attribute without invoking the descriptor protocol:
>
> Retrieve attributes without triggering dynamic lookup via the descriptor protocol, `__getattr__()` or `__getattribute__()`.
>
>
>
Use `isinstance(..., staticmethod)` on the result:
```
>>> from inspect import getattr_static
>>> isinstance(getattr_static(A, 'g'), staticmethod)
True
```
The function can handle both instances and classes, and will scan the full class hierarchy for you:
```
>>> class B(A): pass
...
>>> isinstance(getattr_static(B, 'g'), staticmethod) # inherited
True
>>> isinstance(getattr_static(B(), 'g'), staticmethod) # instance, inherited
True
``` |
14,187,973 | Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static))
Lets concider following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
```
In Python 3 there is no `instancemethod` anymore, everything is function, so the answer related to Python 2 will not work anymore.
As I told, everything is function, so we can call `A.f(0)`, but of course we cannot call `A.f()` (argument missmatch). But if we make an instance `a=A()` and we call `a.f()` Python passes to the function `A.f` the `self` as first argument. Calling `a.g()` prevents from sending it or captures the `self` - so there have to be a way to test if this is staticmethod or not.
So can we check in Python3 if a method was declared as `static` or not? | 2013/01/06 | [
"https://Stackoverflow.com/questions/14187973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889902/"
] | For Python 3.2 or newer, use [`inspect.getattr_static()`](https://docs.python.org/3/library/inspect.html#inspect.getattr_static) to retrieve the attribute without invoking the descriptor protocol:
>
> Retrieve attributes without triggering dynamic lookup via the descriptor protocol, `__getattr__()` or `__getattribute__()`.
>
>
>
Use `isinstance(..., staticmethod)` on the result:
```
>>> from inspect import getattr_static
>>> isinstance(getattr_static(A, 'g'), staticmethod)
True
```
The function can handle both instances and classes, and will scan the full class hierarchy for you:
```
>>> class B(A): pass
...
>>> isinstance(getattr_static(B, 'g'), staticmethod) # inherited
True
>>> isinstance(getattr_static(B(), 'g'), staticmethod) # instance, inherited
True
``` | I needed this solution and wrote the following based on the answer from @root
```
def is_method_static(cls, method_name):
# http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static
for c in cls.mro():
if method_name in c.__dict__:
return isinstance(c.__dict__[method_name], staticmethod)
raise RuntimeError("Unable to find %s in %s" % (method_name, cls.__name__))
``` |
46,132,431 | I have written code to generate numbers from 0500000000 to 0500000100:
```
def generator(nums):
count = 0
while count < 100:
gg=print('05',count, sep='')
count += 1
g = generator(10)
```
as I use linux, I thought I may be able to use this command `python pythonfilename.py >> file.txt`
Yet, I get an error.
So, before `g = generator(10)` I added:
```
with open('file.txt', 'w') as f:
f.write(gg)
f.close()
```
but I got an error:
>
> TypeError: write() argument must be str, not None
>
>
>
Any solution? | 2017/09/09 | [
"https://Stackoverflow.com/questions/46132431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548783/"
] | Here I've assumed we're laying out two general images, rather than plots. If your images are actually plots you've created, then you can lay them out as a single image for display using `gridExtra::grid.arrange` for grid graphics or `par(mfrow=c(1,2))` for base graphics and thereby avoid the complications of laying out two separate images.
I'm not sure if there's a "natural" way to left justify the left-hand image and right-justify the right-hand image. As a hack, you could add a blank "spacer" image to separate the two "real" images and set the widths of each image to match paper-width minus 2\*margin-width.
Here's an example where the paper is assumed to be 8.5" wide and the right and left margins are each 1":
```
---
output: pdf_document
geometry: margin=1in
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(ggplot2)
library(knitr)
# Create a blank image to use for spacing
spacer = ggplot() + theme_void() + ggsave("spacer.png")
```
```{r, out.width=c('2.75in','1in','2.75in')}
include_graphics(c("Rplot59.png","spacer.png", "Rplot60.png"))
```
```
And here's what the document looks like:
[![enter image description here](https://i.stack.imgur.com/jiqHx.png)](https://i.stack.imgur.com/jiqHx.png) | Put them in the same code chunk and do not use align. Let them use html.
THis has worked for me.
```
````{r echo=FALSE, fig.height=3.0, fig.width=3.0}
#type your code here
ggplot(anscombe, aes(x=x1 , y=y1)) + geom_point()
+geom_smooth(method="lm") +
ggtitle("Results for x1 and y1 ")
ggplot(anscombe, aes(x=x2 , y=y2)) + geom_point() +geom_smooth(method="lm") +
ggtitle("Results for x2 and y2 ")
ggplot(anscombe, aes(x=x3 , y=y3)) + geom_point() +geom_smooth(method="lm") +
ggtitle("Results for x3 and y3 ")
ggplot(anscombe, aes(x=x4 , y=y4)) + geom_point() +geom_smooth(method="lm") +
ggtitle("Results for x4 and y4 ")
````
``` |
54,007,542 | input is like:
```
text="""Hi Team from the following Server :
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the following Project Areas :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:1436pt">
<tbody>
<tr>
<td style="height:15.0pt; width:505pt">UNIT TEST - IBM OPAL 3.3 RC3</td>
<td style="width:328pt">https://ratsuite.sby.ibm.com:9460/ccm</td>
<td style="width:603pt">https://ratsuite.sby.ibm.com:9460/ccm/process/project-areas/_ckR-QJiUEeOXmZKjKhPE4Q</td>
</tr>
</tbody>
</table>"""
```
In output i want these 2 lines only, want to remove table tag with data in python:
Hi Team from the following Server :
Please archive the following Project Areas : | 2019/01/02 | [
"https://Stackoverflow.com/questions/54007542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9901523/"
] | Use `BeautifulSoup` to parse HTML
**Ex:**
```
from bs4 import BeautifulSoup
text="""<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the following Project Areas :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:1436pt">
<tbody>
<tr>
<td style="height:15.0pt; width:505pt">UNIT TEST - IBM OPAL 3.3 RC3</td>
<td style="width:328pt">https://ratsuite.sby.ibm.com:9460/ccm</td>
<td style="width:603pt">https://ratsuite.sby.ibm.com:9460/ccm/process/project-areas/_ckR-QJiUEeOXmZKjKhPE4Q</td>
</tr>
</tbody>
</table>"""
soup = BeautifulSoup(text, "html.parser")
for p in soup.find_all("p"):
print(p.text)
```
**Output:**
```
Hi Team from the following Server :
Please archive the following Project Areas :
``` | You can use `HTMLParser` as demonstrated below:
```
from HTMLParser import HTMLParser
s = \
"""
<html>
<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the following Project Areas :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:1436pt">
<tbody>
<tr>
<td style="height:15.0pt; width:505pt">UNIT TEST - IBM OPAL 3.3 RC3</td>
<td style="width:328pt">https://ratsuite.sby.ibm.com:9460/ccm</td>
<td style="width:603pt">https://ratsuite.sby.ibm.com:9460/ccm/process/project-areas/_ckR-QJiUEeOXmZKjKhPE4Q</td>
</tr>
</tbody>
</table>
</html>
"""
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self._last_tag = ''
def handle_starttag(self, tag, attrs):
#print "Encountered a start tag:", tag
self._last_tag = tag
def handle_endtag(self, tag):
#print "Encountered an end tag :", tag
self._last_tag = ''
def handle_data(self, data):
#print "Encountered some data :", data
if self._last_tag == 'p':
print("<%s> tag data: %s" % (self._last_tag, data))
# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed(s)
```
Output:
```
<p> tag data: Hi Team from the following Server :
<p> tag data: Please archive the following Project Areas :
``` |
54,007,542 | input is like:
```
text="""Hi Team from the following Server :
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the following Project Areas :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:1436pt">
<tbody>
<tr>
<td style="height:15.0pt; width:505pt">UNIT TEST - IBM OPAL 3.3 RC3</td>
<td style="width:328pt">https://ratsuite.sby.ibm.com:9460/ccm</td>
<td style="width:603pt">https://ratsuite.sby.ibm.com:9460/ccm/process/project-areas/_ckR-QJiUEeOXmZKjKhPE4Q</td>
</tr>
</tbody>
</table>"""
```
In output i want these 2 lines only, want to remove table tag with data in python:
Hi Team from the following Server :
Please archive the following Project Areas : | 2019/01/02 | [
"https://Stackoverflow.com/questions/54007542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9901523/"
] | Use `BeautifulSoup` to parse HTML
**Ex:**
```
from bs4 import BeautifulSoup
text="""<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the following Project Areas :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:1436pt">
<tbody>
<tr>
<td style="height:15.0pt; width:505pt">UNIT TEST - IBM OPAL 3.3 RC3</td>
<td style="width:328pt">https://ratsuite.sby.ibm.com:9460/ccm</td>
<td style="width:603pt">https://ratsuite.sby.ibm.com:9460/ccm/process/project-areas/_ckR-QJiUEeOXmZKjKhPE4Q</td>
</tr>
</tbody>
</table>"""
soup = BeautifulSoup(text, "html.parser")
for p in soup.find_all("p"):
print(p.text)
```
**Output:**
```
Hi Team from the following Server :
Please archive the following Project Areas :
``` | If you do not want to use external library, you can use `re` module to remove tables:
```
output = re.sub('<table.+?</table>','',text,flags=re.DOTALL)
```
printing output give:
```
Hi Team from the following Server :
<p> </p>
<p>Please archive the following Project Areas :</p>
```
(and 2 empty lines which are not visible there).
Regarding pattern notice that `+` is followed by `?` meaning use non-greedy matching - otherwise it would purge anything between begin of first table and end of last table. `re.DOTALL` is required, because our substrings contain newlines (`\n`) |
54,007,542 | input is like:
```
text="""Hi Team from the following Server :
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the following Project Areas :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:1436pt">
<tbody>
<tr>
<td style="height:15.0pt; width:505pt">UNIT TEST - IBM OPAL 3.3 RC3</td>
<td style="width:328pt">https://ratsuite.sby.ibm.com:9460/ccm</td>
<td style="width:603pt">https://ratsuite.sby.ibm.com:9460/ccm/process/project-areas/_ckR-QJiUEeOXmZKjKhPE4Q</td>
</tr>
</tbody>
</table>"""
```
In output i want these 2 lines only, want to remove table tag with data in python:
Hi Team from the following Server :
Please archive the following Project Areas : | 2019/01/02 | [
"https://Stackoverflow.com/questions/54007542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9901523/"
] | If you do not want to use external library, you can use `re` module to remove tables:
```
output = re.sub('<table.+?</table>','',text,flags=re.DOTALL)
```
printing output give:
```
Hi Team from the following Server :
<p> </p>
<p>Please archive the following Project Areas :</p>
```
(and 2 empty lines which are not visible there).
Regarding pattern notice that `+` is followed by `?` meaning use non-greedy matching - otherwise it would purge anything between begin of first table and end of last table. `re.DOTALL` is required, because our substrings contain newlines (`\n`) | You can use `HTMLParser` as demonstrated below:
```
from HTMLParser import HTMLParser
s = \
"""
<html>
<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the following Project Areas :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:1436pt">
<tbody>
<tr>
<td style="height:15.0pt; width:505pt">UNIT TEST - IBM OPAL 3.3 RC3</td>
<td style="width:328pt">https://ratsuite.sby.ibm.com:9460/ccm</td>
<td style="width:603pt">https://ratsuite.sby.ibm.com:9460/ccm/process/project-areas/_ckR-QJiUEeOXmZKjKhPE4Q</td>
</tr>
</tbody>
</table>
</html>
"""
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self._last_tag = ''
def handle_starttag(self, tag, attrs):
#print "Encountered a start tag:", tag
self._last_tag = tag
def handle_endtag(self, tag):
#print "Encountered an end tag :", tag
self._last_tag = ''
def handle_data(self, data):
#print "Encountered some data :", data
if self._last_tag == 'p':
print("<%s> tag data: %s" % (self._last_tag, data))
# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed(s)
```
Output:
```
<p> tag data: Hi Team from the following Server :
<p> tag data: Please archive the following Project Areas :
``` |
38,776,104 | I would like to redirect the standard error and standard output of a Python script to the same output file. From the terminal I could use
```
$ python myfile.py &> out.txt
```
to do the same task that I want, but I need to do it from the Python script itself.
I looked into the questions [Redirect subprocess stderr to stdout](https://stackoverflow.com/questions/11495783/redirect-subprocess-stderr-to-stdout), [How to redirect stderr in Python?](https://stackoverflow.com/questions/1956142/how-to-redirect-stderr-in-python), and Example 10.10 from [here](http://www.diveintopython.net/scripts_and_streams/stdin_stdout_stderr.html), and then I tried the following:
```
import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a"
```
which rightly prints the letter "a" in the file out.txt; however, when I try the following:
```
import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a # missing end quote, will give error
```
I get the error message "SyntaxError ..." on the terminal, but not in the file out.txt. What do I need to do to send the SyntaxError to the file out.txt? I do not want to write an Exception, because in that case I have to write too many Exceptions in the script. I am using Python 2.7.
Update: As pointed out in the answers and comments below, that SyntaxError will always output to screen, I replaced the line
```
print "a # missing end quote, will give error
```
by
```
print 1/0 # Zero division error
```
The ZeroDivisionError is output to file, as I wanted to have it in my question. | 2016/08/04 | [
"https://Stackoverflow.com/questions/38776104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461999/"
] | This works
```
sys.stdout = open('out.log', 'w')
sys.stderr = sys.stdout
``` | A SyntaxError in a Python file like the above is raised before your program even begins to run:
Python files are compiled just like in any other compiled language - if the parser or compiler can't find sense in your Python file, no executable bytecode is generated, therefore the program does not run.
The correct way to have an exception generated on purpose in your code - from simple test cases like yours, up to implementing complex flow control patterns, is to use the Pyton command `raise`.
Just leave your print there, and a line like this at the end:
```
raise Exception
```
Then you can see that your trick will work.
Your program could fail in runtime in many other ways without an explict raise, like, if you force a division by 0, or simply try to use an unassigned (and therefore "undeclared") variable - but a deliberate SyntaxError will have the effect that the program never runs to start with - not even the first few lines. |
57,843,695 | I haven't changed my system configuration, But I'm spotting this error for the first time today.
I've reported it here: <https://github.com/jupyter/notebook/issues/4871>
```
> jupyter notebook
[I 10:44:20.102 NotebookApp] JupyterLab extension loaded from /usr/local/anaconda3/lib/python3.7/site-packages/jupyterlab
[I 10:44:20.102 NotebookApp] JupyterLab application directory is /usr/local/anaconda3/share/jupyter/lab
[I 10:44:20.104 NotebookApp] Serving notebooks from local directory: /Users/pi
[I 10:44:20.104 NotebookApp] The Jupyter Notebook is running at:
[I 10:44:20.104 NotebookApp] http://localhost:8888/?token=586797fb9049c0faea24f2583c4de32c08d45c89051fb07d
[I 10:44:20.104 NotebookApp] or http://127.0.0.1:8888/?token=586797fb9049c0faea24f2583c4de32c08d45c89051fb07d
[I 10:44:20.104 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 10:44:20.110 NotebookApp]
To access the notebook, open this file in a browser:
file:///Users/pi/Library/Jupyter/runtime/nbserver-65385-open.html
Or copy and paste one of these URLs:
http://localhost:8888/?token=586797fb9049c0faea24f2583c4de32c08d45c89051fb07d
or http://127.0.0.1:8888/?token=586797fb9049c0faea24f2583c4de32c08d45c89051fb07d
[E 10:44:21.457 NotebookApp] Could not open static file ''
[W 10:44:21.512 NotebookApp] 404 GET /static/components/react/react-dom.production.min.js (::1) 9.02ms referer=http://localhost:8888/tree?token=BLA
[W 10:44:21.548 NotebookApp] 404 GET /static/components/react/react-dom.production.min.js (::1) 0.99ms referer=http://localhost:8888/tree?token=BLA
Set
```
Looks like this issue was fixed in `Jupyter 6.0.1`
So the question becomes: can I force-install `jupyter 6.0.1`?
As the initial question has now provoked a second question, I now ask this new question here: [How to force `conda` to install the latest version of `jupyter`?](https://stackoverflow.com/questions/57843733/how-to-force-conda-to-install-the-latest-version-of-jupyter)
Alternatively I can manually provide the missing file, but I'm not sure *where*. I've asked here: [Where does Jupyter install site-packages on macOS?](https://stackoverflow.com/questions/57843888/where-does-jupyter-install-site-packages-on-macos)
Research:
=========
<https://github.com/jupyter/notebook/pull/4772> *"add missing react-dom js to package data #4772"* on 6 Aug 2019
>
> minrk added this to the 6.0.1 milestone on 18 Jul
>
>
>
Ok, so can I get Jupyter Notebook 6.0.1?
`brew cask install anaconda` downloads `~/Library/Caches/Homebrew/downloads/{LONG HEX}--Anaconda3-2019.07-MacOSX-x86_64` which is July, and `conda --version` reports `conda 4.7.10`. But this is for `Anaconda` which is the Package *Manager*.
```
> conda list | grep jupy
jupyter 1.0.0 py37_7
jupyter_client 5.3.1 py_0
jupyter_console 6.0.0 py37_0
jupyter_core 4.5.0 py_0
jupyterlab 1.0.2 py37hf63ae98_0
jupyterlab_server 1.0.0 py_0
```
So that's a bit confusing. No `jupyter notebook` here.
```
> which jupyter
/usr/local/anaconda3/bin/jupyter
> jupyter --version
jupyter core : 4.5.0
jupyter-notebook : 6.0.0
qtconsole : 4.5.1
ipython : 7.6.1
ipykernel : 5.1.1
jupyter client : 5.3.1
jupyter lab : 1.0.2
nbconvert : 5.5.0
ipywidgets : 7.5.0
nbformat : 4.4.0
traitlets : 4.3.2
```
Ok, so it appears `jupyter-notebook` is in `jupyter` which is maintained by Anaconda.
Can we update this?
<https://jupyter.readthedocs.io/en/latest/projects/upgrade-notebook.html>
```
> conda update jupyter
:
```
Alas `jupyter --version` is still `6.0.0` | 2019/09/08 | [
"https://Stackoverflow.com/questions/57843695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/435129/"
] | I fixed this by updating both jupyter on pip and pip3 (just to be safe) and this fixed the problem
using both
>
> `pip install --upgrade jupyter`
>
>
>
and
>
> `pip3 install --upgrade jupyter --no-cache-dir`
>
>
>
I believe you can do this in the terminal as well as in conda's terminal (since conda envs also have pip) | As per [Where does Jupyter install site-packages on macOS?](https://stackoverflow.com/questions/57843888/where-does-jupyter-install-site-packages-on-macos), I locate where on my system `jupyter` is searching for this missing file:
```
> find / -path '*/static/components' 2>/dev/null
/usr/local/anaconda3/pkgs/notebook-6.0.0-py37_0/lib/python3.7/site-packages/notebook/static/components
/usr/local/anaconda3/lib/python3.7/site-packages/notebook/static/components
```
And as per <https://github.com/jupyter/notebook/pull/4772#issuecomment-515794823>, if I download that file and deposit it in the second location, i.e. creating:
```
/usr/local/anaconda3/lib/python3.7/site-packages/notebook/static/components/react/react-dom.production.min.js
```
... now `jupyter notebook` launches without errors.
(*NOTE: Being cautious I have also copied it into the first location. But that doesn't seem to have any effect.*) |
44,175,800 | Simple question: given a string
```
string = "Word1 Word2 Word3 ... WordN"
```
is there a pythonic way to do this?
```
firstWord = string.split(" ")[0]
otherWords = string.split(" ")[1:]
```
Like an unpacking or something?
Thank you | 2017/05/25 | [
"https://Stackoverflow.com/questions/44175800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131783/"
] | Since Python 3 and [PEP 3132](https://www.python.org/dev/peps/pep-3132/), you can use extended unpacking.
This way, you can unpack arbitrary string containing any number of words. The first will be stored into the variable `first`, and the others will belong to the list (possibly empty) `others`.
```
first, *others = string.split()
```
Also, note that default delimiter for `.split()` is a space, so you do not need to specify it explicitly. | From [Extended Iterable Unpacking](https://www.python.org/dev/peps/pep-3132/).
Many algorithms require splitting a sequence in a "first, rest" pair, if you're using Python2.x, you need to try this:
```
seq = string.split()
first, rest = seq[0], seq[1:]
```
and it is replaced by the cleaner and probably more efficient in `Python3.x`:
```
first, *rest = seq
```
For more complex unpacking patterns, the new syntax looks even cleaner, and the clumsy index handling is not necessary anymore. |
28,717,067 | I am trying to place a condition after the for loop. It will print the word available if the retrieved rows is not equal to zero, however if I would be entering a value which is not stored in my database, it will return a message. My problem here is that, if I'd be inputting value that isn't stored on my database, it would not go to the else statement. I'm new to this. What would be my mistake in this function?
```
def search(title):
query = "SELECT * FROM books WHERE title = %s"
entry = (title,)
try:
conn = mysql.connector.connect(user='root', password='', database='python_mysql') # connect to the database server
cursor = conn.cursor()
cursor.execute(query, entry)
rows = cursor.fetchall()
for row in rows:
if row != 0:
print('Available')
else:
print('No available copies of the said book in the library')
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
def main():
title = input("Enter book title: ")
search(title)
if __name__ == '__main__':
main()
``` | 2015/02/25 | [
"https://Stackoverflow.com/questions/28717067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529171/"
] | Quite apart from the 0/NULL confusion, your logic is wrong. If there are no matching rows, you won't get a 0 as the value of a row; in fact you won't get any rows at all, and you will never even get into the for loop.
A much better way to do this would be simply run a COUNT query, get the single result with `fetchone()`, and check that directly.
```
query = "SELECT COUNT(*) FROM books WHERE title = %s"
entry = (title,)
try:
conn = mysql.connector.connect(user='root', password='', database='python_mysql') # connect to the database server
cursor = conn.cursor()
cursor.execute(query, entry)
result = cursor.fetchone()
if result != 0:
print('Available')
else:
print('No available copies of the said book in the library')
``` | In python you should check for `None` not `NULL`. In your code you can just check for object, if it is not None then control should go inside `if` otherwise `else` will be executed
```
for row in rows:
if row:
print('Available')
else:
print('No available copies of the said book in the library')
```
`UPDATE after auther edited the question:`
Now in for loop you should check for column value not the whole `row`. If your column name is suppose `quantity` then `if` statement should be like this
```
if row["quantity"] != 0:
``` |
28,717,067 | I am trying to place a condition after the for loop. It will print the word available if the retrieved rows is not equal to zero, however if I would be entering a value which is not stored in my database, it will return a message. My problem here is that, if I'd be inputting value that isn't stored on my database, it would not go to the else statement. I'm new to this. What would be my mistake in this function?
```
def search(title):
query = "SELECT * FROM books WHERE title = %s"
entry = (title,)
try:
conn = mysql.connector.connect(user='root', password='', database='python_mysql') # connect to the database server
cursor = conn.cursor()
cursor.execute(query, entry)
rows = cursor.fetchall()
for row in rows:
if row != 0:
print('Available')
else:
print('No available copies of the said book in the library')
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
def main():
title = input("Enter book title: ")
search(title)
if __name__ == '__main__':
main()
``` | 2015/02/25 | [
"https://Stackoverflow.com/questions/28717067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529171/"
] | Quite apart from the 0/NULL confusion, your logic is wrong. If there are no matching rows, you won't get a 0 as the value of a row; in fact you won't get any rows at all, and you will never even get into the for loop.
A much better way to do this would be simply run a COUNT query, get the single result with `fetchone()`, and check that directly.
```
query = "SELECT COUNT(*) FROM books WHERE title = %s"
entry = (title,)
try:
conn = mysql.connector.connect(user='root', password='', database='python_mysql') # connect to the database server
cursor = conn.cursor()
cursor.execute(query, entry)
result = cursor.fetchone()
if result != 0:
print('Available')
else:
print('No available copies of the said book in the library')
``` | First of all NULL in python is called None.
Next:
according to documentation:
"The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.
"
enpty list is not None
```
>>> row = []
>>> row is None
False
```
So you need to redesign your if statment in the way like this:
```
for i in rows:
if i:
blah-blah
else:
blah-blah-blah
``` |
65,995,857 | I'm quite new to coding and I'm working on a math problem in python.
To solve it, I would like to extract the first 7 numbers from a string of one hundred 50-digit number (take first 7 numbers, skip 43 numbers, and then take the first 7 again). The numbers aren't separated in any way (just one long string).
Then I want to sum up those fifty seven-digit numbers which I have extracted.
How can I do this?
(I have written this code, but it only takes the first digit, I don't know any stepping/slicing methods to make it seven)
```py
number = """3710728753390210279879799822083759024651013574025046376937677490007126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104210475137780632466768926167069662363382013637841838368417873436172675728112879812849979408065481931592621691275889832738442742289174325203219235894228767964876702721893184745144573600130643909116721685684458871160315327670386486105843025439939619828917593665686757934951621764571418565606295021572231965867550793241933316490635246274190492910143244581382266334794475817892575867718337217661963751590579239728245598838407582035653253593990084026335689488301894586282278288018119938482628201427819413994056758715117009439035398664372827112653829987240784473053190104293586865155060062958648615320752733719591914205172558297169388870771546649911559348760353292171497005693854370070576826684624621495650076471787294438377604532826541087568284431911906346940378552177792951453612327252500029607107508256381565671088525835072145876576172410976447339110607218265236877223636045174237069058518606604482076212098132878607339694128114266041808683061932846081119106155694051268969251934325451728388641918047049293215058642563049483624672216484350762017279180399446930047329563406911573244438690812579451408905770622942919710792820955037687525678773091862540744969844508330393682126183363848253301546861961243487676812975343759465158038628759287849020152168555482871720121925776695478182833757993103614740356856449095527097864797581167263201004368978425535399209318374414978068609844840309812907779179908821879532736447567559084803087086987551392711854517078544161852424320693150332599594068957565367821070749269665376763262354472106979395067965269474259770973916669376304263398708541052684708299085211399427365734116182760315001271653786073615010808570091499395125570281987460043753582903531743471732693212357815498262974255273730794953759765105305946966067683156574377167401875275889028025717332296191766687138199318110487701902712526768027607800301367868099252546340106163286652636270218540497705585629946580636237993140746255962240744869082311749777923654662572469233228109171419143028819710328859780666976089293863828502533340334413065578016127815921815005561868836468420090470230530811728164304876237919698424872550366387845831148769693215490281042402013833512446218144177347063783299490636259666498587618221225225512486764533677201869716985443124195724099139590089523100588229554825530026352078153229679624948164195386821877476085327132285723110424803456124867697064507995236377742425354112916842768655389262050249103265729672370191327572567528565324825826546309220705859652229798860272258331913126375147341994889534765745501184957014548792889848568277260777137214037988797153829820378303147352772158034814451349137322665138134829543829199918180278916522431027392251122869539409579530664052326325380441000596549391598795936352974615218550237130764225512118369380358038858490341698116222072977186158236678424689157993532961922624679571944012690438771072750481023908955235974572318970677254791506150550495392297953090112996751986188088225875314529584099251203829009407770775672113067397083047244838165338735023408456470580773088295917476714036319800818712901187549131054712658197623331044818386269515456334926366572897563400500428462801835170705278318394258821455212272512503275512160354698120058176216521282765275169129689778932238195734329339946437501907836945765883352399886755061649651847751807381688378610915273579297013376217784275219262340194239963916804498399317331273132924185707147349566916674687634660915035914677504995186714302352196288948901024233251169136196266227326746080059154747183079839286853520694694454072476841822524674417161514036427982273348055556214818971426179103425986472045168939894221798260880768528778364618279934631376775430780936333301898264209010848802521674670883215120185883543223812876952786713296124747824645386369930090493103636197638780396218407357239979422340623539380833965132740801111666627891981488087797941876876144230030984490851411606618262936828367647447792391803351109890697907148578694408955299065364044742557608365997664579509666024396409905389607120198219976047599490197230297649139826800329731560371200413779037855660850892521673093931987275027546890690370753941304265231501194809377245048795150954100921645863754710598436791786391670211874924319957006419179697775990283006991536871371193661495281130587638027841075444973307840789923115535562561142322423255033685442488917353448899115014406480203690680639606723221932041495354150312888033953605329934036800697771065056663195481234880673210146739058568557934581403627822703280826165707739483275922328459417065250945123252306082291880205877731971983945018088807242966198081119777158542502016545090413245809786882778948721859617721078384350691861554356628840622574736922845095162084960398013400172393067166682355524525280460972253503534226472524250874054075591789781264330331690"""
first_digits = list(number[::50])
first_digits_int = list(map(int, first_digits))
result = 0
for n in first_digits_int:
result += n
print(result)
``` | 2021/02/01 | [
"https://Stackoverflow.com/questions/65995857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15117090/"
] | Python allows you to iterate over a range with custom step sizes. So that should be allow you to do something like:
```py
your_list = []
for idx in range(0, len(string), 50): # Indexes 0, 50, 100, so on
first_seven_digits = string[idx:idx+7] # Say, "1234567"
str_to_int = int(first_seven_digits) # Converts to the number 1234567
your_list.append(str_to_int) # Add the number to the list
your_sum = sum(your_list) # Find the sum
```
You store the numbers made up of those first 7 digits in a list, and finally, sum them up. | first of all your number string is 4999 characters long so you'll have to add one. secondly if you want to use numpy you could make a 100 by 50 array by reshaping the original 5000 long array. like this
```
arr = np.array(list(number)).reshape(100, 50)
```
than you can slice the arr in a way that the first 7 elements the arrays second axis and all of the first. like this
```
nums = arr[:, :7]
```
than you can just construct your result list by iterating over every element of nums and joining all the chars to a list like so and sum there integers together
```
res = sum([int("".join(n)) for n in nums])
```
so if we putt all that together we get
```
import numpy as np
number = """37107287533902102798797998228083759024651013574025046376937677490007126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104210475137780632466768926167069662363382013637841838368417873436172675728112879812849979408065481931592621691275889832738442742289174325203219235894228767964876702721893184745144573600130643909116721685684458871160315327670386486105843025439939619828917593665686757934951621764571418565606295021572231965867550793241933316490635246274190492910143244581382266334794475817892575867718337217661963751590579239728245598838407582035653253593990084026335689488301894586282278288018119938482628201427819413994056758715117009439035398664372827112653829987240784473053190104293586865155060062958648615320752733719591914205172558297169388870771546649911559348760353292171497005693854370070576826684624621495650076471787294438377604532826541087568284431911906346940378552177792951453612327252500029607107508256381565671088525835072145876576172410976447339110607218265236877223636045174237069058518606604482076212098132878607339694128114266041808683061932846081119106155694051268969251934325451728388641918047049293215058642563049483624672216484350762017279180399446930047329563406911573244438690812579451408905770622942919710792820955037687525678773091862540744969844508330393682126183363848253301546861961243487676812975343759465158038628759287849020152168555482871720121925776695478182833757993103614740356856449095527097864797581167263201004368978425535399209318374414978068609844840309812907779179908821879532736447567559084803087086987551392711854517078544161852424320693150332599594068957565367821070749269665376763262354472106979395067965269474259770973916669376304263398708541052684708299085211399427365734116182760315001271653786073615010808570091499395125570281987460043753582903531743471732693212357815498262974255273730794953759765105305946966067683156574377167401875275889028025717332296191766687138199318110487701902712526768027607800301367868099252546340106163286652636270218540497705585629946580636237993140746255962240744869082311749777923654662572469233228109171419143028819710328859780666976089293863828502533340334413065578016127815921815005561868836468420090470230530811728164304876237919698424872550366387845831148769693215490281042402013833512446218144177347063783299490636259666498587618221225225512486764533677201869716985443124195724099139590089523100588229554825530026352078153229679624948164195386821877476085327132285723110424803456124867697064507995236377742425354112916842768655389262050249103265729672370191327572567528565324825826546309220705859652229798860272258331913126375147341994889534765745501184957014548792889848568277260777137214037988797153829820378303147352772158034814451349137322665138134829543829199918180278916522431027392251122869539409579530664052326325380441000596549391598795936352974615218550237130764225512118369380358038858490341698116222072977186158236678424689157993532961922624679571944012690438771072750481023908955235974572318970677254791506150550495392297953090112996751986188088225875314529584099251203829009407770775672113067397083047244838165338735023408456470580773088295917476714036319800818712901187549131054712658197623331044818386269515456334926366572897563400500428462801835170705278318394258821455212272512503275512160354698120058176216521282765275169129689778932238195734329339946437501907836945765883352399886755061649651847751807381688378610915273579297013376217784275219262340194239963916804498399317331273132924185707147349566916674687634660915035914677504995186714302352196288948901024233251169136196266227326746080059154747183079839286853520694694454072476841822524674417161514036427982273348055556214818971426179103425986472045168939894221798260880768528778364618279934631376775430780936333301898264209010848802521674670883215120185883543223812876952786713296124747824645386369930090493103636197638780396218407357239979422340623539380833965132740801111666627891981488087797941876876144230030984490851411606618262936828367647447792391803351109890697907148578694408955299065364044742557608365997664579509666024396409905389607120198219976047599490197230297649139826800329731560371200413779037855660850892521673093931987275027546890690370753941304265231501194809377245048795150954100921645863754710598436791786391670211874924319957006419179697775990283006991536871371193661495281130587638027841075444973307840789923115535562561142322423255033685442488917353448899115014406480203690680639606723221932041495354150312888033953605329934036800697771065056663195481234880673210146739058568557934581403627822703280826165707739483275922328459417065250945123252306082291880205877731971983945018088807242966198081119777158542502016545090413245809786882778948721859617721078384350691861554356628840622574736922845095162084960398013400172393067166682355524525280460972253503534226472524250874054075591789781264330331690"""
arr = np.array(list(number)).reshape(100, 50)
nums = arr[:, :7]
res = sum([int("".join(n)) for n in nums])
print(res)
``` |
21,307,128 | Since I have to mock a static method, I am using **Power Mock** to test my application.
My application uses \**Camel 2.1*\*2.
I define routes in *XML* that is read by *camel-spring* context.
There were no issues when `Junit` alone was used for testing.
While using power mock, I get the error listed at the end of the post.
I have also listed the XML used.
*Camel* is unable to recognize any of its tags when power mock is used.
I wonder whether the byte-level manipulation done by power mock to mock static methods interferes with camel engine in some way. Let me know what could possibly be wrong.
PS:
The problem disappears if I do not use power mock.
+++++++++++++++++++++++++ Error +++++++++++++++++++++++++++++++++++++++++++++++++
```
[ main] CamelNamespaceHandler DEBUG Using org.apache.camel.spring.CamelContextFactoryBean as CamelContextBeanDefinitionParser
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse JAXB element; nested exception is javax.xml.bind.UnmarshalException: unexpected element (uri:"http://camel.apache.org/schema/spring", local:"camelContext"). Expected elements are <{}aggregate>,<{}aop>,<{}avro>,<{}base64>,<{}batchResequencerConfig>,<{}bean>,<{}beanPostProcessor>,<{}beanio>,<{}bindy>,<{}camelContext>,<{}castor>,<{}choice>,<{}constant>,<{}consumerTemplate>,<{}contextScan>,<{}convertBodyTo>,<{}crypto>,<{}csv>,<{}customDataFormat>,<{}customLoadBalancer>,<{}dataFormats>,<{}delay>,<{}description>,<{}doCatch>,<{}doFinally>,<{}doTry>,<{}dynamicRouter>,<{}el>,<{}endpoint>,<{}enrich>,<{}errorHandler>,<{}export>,<{}expression>,<{}expressionDefinition>,<{}failover>,<{}filter>,<{}flatpack>,<{}from>,<{}groovy>,<{}gzip>,<{}header>,<{}hl7>,<{}idempotentConsumer>,<{}inOnly>,<{}inOut>,<{}intercept>,<{}interceptFrom>,<{}interceptToEndpoint>,<{}javaScript>,<{}jaxb>,<{}jibx>,<{}jmxAgent>,<{}json>,<{}jxpath>,<{}keyStoreParameters>,<{}language>,<{}loadBalance>,<{}log>,<{}loop>,<{}marshal>,<{}method>,<{}multicast>,<{}mvel>,<{}ognl>,<{}onCompletion>,<{}onException>,<{}optimisticLockRetryPolicy>,<{}otherwise>,<{}packageScan>,<{}pgp>,<{}php>,<{}pipeline>,<{}policy>,<{}pollEnrich>,<{}process>,<{}properties>,<{}property>,<{}propertyPlaceholder>,<{}protobuf>,<{}proxy>,<{}python>,<{}random>,<{}recipientList>,<{}redeliveryPolicy>,<{}redeliveryPolicyProfile>,<{}ref>,<{}removeHeader>,<{}removeHeaders>,<{}removeProperty>,<{}resequence>,<{}rollback>,<{}roundRobin>,<{}route>,<{}routeBuilder>,<{}routeContext>,<{}routeContextRef>,<{}routes>,<{}routingSlip>,<{}rss>,<{}ruby>,<{}sample>,<{}secureRandomParameters>,<{}secureXML>,<{}serialization>,<{}setBody>,<{}setExchangePattern>,<{}setFaultBody>,<{}setHeader>,<{}setOutHeader>,<{}setProperty>,<{}simple>,<{}soapjaxb>,<{}sort>,<{}spel>,<{}split>,<{}sql>,<{}sslContextParameters>,<{}sticky>,<{}stop>,<{}streamCaching>,<{}streamResequencerConfig>,<{}string>,<{}syslog>,<{}template>,<{}threadPool>,<{}threadPoolProfile>,<{}threads>,<{}throttle>,<{}throwException>,<{}tidyMarkup>,<{}to>,<{}tokenize>,<{}topic>,<{}transacted>,<{}transform>,<{}unmarshal>,<{}validate>,<{}vtdxml>,<{}weighted>,<{}when>,<{}wireTap>,<{}xmlBeans>,<{}xmljson>,<{}xmlrpc>,<{}xpath>,<{}xquery>,<{}xstream>,<{}zip>,<{}zipFile> at org.apache.camel.spring.handler.CamelNamespaceHandler.parseUsingJaxb(CamelNamespaceHandler.java:169)
at org.apache.camel.spring.handler.CamelNamespaceHandler$CamelContextBeanDefinitionParser.doParse(CamelNamespaceHandler.java:307)
at org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser.parseInternal(AbstractSingleBeanDefinitionParser.java:85)
at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.parse(AbstractBeanDefinitionParser.java:59)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1438)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1428)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:185)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:139)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:108)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at org.apache.camel.spring.SpringCamelContext.springCamelContext(SpringCamelContext.java:100)
at com.ericsson.bss.edm.integrationFramework.Context.<init>(Context.java:50)
at com.ericsson.bss.edm.integrationFramework.RouteEngine.main(RouteEngine.java:55)
at com.ericsson.bss.edm.integrationFramework.RouteEngineTest.testMultiRouteCondition(RouteEngineTest.java:174)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:312)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:296)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:112)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:73)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:284)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:209)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:42)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:24)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
at org.apache.maven.surefire.junitcore.JUnitCoreWrapper.execute(JUnitCoreWrapper.java:62)
at org.apache.maven.surefire.junitcore.JUnitCoreProvider.invoke(JUnitCoreProvider.java:139)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://camel.apache.org/schema/spring", local:"camelContext"). Expected elements are <{}aggregate>,<{}aop>,<{}avro>,<{}base64>,<{}batchResequencerConfig>,<{}bean>,<{}beanPostProcessor>,<{}beanio>,<{}bindy>,<{}camelContext>,<{}castor>,<{}choice>,<{}constant>,<{}consumerTemplate>,<{}contextScan>,<{}convertBodyTo>,<{}crypto>,<{}csv>,<{}customDataFormat>,<{}customLoadBalancer>,<{}dataFormats>,<{}delay>,<{}description>,<{}doCatch>,<{}doFinally>,<{}doTry>,<{}dynamicRouter>,<{}el>,<{}endpoint>,<{}enrich>,<{}errorHandler>,<{}export>,<{}expression>,<{}expressionDefinition>,<{}failover>,<{}filter>,<{}flatpack>,<{}from>,<{}groovy>,<{}gzip>,<{}header>,<{}hl7>,<{}idempotentConsumer>,<{}inOnly>,<{}inOut>,<{}intercept>,<{}interceptFrom>,<{}interceptToEndpoint>,<{}javaScript>,<{}jaxb>,<{}jibx>,<{}jmxAgent>,<{}json>,<{}jxpath>,<{}keyStoreParameters>,<{}language>,<{}loadBalance>,<{}log>,<{}loop>,<{}marshal>,<{}method>,<{}multicast>,<{}mvel>,<{}ognl>,<{}onCompletion>,<{}onException>,<{}optimisticLockRetryPolicy>,<{}otherwise>,<{}packageScan>,<{}pgp>,<{}php>,<{}pipeline>,<{}policy>,<{}pollEnrich>,<{}process>,<{}properties>,<{}property>,<{}propertyPlaceholder>,<{}protobuf>,<{}proxy>,<{}python>,<{}random>,<{}recipientList>,<{}redeliveryPolicy>,<{}redeliveryPolicyProfile>,<{}ref>,<{}removeHeader>,<{}removeHeaders>,<{}removeProperty>,<{}resequence>,<{}rollback>,<{}roundRobin>,<{}route>,<{}routeBuilder>,<{}routeContext>,<{}routeContextRef>,<{}routes>,<{}routingSlip>,<{}rss>,<{}ruby>,<{}sample>,<{}secureRandomParameters>,<{}secureXML>,<{}serialization>,<{}setBody>,<{}setExchangePattern>,<{}setFaultBody>,<{}setHeader>,<{}setOutHeader>,<{}setProperty>,<{}simple>,<{}soapjaxb>,<{}sort>,<{}spel>,<{}split>,<{}sql>,<{}sslContextParameters>,<{}sticky>,<{}stop>,<{}streamCaching>,<{}streamResequencerConfig>,<{}string>,<{}syslog>,<{}template>,<{}threadPool>,<{}threadPoolProfile>,<{}threads>,<{}throttle>,<{}throwException>,<{}tidyMarkup>,<{}to>,<{}tokenize>,<{}topic>,<{}transacted>,<{}transform>,<{}unmarshal>,<{}validate>,<{}vtdxml>,<{}weighted>,<{}when>,<{}wireTap>,<{}xmlBeans>,<{}xmljson>,<{}xmlrpc>,<{}xpath>,<{}xquery>,<{}xstream>,<{}zip>,<{}zipFile>
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:647)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:258)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:253)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:120)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1052)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:483)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:464)
at com.sun.xml.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:75)
at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:152)
at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:244)
at com.sun.xml.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:127)
at com.sun.xml.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:105)
at com.sun.xml.bind.v2.runtime.BinderImpl.associativeUnmarshal(BinderImpl.java:161)
at com.sun.xml.bind.v2.runtime.BinderImpl.unmarshal(BinderImpl.java:132)
at org.apache.camel.spring.handler.CamelNamespaceHandler.parseUsingJaxb(CamelNamespaceHandler.java:167)
... 72 more
```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++ Route.xml +++++++++++++++++++++++++++++++++++++++++++++
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route id="simpleroute">
<from uri="ftp://admin@x.y.z.a:2121/?password=admin&noop=true&maximumReconnectAttempts=3&download=false&delay=2000&throwExceptionOnConnectFailed=true;"/>
<to uri="file:/home/emeensa/NetBeansProjects/CamelFileCopier/output" />
</route>
</camelContext>
</beans>
```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ | 2014/01/23 | [
"https://Stackoverflow.com/questions/21307128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2345966/"
] | This error message usually means that your specified truststore can not be read. What I would check:
* Is the path correct? (I'm sure you checked this...)
* Has the user who started the JVM enough access privileges to read the
trustore?
* When do you set the system properties? Are they already set when the webservice is invoked?
* Perhaps another component has overridden the values. Are the system properties still set when the webservice is invoked?
* Does the trustore contains the Salesforce certificate and is the file not corrupt (e.g. check with `keytool -list`)?
**Edit:**
* Don't use `System.setProperty` but set the options when starting the Java process with `-Djavax.net.ssl.XXX`. The reason for this advice is as follows: The IBM security framework may read the options **before** you set the property (e.g. in a `static` block of a class). Of course this is framework specific and may change from version to version. | ```
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
```
>
> * In my case, I have 2 duplicate Java installations (OpenJDK and
> JDK-17).
> * I installed JDK-17 after configuring environment variable for OpenJDK and before uninstalling OpenJDK.
> * So, maybe that is the problem.
>
>
>
This is how I SOLVED it **in my case:**
* First, I have completely removed openJDK and JDK-17 from my computer (including JDK-17/lib/security/cacerts).
* Then, I deleted the java environment variable and restarted the computer.
* Next, I thoroughly checked that there aren't any JDKs on the computer anymore.
* Finally, I just reinstalled JDK-17 (JDK-17/lib/security/cacerts is default). And it worked fine for me.
**Note:** kill any Java runtime tasks before uninstalling them. |
49,059,660 | I am looking for a simple way to constantly monitor a log file, and send me an email notification every time thhis log file has changed (new lines have been added to it).
The system runs on a Raspberry Pi 2 (OS Raspbian /Debian Stretch) and the log monitors a GPIO python script running as daemon.
I need something very simple and lightweight, don't even care to have the text of the new log entry, because I know what it says, it is always the same. 24 lines of text at the end.
Also, the log.txt file gets recreated every day at midnight, so that might represent another issue.
I already have a working python script to send me a simple email via gmail (called it sendmail.py)
What I tried so far was creating and running the following bash script:
monitorlog.sh
`#!/bin/bash
tail -F log.txt | python ./sendmail.py`
The problem is that it just sends an email every time I execute it, but when the log actually changes, it just quits.
I am really new to linux so apologies if I missed something.
Cheers | 2018/03/01 | [
"https://Stackoverflow.com/questions/49059660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9431262/"
] | You asked for simple:
```
#!/bin/bash
cur_line_count="$(wc -l myfile.txt)"
while true
do
new_line_count="$(wc -l myfile.txt)"
if [ "$cur_line_count" != "$new_line_count" ]
then
python ./sendmail.py
fi
cur_line_count="$new_line_count"
sleep 5
done
``` | I've done this a bunch of different ways. If you run a cron job every minute that counts the number of lines (wc -l) compares that to a stored count (e.g. in /tmp/myfilecounter) and sends the emails when the numbers are different.
If you have inotify, there are more direct ways to get "woken up" when the file changes, e.g <https://serverfault.com/a/780522/97447> or <https://serverfault.com/search?q=inotifywait>.
If you don't mind adding a package to the system, incron is a very convenient way to run a script whenever a file or directory is modified, and it looks like it's supported on raspbian (internally it uses inotify). <https://www.linux.com/learn/how-use-incron-monitor-important-files-and-folders>. Looks like it's as simple as:
```
sudo apt-get install incron
sudo vi /etc/incron.allow # Add your userid to this file (or just rm /etc/incron.allow to let everyone use incron)
incron -e # Add the following line to the "cron" file
/path/to/log.txt IN_MODIFY python ./sendmail.py
```
And you'd be done! |
56,794,886 | guys! So I recently started learning about python classes and objects.
For instance, I have a following list of strings:
```
alist = ["Four", "Three", "Five", "One", "Two"]
```
Which is comparable to a class of Numbers I have:
```
class Numbers(object):
One=1
Two=2
Three=3
Four=4
Five=5
```
How could I convert `alist` into
```
alist = [4, 3, 5, 1, 2]
```
based on the class above?
My initial thought was to create a new (empty) list and use a `for loop` that adds the corresponding object value (e.g. `Numbers.One`) to the empty list as it goes through `alist`. But I'm unsure whether that'd be the most efficient solution.
Therefore, I was wondering if there was a simpler way of completing this task using Python Classes / Inheritance.
I hope someone can help me and explain to me what way would work better and why!
Thank you!! | 2019/06/27 | [
"https://Stackoverflow.com/questions/56794886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10713538/"
] | If you are set on using the class, one way would be to use [`__getattribute__()`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__)
```
print([Numbers().__getattribute__(a) for a in alist])
#[4, 3, 5, 1, 2]
```
But a much better (and more pythonic IMO) way would be to use a `dict`:
```
NumbersDict = dict(
One=1,
Two=2,
Three=3,
Four=4,
Five=5
)
print([NumbersDict[a] for a in alist])
#[4, 3, 5, 1, 2]
``` | **EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments.
Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list with the required elements.
Empty list with for loop
========================
```py
#... Numbers class defined above
alist = ["Four", "Three", "Five", "One", "Two"]
nlist = []
numbers = Numbers()
for anumber in alist:
nlist.append(getattr(numbers, anumber))
print(nlist)
[4, 3, 5, 1, 2]
```
List comprehension with for loop
================================
```py
#... Numbers class defined above
alist = ["Four", "Three", "Five", "One", "Two"]
numbers = Numbers()
nlist = [getattr(numbers, anumber) for anumber in alist]
print(nlist)
[4, 3, 5, 1, 2]
``` |
56,794,886 | guys! So I recently started learning about python classes and objects.
For instance, I have a following list of strings:
```
alist = ["Four", "Three", "Five", "One", "Two"]
```
Which is comparable to a class of Numbers I have:
```
class Numbers(object):
One=1
Two=2
Three=3
Four=4
Five=5
```
How could I convert `alist` into
```
alist = [4, 3, 5, 1, 2]
```
based on the class above?
My initial thought was to create a new (empty) list and use a `for loop` that adds the corresponding object value (e.g. `Numbers.One`) to the empty list as it goes through `alist`. But I'm unsure whether that'd be the most efficient solution.
Therefore, I was wondering if there was a simpler way of completing this task using Python Classes / Inheritance.
I hope someone can help me and explain to me what way would work better and why!
Thank you!! | 2019/06/27 | [
"https://Stackoverflow.com/questions/56794886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10713538/"
] | Most objects (and hence classes) in python have the `__dict__` field, which is a mapping from attribute names to their values. You can access this field using the built-in [`vars`](https://docs.python.org/3/library/functions.html#vars), so
```
values = [vars(Numbers)[a] for a in alist]
```
will give you what you want. | **EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments.
Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list with the required elements.
Empty list with for loop
========================
```py
#... Numbers class defined above
alist = ["Four", "Three", "Five", "One", "Two"]
nlist = []
numbers = Numbers()
for anumber in alist:
nlist.append(getattr(numbers, anumber))
print(nlist)
[4, 3, 5, 1, 2]
```
List comprehension with for loop
================================
```py
#... Numbers class defined above
alist = ["Four", "Three", "Five", "One", "Two"]
numbers = Numbers()
nlist = [getattr(numbers, anumber) for anumber in alist]
print(nlist)
[4, 3, 5, 1, 2]
``` |
56,794,886 | guys! So I recently started learning about python classes and objects.
For instance, I have a following list of strings:
```
alist = ["Four", "Three", "Five", "One", "Two"]
```
Which is comparable to a class of Numbers I have:
```
class Numbers(object):
One=1
Two=2
Three=3
Four=4
Five=5
```
How could I convert `alist` into
```
alist = [4, 3, 5, 1, 2]
```
based on the class above?
My initial thought was to create a new (empty) list and use a `for loop` that adds the corresponding object value (e.g. `Numbers.One`) to the empty list as it goes through `alist`. But I'm unsure whether that'd be the most efficient solution.
Therefore, I was wondering if there was a simpler way of completing this task using Python Classes / Inheritance.
I hope someone can help me and explain to me what way would work better and why!
Thank you!! | 2019/06/27 | [
"https://Stackoverflow.com/questions/56794886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10713538/"
] | While I totally agree that using a `dict` for `Numbers` would be easier and straight forward, but showing you the `Enum` way as your class involves magic numbers and sort of a valid use case for using enums.
A similar implementation using `Enum` would be:
```
from enum import Enum
class Numbers(Enum):
One = 1
Two = 2
Three = 3
Four = 4
Five = 5
```
Then you can use `getattr` and `Numbers.<attr>.value` to get the constant numbers:
```
In [592]: alist = ["Four", "Three", "Five", "One", "Two"]
In [593]: [getattr(Numbers, n).value for n in alist]
Out[593]: [4, 3, 5, 1, 2]
```
---
**Edit based on comment:**
If you want to get the names back from a number list:
```
In [952]: l = [4, 3, 5, 1, 2]
In [953]: [Numbers(num).name for num in l]
Out[953]: ['Four', 'Three', 'Five', 'One', 'Two']
``` | **EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments.
Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list with the required elements.
Empty list with for loop
========================
```py
#... Numbers class defined above
alist = ["Four", "Three", "Five", "One", "Two"]
nlist = []
numbers = Numbers()
for anumber in alist:
nlist.append(getattr(numbers, anumber))
print(nlist)
[4, 3, 5, 1, 2]
```
List comprehension with for loop
================================
```py
#... Numbers class defined above
alist = ["Four", "Three", "Five", "One", "Two"]
numbers = Numbers()
nlist = [getattr(numbers, anumber) for anumber in alist]
print(nlist)
[4, 3, 5, 1, 2]
``` |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]
a = reviews["review"][1].split("disappointed")
print a
b = len(a)
print b
```
The output for the above lines were
```
it came early and was not disappointed. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.
['it came early and was not ', '. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.']
2
```
When I apply the same logic to the entire dataframe using the below line. I receive an error message
```
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
```
Error message:
```
Traceback (most recent call last):
File "C:/Users/gouta/PycharmProjects/MLCourse1/Classifier.py", line 12, in <module>
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
File "C:\Users\gouta\Anaconda2\lib\site-packages\pandas\core\generic.py", line 2360, in __getattr__
(type(self).__name__, name))
AttributeError: 'Series' object has no attribute 'split'
``` | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the data frame:
```
f = lambda x: len(x["review"].split("disappointed")) -1
reviews["disappointed"] = reviews.apply(f, axis=1)
``` | Well, the problem is with:
```
reviews["review"]
```
The above is a Series. In your first snippet, you are doing this:
```
reviews["review"][1].split("disappointed")
```
That is, you are putting an index for the review. You could try looping over all rows of the column and perform your desired action. For example:
```
for index, row in reviews.iterrows():
print len(row['review'].split("disappointed"))
``` |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]
a = reviews["review"][1].split("disappointed")
print a
b = len(a)
print b
```
The output for the above lines were
```
it came early and was not disappointed. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.
['it came early and was not ', '. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.']
2
```
When I apply the same logic to the entire dataframe using the below line. I receive an error message
```
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
```
Error message:
```
Traceback (most recent call last):
File "C:/Users/gouta/PycharmProjects/MLCourse1/Classifier.py", line 12, in <module>
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
File "C:\Users\gouta\Anaconda2\lib\site-packages\pandas\core\generic.py", line 2360, in __getattr__
(type(self).__name__, name))
AttributeError: 'Series' object has no attribute 'split'
``` | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the data frame:
```
f = lambda x: len(x["review"].split("disappointed")) -1
reviews["disappointed"] = reviews.apply(f, axis=1)
``` | You can use `.str` to use string methods on series of strings:
```
reviews["review"].str.split("disappointed")
``` |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]
a = reviews["review"][1].split("disappointed")
print a
b = len(a)
print b
```
The output for the above lines were
```
it came early and was not disappointed. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.
['it came early and was not ', '. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.']
2
```
When I apply the same logic to the entire dataframe using the below line. I receive an error message
```
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
```
Error message:
```
Traceback (most recent call last):
File "C:/Users/gouta/PycharmProjects/MLCourse1/Classifier.py", line 12, in <module>
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
File "C:\Users\gouta\Anaconda2\lib\site-packages\pandas\core\generic.py", line 2360, in __getattr__
(type(self).__name__, name))
AttributeError: 'Series' object has no attribute 'split'
``` | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the data frame:
```
f = lambda x: len(x["review"].split("disappointed")) -1
reviews["disappointed"] = reviews.apply(f, axis=1)
``` | pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made
```
len(reviews['review'].str.split('disappointed')) - 1
```
[pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html) |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]
a = reviews["review"][1].split("disappointed")
print a
b = len(a)
print b
```
The output for the above lines were
```
it came early and was not disappointed. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.
['it came early and was not ', '. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.']
2
```
When I apply the same logic to the entire dataframe using the below line. I receive an error message
```
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
```
Error message:
```
Traceback (most recent call last):
File "C:/Users/gouta/PycharmProjects/MLCourse1/Classifier.py", line 12, in <module>
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
File "C:\Users\gouta\Anaconda2\lib\site-packages\pandas\core\generic.py", line 2360, in __getattr__
(type(self).__name__, name))
AttributeError: 'Series' object has no attribute 'split'
``` | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made
```
len(reviews['review'].str.split('disappointed')) - 1
```
[pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html) | Well, the problem is with:
```
reviews["review"]
```
The above is a Series. In your first snippet, you are doing this:
```
reviews["review"][1].split("disappointed")
```
That is, you are putting an index for the review. You could try looping over all rows of the column and perform your desired action. For example:
```
for index, row in reviews.iterrows():
print len(row['review'].split("disappointed"))
``` |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]
a = reviews["review"][1].split("disappointed")
print a
b = len(a)
print b
```
The output for the above lines were
```
it came early and was not disappointed. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.
['it came early and was not ', '. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.']
2
```
When I apply the same logic to the entire dataframe using the below line. I receive an error message
```
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
```
Error message:
```
Traceback (most recent call last):
File "C:/Users/gouta/PycharmProjects/MLCourse1/Classifier.py", line 12, in <module>
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
File "C:\Users\gouta\Anaconda2\lib\site-packages\pandas\core\generic.py", line 2360, in __getattr__
(type(self).__name__, name))
AttributeError: 'Series' object has no attribute 'split'
``` | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made
```
len(reviews['review'].str.split('disappointed')) - 1
```
[pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html) | You can use `.str` to use string methods on series of strings:
```
reviews["review"].str.split("disappointed")
``` |
72,329,252 | Let's say we have following list. This list contains response times of a REST server in a traffic run.
[1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
I need following output
Percentage of the requests served within a certain time (ms)
50% 3
60% 4
70% 5
80% 6
90% 7
100% 9
How can we get it done in python? This is apache bench kind of output. So basically lets say at 50%, we need to find point in list below which 50% of the list elements are present and so on. | 2022/05/21 | [
"https://Stackoverflow.com/questions/72329252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4137009/"
] | You can try something like this:
```
responseTimes = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
for time in range(3,10):
percentage = len([x for x in responseTimes if x <= time])/(len(responseTimes))
print(f'{percentage*100}%')
```
>
> *"So basically lets say at 50%, we need to find point in list below which 50% of the list elements are present and so on"*
>
>
>
```
responseTimes = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
percentage = 0
time = 0
while(percentage <= 0.5):
percentage = len([x for x in responseTimes if x <= time])/(len(responseTimes))
time+=1
print(f'Every time under {time}(ms) occurrs lower than 50% of the time')
``` | You basically need to compute the cumulative ratio of the sorted response times.
```py
from collections import Counter
values = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
frequency = Counter(values) # {1: 2, 2: 1, 3: 2, ...}
total = 0
n = len(values)
for time in sorted(frequency):
total += frequency[time]
print(time, f'{100*total/n}%')
```
This will print all times with the corresponding ratios.
```py
1 20.0%
2 30.0%
3 50.0%
4 60.0%
5 70.0%
6 80.0%
7 90.0%
9 100.0%
``` |
50,239,640 | In python have three one dimensional arrays of different shapes (like the ones given below)
```
a0 = np.array([5,6,7,8,9])
a1 = np.array([1,2,3,4])
a2 = np.array([11,12])
```
I am assuming that the array `a0` corresponds to an index `i=0`, `a1` corresponds to index `i=1` and `a2` corresponds to `i=2`. With these assumptions I want to construct a new two dimensional array where the rows would correspond to indices of the arrays (`i=0,1,2`) and the columns would be entries of the arrays `a0, a1, a2`.
In the example that I have given here, I will like the two dimensional array to look like
```
result = np.array([ [0,5], [0,6], [0,7], [0,8], [0,9], [1,1], [1,2],\
[1,3], [1,4], [2,11], [2,12] ])
```
I will very appreciate to have an answer as to how I can achieve this. In the actual problem that I am working with, I am dealing more than three one dimensional arrays. So, it will be very nice if the answer gives consideration to this. | 2018/05/08 | [
"https://Stackoverflow.com/questions/50239640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761166/"
] | You can use `numpy` stack functions to speed up:
```
aa = [a0, a1, a2]
np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T
``` | One way to do this would be a simple list comprehension:
```
result = np.array([[i, arr_v] for i, arr in enumerate([a0, a1, a2])
for arr_v in arr])
>>> result
array([[ 0, 5],
[ 0, 6],
[ 0, 7],
[ 0, 8],
[ 0, 9],
[ 1, 1],
[ 1, 2],
[ 1, 3],
[ 1, 4],
[ 2, 11],
[ 2, 12]])
```
Adressing your concern about scaling this to more arrays, you can easily add as many arrays as you wish by simply creating a list of your array names, and using that list as the argument to `enumerate`:
```
.... for i, arr in enumerate(my_list_of_arrays) ...
``` |
50,239,640 | In python have three one dimensional arrays of different shapes (like the ones given below)
```
a0 = np.array([5,6,7,8,9])
a1 = np.array([1,2,3,4])
a2 = np.array([11,12])
```
I am assuming that the array `a0` corresponds to an index `i=0`, `a1` corresponds to index `i=1` and `a2` corresponds to `i=2`. With these assumptions I want to construct a new two dimensional array where the rows would correspond to indices of the arrays (`i=0,1,2`) and the columns would be entries of the arrays `a0, a1, a2`.
In the example that I have given here, I will like the two dimensional array to look like
```
result = np.array([ [0,5], [0,6], [0,7], [0,8], [0,9], [1,1], [1,2],\
[1,3], [1,4], [2,11], [2,12] ])
```
I will very appreciate to have an answer as to how I can achieve this. In the actual problem that I am working with, I am dealing more than three one dimensional arrays. So, it will be very nice if the answer gives consideration to this. | 2018/05/08 | [
"https://Stackoverflow.com/questions/50239640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761166/"
] | You can use `numpy` stack functions to speed up:
```
aa = [a0, a1, a2]
np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T
``` | Here's an almost vectorized approach -
```
L = [a0,a1,a2] # list of all arrays
lens = [len(i) for i in L] # only looping part*
out = np.dstack(( np.repeat(np.arange(len(L)), lens), np.concatenate(L)))
```
\*The looping part is simply to get the lengths of the arrays, which should have negligible impact on the total runtime.
Sample run -
```
In [19]: L = [a0,a1,a2] # list of all arrays
In [20]: lens = [len(i) for i in L]
In [21]: np.dstack(( np.repeat(np.arange(len(L)), lens), np.concatenate(L)))
Out[21]:
array([[[ 0, 5],
[ 0, 6],
[ 0, 7],
[ 0, 8],
[ 0, 9],
[ 1, 1],
[ 1, 2],
[ 1, 3],
[ 1, 4],
[ 2, 11],
[ 2, 12]]])
```
Another way could be to avoid `np.repeat` and use some array-initialization + cumsum method, which would be better for large number of arrays, as shown below -
```
col1 = np.concatenate(L)
col0 = np.zeros(len(col1), dtype=col1.dtype)
col0[np.cumsum(lens[:-1])] = 1
out = np.dstack((col0.cumsum(), col1))
```
Or use `np.maximum.accumulate` to replace the second `cumsum` -
```
col0[np.cumsum(lens[:-1])] = np.arange(1,len(L))
out = np.dstack((np.maximum.accumulate(col0), col1))
``` |
45,939,564 | I am accessing a python file via python.
The google sheets looks like the following:
[![enter image description here](https://i.stack.imgur.com/eIW7v.png)](https://i.stack.imgur.com/eIW7v.png)
But when I access it via:
```
self.probe=[]
self.scope = ['https://spreadsheets.google.com/feeds']
self.creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', self.scope)
self.client = gspread.authorize(self.creds)
self.sheet = self.client.open('Beziehende').sheet1
self.probe = self.sheet.get_all_records()
print(self.probe)
```
it results in [![enter image description here](https://i.stack.imgur.com/2tHia.png)](https://i.stack.imgur.com/2tHia.png)
Ho can I get the results in the same order as they are written in the google sheet?
Thank you for your help.
**Edit** Sorry, here are some more information. My program has two functions:
1.) It can check if a name / address etc. is already in the database. If the name is in the database, it prints all the information about that person.
2.) It lets me add people's information to the database.
**The Problem**: I am loading the whole database into the list and later writing it all back. But when writing it back, the order gets messed up, as the get\_all\_records stored it in a random order. (This is the very first program I have ever written by myself, so please forgive the bad coding).
I wanted to know if there is a possibility to get the data in order. but if not, than I just have to find a way, online to write the newest entry (which is probably more efficient anyway I guess...)
```
def create_window(self):
self.t = Toplevel(self)
self.t.geometry("250x150")
Message(self.t, text="Name", width=100, anchor=W).grid(row=1, column=1)
self.name_entry = Entry(self.t)
self.name_entry.grid(row=1, column=2)
Message(self.t, text="Adresse", width=100, anchor=W).grid(row=2, column=1)
self.adr_entry = Entry(self.t)
self.adr_entry.grid(row=2, column=2)
Message(self.t, text="Organisation", width=100, anchor=W).grid(row=3, column=1)
self.org_entry = Entry(self.t)
self.org_entry.grid(row=3, column=2)
Message(self.t, text="Datum", width=100, anchor=W).grid(row=4, column=1)
self.date_entry = Entry(self.t)
self.date_entry.grid(row=4, column=2)
self.t.button = Button(self.t, text="Speichern", command=self.verify).grid(row=5, column=2)
#name
#window = Toplevel(self.insert_window)
def verify(self):
self.ver = Toplevel(self)
self.ver.geometry("300x150")
self.ver.grid_columnconfigure(1, minsize=100)
Message(self.ver, text=self.name_entry.get(), width=100).grid(row=1, column=1)
Message(self.ver, text=self.adr_entry.get(), width=100).grid(row=2, column=1)
Message(self.ver, text=self.org_entry.get(), width=100).grid(row=3, column=1)
Message(self.ver, text=self.date_entry.get(), width=100).grid(row=4, column=1)
confirm_button=Button(self.ver, text='Bestätigen', command=self.data_insert).grid(row=4, column=1)
cancle_button=Button(self.ver, text='Abbrechen', command=self.ver.destroy).grid(row=4, column=2)
def data_insert(self):
new_dict = collections.OrderedDict()
new_dict['name'] = self.name_entry.get()
new_dict['adresse'] = self.adr_entry.get()
new_dict['organisation'] = self.org_entry.get()
new_dict['datum'] = self.date_entry.get()
print(new_dict)
self.probe.append(new_dict)
#self.sheet.update_acell('A4',new_dict['name'])
self.update_gsheet()
self.ver.destroy()
self.t.destroy()
def update_gsheet(self):
i = 2
for dic_object in self.probe:
j = 1
for category in dic_object:
self.sheet.update_cell(i,j,dic_object[category])
j += 1
i += 1
def search(self):
print(self.probe)
self.result = []
self.var = self.entry.get() #starting index better
self.search_algo()
self.outputtext.delete('1.0', END)
for dict in self.result:
print(dict['Name'], dict['Adresse'], dict['Organisation'])
self.outputtext.insert(END, dict['Name'] + '\n')
self.outputtext.insert(END, dict['Adresse']+ '\n')
self.outputtext.insert(END, dict['Organisation']+ '\n')
self.outputtext.insert(END, 'Erhalten am '+dict['Datum']+'\n'+'\n')
if not self.result:
self.outputtext.insert(END, 'Name not found')
return FALSE
return TRUE
def search_algo(self):
category = self.v.get()
print(category)
for dict_object in self.probe:
if dict_object[category] == self.var:
self.result.append(dict_object)
``` | 2017/08/29 | [
"https://Stackoverflow.com/questions/45939564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3554329/"
] | I'm not familiar with gspread, which appears to be a third-party client for the Google Sheets API, but it looks like you should be using [`get_all_values`](https://github.com/burnash/gspread#getting-all-values-from-a-worksheet-as-a-list-of-lists) rather than `get_all_records`. That will give you a list of lists, rather than a list of dicts. | Python dictionaries are unordered. There is the [OrderedDict](https://docs.python.org/3.6/library/collections.html#collections.OrderedDict) in collections, but hard to say more about what the best course of action should be without more insight into why you need this dictionary ordered... |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
```
I'm running Ubuntu Trusty 14.04 Server.
How do I upgrade or update my sqlite version to >=3.8.3?
*I ran*
`$ apt list --installed | grep sqlite`
```
libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
```
*and*
`sudo apt install --only-upgrade libsqlite3-0`
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.
```
EDIT:
the `settings.py` is stock standard:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
``` | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | I've just been through this. I had to install a separate newer version of SQLite, from
<https://www.sqlite.org/download.html>
That is in /usr/local/bin. Then I had to recompile Python, telling it to look there:
```
sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations
sudo LD_RUN_PATH=/usr/local/lib make altinstall
```
To check which version of SQLite Python is using:
```
$ python
Python 3.7.3 (default, Apr 12 2019, 16:23:13)
>>> import sqlite3
>>> sqlite3.sqlite_version
'3.27.2'
``` | In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it. |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
```
I'm running Ubuntu Trusty 14.04 Server.
How do I upgrade or update my sqlite version to >=3.8.3?
*I ran*
`$ apt list --installed | grep sqlite`
```
libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
```
*and*
`sudo apt install --only-upgrade libsqlite3-0`
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.
```
EDIT:
the `settings.py` is stock standard:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
``` | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | I've just been through this. I had to install a separate newer version of SQLite, from
<https://www.sqlite.org/download.html>
That is in /usr/local/bin. Then I had to recompile Python, telling it to look there:
```
sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations
sudo LD_RUN_PATH=/usr/local/lib make altinstall
```
To check which version of SQLite Python is using:
```
$ python
Python 3.7.3 (default, Apr 12 2019, 16:23:13)
>>> import sqlite3
>>> sqlite3.sqlite_version
'3.27.2'
``` | I have applied the following fix and it worked for my CentOS 7.x server.
Edit `/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py` file as per the below example:
```
def check_sqlite_version():
# if Database.sqlite_version_info < (3, 8, 3):
# 2018-07-07, edit
if Database.sqlite_version_info < (3, 6, 3):
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
``` |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
```
I'm running Ubuntu Trusty 14.04 Server.
How do I upgrade or update my sqlite version to >=3.8.3?
*I ran*
`$ apt list --installed | grep sqlite`
```
libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
```
*and*
`sudo apt install --only-upgrade libsqlite3-0`
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.
```
EDIT:
the `settings.py` is stock standard:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
``` | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18):
1. Download SQLite tarball from <https://www.sqlite.org/download.html>
2. Extract the contents and cd into the folder.
3. Run the following commands:
./configure
sudo make install
4. Now edit the `activate` script used to start your virtualenv so Python looks in the right place for the newly installed SQLite. Add the following line to the top of `/path/to/virtualenv/bin/activate`:
export LD\_LIBRARY\_PATH="/usr/local/lib"
Now, when active, Django 2.2+ should work fine in the virtualenv. Hope that helps. | I've just been through this. I had to install a separate newer version of SQLite, from
<https://www.sqlite.org/download.html>
That is in /usr/local/bin. Then I had to recompile Python, telling it to look there:
```
sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations
sudo LD_RUN_PATH=/usr/local/lib make altinstall
```
To check which version of SQLite Python is using:
```
$ python
Python 3.7.3 (default, Apr 12 2019, 16:23:13)
>>> import sqlite3
>>> sqlite3.sqlite_version
'3.27.2'
``` |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
```
I'm running Ubuntu Trusty 14.04 Server.
How do I upgrade or update my sqlite version to >=3.8.3?
*I ran*
`$ apt list --installed | grep sqlite`
```
libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
```
*and*
`sudo apt install --only-upgrade libsqlite3-0`
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.
```
EDIT:
the `settings.py` is stock standard:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
``` | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18):
1. Download SQLite tarball from <https://www.sqlite.org/download.html>
2. Extract the contents and cd into the folder.
3. Run the following commands:
./configure
sudo make install
4. Now edit the `activate` script used to start your virtualenv so Python looks in the right place for the newly installed SQLite. Add the following line to the top of `/path/to/virtualenv/bin/activate`:
export LD\_LIBRARY\_PATH="/usr/local/lib"
Now, when active, Django 2.2+ should work fine in the virtualenv. Hope that helps. | In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it. |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
```
I'm running Ubuntu Trusty 14.04 Server.
How do I upgrade or update my sqlite version to >=3.8.3?
*I ran*
`$ apt list --installed | grep sqlite`
```
libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
```
*and*
`sudo apt install --only-upgrade libsqlite3-0`
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.
```
EDIT:
the `settings.py` is stock standard:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
``` | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | This error comes because your virtual environment could not connect to newly updated sqlite3 database. For that you have to update your sqlite3 database version manually and then give path of it to your virtual environment. Kindly follow below steps:
1. Download latest sqlite3 from official site. (<https://www.sqlite.org/download.html>)`wget http://www.sqlite.org/sqlite-autoconf-3070603.tar.gz`
2. Then go to that folder and fire command.
`tar xvfz sqlite-autoconf-3070603.tar.gz`
3. Go to respective folder. `cd sqlite-autoconf-3070603`
4. `./configure`
5. `make`
6. `make install` It may take too time but wait till end. If it's take too much then terminate that process and continue rest of steps.
7. Now you successfully install updated sqlite3. Now fire this command `sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations`
8. Open your activate file of virtual environment (e.g., venv/bin/activate) and add this line top of the file...
`export LD_LIBRARY_PATH="/usr/local/lib"`
9. Now for checking you can type this commands to your python shell
```py
$ python
Python 3.7.3 (default, Apr 12 2019, 16:23:13)
>>> import sqlite3
>>> sqlite3.sqlite_version
'3.27.2'
``` | In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it. |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
```
I'm running Ubuntu Trusty 14.04 Server.
How do I upgrade or update my sqlite version to >=3.8.3?
*I ran*
`$ apt list --installed | grep sqlite`
```
libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
```
*and*
`sudo apt install --only-upgrade libsqlite3-0`
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.
```
EDIT:
the `settings.py` is stock standard:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
``` | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18):
1. Download SQLite tarball from <https://www.sqlite.org/download.html>
2. Extract the contents and cd into the folder.
3. Run the following commands:
./configure
sudo make install
4. Now edit the `activate` script used to start your virtualenv so Python looks in the right place for the newly installed SQLite. Add the following line to the top of `/path/to/virtualenv/bin/activate`:
export LD\_LIBRARY\_PATH="/usr/local/lib"
Now, when active, Django 2.2+ should work fine in the virtualenv. Hope that helps. | I have applied the following fix and it worked for my CentOS 7.x server.
Edit `/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py` file as per the below example:
```
def check_sqlite_version():
# if Database.sqlite_version_info < (3, 8, 3):
# 2018-07-07, edit
if Database.sqlite_version_info < (3, 6, 3):
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
``` |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
```
I'm running Ubuntu Trusty 14.04 Server.
How do I upgrade or update my sqlite version to >=3.8.3?
*I ran*
`$ apt list --installed | grep sqlite`
```
libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
```
*and*
`sudo apt install --only-upgrade libsqlite3-0`
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.
```
EDIT:
the `settings.py` is stock standard:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
``` | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | This error comes because your virtual environment could not connect to newly updated sqlite3 database. For that you have to update your sqlite3 database version manually and then give path of it to your virtual environment. Kindly follow below steps:
1. Download latest sqlite3 from official site. (<https://www.sqlite.org/download.html>)`wget http://www.sqlite.org/sqlite-autoconf-3070603.tar.gz`
2. Then go to that folder and fire command.
`tar xvfz sqlite-autoconf-3070603.tar.gz`
3. Go to respective folder. `cd sqlite-autoconf-3070603`
4. `./configure`
5. `make`
6. `make install` It may take too time but wait till end. If it's take too much then terminate that process and continue rest of steps.
7. Now you successfully install updated sqlite3. Now fire this command `sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations`
8. Open your activate file of virtual environment (e.g., venv/bin/activate) and add this line top of the file...
`export LD_LIBRARY_PATH="/usr/local/lib"`
9. Now for checking you can type this commands to your python shell
```py
$ python
Python 3.7.3 (default, Apr 12 2019, 16:23:13)
>>> import sqlite3
>>> sqlite3.sqlite_version
'3.27.2'
``` | I have applied the following fix and it worked for my CentOS 7.x server.
Edit `/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py` file as per the below example:
```
def check_sqlite_version():
# if Database.sqlite_version_info < (3, 8, 3):
# 2018-07-07, edit
if Database.sqlite_version_info < (3, 6, 3):
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
``` |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
```
I'm running Ubuntu Trusty 14.04 Server.
How do I upgrade or update my sqlite version to >=3.8.3?
*I ran*
`$ apt list --installed | grep sqlite`
```
libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic]
libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed]
libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed]
python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed]
sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed]
```
*and*
`sudo apt install --only-upgrade libsqlite3-0`
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
libsqlite3-0 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.
```
EDIT:
the `settings.py` is stock standard:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
``` | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18):
1. Download SQLite tarball from <https://www.sqlite.org/download.html>
2. Extract the contents and cd into the folder.
3. Run the following commands:
./configure
sudo make install
4. Now edit the `activate` script used to start your virtualenv so Python looks in the right place for the newly installed SQLite. Add the following line to the top of `/path/to/virtualenv/bin/activate`:
export LD\_LIBRARY\_PATH="/usr/local/lib"
Now, when active, Django 2.2+ should work fine in the virtualenv. Hope that helps. | This error comes because your virtual environment could not connect to newly updated sqlite3 database. For that you have to update your sqlite3 database version manually and then give path of it to your virtual environment. Kindly follow below steps:
1. Download latest sqlite3 from official site. (<https://www.sqlite.org/download.html>)`wget http://www.sqlite.org/sqlite-autoconf-3070603.tar.gz`
2. Then go to that folder and fire command.
`tar xvfz sqlite-autoconf-3070603.tar.gz`
3. Go to respective folder. `cd sqlite-autoconf-3070603`
4. `./configure`
5. `make`
6. `make install` It may take too time but wait till end. If it's take too much then terminate that process and continue rest of steps.
7. Now you successfully install updated sqlite3. Now fire this command `sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations`
8. Open your activate file of virtual environment (e.g., venv/bin/activate) and add this line top of the file...
`export LD_LIBRARY_PATH="/usr/local/lib"`
9. Now for checking you can type this commands to your python shell
```py
$ python
Python 3.7.3 (default, Apr 12 2019, 16:23:13)
>>> import sqlite3
>>> sqlite3.sqlite_version
'3.27.2'
``` |
46,143,091 | I'm pretty new to python so it's a basic question.
I have data that I imported from a csv file. Each row reflects a person and his data. Two attributes are Sex and Pclass. I want to add a new column (predictions) that is fully depended on those two in one line. If both attributes' values are 1 it should assign 1 to the person's predictions data field, 0 otherwise.
How do I do it in one line (let's say with Pandas)? | 2017/09/10 | [
"https://Stackoverflow.com/questions/46143091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5252187/"
] | You could try adding a composite index
```
create index test on screenshot (DateTaken, id)
``` | Try running this query:
```
SELECT COUNT(*) as total
FROM screenshot
WHERE DateTaken BETWEEN '2000-05-01' AND '2000-06-10';
```
The reference to `ID` in the `SELECT` could be affecting the use of the index. |
46,143,091 | I'm pretty new to python so it's a basic question.
I have data that I imported from a csv file. Each row reflects a person and his data. Two attributes are Sex and Pclass. I want to add a new column (predictions) that is fully depended on those two in one line. If both attributes' values are 1 it should assign 1 to the person's predictions data field, 0 otherwise.
How do I do it in one line (let's say with Pandas)? | 2017/09/10 | [
"https://Stackoverflow.com/questions/46143091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5252187/"
] | There is no problem. Your index is fine. To explain...
The `5730138` in `EXPLAIN` is an *estimate*. It can be larger or smaller than the actual value, sometimes by a large amount. Do not be bothered by it.
You have 2.8M of screenshots in that date range, correct? Well, it could take 15 seconds to scan the index to count that many rows.
If you would like further analysis, please provide:
RAM size
`innodb_buffer_pool_size`
`SHOW CREATE TABLE screenshot;` (this will show the Engine)
How big the table is (GB)
What type of disk you have (spinning versus SSD)
With those, we can discuss further the impact of caching and I/O and engine. And it may help explain the "15 seconds" versus "20".
(And, yes, use `COUNT(*)`, not `COUNT(x)` unless you need to test `x` for NULL.)
If you are using InnoDB, then `INDEX(DateTaken, id)` is identical to `INDEX(DateTaken)`, so I suggest you were hasty at accepting that answer.
**Buffer pool**
`innodb_buffer_pool_size` should be set to about 70% of RAM. What you have is so tiny (the old 16M default), that not even the suggested index can fit in cache. Hence, the query will always be hitting the disk, at least some of the time. Increasing the buffer pool should significantly improve the speed, perhaps down to 2 seconds. | Try running this query:
```
SELECT COUNT(*) as total
FROM screenshot
WHERE DateTaken BETWEEN '2000-05-01' AND '2000-06-10';
```
The reference to `ID` in the `SELECT` could be affecting the use of the index. |
71,568,396 | We are using a beam multi-language pipeline using python and java(ref <https://beam.apache.org/documentation/sdks/python-multi-language-pipelines/>). We are creating a cross-language pipeline using java. We have some external jar files that required a java library path. Code gets compiled properly and is able to create a jar file. When I run the jar file it creates a Grpc server but when I use the python pipeline to call External transform it is not picking up the java library path it picks the default java library path.
![jni_emdq required library path to overwrite](https://i.stack.imgur.com/N24DB.png)
Tried -Djava.library.path=<path\_to\_dll> while running jar file.
Tried System.setProperty(“java.library.path”, “/path/to/library”).
(Ref <https://examples.javacodegeeks.com/java-library-path-what-is-java-library-and-how-to-use/>)
Tried JvmInitializer of beam to overwrite system property. (Ref <https://examples.javacodegeeks.com/java-library-path-what-is-java-library-and-how-to-use/>)
Tried to pull code beam open source and tried to overwrite system proprty before expansion starts. It overwrite but it is not picking correct java path when calls using python external transform. (ref <https://github.com/apache/beam/blob/master/sdks/java/expansion-service/src/main/java/org/apache/beam/sdk/expansion/service/ExpansionService.java>) | 2022/03/22 | [
"https://Stackoverflow.com/questions/71568396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9648514/"
] | A Worksheet Change Event: Monitor Change in Column's Data
---------------------------------------------------------
* I personally would go with JvdV's suggestion in the comments.
* On each manual change of a cell, e.g. in column `A`, it will check the formula
`=SUM(A2:ALastRow)` in cell `A1` and if it is not correct it will overwrite it with the correct one.
* You can use this for multiple non-adjacent columns e.g. `"A,C:D,E"`.
* Nothing needs to be run. Just copy the code into the appropriate sheet module e.g. `Sheet1` and exit the Visual Basic Editor.
**Sheet Module e.g. `Sheet1` (not Standard Module e.g. `Module1`)**
```
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
UpdateFirstRowFormula Target, "A"
End Sub
Private Sub UpdateFirstRowFormula( _
ByVal Target As Range, _
ByVal ColumnList As String)
On Error GoTo ClearError
Dim ws As Worksheet: Set ws = Target.Worksheet
Dim Cols() As String: Cols = Split(ColumnList, ",")
Application.EnableEvents = False
Dim irg As Range, arg As Range, crg As Range, lCell As Range
Dim n As Long
Dim Formula As String
For n = 0 To UBound(Cols)
With ws.Columns(Cols(n))
With .Resize(.Rows.Count - 1).Offset(1)
Set irg = Intersect(.Cells, Target.EntireColumn)
End With
End With
If Not irg Is Nothing Then
For Each arg In irg.Areas
For Each crg In arg.Columns
Set lCell = crg.Find("*", , xlFormulas, , , xlPrevious)
If Not lCell Is Nothing Then
Formula = "=SUM(" & crg.Cells(1).Address(0, 0) & ":" _
& lCell.Address(0, 0) & ")"
With crg.Cells(1).Offset(-1)
If .Formula <> Formula Then .Formula = Formula
End With
End If
Next crg
Next arg
Set irg = Nothing
End If
Next n
SafeExit:
If Not Application.EnableEvents Then Application.EnableEvents = True
Exit Sub
ClearError:
Debug.Print "Run-time error '" & Err.Number & "': " & Err.Description
Resume SafeExit
End Sub
``` | Use a nested function as below:
=SUM(OFFSET(A2,,,COUNTA(A2:A26))) |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemented, and what makes I/O asynchronous. I was trying to read the source code, but it's thousands of lines of not the highest grade C code, a lot of which deals with auxiliary objects, but most crucially, it is hard to connect between Python syntax and what C code it would translate into.
Asycnio's own documentation is even less helpful. There's no information there about how it works, only some guidelines about how to use it, which are also sometimes misleading / very poorly written.
I'm familiar with Go's implementation of coroutines, and was kind of hoping that Python did the same thing. If that was the case, the code I came up in the post linked above would have worked. Since it didn't, I'm now trying to figure out why. My best guess so far is as follows, please correct me where I'm wrong:
1. Procedure definitions of the form `async def foo(): ...` are actually interpreted as methods of a class inheriting `coroutine`.
2. Perhaps, `async def` is actually split into multiple methods by `await` statements, where the object, on which these methods are called is able to keep track of the progress it made through the execution so far.
3. If the above is true, then, essentially, execution of a coroutine boils down to calling methods of coroutine object by some global manager (loop?).
4. The global manager is somehow (how?) aware of when I/O operations are performed by Python (only?) code and is able to choose one of the pending coroutine methods to execute after the current executing method relinquished control (hit on the `await` statement).
In other words, here's my attempt at "desugaring" of some `asyncio` syntax into something more understandable:
```
async def coro(name):
print('before', name)
await asyncio.sleep()
print('after', name)
asyncio.gather(coro('first'), coro('second'))
# translated from async def coro(name)
class Coro(coroutine):
def before(self, name):
print('before', name)
def after(self, name):
print('after', name)
def __init__(self, name):
self.name = name
self.parts = self.before, self.after
self.pos = 0
def __call__():
self.parts[self.pos](self.name)
self.pos += 1
def done(self):
return self.pos == len(self.parts)
# translated from asyncio.gather()
class AsyncIOManager:
def gather(*coros):
while not every(c.done() for c in coros):
coro = random.choice(coros)
coro()
```
Should my guess prove correct: then I have a problem. How does I/O actually happen in this scenario? In a separate thread? Is the whole interpreter suspended and I/O happens outside the interpreter? What exactly is meant by I/O? If my python procedure called C `open()` procedure, and it in turn sent interrupt to kernel, relinquishing control to it, how does Python interpreter know about this and is able to continue running some other code, while kernel code does the actual I/O and until it wakes up the Python procedure which sent the interrupt originally? How can Python interpreter in principle, be aware of this happening? | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | It all boils down to the two main challenges that asyncio is addressing:
* How to perform multiple I/O in a single thread?
* How to implement cooperative multitasking?
The answer to the first point has been around for a long while and is called a [select loop](https://en.wikipedia.org/wiki/Asynchronous_I/O#Select(/poll)_loops). In python, it is implemented in the [selectors module](https://docs.python.org/3/library/selectors.html).
The second question is related to the concept of [coroutine](https://en.wikipedia.org/wiki/Coroutine), i.e. functions that can stop their execution and be restored later on. In python, coroutines are implemented using [generators](https://wiki.python.org/moin/Generators) and the [yield from](https://www.python.org/dev/peps/pep-0380/) statement. That's what is hiding behind the [async/await syntax](https://www.python.org/dev/peps/pep-0492/).
More resources in this [answer](https://stackoverflow.com/a/41208685/2846140).
---
**EDIT:** Addressing your comment about goroutines:
The closest equivalent to a goroutine in asyncio is actually not a coroutine but a task (see the difference in the [documentation](https://docs.python.org/3/library/asyncio-task.html)). In python, a coroutine (or a generator) knows nothing about the concepts of event loop or I/O. It simply is a function that can stop its execution using `yield` while keeping its current state, so it can be restored later on. The `yield from` syntax allows for chaining them in a transparent way.
Now, within an asyncio task, the coroutine at the very bottom of the chain always ends up yielding a [future](https://docs.python.org/3.4/library/asyncio-task.html#asyncio.Future). This future then bubbles up to the event loop, and gets integrated into the inner machinery. When the future is set to done by some other inner callback, the event loop can restore the task by sending the future back into the coroutine chain.
---
**EDIT:** Addressing some of the questions in your post:
>
> How does I/O actually happen in this scenario? In a separate thread? Is the whole interpreter suspended and I/O happens outside the interpreter?
>
>
>
No, nothing happens in a thread. I/O is always managed by the event loop, mostly through file descriptors. However the registration of those file descriptors is usually hidden by high-level coroutines, making the dirty work for you.
>
> What exactly is meant by I/O? If my python procedure called C open() procedure, and it in turn sent interrupt to kernel, relinquishing control to it, how does Python interpreter know about this and is able to continue running some other code, while kernel code does the actual I/O and until it wakes up the Python procedure which sent the interrupt originally? How can Python interpreter in principle, be aware of this happening?
>
>
>
An I/O is any blocking call. In asyncio, all the I/O operations should go through the event loop, because as you said, the event loop has no way to be aware that a blocking call is being performed in some synchronous code. That means you're not supposed to use a synchronous `open` within the context of a coroutine. Instead, use a dedicated library such [aiofiles](https://github.com/Tinche/aiofiles) which provides an asynchronous version of `open`. | If you picture an airport control tower, with many planes waiting to land on the same runway. The control tower can be seen as the event loop and runway as the thread. Each plane is a separate function waiting to execute. In reality only one plane can land on the runway at a time. What asyncio basically does it allows many planes to land simultaneously on the same runway by using the event loop to suspend functions and allow other functions to run when you use the await syntax it basically means that plane(function can be suspended and allow other functions to process |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemented, and what makes I/O asynchronous. I was trying to read the source code, but it's thousands of lines of not the highest grade C code, a lot of which deals with auxiliary objects, but most crucially, it is hard to connect between Python syntax and what C code it would translate into.
Asycnio's own documentation is even less helpful. There's no information there about how it works, only some guidelines about how to use it, which are also sometimes misleading / very poorly written.
I'm familiar with Go's implementation of coroutines, and was kind of hoping that Python did the same thing. If that was the case, the code I came up in the post linked above would have worked. Since it didn't, I'm now trying to figure out why. My best guess so far is as follows, please correct me where I'm wrong:
1. Procedure definitions of the form `async def foo(): ...` are actually interpreted as methods of a class inheriting `coroutine`.
2. Perhaps, `async def` is actually split into multiple methods by `await` statements, where the object, on which these methods are called is able to keep track of the progress it made through the execution so far.
3. If the above is true, then, essentially, execution of a coroutine boils down to calling methods of coroutine object by some global manager (loop?).
4. The global manager is somehow (how?) aware of when I/O operations are performed by Python (only?) code and is able to choose one of the pending coroutine methods to execute after the current executing method relinquished control (hit on the `await` statement).
In other words, here's my attempt at "desugaring" of some `asyncio` syntax into something more understandable:
```
async def coro(name):
print('before', name)
await asyncio.sleep()
print('after', name)
asyncio.gather(coro('first'), coro('second'))
# translated from async def coro(name)
class Coro(coroutine):
def before(self, name):
print('before', name)
def after(self, name):
print('after', name)
def __init__(self, name):
self.name = name
self.parts = self.before, self.after
self.pos = 0
def __call__():
self.parts[self.pos](self.name)
self.pos += 1
def done(self):
return self.pos == len(self.parts)
# translated from asyncio.gather()
class AsyncIOManager:
def gather(*coros):
while not every(c.done() for c in coros):
coro = random.choice(coros)
coro()
```
Should my guess prove correct: then I have a problem. How does I/O actually happen in this scenario? In a separate thread? Is the whole interpreter suspended and I/O happens outside the interpreter? What exactly is meant by I/O? If my python procedure called C `open()` procedure, and it in turn sent interrupt to kernel, relinquishing control to it, how does Python interpreter know about this and is able to continue running some other code, while kernel code does the actual I/O and until it wakes up the Python procedure which sent the interrupt originally? How can Python interpreter in principle, be aware of this happening? | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | It all boils down to the two main challenges that asyncio is addressing:
* How to perform multiple I/O in a single thread?
* How to implement cooperative multitasking?
The answer to the first point has been around for a long while and is called a [select loop](https://en.wikipedia.org/wiki/Asynchronous_I/O#Select(/poll)_loops). In python, it is implemented in the [selectors module](https://docs.python.org/3/library/selectors.html).
The second question is related to the concept of [coroutine](https://en.wikipedia.org/wiki/Coroutine), i.e. functions that can stop their execution and be restored later on. In python, coroutines are implemented using [generators](https://wiki.python.org/moin/Generators) and the [yield from](https://www.python.org/dev/peps/pep-0380/) statement. That's what is hiding behind the [async/await syntax](https://www.python.org/dev/peps/pep-0492/).
More resources in this [answer](https://stackoverflow.com/a/41208685/2846140).
---
**EDIT:** Addressing your comment about goroutines:
The closest equivalent to a goroutine in asyncio is actually not a coroutine but a task (see the difference in the [documentation](https://docs.python.org/3/library/asyncio-task.html)). In python, a coroutine (or a generator) knows nothing about the concepts of event loop or I/O. It simply is a function that can stop its execution using `yield` while keeping its current state, so it can be restored later on. The `yield from` syntax allows for chaining them in a transparent way.
Now, within an asyncio task, the coroutine at the very bottom of the chain always ends up yielding a [future](https://docs.python.org/3.4/library/asyncio-task.html#asyncio.Future). This future then bubbles up to the event loop, and gets integrated into the inner machinery. When the future is set to done by some other inner callback, the event loop can restore the task by sending the future back into the coroutine chain.
---
**EDIT:** Addressing some of the questions in your post:
>
> How does I/O actually happen in this scenario? In a separate thread? Is the whole interpreter suspended and I/O happens outside the interpreter?
>
>
>
No, nothing happens in a thread. I/O is always managed by the event loop, mostly through file descriptors. However the registration of those file descriptors is usually hidden by high-level coroutines, making the dirty work for you.
>
> What exactly is meant by I/O? If my python procedure called C open() procedure, and it in turn sent interrupt to kernel, relinquishing control to it, how does Python interpreter know about this and is able to continue running some other code, while kernel code does the actual I/O and until it wakes up the Python procedure which sent the interrupt originally? How can Python interpreter in principle, be aware of this happening?
>
>
>
An I/O is any blocking call. In asyncio, all the I/O operations should go through the event loop, because as you said, the event loop has no way to be aware that a blocking call is being performed in some synchronous code. That means you're not supposed to use a synchronous `open` within the context of a coroutine. Instead, use a dedicated library such [aiofiles](https://github.com/Tinche/aiofiles) which provides an asynchronous version of `open`. | It allows you to write single-threaded asynchronous code and implement concurrency in Python. Basically, `asyncio` provides an event loop for asynchronous programming. For example, if we need to make requests without blocking the main thread, we can use the `asyncio` library.
The asyncio module allows for the implementation of asynchronous programming
using a combination of the following elements:
* Event loop: The asyncio module allows an event loop per process.
* Coroutines: A coroutine is a generator that follows certain conventions. Its most interesting feature is that it can be suspended during execution to wait for external processing (the some routine in I/O) and return from the point it had stopped when the external processing was done.
* Futures: Futures represent a process that has still not finished. A future is an object that is supposed to have a result in the future and represents uncompleted tasks.
* Tasks: This is a subclass of `asyncio`.Future that encapsulates and manages
coroutines. We can use the asyncio.Task object to encapsulate a coroutine.
The most important concept within `asyncio` is the event loop. An event loop
allows you to write asynchronous code using either callbacks or coroutines.
The keys to understanding `asyncio` are the terms of coroutines and the event
loop. **Coroutines** are stateful functions whose execution can be stopped while another I/O operation is being executed. An event loop is used to orchestrate the execution of the coroutines.
To run any coroutine function, we need to get an event loop. We can do this
with
```
loop = asyncio.get_event_loop()
```
This gives us a `BaseEventLoop` object. This has a `run_until_complete` method that takes in a coroutine and runs it until completion. Then, the coroutine returns a result. At a low level, an event loop executes the `BaseEventLoop.rununtilcomplete(future)` method. |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 1