qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
14,075,337 | I have a csv file with date, time., price, mag, signal.
62035 rows; there are 42 times of day associated to each unique date in the file.
For each date, when there is an 'S' in the signal column append the corresponding price at the time the 'S' occurred. Below is the attempt.
```
from pandas import *
from numpy imp... | 2012/12/28 | [
"https://Stackoverflow.com/questions/14075337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1374969/"
] | Using @Max Fellows' handy example data, we can have a look at it in `pandas`. [BTW, you should always try to provide a short, self-contained, correct example (see [here](http://sscce.org/) for more details), so that the people trying to help you don't have to spend time coming up with one.]
First, `import pandas as pd... | This is what I think you're trying to accomplish based on your edit: for every date in your CSV file, group the date along with a list of prices for each item with a signal of "S".
You didn't include any sample data in your question, so I made a test one that I hope matches the format you described:
```
12/28/2012,1:... |
70,352,477 | I am wondering if it is possible to do grouping of lists in python in a simple way without importing any libraries.
and example of input could be:
```py
a="0 0 1 2 1"
```
and output
```
[(0,0),(1,1),(2)]
```
I am thinking something like the implementation of itertools groupby
```py
class groupby:
# [k for k... | 2021/12/14 | [
"https://Stackoverflow.com/questions/70352477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12868928/"
] | I just realized how to do it.
```py
{k:[v for v in a.split() if v == k] for k in set(a.split())}
```
or
```py
[tuple(v for v in a.split() if v == k) for k in set(a.split())]
```
however - this solution can not be used on dictionaties because dicts are not hashable - so maybe thats one of the reasons why the itert... | How about using `a.split(' ')` then using for loop to do that? |
70,352,477 | I am wondering if it is possible to do grouping of lists in python in a simple way without importing any libraries.
and example of input could be:
```py
a="0 0 1 2 1"
```
and output
```
[(0,0),(1,1),(2)]
```
I am thinking something like the implementation of itertools groupby
```py
class groupby:
# [k for k... | 2021/12/14 | [
"https://Stackoverflow.com/questions/70352477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12868928/"
] | To group the items by value (as opposed to grouping by changes as itertools groupby would do), you can use a list comprehension that embeds a dictionary to organize the data into lists:
```
a="0 0 1 2 1"
groups = [ g[v] for g in [dict()] for v in map(int,a.split())
if g.setdefault(v,[]).append(v) or len(g... | How about using `a.split(' ')` then using for loop to do that? |
63,315,233 | If I have two matrices a and b, is there any function I can find the matrix x, that when dot multiplied by a makes b? Looking for python solutions, for matrices in the form of numpy arrays. | 2020/08/08 | [
"https://Stackoverflow.com/questions/63315233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12818944/"
] | This problem of finding X such as `A*X=B` is equivalent to search the "inverse of A", i.e. a matrix such as `X = Ainverse * B`.
For information, in math `Ainverse` is noted `A^(-1)` ("A to the power -1", but you can say "A inverse" instead).
In numpy, this is a builtin function to find the inverse of a matrix `a`:
`... | if `A` is a full rank, square matrix
```
import numpy as np
from numpy.linalg import inv
X = inv(A) @ B
```
if not, then such a matrix does not exist, but we can approximate it
```
import numpy as np
from numpy.linalg import inv
X = inv(A.T @ A) @ A.T @ B
``` |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | How about:
```
>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'
``` | The most pythonic solution is
```
tuples = [(1, 2), (3, 4)]
tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]
result = ', '.join(tuple_strings)
``` |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | you might want to use something such simple as:
```
>>> l = [(1,2), (3,4)]
>>> str(l).strip('[]')
'(1, 2), (3, 4)'
```
.. which is handy, but not guaranteed to work correctly | I think this is pretty neat:
```python
>>> l = [(1,2), (3,4)]
>>> "".join(str(l)).strip('[]')
'(1,2), (3,4)'
```
Try it, it worked like a charm for me. |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | I think this is pretty neat:
```python
>>> l = [(1,2), (3,4)]
>>> "".join(str(l)).strip('[]')
'(1,2), (3,4)'
```
Try it, it worked like a charm for me. | Three more :)
```
l = [(1,2), (3,4)]
unicode(l)[1:-1]
# u'(1, 2), (3, 4)'
("%s, "*len(l) % tuple(l))[:-2]
# '(1, 2), (3, 4)'
", ".join(["%s"]*len(l)) % tuple(l)
# '(1, 2), (3, 4)'
``` |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | How about
```
l = [(1, 2), (3, 4)]
print repr(l)[1:-1]
# (1, 2), (3, 4)
``` | Three more :)
```
l = [(1,2), (3,4)]
unicode(l)[1:-1]
# u'(1, 2), (3, 4)'
("%s, "*len(l) % tuple(l))[:-2]
# '(1, 2), (3, 4)'
", ".join(["%s"]*len(l)) % tuple(l)
# '(1, 2), (3, 4)'
``` |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | How about:
```
>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'
``` | I think this is pretty neat:
```python
>>> l = [(1,2), (3,4)]
>>> "".join(str(l)).strip('[]')
'(1,2), (3,4)'
```
Try it, it worked like a charm for me. |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | You can try something like this ([see also on ideone.com](http://ideone.com/VfbJp)):
```
myList = [(1,2),(3,4)]
print ",".join("(%s,%s)" % tup for tup in myList)
# (1,2),(3,4)
``` | The most pythonic solution is
```
tuples = [(1, 2), (3, 4)]
tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]
result = ', '.join(tuple_strings)
``` |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | The most pythonic solution is
```
tuples = [(1, 2), (3, 4)]
tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]
result = ', '.join(tuple_strings)
``` | Three more :)
```
l = [(1,2), (3,4)]
unicode(l)[1:-1]
# u'(1, 2), (3, 4)'
("%s, "*len(l) % tuple(l))[:-2]
# '(1, 2), (3, 4)'
", ".join(["%s"]*len(l)) % tuple(l)
# '(1, 2), (3, 4)'
``` |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | you might want to use something such simple as:
```
>>> l = [(1,2), (3,4)]
>>> str(l).strip('[]')
'(1, 2), (3, 4)'
```
.. which is handy, but not guaranteed to work correctly | Three more :)
```
l = [(1,2), (3,4)]
unicode(l)[1:-1]
# u'(1, 2), (3, 4)'
("%s, "*len(l) % tuple(l))[:-2]
# '(1, 2), (3, 4)'
", ".join(["%s"]*len(l)) % tuple(l)
# '(1, 2), (3, 4)'
``` |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | you might want to use something such simple as:
```
>>> l = [(1,2), (3,4)]
>>> str(l).strip('[]')
'(1, 2), (3, 4)'
```
.. which is handy, but not guaranteed to work correctly | You can try something like this ([see also on ideone.com](http://ideone.com/VfbJp)):
```
myList = [(1,2),(3,4)]
print ",".join("(%s,%s)" % tup for tup in myList)
# (1,2),(3,4)
``` |
3,292,643 | Which is the most pythonic way to convert a list of tuples to string?
I have:
```
[(1,2), (3,4)]
```
and I want:
```
"(1,2), (3,4)"
```
My solution to this has been:
```
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
```
Is there a more pythonic way to do this? | 2010/07/20 | [
"https://Stackoverflow.com/questions/3292643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170912/"
] | How about:
```
>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'
``` | Three more :)
```
l = [(1,2), (3,4)]
unicode(l)[1:-1]
# u'(1, 2), (3, 4)'
("%s, "*len(l) % tuple(l))[:-2]
# '(1, 2), (3, 4)'
", ".join(["%s"]*len(l)) % tuple(l)
# '(1, 2), (3, 4)'
``` |
14,897,426 | My XML file test.xml contains the following tags
```
<?xml version="1.0" encoding="ISO-8859-1"?>
<AppName>
<author>Subho Halder</author>
<description> Description</description>
<date>2012-11-06</date>
<out>Output 1</out>
<out>Output 2</out>
<out>Output 3</out>
</AppName>
```
I wan... | 2013/02/15 | [
"https://Stackoverflow.com/questions/14897426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122840/"
] | Try [`len(dom.getElementsByTagName('out'))`](http://docs.python.org/2/library/xml.dom.html#document-objects)
```
from xml.dom.minidom import parseString
file = open('test.xml','r')
data = file.read()
file.close()
dom = parseString(data)
print len(dom.getElementsByTagName('out'))
```
gives
```
3
``` | I would recommend using lxml
```
import lxml.etree
doc = lxml.etree.parse(test.xml)
count = doc.xpath('count(//out)')
```
You can look up more information on XPATH [here](http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/xpath.html). |
14,897,426 | My XML file test.xml contains the following tags
```
<?xml version="1.0" encoding="ISO-8859-1"?>
<AppName>
<author>Subho Halder</author>
<description> Description</description>
<date>2012-11-06</date>
<out>Output 1</out>
<out>Output 2</out>
<out>Output 3</out>
</AppName>
```
I wan... | 2013/02/15 | [
"https://Stackoverflow.com/questions/14897426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122840/"
] | Try [`len(dom.getElementsByTagName('out'))`](http://docs.python.org/2/library/xml.dom.html#document-objects)
```
from xml.dom.minidom import parseString
file = open('test.xml','r')
data = file.read()
file.close()
dom = parseString(data)
print len(dom.getElementsByTagName('out'))
```
gives
```
3
``` | If you want you can also use [ElementTree](https://docs.python.org/2/library/xml.etree.elementtree.html). With the function below you will get a dictionary with the tag names as the key and number of times this tag is encountered in you XML file.
```
import xml.etree.ElementTree as ET
from collections import Counter
... |
56,911,541 | I am new to python/flask so need your help.
I have multiselect dropdown like below
I have a multiselect in html file like this:
```
<select multiple id="mymultiselect" name="mymultiselect">
<option value="1">India</option>
<option value="2">USA</option>
<option value="3"... | 2019/07/06 | [
"https://Stackoverflow.com/questions/56911541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11746629/"
] | One way would be to create a pipe in the parent process. Each child process closes the write end of the pipe, then calls `read` (which blocks). When the parent process is ready, it closes both ends of its pipe. This makes all the children return from `read` and they can now close their read end of the pipe and proceed ... | For situations like this, I sometimes use [atomic](https://en.cppreference.com/w/c/atomic) operation. You can use atomic flags to notify sub-process, but it creates busy-waiting. So you can use it on a very special cases.
Other method is to create an event with something like `pthread_cond_broadcast()` and `pthread_co... |
45,734,960 | I want to write my own small mailserver application in python with **aiosmtpd**
a) for educational purpose to better understand mailservers
b) to realize my own features
So my question is, what is missing (besides aiosmtpd) for an **Mail-Transfer-Agent**, that can send and receive emails to/from other full MTAs ... | 2017/08/17 | [
"https://Stackoverflow.com/questions/45734960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6002171/"
] | The most important thing about running your own SMTP server is that you **must not be an open relay**. That means you must not accept messages from strangers and relay them to any destination on the internet, since that would enable spammers to send spam through your SMTP server -- which would quickly get you blocked.
... | You may consider the following features:
* Message threading
* Support for Delivery status
* Support for POP and IMAP protocols
* Supports for protocols such as RFC 2821 SMTP and RFC 2033 LMTP email message transport
* Support Multiple message tagging
* Support for PGP/MIME (RFC2015)
* Support list-reply
* Lets each u... |
45,734,960 | I want to write my own small mailserver application in python with **aiosmtpd**
a) for educational purpose to better understand mailservers
b) to realize my own features
So my question is, what is missing (besides aiosmtpd) for an **Mail-Transfer-Agent**, that can send and receive emails to/from other full MTAs ... | 2017/08/17 | [
"https://Stackoverflow.com/questions/45734960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6002171/"
] | aiosmtpd is an excellent tool for writing custom routing and header rewriting rules for email. However, aiosmtpd is not an MTA, since it does not do message queuing or DSN generation. One popular choice of MTA is postfix, and since postfix can be configured to relay all emails for a domain to another local SMTP server ... | You may consider the following features:
* Message threading
* Support for Delivery status
* Support for POP and IMAP protocols
* Supports for protocols such as RFC 2821 SMTP and RFC 2033 LMTP email message transport
* Support Multiple message tagging
* Support for PGP/MIME (RFC2015)
* Support list-reply
* Lets each u... |
45,734,960 | I want to write my own small mailserver application in python with **aiosmtpd**
a) for educational purpose to better understand mailservers
b) to realize my own features
So my question is, what is missing (besides aiosmtpd) for an **Mail-Transfer-Agent**, that can send and receive emails to/from other full MTAs ... | 2017/08/17 | [
"https://Stackoverflow.com/questions/45734960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6002171/"
] | aiosmtpd is an excellent tool for writing custom routing and header rewriting rules for email. However, aiosmtpd is not an MTA, since it does not do message queuing or DSN generation. One popular choice of MTA is postfix, and since postfix can be configured to relay all emails for a domain to another local SMTP server ... | The most important thing about running your own SMTP server is that you **must not be an open relay**. That means you must not accept messages from strangers and relay them to any destination on the internet, since that would enable spammers to send spam through your SMTP server -- which would quickly get you blocked.
... |
34,147,515 | When playing around with the Python interpreter, I stumbled upon this conflicting case regarding the `is` operator:
If the evaluation takes place in the function it returns `True`, if it is done outside it returns `False`.
```
>>> def func():
... a = 1000
... b = 1000
... return a is b
...
>>> a = 1000
>... | 2015/12/08 | [
"https://Stackoverflow.com/questions/34147515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4952130/"
] | tl;dr:
------
As the [reference manual](https://docs.python.org/3.5/reference/executionmodel.html#structure-of-a-program) states:
>
> A block is a piece of Python program text that is executed as a unit.
> The following are blocks: a module, a function body, and a class definition.
> **Each command typed interactive... | At the interactive prompt, entry are [compiled in a *single* mode](https://docs.python.org/3/library/functions.html#compile) which processes one complete statement at a time. The compiler itself (in [Python/compile.c](https://hg.python.org/cpython/file/tip/Python/compile.c)) tracks the constants in a dictionary called ... |
23,819,117 | I use python 3.4 and I can format strings in two ways:
```
print("%d %d" %(1, 2))
```
and
```
print("{:d} {:d}".format(1, 2))
```
In [documentation](https://docs.python.org/2/library/string.html) they show examples only using 'format'. Do it mean that using '%' is not good, or it does not matter which version to... | 2014/05/23 | [
"https://Stackoverflow.com/questions/23819117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3654650/"
] | Quoting from the [official documentation](https://docs.python.org/2/library/stdtypes.html#str.format),
>
> This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.
>
>
>
So, `format` is the recommended way ... | In addition to the recommendations on the official site the format() method is more flexible, powerful and readable than operator '%'.
For example:
```
>>> '{2}, {1}, {0}'.format(*'abc')
'c, b, a'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'... |
61,417,765 | Disclaimer. I am new to python and trying to learn. I have a list of dictionaries containing address information I would like to iterate over and then pass into a function as arguments.
`print(data)`
`[{'firstName': 'John', 'lastName': 'Smith', 'address': '123 Lane', 'country': 'United States', 'state': 'TX', 'city':... | 2020/04/24 | [
"https://Stackoverflow.com/questions/61417765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3950634/"
] | You already have all the logic to process a *single* data point, just expand it to *multiple* data points as shown below using a loop.
```
from usps import USPSApi, Address
for item in data:
kwargs = dict()
kwargs['name'] = item['lastName']
kwargs['address_1'] = item['address']
kwargs['city'] = item[... | If the intention is to get the key's values in a variable:
```
d_data = [{'firstName': 'John', 'lastName': 'Smith', 'address': '123 Lane', 'country': 'United States', 'state': 'TX', 'city': 'Springfield', 'zip': '12345'}, {'firstName': 'Mary', 'lastName': 'Smith', 'address': '321 Lanet', 'country': 'United States', 's... |
55,239,297 | I'm never done development in a career as a software programmer
I'm given this domain name on NameCheap with the server disk. Now I design Django app and trying to deploy on the server but I had problems (stated below)
```
[ E 2019-03-19 06:23:19.7356 598863/T2n age/Cor/App/Implementation.cpp:221 ]: Could not spawn p... | 2019/03/19 | [
"https://Stackoverflow.com/questions/55239297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10865416/"
] | When you setup a python app in cpanel, you specify the folder where you have setup the app. That will be the folder that will contain your passenger\_wsgi.py file. You have to upload your django project to that same folder. To make sure they you have uploaded to the right directory, just have this simple check\_ your `... | The answer very simple, my server is using a programme name passenger, the official website for more information: <https://www.phusionpassenger.com/>
Now error very simply; **passenger can't find my application**, All I did was move my project and app folder on the same layer passenger\_wsgi.py and it works like charm... |
62,903,138 | Here is my attempt:
```
int* globalvar = new int[8];
void cpp_init(){
for (int i = 0; i < 8; i++)
globalvar[i] = 0;
}
void writeAtIndex(int index, int value){
globalvar[index] = value;
}
int accessIndex(int index){
return globalvar[index];
}
BOOST_PYTHON_MODULE(MpUtils){
def("cpp_init", &cpp_in... | 2020/07/14 | [
"https://Stackoverflow.com/questions/62903138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11627201/"
] | Processes can generally access only their own memory space.
You can possibly use the [shared\_memory](https://docs.python.org/3/library/multiprocessing.shared_memory.html#multiprocessing.shared_memory.SharedMemory) module of multiprocessing to share the same array across processes. See example in the linked page. | The following loop will create a list of processes with consecutive first `args`, from `0` to `9`. (First process has `0`, second one `1` and so on.)
```
for i in range(0, 10):
processes.append( Process( target=do_stuff, args=(i,) ) )
```
The writing may take a list of numbers, but the call to `writeAtIn... |
33,697,379 | Now this could be me being **very** stupid here but please see the below code.
I am trying to work out what percentage of my carb goal I've already consumed at the point I run the script. I get the totals and store them in `carbsConsumed` and `carbsGoal`. `carbsPercent` then calculates the percentage consumed. Howeve... | 2015/11/13 | [
"https://Stackoverflow.com/questions/33697379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4461239/"
] | Try this:
```
carbsPercent = (float(carbsConsumed) / carbsGoal) * 100
```
The problem is that in Python 2.7, the default division mode is integer division, so 1000/1200 = 0. The way you force Python to change that is to cast at least one operand IN THE DIVISION operation to a float. | For easily portable code, in `python2`, see <https://stackoverflow.com/a/10768737/610569>:
```
from __future__ import division
carbsPercent = (carbsConsumed / carbsGoal) * 100
```
E.g.
```
$ python
>>> from __future__ import division
>>> 6 / 5
1.2
$ python3
>>> 6 / 5
1.2
``` |
46,520,136 | Is there any way to run a function from python and a function from java in one app in parallel and get the result of each function to do another process? | 2017/10/02 | [
"https://Stackoverflow.com/questions/46520136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6700881/"
] | There are at least three ways to achieve that.
a) You could use `java.lang.Runtime` (as in `Runtime.getRuntime().exec(...)`) to launch an external process (from Java side), the external process being your Python script.
b) You could do the same as a), just using Python as launcher.
c) You could use some Python-Java ... | You should probably look for **[jython](https://wiki.python.org/jython/WhyJython)**. This support `Java` and `Python`. |
40,239,866 | I'm trying to list the containers under an azure account using the python sdk - why do I get the following?
```
>>> azure.storage.blob.baseblobservice.BaseBlobService(account_name='x', account_key='x').list_containers()
>>> <azure.storage.models.ListGenerator at 0x7f7cf935fa58>
```
Surely the above is a call to the ... | 2016/10/25 | [
"https://Stackoverflow.com/questions/40239866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693831/"
] | you get the following according to [source code](https://github.com/Azure/azure-storage-python/blob/54e60c8c029f41d2573233a70021c4abf77ce67c/azure-storage-blob/azure/storage/blob/baseblobservice.py#L609) it return `ListGenerator(resp, self._list_containers, (), kwargs)`
you can access what you want as follow:
python2... | for python 3 and more recent distribution of `azure` libraries, you can do:
```
from azure.storage.blob import BlockBlobService
block_blob_service = BlockBlobService(account_name=account_name, account_key=account_key)
containers = block_blob_service.list_containers()
for c in containers:
print(c.name)
``` |
40,239,866 | I'm trying to list the containers under an azure account using the python sdk - why do I get the following?
```
>>> azure.storage.blob.baseblobservice.BaseBlobService(account_name='x', account_key='x').list_containers()
>>> <azure.storage.models.ListGenerator at 0x7f7cf935fa58>
```
Surely the above is a call to the ... | 2016/10/25 | [
"https://Stackoverflow.com/questions/40239866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693831/"
] | you get the following according to [source code](https://github.com/Azure/azure-storage-python/blob/54e60c8c029f41d2573233a70021c4abf77ce67c/azure-storage-blob/azure/storage/blob/baseblobservice.py#L609) it return `ListGenerator(resp, self._list_containers, (), kwargs)`
you can access what you want as follow:
python2... | According to **[source code](https://github.com/Azure/azure-storage-python/blob/54e60c8c029f41d2573233a70021c4abf77ce67c/azure-storage-blob/azure/storage/blob/baseblobservice.py#L573)**
You can access the containers in the storage account by using the snippet below:
```
from azure.storage.blob.baseblobservice import ... |
40,239,866 | I'm trying to list the containers under an azure account using the python sdk - why do I get the following?
```
>>> azure.storage.blob.baseblobservice.BaseBlobService(account_name='x', account_key='x').list_containers()
>>> <azure.storage.models.ListGenerator at 0x7f7cf935fa58>
```
Surely the above is a call to the ... | 2016/10/25 | [
"https://Stackoverflow.com/questions/40239866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693831/"
] | for python 3 and more recent distribution of `azure` libraries, you can do:
```
from azure.storage.blob import BlockBlobService
block_blob_service = BlockBlobService(account_name=account_name, account_key=account_key)
containers = block_blob_service.list_containers()
for c in containers:
print(c.name)
``` | According to **[source code](https://github.com/Azure/azure-storage-python/blob/54e60c8c029f41d2573233a70021c4abf77ce67c/azure-storage-blob/azure/storage/blob/baseblobservice.py#L573)**
You can access the containers in the storage account by using the snippet below:
```
from azure.storage.blob.baseblobservice import ... |
67,401,326 | i have json file as below .Using python i want a fetch a record for source\_name = 'Abc' . How i can achieve it
---json file: file.json
```
[{
"source_name" :"Abc",
"target_table" : "TABLE1",
"schema": "col1 string, col2 string"
},
{
"source_name" :"xyz",
"target_table" : "TABLE2",
"schema"... | 2021/05/05 | [
"https://Stackoverflow.com/questions/67401326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050708/"
] | You can use list comprehensions, which is considered to be more pythonic since the initial data is a list of dictionaries.
```
# using list comprehension
result = [element for element in json.load(json_file) if element['source_name'] == "Abc"]
# without using list comprehension
for element in json.load(json_file):
... | Try this.
```
data = [{
"source_name" :"Abc",
"target_table" : "TABLE1",
"schema": "col1 string, col2 string"
},
{
"source_name" :"xyz",
"target_table" : "TABLE2",
"schema": "col3 string, col4 string"
}
]
l = len(data)
n = 0
while n < l:
if (data[n]["source_name"] == "Abc"):
pr... |
4,128,462 | I just started working in an environment that uses multiple programming languages, doesn't have source control and doesn't have automated deploys.
I am interested in recommending VSS for source control and using CruiseControl.net for automated deploys but I have only used CC.NET with ASP.NET applications. Is it possib... | 2010/11/08 | [
"https://Stackoverflow.com/questions/4128462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/226897/"
] | Yes you can.
CC .net is written in .Net but can handle any project. Your project langage does not matter, you can still use Batch, Powershell, Nant or MsBuild scripts. You may also use Cruise Control or Hudson, as you like.
As for the source control provider, I would prefer svn (or even git) but that's more a matter ... | VSS is [unsafe for any source](http://www.developsense.com/testing/VSSDefects.html) and is damn near useless outside visual studio. And cruise control is painful to learn and make work at best. Your heart is in the right place, but you probably want slightly different technical solutions. For SCM, you probably want eit... |
39,615,436 | When using LDA model, I get different topics each time and I want to replicate the same set. I have searched for the similar question in Google such as [this](https://groups.google.com/forum/#!topic/gensim/s1EiOUsqT8s).
I fix the seed as shown in the article by `num.random.seed(1000)` but it doesn't work. I read the `... | 2016/09/21 | [
"https://Stackoverflow.com/questions/39615436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6858032/"
] | First: there is no problem.
For international sites Unicode is often the preferred choice, as it can combine all possible scripts on one page (if the fonts can display them).
For a Chinese-only site, say combined with plain ASCII, you can display the page in a Chinese encoding.
Now the XML can be in UTF-8, a Unicode... | use dom4j and reload xml file;
```
org.dom4j.io.SAXReader reader=new SAXReader();
org.dom4j.Document doc=reader.read(new File(yourFilePath));
org.dom4j.io.OutputFormat format=new OutputFormat();
format.setEncoding("utf-8");
org.dom4j.io.XMLWriter writer=new XMLWriter(new FileOutputStream(path),format);
writer.write(... |
12,201,498 | I am a beginer python learner. I am trying to create a basic dictionary where random meaning of words will come and user have to input the correct word. I used the following method, but random doesn't work. I always get the first word first and when the last word finishes, I get infinite 'none' until I kill it. Using p... | 2012/08/30 | [
"https://Stackoverflow.com/questions/12201498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1570162/"
] | ```
#!/usr/bin/env perl
use strict;
use warnings;
my $data = <<END;
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 152.225.244.1
DHCP Server . . . . . . . . . . . : 10.204.40.57
DNS Servers . . . . . . . . . . . : 10.204.127.11
10.207.2.50
... | I would use [`unpack`](http://perldoc.perl.org/functions/unpack.html) instead of regular expressions for parsing column-based data:
```
#!/usr/bin/env perl
use strict;
use warnings;
while (<DATA>) {
my ($ip) = unpack 'x36 A*';
print "$ip\n";
}
__DATA__
DNS Servers . . . . . . . . . . . : 10.204.127.11
... |
12,201,498 | I am a beginer python learner. I am trying to create a basic dictionary where random meaning of words will come and user have to input the correct word. I used the following method, but random doesn't work. I always get the first word first and when the last word finishes, I get infinite 'none' until I kill it. Using p... | 2012/08/30 | [
"https://Stackoverflow.com/questions/12201498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1570162/"
] | ```
#!/usr/bin/env perl
use strict;
use warnings;
my $data = <<END;
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 152.225.244.1
DHCP Server . . . . . . . . . . . : 10.204.40.57
DNS Servers . . . . . . . . . . . : 10.204.127.11
10.207.2.50
... | Match
```
DNS.+?:(\s*([\d.]+).)+
```
and pull out the groups. This assumes you have the entire multi-line string in one blob, ans that the extracted text may contain newlines and other whitespace.
The last dot is to match the newline, you need to use `/m` option |
12,201,498 | I am a beginer python learner. I am trying to create a basic dictionary where random meaning of words will come and user have to input the correct word. I used the following method, but random doesn't work. I always get the first word first and when the last word finishes, I get infinite 'none' until I kill it. Using p... | 2012/08/30 | [
"https://Stackoverflow.com/questions/12201498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1570162/"
] | ```
#!/usr/bin/env perl
use strict;
use warnings;
my $data = <<END;
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 152.225.244.1
DHCP Server . . . . . . . . . . . : 10.204.40.57
DNS Servers . . . . . . . . . . . : 10.204.127.11
10.207.2.50
... | Personally, I'd go in a different direction. Instead of manually parsing the output of ipconfig, I'd use the Win32::IPConfig module.
[Win32::IPConfig - IP Configuration Settings for Windows NT/2000/XP/2003](http://search.cpan.org/~jmacfarla/Win32-IPConfig-0.10/lib/Win32/IPConfig.pm)
```
use Win32::IPConfig;
use Data::... |
12,201,498 | I am a beginer python learner. I am trying to create a basic dictionary where random meaning of words will come and user have to input the correct word. I used the following method, but random doesn't work. I always get the first word first and when the last word finishes, I get infinite 'none' until I kill it. Using p... | 2012/08/30 | [
"https://Stackoverflow.com/questions/12201498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1570162/"
] | ```
#!/usr/bin/env perl
use strict;
use warnings;
my $data = <<END;
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 152.225.244.1
DHCP Server . . . . . . . . . . . : 10.204.40.57
DNS Servers . . . . . . . . . . . : 10.204.127.11
10.207.2.50
... | Match against this regex (see [**in action**](http://regexr.com?320ji)):
```
DNS Servers.*:\s*(.*(?:[\n\r]+\s+.*(?:[\n\r]+\s+.*)?)?)
```
First capture group will be your three IP's (atmost three) as you requested. You need to trim whitespaces surely.
**Edit:** Regex fixed to match at most three IP's. If there is le... |
58,801,994 | I have images with Borders like the below. Can I use OpenCV or python to remove the borders like this in images?
I used the following code to crop, but it didn't work.
```
copy = Image.fromarray(img_final_bin)
try:
bg = Image.new(copy.mode, copy.size, copy.getpixel((0, 0)))
except:
return None
diff = ImageCho... | 2019/11/11 | [
"https://Stackoverflow.com/questions/58801994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9186998/"
] | Here's an approach using thresholding + contour filtering. The idea is to threshold to obtain a binary image. From here we find contours and filter using a maximum area threshold. We draw all contours that pass this filter onto a blank mask then perform bitwise operations to remove the border. Here's the result with th... | You could also use Werk24's API for reading Technical Drawings: [www.werk24.io](https://werk24.io)
```py
from werk24 import W24TechreadClient, W24AskCanvasThumbnail
async with W24TechreadClient.make_from_env() as session:
response = await session.read_drawing(document_bytes,[W24AskCanvasThumbnail()])
```
It al... |
70,972,961 | I have this list of objects which have p1, and p2 parameter (and some other stuff).
```
Job("J1", p1=8, p2=3)
Job("J2", p1=7, p2=11)
Job("J3", p1=5, p2=12)
Job("J4", p1=10, p2=5)
...
Job("J222",p1=22,p2=3)
```
With python, I can easily get max value of p2 by
```
(max(job.p2 for job in instance.jobs))
```
but how ... | 2022/02/03 | [
"https://Stackoverflow.com/questions/70972961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18110528/"
] | You can do it like this:
```html
<style>
.input-wrapper {
display: flex;
position: relative;
}
.input-wrapper .icon {
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 0 10px;
}
.input-wrapper input {
padding: 0 0 0 25px;
height: 50px;
}
</style>
<div class="input-wrapper">
<i cl... | There are two styling options you can use. These are block and flex.
Block will not be responsive while flex will be responsive. I hope this solve your issue. |
70,777,985 | I'm trying to create a pandas multiIndexed dataframe that is a summary of the unique values in each column.
Is there an easier way to have this information summarized besides creating this dataframe?
Either way, it would be nice to know how to complete this code challenge. Thanks for your help! Here is the toy datafr... | 2022/01/19 | [
"https://Stackoverflow.com/questions/70777985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17119804/"
] | Well, there are many ways to handle errors, it really depends on what you want to do in case of an error.
In your current setup, the solution is straightforward: **first, `NotificationException` should extend `RuntimeException`**, thus, in case of an HTTP error, `.block()` will throw a `NotificationException`. It is a... | Using imperative/blocking style you can surround it with a try-catch:
```java
try {
webClient.post()
.uri("http://localhost:9000/api")
.body(BodyInserters.fromValue(notification))
.retrieve()
.onStatus(HttpStatus::isError, clientResponse -> Mono.error(NotificationExc... |
25,737,589 | I run a django app via gunicorn, supervisor and nginx as reverse proxy and struggle to make my gunicorn access log show the actual ip instead of 127.0.0.1:
Log entries look like this at the moment:
```
127.0.0.1 - - [09/Sep/2014:15:46:52] "GET /admin/ HTTP/1.0" ...
```
supervisord.conf
```
[program:gunicorn]
comma... | 2014/09/09 | [
"https://Stackoverflow.com/questions/25737589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/640916/"
] | The problem is that you need to configure [`gunicorn`'s logging](http://docs.gunicorn.org/en/0.17.0/configure.html#logging), because it will (by default) not display any custom headers.
From the documentation, we find out that the default access log format is controlled by [`access_log_format`](http://docs.gunicorn.or... | Note that headers containing `-` should be referred to here by replacing `-` with `_`, thus `X-Forwarded-For` becomes `%({X_Forwarded_For}i)s`. |
16,640,610 | So I tried to use parses generator [waxeye](http://waxeye.org/), but as I try to use tutorial example of program in python using generated parser I get error:
```
AttributeError: 'module' object has no attribute 'Parser'
```
Here's part of code its reference to:
```
import waxeye
import parser
p = parser.Parser()
... | 2013/05/19 | [
"https://Stackoverflow.com/questions/16640610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1334531/"
] | can you try this code and then please tell me result.
be sure you check all file names.
```
@Override
protected void onCreate(Bundle savedInstanceState) {
//.......
DatabaseHelper dbHelper = new DatabaseHelper(this);
dbHelper.createDatabase();
dbHelper.openDatabase();
// do stuff
Cursor da... | remove **.db** extension from both **DB\_NAME** and **.open("database.db")**
It looks ugly but currently same thing is working for me....
And before installing new apk please do ***Clear Data*** for earlier installed apk
And still if it won't work, please mention your database size. |
48,630,957 | I'm using subprocess in Python and passing ec2 instance id at runtime..while giving instance id it is taking as a string and throwing error saying instance id is not valid. Please don't suggest boto3 package as my company restricted of using it.My question is how can I send the character+integer+special character at ru... | 2018/02/05 | [
"https://Stackoverflow.com/questions/48630957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9318698/"
] | Are you intending to pass the literal string `"instanceid"`?
Surely you mean to use its value?
```
subprocess.call(["aws", "ec2", "describe-instances", "--instance-ids", f'"{instanceid}"'])
```
or
```
subprocess.call(["aws", "ec2", "describe-instances", "--instance-ids", '"{}"'.format(instanceid)])
```
if not usi... | This has nothing to do with "passing integer or character types", whatever that means.
You are passing the literal value `"instanceid"`, complete with quotes, rather than the value of the instanceid argument to your script. You did do both sets of quotes.
(And really, you should take up this silly "restriction" abou... |
17,436,045 | I'm sure this is something easy to do for someone with programming skills (unlike me). I am playing around with the Google Sites API. Basically, I want to be able to batch-create a bunch of pages, instead of having to do them one by one using the slow web form, which is a pain.
I have installed all the necessary file... | 2013/07/02 | [
"https://Stackoverflow.com/questions/17436045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2544281/"
] | Variable 'initialization' will always trigger an event. From the last Verilog standard([IEEE 1364-2005](http://standards.ieee.org/findstds/standard/1364-2005.html)):
>
> If a variable declaration assignment is used (see 6.2.1), the variable
> shall take this value as if the assignment occurred in a blocking
> assig... | A good reference for order of events is this paper:
<http://www.sunburst-design.com/papers/CummingsSNUG2000SJ_NBA_rev1_2.pdf>
page 6 has a diagram of the order of events as far as evaluation of variables and triggering goes. |
28,379,373 | In python is there any way at all to get a function to use a variable and return it without passing it in as an argument? | 2015/02/07 | [
"https://Stackoverflow.com/questions/28379373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3983128/"
] | What you ask **is** possible. If a function doesn't re-bind (e.g, assign to) a name, but uses it, that name is taken as a *global* one, e.g:
```
def f():
print(foo)
foo = 23
f()
```
will do what you ask. However, it's a dubious idea already: why not just `def f(foo):` and call `f(23)`, so much more direct and c... | As @Alex Martelli pointed out, you *can*... but *should* you? That's the more relevant question, IMO.
I understand the *appeal* of what you're asking. It seems like it should *just be* good form because otherwise you'd have to pass the variables everywhere, which of course seems wasteful.
I won't presume to know how... |
46,318,530 | Hello all I'm very new to python, so just bear with me.
I have a sample json file in this format.
```
[{
"5":"5",
"0":"0",
"1":"1"},{
"14":"14",
"11":"11",
"15":"15"},{
"25":"25",
"23":"23",
"22":"22"}]
```
I would like to convert the json file to csv in a specific way. All the values in 1 map i.e., `{` and `}` in t... | 2017/09/20 | [
"https://Stackoverflow.com/questions/46318530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7923318/"
] | `bytes(iterator)` create bytes object from iterator using internal C-API `_PyBytes_FromIterator` function, which use special `_PyBytes_Writer` protocol. It internaly use a buffer, which resize when it overflows using a rule:
```
bufsize += bufsize / OVERALLOCATE_FACTOR
```
For linux OVERALLOCATE\_FACTOR=4, for wind... | this is probably more a remark or discussion start than an answer but I think it's better to format it like this.
I just hooking in 'cause I find this topic very inteeresting as well.
I would recommend to paste the real call and generator mock. Since imho the generator expression example does not fit really well for y... |
46,318,530 | Hello all I'm very new to python, so just bear with me.
I have a sample json file in this format.
```
[{
"5":"5",
"0":"0",
"1":"1"},{
"14":"14",
"11":"11",
"15":"15"},{
"25":"25",
"23":"23",
"22":"22"}]
```
I would like to convert the json file to csv in a specific way. All the values in 1 map i.e., `{` and `}` in t... | 2017/09/20 | [
"https://Stackoverflow.com/questions/46318530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7923318/"
] | `bytes(iterator)` create bytes object from iterator using internal C-API `_PyBytes_FromIterator` function, which use special `_PyBytes_Writer` protocol. It internaly use a buffer, which resize when it overflows using a rule:
```
bufsize += bufsize / OVERALLOCATE_FACTOR
```
For linux OVERALLOCATE\_FACTOR=4, for wind... | Creating immutable types from arbitrary sized iterables is a common task for Python. Most notably, `tuple` is an ubiquitous immutable type. This makes it a necessity to *efficiently* create such instances – constantly creating and discarding intermediate instances would not be efficient.
Using a generator as the sourc... |
57,643,746 | I have a pipeline with a set of PTransforms and my method is getting very long.
I'd like to write my DoFns and my composite transforms in a separate package and use them back in my main method. With python it's pretty straightforward, how can I achieve that with Scio? I don't see any example of doing that. :(
```
... | 2019/08/25 | [
"https://Stackoverflow.com/questions/57643746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9726037/"
] | You can try to use the encoding option "Latin-1" standard (also known as ISO 8859-1 or ISO/IEC 8859-1).
```
library(data.table)
type <- fread(file.path("C:/Users/Alonso/Desktop/Tesis_MGII/Avance_mayo/escrito/natural-disasters-by-type.csv", encoding = "Latin-1"))
``` | Use the encoding option inside your read.csv code.
Following code sample is working for me:
```
file <- textConnection("# ---------------------
#
# ---------------------
Año, Número
2001, 3152
2002, 3200
2003, 3500
2004, 3700
2005, 3850
2006, 4200", encoding = c("UTF-8"))
file
# read data from textConnection
desas... |
57,643,746 | I have a pipeline with a set of PTransforms and my method is getting very long.
I'd like to write my DoFns and my composite transforms in a separate package and use them back in my main method. With python it's pretty straightforward, how can I achieve that with Scio? I don't see any example of doing that. :(
```
... | 2019/08/25 | [
"https://Stackoverflow.com/questions/57643746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9726037/"
] | You can try to use the encoding option "Latin-1" standard (also known as ISO 8859-1 or ISO/IEC 8859-1).
```
library(data.table)
type <- fread(file.path("C:/Users/Alonso/Desktop/Tesis_MGII/Avance_mayo/escrito/natural-disasters-by-type.csv", encoding = "Latin-1"))
``` | For what it's worth: `read_csv` imports columns with row names and column names in Spanish for me without specifying any encoding and `ggplot2` is able to graph them. The defaults should be UTF-8 and perfectly capable of handling Spanish special characters. You do not even need to add backticks ``. Unfortunately the th... |
61,996,944 | I'm completely new to the Python world, so I've been struggling with this issue for a couple days now. I thank you guys in advance.
I have been trying to separate a single Row and column text in three diferente ones. To explain myself better, here's where I am.
So this is my pandas dataframe from a csv:
In[2]:
```
... | 2020/05/25 | [
"https://Stackoverflow.com/questions/61996944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611327/"
] | You can use `assign` with `str.split` like below. But format of text should be fixed.
```
df.assign(number = df.institution.str.split().str[0], \
unit_id = df.institution.str.split().str[-1])
```
Output:
```
institution number unit_id
0 1.1.2. Consejo Nacio... | Just a thought, but what about using named capture groups in a regular expression. For example, use the following after you imported your CSV-file:
```
df.iloc[:,0].str.extract(r'^(?P<number>[\d.]*)\s+(?P<instituion>.*)\s+\((?P<unit_id>[A-Z\d]*)\)$')
```
This would expand your dataframe as such:
```
number ... |
61,996,944 | I'm completely new to the Python world, so I've been struggling with this issue for a couple days now. I thank you guys in advance.
I have been trying to separate a single Row and column text in three diferente ones. To explain myself better, here's where I am.
So this is my pandas dataframe from a csv:
In[2]:
```
... | 2020/05/25 | [
"https://Stackoverflow.com/questions/61996944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611327/"
] | You can use `assign` with `str.split` like below. But format of text should be fixed.
```
df.assign(number = df.institution.str.split().str[0], \
unit_id = df.institution.str.split().str[-1])
```
Output:
```
institution number unit_id
0 1.1.2. Consejo Nacio... | If your data is tidy enough you can perform all three steps in one command using `pd.Series.str.extract()` which can split a series of strings into columns by regex, ie.:
```
df.institution.str.extract(r'(?P<number>[0-9.]+) (?P<institution>[A-Za-z ]+) \((?P<unit_id>[A-Z0-9]+)')
```
If the missing values cause a pro... |
36,002,647 | Given an iterator `i`, I want an iterator that yields each element `n` times, i.e., the equivalent of this function
```
def duplicate(i, n):
for x in i:
for k in range(n):
yield x
```
Is there an one-liner for this?
Related question: [duplicate each member in a list - python](https://stackov... | 2016/03/15 | [
"https://Stackoverflow.com/questions/36002647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2201385/"
] | ```
itertools.chain.from_iterable(itertools.izip(*itertools.tee(source, n)))
```
Example:
```
>>> x = (a**2 for a in xrange(5))
>>> list(itertools.chain.from_iterable(itertools.izip(*itertools.tee(x, 3))))
[0, 0, 0, 1, 1, 1, 4, 4, 4, 9, 9, 9, 16, 16, 16]
```
Another way:
```
itertools.chain.from_iterable(itertool... | Use a generator expression:
```
>>> x = (n for n in range(4))
>>> i = (v for v in x for _ in range(3))
>>> list(i)
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]
``` |
36,002,647 | Given an iterator `i`, I want an iterator that yields each element `n` times, i.e., the equivalent of this function
```
def duplicate(i, n):
for x in i:
for k in range(n):
yield x
```
Is there an one-liner for this?
Related question: [duplicate each member in a list - python](https://stackov... | 2016/03/15 | [
"https://Stackoverflow.com/questions/36002647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2201385/"
] | This is my simple solution, if you want to duplicate each element same times. It returns a generator expression, which should be memory efficient.
```
def duplicate(i, n):
return (k for k in i for j in range(n))
```
An example usage could be,
```
print (list(duplicate(range(1, 10), 3)))
```
Which prints,
>... | ```
itertools.chain.from_iterable(itertools.izip(*itertools.tee(source, n)))
```
Example:
```
>>> x = (a**2 for a in xrange(5))
>>> list(itertools.chain.from_iterable(itertools.izip(*itertools.tee(x, 3))))
[0, 0, 0, 1, 1, 1, 4, 4, 4, 9, 9, 9, 16, 16, 16]
```
Another way:
```
itertools.chain.from_iterable(itertool... |
36,002,647 | Given an iterator `i`, I want an iterator that yields each element `n` times, i.e., the equivalent of this function
```
def duplicate(i, n):
for x in i:
for k in range(n):
yield x
```
Is there an one-liner for this?
Related question: [duplicate each member in a list - python](https://stackov... | 2016/03/15 | [
"https://Stackoverflow.com/questions/36002647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2201385/"
] | This is my simple solution, if you want to duplicate each element same times. It returns a generator expression, which should be memory efficient.
```
def duplicate(i, n):
return (k for k in i for j in range(n))
```
An example usage could be,
```
print (list(duplicate(range(1, 10), 3)))
```
Which prints,
>... | Use a generator expression:
```
>>> x = (n for n in range(4))
>>> i = (v for v in x for _ in range(3))
>>> list(i)
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]
``` |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | >
> A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
>
>
>
Obviously a pr... | >
> A priviledged cleint can invoke the private constructor reflectively with
> the aid of the
> AccessibleObject.setAccessible method,
> If you need to defend this, modify the
> constructor. My question is: How
> exactly can a private constructor is
> invoked? and what is
> AccessibleObject.setAccessible??
>
... |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | >
> A priviledged cleint can invoke the private constructor reflectively with
> the aid of the
> AccessibleObject.setAccessible method,
> If you need to defend this, modify the
> constructor. My question is: How
> exactly can a private constructor is
> invoked? and what is
> AccessibleObject.setAccessible??
>
... | The first rule of the Singleton (Anti-) Pattern is *don't use it*. The second rule is *don't use it* for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, *especially* if it is a dependency of those classes. Use dependency injection instead. There are va... |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | >
> A priviledged cleint can invoke the private constructor reflectively with
> the aid of the
> AccessibleObject.setAccessible method,
> If you need to defend this, modify the
> constructor. My question is: How
> exactly can a private constructor is
> invoked? and what is
> AccessibleObject.setAccessible??
>
... | Example singleton lazy init:
Class main:
```
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
... |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | >
> A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
>
>
>
Obviously a pr... | Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most [over-used patterns](http://aabs.wordpress.com/2007/03/08/singleton-%E2%80%93-the-most-overused-pattern/). It's gotten to the point that some consider them an ["anti-patter... |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most [over-used patterns](http://aabs.wordpress.com/2007/03/08/singleton-%E2%80%93-the-most-overused-pattern/). It's gotten to the point that some consider them an ["anti-patter... | The first rule of the Singleton (Anti-) Pattern is *don't use it*. The second rule is *don't use it* for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, *especially* if it is a dependency of those classes. Use dependency injection instead. There are va... |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most [over-used patterns](http://aabs.wordpress.com/2007/03/08/singleton-%E2%80%93-the-most-overused-pattern/). It's gotten to the point that some consider them an ["anti-patter... | Example singleton lazy init:
Class main:
```
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
... |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | >
> A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
>
>
>
Obviously a pr... | The first rule of the Singleton (Anti-) Pattern is *don't use it*. The second rule is *don't use it* for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, *especially* if it is a dependency of those classes. Use dependency injection instead. There are va... |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | >
> A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
>
>
>
Obviously a pr... | Example singleton lazy init:
Class main:
```
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
... |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | The first rule of the Singleton (Anti-) Pattern is *don't use it*. The second rule is *don't use it* for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, *especially* if it is a dependency of those classes. Use dependency injection instead. There are va... | Example singleton lazy init:
Class main:
```
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
... |
8,342,891 | I'm very new to Python and have a question. Currently I'm using this to calculate the times between a message goes out and the message comes in. The resulting starting time, time delta, and the Unique ID are then presented in file. As well, I'm using Python 2.7.2
Currently it is subtracting the two times and the resul... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8342891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057243/"
] | If `float(out_ts)` are hours, then `'{0:.3f}'.format(float(out_ts) * 3600.)` will give you the text representation of seconds with three digits after decimal point. | >
> How can I force it to always display the exact number.
>
>
>
This is sometimes not possible, because of floating point inaccuracies
What you *can* do on the other hand is to format your floats as you wish. See [here](http://docs.python.org/library/stdtypes.html#string-formatting-operations) for instructions.
... |
2,036,260 | >
> **Possible Duplicate:**
>
> [Django Unhandled Exception](https://stackoverflow.com/questions/1925898/django-unhandled-exception)
>
>
>
I'm randomly getting 500 server errors and trying to diagnose the problem. The setup is:
Apache + mod\_python + Django
My 500.html page is being served by Django, but I h... | 2010/01/10 | [
"https://Stackoverflow.com/questions/2036260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87719/"
] | Yes, you should have an entry in your apache confs as to where the error log is for the virtual server.
For instance the name of my virtual server is djangoserver, and in my /etc/apache2/sites-enabled/djangoserver file is the line
```
ErrorLog /var/log/apache2/djangoserver-errors.log
```
Although now that I reread y... | Salsa makes several good suggestions. I would add that the Django development server is an excellent environment for tracking these things down. Sometimes I even run it from the production directory (gasp!) with `./manage.py runserver 0.0.0.0:8000` so I *know* I'm running the same code.
Admittedly sometimes something ... |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | I had a similar problem, where I installed Xcode 11.1, and installed the components and everything within the same folder where I had Xcode 10.2.1. Then, I tried to go back to Xcode 10.2.1 and couldn't opened as it was asking me to install components again, and when I tried I was getting this error.
>
> The package “... | You may solve this issue by setting the date of your Mac as October 1st, 2019. But this is just a hack! The real solution (suggested by apple) is this:
All you have to is to upgrade Xcode
-----------------------------------
**But** there is a [known Issues on apple developers site](https://developer.apple.com/documen... |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | At macOS Catalina
```
cd /Applications/Xcode.app/Contents/Resources/Packages
sudo rm -rf MobileDevice.pkg
sudo rm -rf MobileDeviceDevelopment.pkg
```
Try again.
It means you entered on the Xcode downloaded packages and remove it. I really don't understand how Apple do but if you remove Xcode will download it again ... | For me, I just uninstalled (deleted the app from the Applications folder) and then went back to app store and clicked the cloud icon and it downloaded fresh and installed. Now all is good and back to normal. |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | Try to run `Xcode-beta` instead of `Xcode` to install additional components. After that you'll be able to use `Xcode` release. | This requires Xcode 11.1 to be installed.
I was not able to update to Xcode 11.1 until I updated macOS Catalina to 10.15.1. After updating my macOS, I was able to install Xcode 11.1, which also allowed the installation of the additional components package. |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | I had a similar problem, where I installed Xcode 11.1, and installed the components and everything within the same folder where I had Xcode 10.2.1. Then, I tried to go back to Xcode 10.2.1 and couldn't opened as it was asking me to install components again, and when I tried I was getting this error.
>
> The package “... | This requires Xcode 11.1 to be installed.
I was not able to update to Xcode 11.1 until I updated macOS Catalina to 10.15.1. After updating my macOS, I was able to install Xcode 11.1, which also allowed the installation of the additional components package. |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | ```
rm -rf /Applications/Xcode.app/Contents/Resources/Packages/*.pkg
```
It will work and re-open the x-code | This requires Xcode 11.1 to be installed.
I was not able to update to Xcode 11.1 until I updated macOS Catalina to 10.15.1. After updating my macOS, I was able to install Xcode 11.1, which also allowed the installation of the additional components package. |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | At macOS Catalina
```
cd /Applications/Xcode.app/Contents/Resources/Packages
sudo rm -rf MobileDevice.pkg
sudo rm -rf MobileDeviceDevelopment.pkg
```
Try again.
It means you entered on the Xcode downloaded packages and remove it. I really don't understand how Apple do but if you remove Xcode will download it again ... | Here's what I did to resolve:
Right click the xcode.app > show package contents > Contents > Developer > Platforms > iPhoneOS.platform > Device Support
I am on XCode 10.2.1. I had downloaded a 13.7 folder and contents from an external GitHub site and imported that folder into here for running my app on a physical iPh... |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | At macOS Catalina
```
cd /Applications/Xcode.app/Contents/Resources/Packages
sudo rm -rf MobileDevice.pkg
sudo rm -rf MobileDeviceDevelopment.pkg
```
Try again.
It means you entered on the Xcode downloaded packages and remove it. I really don't understand how Apple do but if you remove Xcode will download it again ... | Reinstall Xcode 11.1 from <https://developer.apple.com/download/more/> . Afterwards the update works. |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | You may solve this issue by setting the date of your Mac as October 1st, 2019. But this is just a hack! The real solution (suggested by apple) is this:
All you have to is to upgrade Xcode
-----------------------------------
**But** there is a [known Issues on apple developers site](https://developer.apple.com/documen... | For me, I just uninstalled (deleted the app from the Applications folder) and then went back to app store and clicked the cloud icon and it downloaded fresh and installed. Now all is good and back to normal. |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | I had a similar problem, where I installed Xcode 11.1, and installed the components and everything within the same folder where I had Xcode 10.2.1. Then, I tried to go back to Xcode 10.2.1 and couldn't opened as it was asking me to install components again, and when I tried I was getting this error.
>
> The package “... | For me, I just uninstalled (deleted the app from the Applications folder) and then went back to app store and clicked the cloud icon and it downloaded fresh and installed. Now all is good and back to normal. |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | Edit and set the date of your Mac as October 1st, 2019. | I had a similar problem, where I installed Xcode 11.1, and installed the components and everything within the same folder where I had Xcode 10.2.1. Then, I tried to go back to Xcode 10.2.1 and couldn't opened as it was asking me to install components again, and when I tried I was getting this error.
>
> The package “... |
30,668,557 | I have a problem loading an external dll using Python through Python for .NET. I have tried different methodologis following stackoverflow and similar. I will try to summarize the situation and to describe all the steps that I've done.
I have a dll named for e.g. Test.NET.dll. I checked with dotPeek and I can see, cli... | 2015/06/05 | [
"https://Stackoverflow.com/questions/30668557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3075816/"
] | >
> The return value of this decorator is ignored.
>
>
>
This is irrelevant to your situation. The return value of parameter decorators is ignored because they don't need to be able to replace anything (unlike method and class decorators which can replace the descriptor).
>
> My problem is that when I try to imp... | For my case I used a simple solution **without reflect metadata** API but **using method decoration**.
You can modify it for your purposes:
```
type THandler = (param: any, paramIndex: number, params: any[]) => void;
/**
* @example
* @Params((param1) => someHandlerFn(param1), ...otherParams)
* public async someMe... |
49,369,438 | I'm trying to create a blobstore entry from an image data-uri object, but am getting stuck.
Basically, I'm posting via ajax the data-uri as text, an example of the payload:
```
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPA...
```
I'm trying to receive this payload with the following handler. I'm assuming I need... | 2018/03/19 | [
"https://Stackoverflow.com/questions/49369438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/791793/"
] | There are a couple of ways to view your question and the sample code you posted, and it's a little confusing what you need because you are mixing strategies and technologies.
**POST base64 to `_ah/upload/...`**
Your service uses `create_upload_url()` to make a one-time upload URL/session for your client. Your client ... | An image object (<https://cloud.google.com/appengine/docs/standard/python/refdocs/google.appengine.api.images>) isn't a Datastore entity, so it has no key. You need to actually save the image to blobstore[2] or Google Cloud Storage[1] then get a serving url for your image.
[1] <https://cloud.google.com/appengine/docs/... |
59,156,316 | I have a python code like this to interact with an API
```
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import json
from pprint import pprint
key = "[SOME_KEY]" # FROM API PROVIDER
secret = "[SOME_SECRET]" # FROM API PROVIDER
api_client = BackendApplica... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59156316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11719873/"
] | Have you tried to you send a header paramter with this requests?
```py
headers = {"Content-Type": "application/json"}
response = client.post(url, data=json.dumps(body), headers=headers)
``` | This is how I was able to configure the POST request for exchanging the code for a token.
```py
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import WebApplicationClient, BackendApplicationClient
from requests.auth import HTTPBasicAuth
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
authorizati... |
31,932,371 | I have both Python 2.7 and Python 3.4 installed on my MacBook, as both are needed sometimes.
Python 2.7 is shipped by Apple itself.
Python 3.4 is installed by Mac OS X 64-bit/32-bit installer in the link
<https://www.python.org/downloads/release/python-343/>
Here is how I installed Meld on Mac OS X 10.10:
1. Instal... | 2015/08/11 | [
"https://Stackoverflow.com/questions/31932371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4778233/"
] | This should solve the problem: `brew link --overwrite python` | I use Linux. I have no clue about Apple and the special things they do. But judging from the error messages given it seems that
1. bash starts *the meld program*
2. *the meld program* refers to *the python program in **someplace***
3. **someplace** is wrong in *the meld program*, causing the bash error message
Now h... |
31,932,371 | I have both Python 2.7 and Python 3.4 installed on my MacBook, as both are needed sometimes.
Python 2.7 is shipped by Apple itself.
Python 3.4 is installed by Mac OS X 64-bit/32-bit installer in the link
<https://www.python.org/downloads/release/python-343/>
Here is how I installed Meld on Mac OS X 10.10:
1. Instal... | 2015/08/11 | [
"https://Stackoverflow.com/questions/31932371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4778233/"
] | This should solve the problem: `brew link --overwrite python` | It is highly recommended not to use the System Python on osx, but install a separate version of Python (for a list of the reasons see for example this page [here](https://github.com/MacPython/wiki/wiki/Which-Python)).
The reason boils down to the fact that OSX depends on it's own Python installation, which you should ... |
8,380,733 | I'm trying to run a custom django command as a scheduled task on Heroku. I am able to execute the custom command locally via: `python manage.py send_daily_email`. (note: I do NOT have any problems with the custom management command itself)
However, Heroku is giving me the following exception when trying to "Run" the ... | 2011/12/05 | [
"https://Stackoverflow.com/questions/8380733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/873197/"
] | You are probably using a different interpreter.
Check to make sure shell python is the same as the one you reference in your script /usr/bin/python . It could be that there is a different one in your path, which would explain why it works when you run `python manage.py` but not your shell scrip which you explicitly r... | In addition, this can also be resolved by adding your home directory to your Python path. A quick and unobtrusive way to accomplish that is to add it to the PYTHONPATH environment variable (which is generally /app on the Heroku Cedar stack).
Add it via the heroku config command:
```
$ heroku config:add PYTHONPATH=/ap... |
5,077,765 | I am using Google App Engine's datastore and wants to retrieve an entity whose key value is written as
```
ID/Name
id=1
```
Can anyone suggest me a GQL query to view that entity in datastore admin console and also in my python program? | 2011/02/22 | [
"https://Stackoverflow.com/questions/5077765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/617462/"
] | From your application use the [get\_by\_id()](http://code.google.com/intl/it/appengine/docs/python/datastore/modelclass.html#Model_get_by_id) class method of the Model:
```
entity = YourModel.get_by_id(1)
```
From Datastore viewer you should use the `KEY` function:
```
SELECT * FROM YourModel WHERE __key__ = KEY('Y... | An application can retrieve a model instance for a given Key using the [get()](http://code.google.com/appengine/docs/python/datastore/functions.html#get) function.
```
class member(db.Model):
firstName=db.StringProperty(verbose_name='First Name',required=False)
lastName=db.StringProperty(verbose_name='Last Nam... |
8,062,564 | I try to apply image filters using python's [PIL](http://www.pythonware.com/products/pil/). The code is straight forward:
```
im = Image.open(fnImage)
im = im.filter(ImageFilter.BLUR)
```
This code works as expected on PNGs, JPGs and on 8-bit TIFs. However, when I try to apply this code on 16-bit TIFs, I get the fol... | 2011/11/09 | [
"https://Stackoverflow.com/questions/8062564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17523/"
] | Your TIFF image's mode is most likely a "I;16".
In the current version of ImageFilter, kernels can only be applied to
"L" and "RGB" images (see source of ImageFilter.py)
Try converting first to another mode:
```
im.convert('L')
```
If it fails, try:
```
im.mode = 'I'
im = im.point(lambda i:i*(1./256)).convert('L'... | To move ahead, try using [ImageMagick](http://www.imagemagick.org/script/index.php), look for PythonMagick hooks to the program. On the command prompt, you can use `convert.exe image-16.tiff -blur 2x2 output.tiff`. Didn't manage to install PythonMagick in my windows OS as the source needs compiling. |
13,103,806 | So I have been working on a two player "guess the number" program.
But im just having trouble with one thing.
So here's code:
```
import time
import random
thenumber = random.randint(1, 10)
print "Welcome to Noah's Two Player guess a number game."
print "What is player one's name?"
player1 = raw_input()
print "What i... | 2012/10/27 | [
"https://Stackoverflow.com/questions/13103806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779877/"
] | I guess you need quotes around `yes` : `choice =='yes'` , otherwise python will think that `yes` is a variable. | try `if choice == 'yes':`. You're comparing it with a symbol that isn't defined.
Note there are no 'variables' in Python, only symbols and their values(with their types internally understood by the language interpreter). Think of them as names you give to various objects. They're all symbols. |
73,697,975 | I am working on a Django application where I have used twilio to send sms and whatsapp messages and the sendgrid api for sending the emails. The problem occurs in scheduled messages in all three. For example, if I have schedule an email to be sent at 06:24 PM(scheduled time is 06:24 PM), then I am receiving the email a... | 2022/09/13 | [
"https://Stackoverflow.com/questions/73697975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19663784/"
] | If need replace missing value in `country` column by last value after split `city` by `,` use:
```
df['country'] = df['country'].fillna(df['city'].str.split(',').str[-1])
```
Or if need assign all column in `country` column:
```
df['country'] = df['city'].str.split(',').str[-1]
``` | You can use [`str.extract`](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extract.html) with a word regex `\w+` anchored to the end of the string (`$`) to get the last word:
```
# replacing all values
df['country'] = df['city'].str.extract('(\w+)$', expand=False)
# only updating NaNs
df.loc[df['count... |
71,431,272 | I'm having a problem with calling my TextInputs from one class in another. I have a special class inheriting from TextInput, which makes moving with arrows possible, in my MainScreen I want to grab the letters from TextInputs and later on do something with them, however I need to pass them into this class first. I don'... | 2022/03/10 | [
"https://Stackoverflow.com/questions/71431272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15846202/"
] | I finally figured this one out. I ended up using a callback in the onchange attribute that set the value of the current property in the loop.
```
<div class="form-section">
@foreach (var property in DataModel.GetType().GetProperties())
{
var propertyString = $"DataModel.{property.Name.ToString()}";
@if (p... | I think what @nocturns2 said is correct, you could try this code:
```
@if (property.PropertyType == typeof(DateTime))
{
DateTime.TryParse(YourPropertyString, out var parsedValue);
var resutl= (YourType)(object)parsedValue
<InputDate id=@"property.Name" @bind-Value="@resutl">
}
``` |
71,431,272 | I'm having a problem with calling my TextInputs from one class in another. I have a special class inheriting from TextInput, which makes moving with arrows possible, in my MainScreen I want to grab the letters from TextInputs and later on do something with them, however I need to pass them into this class first. I don'... | 2022/03/10 | [
"https://Stackoverflow.com/questions/71431272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15846202/"
] | I finally figured this one out. I ended up using a callback in the onchange attribute that set the value of the current property in the loop.
```
<div class="form-section">
@foreach (var property in DataModel.GetType().GetProperties())
{
var propertyString = $"DataModel.{property.Name.ToString()}";
@if (p... | Here's a componentized version with an example component for DateOnlyFields
```
@using System.Reflection
@using System.Globalization
<input type="date" value="@GetValue()" @onchange=this.OnChanged @attributes=UserAttributes />
@code {
[Parameter] [EditorRequired] public object? Model { get; set; }
[Paramete... |
22,727,782 | I'd previously used Anaconda to handle python, but I'm and start working with virtual environments.
I set up virtualenv and virtualenvwrapper, and have been trying to add modules, specifically scrapy and lxml, for a project I want to try.
Each time I pip install, I hit an error.
For scrapy:
```
File "/home/philip/E... | 2014/03/29 | [
"https://Stackoverflow.com/questions/22727782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3115915/"
] | I had the same problem in Ubuntu 14.04. I've solved it with the instructions of the page linked by @jdigital and the openssl-dev library pointed by @user3115915. Just to help others:
```
sudo apt-get install libxslt1-dev libxslt1.1 libxml2-dev libxml2 libssl-dev
sudo pip install scrapy
``` | In my case, I solve the problem installing all the libraries that Manuel mention plus the extra library: libffi-dev
<https://askubuntu.com/questions/499714/error-installing-scrapy-in-virtualenv-using-pip> |
22,727,782 | I'd previously used Anaconda to handle python, but I'm and start working with virtual environments.
I set up virtualenv and virtualenvwrapper, and have been trying to add modules, specifically scrapy and lxml, for a project I want to try.
Each time I pip install, I hit an error.
For scrapy:
```
File "/home/philip/E... | 2014/03/29 | [
"https://Stackoverflow.com/questions/22727782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3115915/"
] | I had the same problem in Ubuntu 14.04. I've solved it with the instructions of the page linked by @jdigital and the openssl-dev library pointed by @user3115915. Just to help others:
```
sudo apt-get install libxslt1-dev libxslt1.1 libxml2-dev libxml2 libssl-dev
sudo pip install scrapy
``` | Updated from @Mario C. and @Manuel,
Here is commands:
```
sudo apt-get install libxslt1-dev libxslt1.1 libxml2-dev libxml2 libssl-dev libffi-dev
sudo pip install scrapy
``` |
22,727,782 | I'd previously used Anaconda to handle python, but I'm and start working with virtual environments.
I set up virtualenv and virtualenvwrapper, and have been trying to add modules, specifically scrapy and lxml, for a project I want to try.
Each time I pip install, I hit an error.
For scrapy:
```
File "/home/philip/E... | 2014/03/29 | [
"https://Stackoverflow.com/questions/22727782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3115915/"
] | In my case, I solve the problem installing all the libraries that Manuel mention plus the extra library: libffi-dev
<https://askubuntu.com/questions/499714/error-installing-scrapy-in-virtualenv-using-pip> | Updated from @Mario C. and @Manuel,
Here is commands:
```
sudo apt-get install libxslt1-dev libxslt1.1 libxml2-dev libxml2 libssl-dev libffi-dev
sudo pip install scrapy
``` |
65,093,883 | I often debug my python code by plotting NumPy arrays in the vscode debugger.
Often I spend more than 3s looking at a plot. When I do vscode prints the extremely
long warning below. It's very annoying because I then have to scroll up a lot
all the time to see previous debugging outputs. Where is this PYDEVD\_WARN\_EVAL... | 2020/12/01 | [
"https://Stackoverflow.com/questions/65093883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8726027/"
] | If found a way to adapt the launch.json which takes care of this problem.
```
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"env": {"DISPLAY":":1",
... | If you are keen to surpress the warning, you'd go like this:
In this documentation, point 28.6.3, you can do so:
<https://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings>
Here's the code if the link dies in the future.
```
import warnings
def fxn():
warnings.warn("deprecated", Deprecati... |
65,093,883 | I often debug my python code by plotting NumPy arrays in the vscode debugger.
Often I spend more than 3s looking at a plot. When I do vscode prints the extremely
long warning below. It's very annoying because I then have to scroll up a lot
all the time to see previous debugging outputs. Where is this PYDEVD\_WARN\_EVAL... | 2020/12/01 | [
"https://Stackoverflow.com/questions/65093883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8726027/"
] | If found a way to adapt the launch.json which takes care of this problem.
```
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"env": {"DISPLAY":":1",
... | based on [here](https://github.com/microsoft/vscode-python/issues/2752#issuecomment-471640985), you can simply set the timeout parameter of debug configuration(launch.json). for example, sth like this:
```
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Django",
"ty... |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | With matplotlib you can use (as shown in the matplotlib [documentation](https://matplotlib.org/2.0.0/users/image_tutorial.html))
```
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('image_name.png')
```
And plot the image if you want
```
imgplot = plt.imshow(img)
``` | From [documentation](https://matplotlib.org/3.1.1/api/image_api.html?highlight=matplotlib%20image#module-matplotlib.image.imread):
>
> Matplotlib can only read PNGs natively. Further image formats are supported via the optional dependency on Pillow.
>
>
>
So in case of `PNG` we may use `plt.imread()`. In other c... |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | With matplotlib you can use (as shown in the matplotlib [documentation](https://matplotlib.org/2.0.0/users/image_tutorial.html))
```
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('image_name.png')
```
And plot the image if you want
```
imgplot = plt.imshow(img)
``` | you can try to use cv2 like this
```py
import cv2
image= cv2.imread('image page')
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
``` |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | >
> If you just want to **read an image in Python** using the specified
> libraries only, I will go with `matplotlib`
>
>
>
**In matplotlib :**
```
import matplotlib.image
read_img = matplotlib.image.imread('your_image.png')
``` | you can try to use cv2 like this
```py
import cv2
image= cv2.imread('image page')
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
``` |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | >
> If you just want to **read an image in Python** using the specified
> libraries only, I will go with `matplotlib`
>
>
>
**In matplotlib :**
```
import matplotlib.image
read_img = matplotlib.image.imread('your_image.png')
``` | **Easy way**
from IPython.display import Image
Image(filename ="Covid.jpg" size ) |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | You can also use [Pillow](https://python-pillow.org/) like this:
```
from PIL import Image
image = Image.open("image_path.jpg")
image.show()
``` | I read all answers but I think one of the best method is using [openCV](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_image_display/py_image_display.html) library.
```
import cv2
img = cv2.imread('your_image.png',0)
```
and for displaying the image, use the following code :
```
fr... |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | For the better answer, you can use these lines of code.
Here is the example maybe help you :
```
import cv2
image = cv2.imread('/home/pictures/1.jpg')
plt.imshow(image)
plt.show()
```
In **`imread()`** you can pass the directory .so you can also use `str()` and `+` to combine dynamic directories and fixed director... | you can try to use cv2 like this
```py
import cv2
image= cv2.imread('image page')
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
``` |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | You can also use [Pillow](https://python-pillow.org/) like this:
```
from PIL import Image
image = Image.open("image_path.jpg")
image.show()
``` | you can try to use cv2 like this
```py
import cv2
image= cv2.imread('image page')
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
``` |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | ```
import matplotlib.pyplot as plt
image = plt.imread('images/my_image4.jpg')
plt.imshow(image)
```
*Using 'matplotlib.pyplot.imread' is recommended by warning messages in jupyter.* | For the better answer, you can use these lines of code.
Here is the example maybe help you :
```
import cv2
image = cv2.imread('/home/pictures/1.jpg')
plt.imshow(image)
plt.show()
```
In **`imread()`** you can pass the directory .so you can also use `str()` and `+` to combine dynamic directories and fixed director... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.