Unnamed: 0
int64 0
1.91M
| id
int64 337
73.8M
| title
stringlengths 10
150
| question
stringlengths 21
64.2k
| answer
stringlengths 19
59.4k
| tags
stringlengths 5
112
| score
int64 -10
17.3k
|
---|---|---|---|---|---|---|
1,903,700 | 70,802,626 |
Is there a "list-membership binary if" in Python?
|
<p>I am looking for some kind of "binary" (non-ternary) <code>if</code> that allows to define list membership in Python, similar to how it works in list comprehensions. Consider the following piece of code:</p>
<pre class="lang-py prettyprint-override"><code>abc = (1, 0, 2)
my_list = [i for i in abc if i]
# observed: [1, 2]
a = 1
b = 0
c = 2
my_list = ["d" if a; "e" if b; "f" if c]
# expected: ["d", "f"]
</code></pre>
<p>While the first block works, the second does not (not surprisingly). I would find this syntax quite pythonic, however. Is there anything that comes close to it, such as</p>
<pre class="lang-py prettyprint-override"><code>my_list = ["d" if a else Nothing; "e" if b else Nothing; "f" if c else Nothing]
</code></pre>
|
<p>The <code>if</code> in a list comprehension is not an expression itself, only part of the syntax of a generator expression that allows you to provide a <em>single</em> Boolean condition to filter what the generator produces.</p>
<p>Your second block can be written as</p>
<pre><code>my_list = [value
for (value, condition) in zip(["d", "e", "f"],
[a, b, c])
if condition]
</code></pre>
<p>As pointed out by user2357112 supports Monica, this is captured by the <code>compress</code> type provided by the <code>itertools</code> module:</p>
<pre><code>from itertools import compress
my_list = list(compress(["d", "e", "f"],
[a, b, c]))
</code></pre>
|
python|syntax
| 5 |
1,903,701 | 70,915,526 |
Python : Async random broken?
|
<p>so rn I am working in asynchronous python, and i have to deal with random number.
Problem is that, for numbers between 0 and 4, I get the same numbers very often, like as follows :</p>
<pre><code>3 2 0 2 4 0 1 4 2 1 4 2 1 3 2 3 2 2 2 1 0 3 2 2 2 0 0 4 3 0 3 4 4 0 3 3 3 3 2 4 4 4 0
</code></pre>
<p>of course there is only five possibilities but look at the end, i got 4 number 3 in a row, which is roughly 1/625 chance, and we don't talk about the times i get the same number 3 times in a row.</p>
<p>My code looks like this :</p>
<pre><code>when async ready :
random.seed(time.time())
async event:
index = random.randint(0,4)
async.send(someList[index])
</code></pre>
<p>Also it is a discord bot so the code runs continuously, so the seed is only donc once if that matters</p>
|
<p>Without a more complete, yet minimal example, we cannot be sure if the code you use works as intended, but in a 42 element long list, it is quite common to have a value repeated 4 times in a row. Check the following code that generates 1000 times a 42 long random list, checks the longest repetition in each list, and counts how often happens it.</p>
<pre class="lang-py prettyprint-override"><code>import random
import matplotlib.pyplot as plt
length_of_longest = []
for j in range(1000):
random.seed(j)
rndstr = "".join([str(random.randint(0, 4)) for _ in range(42)])
for i in range(1, 42):
total = 0
for my_str in "01234":
for_my_str = rndstr.count(my_str*i)
total += for_my_str
if total == 0:
length_of_longest.append(i-1) # this length was not found
break
# plot the results
fig, ax = plt.subplots()
ax.set_xticks([i+0.5 for i in range(8)], labels=range(8))
fig.patch.set_facecolor('white')
plt.hist(length_of_longest,bins=range(0,max(length_of_longest)+2))
</code></pre>
<p>This produces the following plot:</p>
<p><a href="https://i.stack.imgur.com/DPAG7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DPAG7.png" alt="enter image description here" /></a></p>
<p>The x-axis tells how often was the longest repetition x long (e.g. at x=5, then there was a 11111 or 33333 or ... in the sequence), and y tells how many series were found with this property out of 1000.</p>
<p>It can be seen that in around 15%-20% of the cases, the length of the longest sequence is 4, but it can also occur a couple of times out of 1000, that the same value is chosen 7 times in a row.</p>
|
python|asynchronous|random
| 2 |
1,903,702 | 11,677,130 |
Passing a Hebrew file name as command line argument in Windows
|
<p>I have a small Python program. I use the the Windows registry to enable the opening of files using the right-click context menu. My registry entry:</p>
<blockquote>
<p>C:\Users\me\projects\mynotepad\notepad.exe "%1"</p>
</blockquote>
<p>When I try and open a file with a Hebrew name using my right-click context menu, I get the file name as question marks, and I get an exception while trying to get the file size.</p>
<p>Here is my code:</p>
<pre><code>file_name = sys.argv[1]
file_size = os.path.getsize(unicode(file_name))
</code></pre>
<p>I have tried this:</p>
<pre><code>file_name = sys.argv[1].decode("cp1255").encode('utf-8')
file_size = os.path.getsize(unicode(file_name))
</code></pre>
<p>But it didn't work.</p>
<p>Any advice?</p>
|
<p>Turns out it's a problem. See <a href="https://stackoverflow.com/questions/846850/read-unicode-characters-from-command-line-arguments-in-python-2-x-on-windows">here</a> for the solution. You need to resort to Windows API to get the arguments.</p>
|
python|unicode|command-line-arguments|hebrew
| 2 |
1,903,703 | 33,612,318 |
How can i combine two queries in sqlalchemy - raw and orm?
|
<p>I have these queries:</p>
<pre><code> funds_subq = text('''select distinct on (user_id) user_id,
last_value(amount) over(PARTITION BY user_id order BY id asc RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
from transactions order by user_id, ts_spawn desc''')
g1 = aliased(Group)
u1 = aliased(User)
users = Session.query(User.id.label('user_id'),
User.name.label('user_name'),
User.funds.label('user_funds'),
Group.id.label('group_id'),
Group.parent_id.label('parent_id'),
u1.id.label('owner_id'),
u1.name.label('owner_name')). \
select_from(User). \
join(Group, Group.id == User.group_id). \
outerjoin(g1, g1.id == Group.parent_id). \
outerjoin(u1, u1.id == g1.owner_id)
</code></pre>
<p>So, how can I join the first to the second?
I tried something like this:</p>
<pre><code>users = users.outerjoin(funds_subq, funds_subq.c.user_ud == User.id)
</code></pre>
<p>Of course, it did not worked, because funds_subq does not have <code>c</code> attribute and it does not have <code>subquery()</code> attribute too.
And <a href="https://bitbucket.org/zzzeek/sqlalchemy/issues/3049/support-range-specificaiton-in-window" rel="nofollow">that</a> issue shows that there is no way to use my version of the window query.</p>
<p>How can I implement my query?</p>
|
<p>I forgot about the question :)</p>
<p>There is my solution:</p>
<pre><code> from sqlalchemy.sql.expression import ColumnElement
from sqlalchemy.ext.compiler import compiles
class Extreme(ColumnElement):
def __init__(self, request_column, partition_by, order_by, last=True):
super(Extreme, self).__init__()
self.request_column = request_column
self.partition_by = partition_by
self.order_by = order_by
self.last = last
# @property
# def type(self):
# return self.func.type
def extreme_last(request_column, partition_by, order_by):
"""
function returns last_value clause like this:
last_value(transactions.remains) OVER (
PARTITION BY transaction.user_id
order BY transactions.id asc
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
it returns last value of transaction.remains for every user, that means that we can get real balance of every user
:param request_column: column, which last value we need
:param partition_by: for what entity do we need last_value, e.g. user_id
:param order_by: ordering for get last_value
:return:
"""
return Extreme(request_column, partition_by, order_by)
def extreme_first(request_column, partition_by, order_by):
"""
as same as the `extreme_last` above, but returns first value
:param request_column:
:param partition_by:
:param order_by:
:return:
"""
return Extreme(request_column, partition_by, order_by, last=False)
@compiles(Extreme)
def compile_keep(extreme, compiler, **kwargs):
return "%s(%s) OVER (PARTITION BY %s order BY %s asc RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)" % (
"last_value" if extreme.last else "first_value",
compiler.process(extreme.request_column),
compiler.process(extreme.partition_by),
compiler.process(extreme.order_by)
)
</code></pre>
<p>And there is an example of using. The query returns <code>remains</code> field of the last row of every user:</p>
<pre><code>Session.query(distinct(Transaction.user_id).label('user_id'),
extreme_last(Transaction.remains,
partition_by=Transaction.user_id,
order_by=Transaction.id).label('remains'))
</code></pre>
|
python|sql|postgresql|sqlalchemy
| 0 |
1,903,704 | 33,730,551 |
how to sort tuple value from list in python
|
<p>I have list of tuple values. I need to sort value by id from the tuple list. Can anyone help me to do this.</p>
<pre><code> l = [('abc','23'),('ghi','11'),('sugan','12'),('shankar','10')]
</code></pre>
<p>I need a output like this.</p>
<pre><code> l = [('shankar','10'),('ghi','11'),('sugan','12'),('abc','23')]
</code></pre>
<p>and also if i need to sort like this means</p>
<pre><code> l = [('abc', '23'),('sugan', '12'),('ghi', '11'),('shankar', '10')]
</code></pre>
|
<p>You may pass <code>key</code> param to sorted function.</p>
<pre><code>>>> l = [('abc','23'),('ghi','11'),('sugan','12'),('shankar','10')]
>>> sorted(l, key=lambda x: int(x[1]))
[('shankar', '10'), ('ghi', '11'), ('sugan', '12'), ('abc', '23')]
>>>
</code></pre>
|
python|sorting|tuples
| 6 |
1,903,705 | 33,850,850 |
Python:not getting Length of longest common subsequence of lists
|
<p>I tried to implement in LCS in simplest way I can but I am not getting the right value. Instead of 4 I get . I am not sure whats wrong with my code:</p>
<pre><code>X= ['A','B','C','B','D','A','B']
Y= ['B','D','C','A','B','A','X','Y']
m= len(X)
n= len(Y)
c={}
for i in range(1,m) :
c[i,0]=0
for j in range(0,n):
c[0,j]=0
for i in range (1,m):
for j in range (1,n):
if X[i]==Y[j]:
c[i,j]=c[i-1,j-1]+1
elif c[i-1,j] >= c[i,j-1]:
c[i,j]=c[i-1,j]
else:
c[i,j]=c[i,j-1]
print c[m-1,n-1]
print c
</code></pre>
|
<p>It looks like the one-indexing you're using might be the root of your problem. If I understand correctly, you're looking for the LCS 'BCBA' of length 4, but you never actually compare the first entry to anything, so you don't have the opportunity to match the 'B' that is the first element of Y.</p>
<p>I made some slight modifications to your code and got a solution of 4:</p>
<pre><code>X = ['A', 'B', 'C', 'B', 'D', 'A', 'B']
Y = ['B', 'D', 'C', 'A', 'B', 'A', 'X', 'Y']
m = len(X)
n = len(Y)
c = {}
for i in range(0, m+1):
c[i, 0] = 0
for j in range(0, n+1):
c[0, j] = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if X[i-1] == Y[j-1]:
c[i, j] = c[i - 1, j - 1] + 1
else:
c[i, j] = max(c[i-1, j],
c[i, j-1])
print c[m, n]
</code></pre>
<p>Hope this helps.</p>
|
python|algorithm|dynamic-programming
| 2 |
1,903,706 | 46,859,304 |
Permutations of a numpy array into an ndarray or matrix
|
<pre><code>foo = np.array([1,2,3,4])
</code></pre>
<p>I have a numpy array <code>foo</code> that I would like to transform into an ndarry or a matrix, similar to this:</p>
<pre><code>bar = np.array([[1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3]])
</code></pre>
<p>Any suggestions on how to do this efficiently, as my source array <code>foo</code> will vary in size, and I'll need to do this transformation millions of times.</p>
|
<p>For a massive performance we could incorporate <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/#indexing-scheme-strides" rel="nofollow noreferrer"><code>strides</code></a> here. The trick is to concatenate the original array with the sliced array ending at the second last element and then taking sliding windows of lengths same as the length of the original array.</p>
<p>Hence, the implementation would be -</p>
<pre><code>def strided_method(ar):
a = np.concatenate(( ar, ar[:-1] ))
L = len(ar)
n = a.strides[0]
return np.lib.stride_tricks.as_strided(a, (L,L), (n,n), writeable=False)
</code></pre>
<p>The output would be read-only and a view of the concatenated array and as such would have a constant time almost irrespective of the array size. This means a hugely efficient solution. If you need writable output with its own memory space, make a copy there, as shown in the timings later on.</p>
<p>Sample run -</p>
<pre><code>In [51]: foo = np.array([1,2,3,4])
In [52]: strided_method(foo)
Out[52]:
array([[1, 2, 3, 4],
[2, 3, 4, 1],
[3, 4, 1, 2],
[4, 1, 2, 3]])
</code></pre>
<p>Runtime test -</p>
<pre><code>In [53]: foo = np.random.randint(0,9,(1000))
# @cᴏʟᴅsᴘᴇᴇᴅ's loopy soln
In [54]: %timeit np.array([np.roll(foo, -x) for x in np.arange(foo.shape[0])])
100 loops, best of 3: 12.7 ms per loop
In [55]: %timeit strided_method(foo)
100000 loops, best of 3: 7.46 µs per loop
In [56]: %timeit strided_method(foo).copy()
1000 loops, best of 3: 454 µs per loop
</code></pre>
|
python|arrays|performance|numpy|permutation
| 3 |
1,903,707 | 37,868,201 |
Converting a scapy packet to string produces an E?
|
<p>I'm currently working on using scapy for sending data packets, and I've run into a weird issue. When I create a packet as such:</p>
<pre><code>pack = IP(dst="127.0.0.1", id=local_ID)/UDP()/chunk
</code></pre>
<p>and then convert that packet to a string (so I can send it via a socket)</p>
<pre><code>sendPack = str(pack)
</code></pre>
<p>the result of sendPack is wrong.</p>
<p>For instance, in my test file, I have the numbers 1-8000 ordered as such</p>
<pre><code>1
2
3
...
</code></pre>
<p>then, when I <code>print("SEND_PACK: "+sendPack)</code>
it produces the following:</p>
<pre><code>E
2
3
...
</code></pre>
<p>Everything else is perfect except for the <code>E</code></p>
<p>I can't understand where that <code>E</code> is coming from, or what it means.</p>
<p>It's also worth noting that I have verified that <code>pack</code> contains the correct data, and that regardless of what the first line of the test file is, the first line of the output is always an <code>E</code></p>
<p>Thanks!</p>
|
<p>To those interested, I fixed the issue by doing the following:</p>
<p>As pointed out above, the E was a result of me printing the packet, not it's contents. In order to access the contents I wanted, I had to do the following:</p>
<pre><code>sendPack = pack[UDP].load #Get the packet's load at the UDP layer
id = pack[IP].ID #Get the ID at the IP layer
</code></pre>
<p>The documentation for Scapy is sparse, so I didn't realize that I could access the individual fields of each packet this way.</p>
<p>Here's <a href="https://thepacketgeek.com/scapy-p-04-looking-at-packets/%20%22where%20I%20found%20this%20fix" rel="nofollow">where I found this fix</a></p>
|
python|string|sockets|scapy
| 1 |
1,903,708 | 38,034,495 |
How to print all factorization of an integer in Python 3.5.1
|
<p>I am new to programming and trying to learn for loop, nested for loop with if statement.</p>
<p>I have written this code to produce all factorisations of an integer <code>n</code>:</p>
<pre><code>n=int(input())
for i in range(0,n+1):
for j in range(0,i):
if i*j == n:
print(i,'times',j,'equals',n)
break
</code></pre>
<p>now if n=10 it produces the following result:</p>
<blockquote>
<p>5 times 2 equals 10<br>
10 times 1 equals 10</p>
</blockquote>
<p>The are couple of problems with this one. First is that it ignores the first factorisation i.e.</p>
<blockquote>
<p>1 times 10 equals 10</p>
</blockquote>
<p>Second problem i want the <code>i</code> and <code>j</code> to be swapped in result i.e. it should say:</p>
<blockquote>
<p>1 times 10 equals 10<br>
2 times 5 equals 10<br>
10 times 1 equals 10</p>
</blockquote>
<p>not</p>
<blockquote>
<p>1 times 10 equals 10<br>
5 times 2 equals 10<br>
10 times 1 equals 10</p>
</blockquote>
|
<p>Try this:</p>
<pre><code>n = int(input())
for i in range(1, int(n / 2) + 1):
for j in range(1, i):
if i * j == n:
print(j, ' times ', i, ' equals ' , n)
</code></pre>
<blockquote>
<p>Few observations:</p>
<ul>
<li>You may not require the break statement if you want to have all the factors</li>
<li>There may be duplicates also</li>
<li>You may start the loop from 1</li>
<li>You may limit the first loop to n/2 as n/2 is the greatest factor less than n</li>
</ul>
<p>Please take this code as a starting point and not a copy-paste solution.</p>
</blockquote>
|
python|factorization
| 0 |
1,903,709 | 67,635,071 |
CURL command in Python's requests
|
<p>Can you please help me convert the following CURL command into a command for Python's requests library?</p>
<pre><code>curl -F pdb_file[pathvar]=@/path/myfile.pdb -X POST https://proteins.plus/api/pdb_files_rest -H "Accept: application/json"
</code></pre>
<p>I've tried many things, like this:</p>
<pre><code>import requests
file = open("3w32.pdb", "rb")
url = "https://proteins.plus/api/pdb_files_rest"
response = requests.post(url, data=file)
response.json()
</code></pre>
<p>or this:</p>
<pre><code>import requests
file = open("3w32.pdb", "rb")
url = "https://proteins.plus/api/pdb_files_rest"
response = requests.post(url, data={"pdb_file[pathvar]": file}, json={"Accept": "application/json"})
response.json()
</code></pre>
<p>but I can't make it work. I either get an error from the server, or a JSONDecodeError in Python.</p>
|
<p>Try this answer <a href="https://stackoverflow.com/a/22567429/4252013">https://stackoverflow.com/a/22567429/4252013</a>
Instead of using "data" argument try with "file"</p>
|
python|curl|python-requests
| 0 |
1,903,710 | 67,704,331 |
Regex should fail if pattern is followed by another pattern
|
<p>I need to detect <code>@username</code> mentions within a message, but NOT if it is in the form of <code>@username[user_id]</code>. I have a regex that can match the <code>@username</code> part, but am struggling to negate the match if it is followed by <code>\[\d\]</code>.</p>
<pre class="lang-py prettyprint-override"><code>import re
username_regex = re.compile(r'@([\w.@-]+[\w])')
usernames = username_regex.findall("Hello @kevin") # correctly finds kevin
usernames = username_regex.findall("Hello @kevin.") # correctly finds kevin
usernames = username_regex.findall("Hello @kevin[1].") # shouldn't find kevin but does
</code></pre>
<p>The regex allows for usernames that contain <code>@</code>, <code>.</code> and <code>-</code>, but need to end with a <code>\w</code> character (<code>[a-zA-Z0-9_]</code>). How can I extend the regex so that it fails if the username is followed by the userid in the <code>[1]</code> form?</p>
<p>I tried <code>@([\w.@-]+[\w])(?!\[\d+\])</code> but then it matches <code>kevi</code> </p>
<p>I'm using Python 3.10.</p>
|
<p>You can "emulate" possessive matching with</p>
<pre class="lang-py prettyprint-override"><code>@(?=([\w.@-]*\w))\1(?!\[\d+\])
</code></pre>
<p>See the <a href="https://regex101.com/r/N431a6/1/" rel="nofollow noreferrer">regex demo</a>.</p>
<p><em>Details</em>:</p>
<ul>
<li><code>@</code> - a <code>@</code> char</li>
<li><code>(?=([\w.@-]*\w))</code> - a positive lookahead that matches and captures into Group 1 zero or more word, <code>.</code>, <code>@</code> and <code>-</code> chars, as many as possible, and then a word char immediately to the right of the current position (the text is not consumed, the regex engine index stays at the same location)</li>
<li><code>\1</code> - the text matched and captured in Group 1 (this consumes the text captured with the lookahead pattern, mind that backreferences are atomic by nature)</li>
<li><code>(?!\[\d+\])</code> - a negative lookahead that fails the match if there is <code>[</code> + one or more digits + <code>]</code> immediately to the right of the current location.</li>
</ul>
|
python|regex
| 2 |
1,903,711 | 61,352,148 |
Extracting the entities from Spacy and putting in new dataframe
|
<p>So I followed the answer in this question (<a href="https://stackoverflow.com/questions/60116419/extract-entity-from-dataframe-using-spacy">Extract entity from dataframe using spacy</a>) and that solved me being able to iterate on a DF. </p>
<p>Issues I am facing is trying to take these results, add a column from original df then put all this into a new df. I want the DOI from original df, the entity text and entity labels from the NER.</p>
<p>Code to grab and put into list:</p>
<pre><code>entities=[]
nlp = spacy.load("en_ner_bionlp13cg_md")
for i in df['Abstract'].tolist():
doc = nlp(i)
for entity in doc.ents:
entities.append((df.DOI, entity.text , entity.label_))
</code></pre>
<p>Then I take the entities list and feed into a new df:</p>
<pre><code>df_ner = pd.DataFrame.from_records(entities, columns =['DOI', 'ent_name', 'ent_type'])
</code></pre>
<p>Unfortunately, only the first records gets loaded into the df. What am i missing?</p>
<pre><code>DOI ent_name ent_type
0 3 10.7501/j.issn.0253-2670.2020.... COVID-19 GENE_OR_GENE_PRODUCT
1 3 10.7501/j.issn.0253-2670.2020.... ACE2 GENE_OR_GENE_PRODUCT
2 3 10.7501/j.issn.0253-2670.2020.... angiotensin converting enzyme II GENE_OR_GENE_PRODUCT
3 3 10.7501/j.issn.0253-2670.2020.... ACE2 GENE_OR_GENE_PRODUCT
4 3 10.7501/j.issn.0253-2670.2020.... UniProt GENE_OR_GENE_PRODUCT
</code></pre>
|
<p>This worked:</p>
<pre><code>getattr(tqdm, '_instances', {}).clear() # ⬅ clear the progress
spacy.prefer_gpu()
nlp = spacy.load("en_ner_bionlp13cg_md")
entities=[]
uuid = str(df.uuid)
for i in tqdm(df['Abstract'].tolist(),bar_format="{l_bar}%s{bar}%s{r_bar}" % (Fore.GREEN, Fore.RESET)):
doc = nlp(i)
for entity in doc.ents:
entities.append((i, entity.text, entity.label_, uuid))
</code></pre>
|
python|pandas|nlp|spacy
| 0 |
1,903,712 | 65,863,226 |
Turning loop comprehensions into numpy form
|
<p>Is there anyway I could convert the standard deviation function to be computed just like the <code>y_mean</code> and <code>xy_mean</code> functions. I don't want to use a for loop for calculating the standard deviation or a function that takes a lot of RAM memory. I am trying to use <code>np.convolve()</code> function for calculating the standard deviation <code>std</code>.</p>
<p>variables:</p>
<pre><code>number = 5
PC_list= np.array([457.334015,424.440002,394.795990,408.903992,398.821014,402.152008,435.790985,423.204987,411.574005,
404.424988,399.519989,377.181000,375.467010,386.944000,383.614990,375.071991,359.511993,328.865997,
320.510010,330.079010,336.187012,352.940002,365.026001,361.562012,362.299011,378.549011,390.414001,
400.869995,394.773010,382.556000])
</code></pre>
<p>Vanilla python functions:</p>
<pre><code>y_mean = sum(PC_list[i:i+number])/number
xy_mean = sum([x * (i + 1) for i, x in enumerate(PC_list[i:i+number])])/number
std = (sum([(k - y_mean)**2 for k in PC_list[i:i+number]])/(number-1))**0.5
</code></pre>
<p>Numpy versions:</p>
<pre><code>y_mean = (np.convolve(PC_list, np.ones(shape=(number)), mode='valid')/number)[:-1]
xy_mean = (np.convolve(PC_list, np.arange(number, 0, -1), mode='valid'))[:-1]
std = ?
</code></pre>
|
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.as_strided.html" rel="nofollow noreferrer"><code>np.lib.stride_tricks.as_strided</code></a> and <a href="https://numpy.org/doc/stable/reference/generated/numpy.std.html" rel="nofollow noreferrer"><code>np.std</code></a> with <code>ddof=1</code>:</p>
<pre><code>>>> np.std(
np.lib.stride_tricks.as_strided(
PC_list,
shape=(PC_list.shape[0] - number + 1, number),
strides=PC_list.strides*2
),
axis=-1,
ddof=1
)
array([25.35313557, 11.6209317 , 16.32415133, 15.46019574, 15.29513506,
14.02947067, 14.68620846, 17.04664993, 16.38348865, 12.9925946 ,
9.58525968, 5.32623099, 10.61466493, 23.71209646, 27.85489139,
23.31091745, 14.78211757, 12.11214834, 17.90301391, 15.42895731,
11.7602241 , 9.27171536, 12.57714149, 17.25865608, 15.2717403 ,
9.02825105])
</code></pre>
<p>Otherwise you can move use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.std.html" rel="nofollow noreferrer"><code>pandas.Series.rolling.std</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.dropna.html" rel="nofollow noreferrer"><code>pandas.Series.dropna</code></a> then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_numpy.html" rel="nofollow noreferrer"><code>pandas.Series.to_numpy</code></a>:</p>
<pre><code>>>> pd.Series(PC_list).rolling(number).std().dropna().to_numpy()
array([25.35313557, 11.6209317 , 16.32415133, 15.46019574, 15.29513506,
14.02947067, 14.68620846, 17.04664993, 16.38348865, 12.9925946 ,
9.58525968, 5.32623099, 10.61466493, 23.71209646, 27.85489139,
23.31091745, 14.78211757, 12.11214834, 17.90301391, 15.42895731,
11.7602241 , 9.27171536, 12.57714149, 17.25865608, 15.2717403 ,
9.02825105])
</code></pre>
<p><strong>EXPLANATION</strong>:
<code>np.lib.stride_tricks.as_strided</code> is used to reshape the array in a special way, that resembles rolling:</p>
<pre><code>>>> np.lib.stride_tricks.as_strided(
PC_list,
shape=(PC_list.shape[0] - number + 1, number),
strides=PC_list.strides*2
)
array([[457.334015, 424.440002, 394.79599 , 408.903992, 398.821014], #index: 0,1,2,3,4
[424.440002, 394.79599 , 408.903992, 398.821014, 402.152008], #index: 1,2,3,4,5
[394.79599 , 408.903992, 398.821014, 402.152008, 435.790985], #index: 2,3,4,5,6
[408.903992, 398.821014, 402.152008, 435.790985, 423.204987], # ... and so on
[398.821014, 402.152008, 435.790985, 423.204987, 411.574005],
[402.152008, 435.790985, 423.204987, 411.574005, 404.424988],
[435.790985, 423.204987, 411.574005, 404.424988, 399.519989],
[423.204987, 411.574005, 404.424988, 399.519989, 377.181 ],
[411.574005, 404.424988, 399.519989, 377.181 , 375.46701 ],
[404.424988, 399.519989, 377.181 , 375.46701 , 386.944 ],
[399.519989, 377.181 , 375.46701 , 386.944 , 383.61499 ],
[377.181 , 375.46701 , 386.944 , 383.61499 , 375.071991],
[375.46701 , 386.944 , 383.61499 , 375.071991, 359.511993],
[386.944 , 383.61499 , 375.071991, 359.511993, 328.865997],
[383.61499 , 375.071991, 359.511993, 328.865997, 320.51001 ],
[375.071991, 359.511993, 328.865997, 320.51001 , 330.07901 ],
[359.511993, 328.865997, 320.51001 , 330.07901 , 336.187012],
[328.865997, 320.51001 , 330.07901 , 336.187012, 352.940002],
[320.51001 , 330.07901 , 336.187012, 352.940002, 365.026001],
[330.07901 , 336.187012, 352.940002, 365.026001, 361.562012],
[336.187012, 352.940002, 365.026001, 361.562012, 362.299011],
[352.940002, 365.026001, 361.562012, 362.299011, 378.549011],
[365.026001, 361.562012, 362.299011, 378.549011, 390.414001],
[361.562012, 362.299011, 378.549011, 390.414001, 400.869995],
[362.299011, 378.549011, 390.414001, 400.869995, 394.77301 ],
[378.549011, 390.414001, 400.869995, 394.77301 , 382.556 ]])
</code></pre>
<p>Now if we take the <code>std</code> of the above array across the last axis, to obtain the rolling <code>std</code>. By default <code>numpy</code> uses <code>ddof=0</code>, i.e. Delta Degrees of Freedom = 0, which means for <code>number</code> amount of samples, the divisor will be equal to <code>number - 0</code>. Now as you want <code>number - 1</code>, you need <code>ddof=1</code>.</p>
|
python|function|numpy|iterator|slice
| 1 |
1,903,713 | 65,807,006 |
How to append serial data on textbrowser pyqt5 receiving from serial port python pyqt
|
<p>My goal is to create a GUI using PyQt5 with functionality to receive data from serial port.</p>
<ul>
<li>This data should be printed into text browser inside the GUI.</li>
<li>Data should be printed there continuously.</li>
<li>Reading should be toggled by pushing button.</li>
</ul>
<p>This is the GUI part of the code:</p>
<pre><code>class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(540, 60, 101, 61))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(30, -10, 221, 71))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(30, 60, 81, 51))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(160, 130, 141, 81))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(20, 180, 201, 61))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(700, 240, 81, 51))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(20, 330, 251, 21))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(30, 240, 651, 71))
font = QtGui.QFont()
font.setPointSize(12)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setObjectName("lineEdit_2")
self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
self.textBrowser.setGeometry(QtCore.QRect(260, 150, 381, 51))
font = QtGui.QFont()
font.setPointSize(12)
self.textBrowser.setFont(font)
self.textBrowser.setObjectName("textBrowser")
self.textBrowser_2 = QtWidgets.QTextBrowser(self.centralwidget)
self.textBrowser_2.setGeometry(QtCore.QRect(30, 371, 731, 181))
font = QtGui.QFont()
font.setPointSize(12)
self.textBrowser_2.setFont(font)
self.textBrowser_2.setObjectName("textBrowser_2")
self.Clear = QtWidgets.QPushButton(self.centralwidget)
self.Clear.setGeometry(QtCore.QRect(140, 330, 101, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.Clear.setFont(font)
self.Clear.setObjectName("Clear")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(270, 330, 81, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(100, 60, 91, 61))
font = QtGui.QFont()
font.setPointSize(12)
self.comboBox.setFont(font)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(250, 70, 81, 41))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.comboBox_2 = QtWidgets.QComboBox(self.centralwidget)
self.comboBox_2.setGeometry(QtCore.QRect(360, 60, 91, 61))
font = QtGui.QFont()
font.setPointSize(12)
self.comboBox_2.setFont(font)
self.comboBox_2.setObjectName("comboBox_2")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.pushButton.clicked.connect(self.Connect)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
</code></pre>
<p>This is the reading function:</p>
<pre><code>def Connect(self,MainWindow):
port=self.comboBox.currentText()
baudrate=self.comboBox_2.currentText()
serialPort = serial.Serial(port = port, baudrate=baudrate,
bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
serialString = " "
while(1):
if(serialPort.in_waiting > 0):
serialString = serialPort.readline()
print(serialString.decode('ascii'))
serialPort.write(b"Thank you for sending data \r\n")
</code></pre>
|
<p>So to append any text to the textBrowser simply use this line of code:</p>
<pre><code>self.textBrowser.append(serialString.decode('ascii')) #Append text to the GUI
</code></pre>
<hr />
<ul>
<li>But you are using <code>while</code> loop inside a GUI. <strong>This wil cause the
whole GUI to freeze and your app won't responded to any of your
input.</strong></li>
<li>You have to use threading for you to don't freeze the GUI.</li>
</ul>
<p>Assert this to your code:</p>
<pre><code>import Threading
...
#This should go instaed of the line 140: self.pushButton.clicked.connect(self.Connect)
self.pushButton.clicked.connect(lambda: Threading.Thread(target = self.Connect).start())
...
</code></pre>
|
python|pyqt5|qtserialport
| 0 |
1,903,714 | 43,418,752 |
Python While Loop not registering raw_input from from previous variable
|
<p>I'm using Python 2.7.13 and Windows Powershell. When I run the program, the first <code>raw_input()</code> isn't recognized, regardless of whether, "yes", "y", or "Yes", are entered.</p>
<p>Ideally, I'm wanting the program to register whether any of these options are initially used. If one of these options isn't used, the while loop continues to display the "Type 'yes' when you are ready to begin" message, until the appropriate input is received from the user. Any help would be greatly appreciated!</p>
<pre><code># This is a questionnaire form for a python programming exercise.
print "Hello, Sir or Madame.",
print "My name is Oswald, and I will be asking you a few questions, today."
print "Are you ready to begin?"
answer_1 = raw_input()
while answer_1 != "yes" or answer_1 != "y" or answer_1 != "Yes":
print "Type 'yes' when you are ready to begin."
answer_1 = raw_input()
if (answer_1 == "yes") or (answer_1 == "y") or (answer_1 == "Yes"):
print "What is your name"
name = raw_input()
print "What is your favorite color?"
color = raw_input()
print "Where do you live?"
home = raw_input()
print "So, you're %r. You're favorite color is %r, and you live in %r" % (name, color, home)
</code></pre>
|
<p>Alright, I believe I've gotten it to work how you want it to.</p>
<p>First things first:
I made your condition evaluate to a single True or False by having it do this.</p>
<pre><code>condition = ((answer_1 == "yes") or (answer_1 == "y") or (answer_1 == "Yes"))
</code></pre>
<p>Then to start your while loop you just need to do this:</p>
<pre><code>while not condition:
print "Type 'yes' when you are ready to begin."
answer_1 = raw_input()
condition = ((answer_1 == "yes") or (answer_1 == "y") or (answer_1 == "Yes"))
</code></pre>
<p>Then and this is the important part.
You need to move the questions out side of the while loop.
Because if the while evaluates to true, it will ask you repetitively if your ready.
But say you answer yes at the beginning the while loop evaluates to False and the code for the questions is skipped.
If you want it to ask the questions repetitively just put them in a </p>
<pre><code>while True:
#ask the questions
</code></pre>
<p>Oh also, you won't need the if statement if you do it this way.
That is because if you answer no at the beginning, you'll enter the while loop until you enter yes. After which the loop closes, and the questions are asked. </p>
<p>I hope that answers your question.
Keep up the good work!</p>
|
python|loops|if-statement|while-loop|raw-input
| 0 |
1,903,715 | 48,607,163 |
Pandas : extracting values from unknown data structure in pandas series
|
<p>I have a pandas series, such that each row of the series includes a string with the following format (key - value structure):</p>
<blockquote>
<p>"Customer Name - Eric\nFamily Name - Lammela\n<strong>Shirt</strong> color - white\n\n"
field inside the string might change:
"Customer Name - Leo\nFamily Name - Messi\n<strong>Pants</strong> color - black\n"</p>
</blockquote>
<p>I would like to convert the whole series into a DataFrame.
What is the most efficient way?</p>
|
<p>You could try something like this. I have used the example you provided to try it out.</p>
<pre><code>import re
import pandas as pd
# Stored your example in the string
s = pd.Series(["Customer Name - Eric\nFamily Name - Lammela\nShirt color - white\n\n","Customer Name - Leo\nFamily Name - Messi\nPants color - black\n"])
# Define a function to convert each string in the Series to a json format
def str_to_dict(txt):
txt = txt.rstrip('\n')
txt = re.sub('^', '{"', txt)
txt = re.sub(' - ', '": "', txt)
txt = re.sub('\n', '", "', txt)
txt = re.sub('$', '"}', txt)
return(txt)
# Apply the function to the Series and store the results in a new Series
s1 = s.apply(str_to_dict)
# Create an empty DataFrame
df = pd.DataFrame()
# Loop through the converted Series and append the items to the DataFrame
# after using json to convert them to a dictionary
for c in s1:
df = df.append(json.loads(c), ignore_index=True)
# Printed the df to check the results.
print(df)
Customer Name Family Name Shirt color Pants color
0 Eric Lammela white NaN
1 Leo Messi NaN black
</code></pre>
<p>Hope this helps.</p>
|
python|pandas|parsing
| 0 |
1,903,716 | 48,851,446 |
Django: django.core.exceptions.ImproperlyConfigured: WSGI application 'wsgi.application' could not be loaded; Error importing module
|
<p>I used to check every answer to this question< but NOTHING helped me.
Here's a error:</p>
<pre><code>edjango.core.exceptions.ImproperlyConfigured: WSGI application 'wsgi.application' could not be loaded; Error importing module.
</code></pre>
<p>In settings file is:</p>
<pre><code>WSGI_APPLICATION = 'wsgi.application'
</code></pre>
<p>and WSGI file is:</p>
<pre><code>import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyLittleTest.settings")
application = get_wsgi_application()
</code></pre>
<p>Can you help me with this issue plz?</p>
|
<p>I think you need:</p>
<pre><code>WSGI_APPLICATION = 'mylittletest.wsgi.application'
</code></pre>
<p>or how your project is called.</p>
|
django|python-3.x
| -1 |
1,903,717 | 19,842,414 |
Numpy subarray for arbitrary number of dimension
|
<p>In Numpy, let's say you have a Nd-array A, you can slice the last dimension by doing <code>A[...,0]</code> or you can slice the first dimension by doing <code>A[0]</code>. I want to generalize this operation for all dimension (not just first or last) and i want this for Nd-array of arbitrary N so that if A3 is a 3d-array and A4 is a 4d-array, <code>func(A3, dim = 1, slice = 0)</code> give me <code>A3[ : , 0 , :]</code> and <code>func(A4, dim = 1, slice = 0)</code> give me <code>A4[ : , 0 , : , : ]</code>.</p>
<p>I've look for this for some time and finally figured out how to do it without doing horrible hack (like swapping dimension until the one of interest is in last place). So the code i'm posting here works for my need but </p>
<p>1) I'm always looking for advice to better myself</p>
<p>2) As I said, I've look for this for some time and never found anything so it could be usefull for others.</p>
<pre><code>def fancy_subarray(farray, fdim, fslice):
# Return the farray slice at position fslice in dimension fdim
ndim = farray.ndim
# Handle negative dimension and slice indexing
if fdim < 0:
fdim += ndim
if fslice < 0:
fslice += v.shape[fdim]
# Initilize slicing tuple
obj = ()
for i in range(ndim):
if i == fdim:
# Only element fslice in that dimension
obj += (slice(fslice, fslice+1, 1),)
else:
# "Full" dimension
obj += (slice(None,None,1),)
return farray[obj].copy()
</code></pre>
<p>So this little function just builds a slicing tuple by concatenating <code>slice(None,None,1)</code> in the position of the dimension we don't want to slice and <code>slice(fslice, fslice+1, 1)</code> in the dimension of interest. It than returns a subarray. It handles negative indexes. </p>
<p>There's a slight difference with this and straight up indexing: if A3 is 3x4x5, <code>A3[:,0,:]</code> is gonna be 3x5 while <code>fancy_subarray(A3, fdim = 1, fslice = 0)</code> is gonna be 3x1x5. Also the function handle out of bound dimension and indexes "naturally". If <code>fdim >= farray.ndim</code> the function just returns the full array because the if condition inside the for loop is never True and if <code>fslice >= farray.shape[fdim]</code> the returned subarray will have a size of 0 in dimension fdim.</p>
<p>This can easily be extended to more than just selecting one element in one dimension of course.</p>
<p>Thanks!</p>
|
<p>I think you are overcomplicating things, especially when handling <code>fslice</code>. If you simply did:</p>
<pre><code>def fancy_subarray(farray, fdim, fslice):
fdim += farray.ndim if fdim < 0 else 0
index = ((slice(None),) * fdim + (fslice,) +
(slice(None),) * (farray.ndim - fdim - 1))
return farray[index]
</code></pre>
<p>Then not only do you make your code more compact, but the same function can take single indices, slices or even lists of indices:</p>
<pre><code>>>> fancy_subarray(a, 1, 2)
array([[10, 11, 12, 13, 14],
[30, 31, 32, 33, 34],
[50, 51, 52, 53, 54]])
>>> fancy_subarray(a, 1, slice(2,3))
array([[[10, 11, 12, 13, 14]],
[[30, 31, 32, 33, 34]],
[[50, 51, 52, 53, 54]]])
>>> fancy_subarray(a, 1, [2, 3])
array([[[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39]],
[[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]]])
</code></pre>
|
numpy|multidimensional-array|slice|matrix-indexing
| 1 |
1,903,718 | 19,974,917 |
multiple file output in hadoop mapreduce streaming
|
<p>Im using hadoop map and reduce program . And i need to read a multiple file and output it into multiple files </p>
<p>Example </p>
<pre><code>Input \ one.txt
two.txt
three.txt
Output \
one_out.txt
two_out.txt
</code></pre>
<p>I need to get some thing like this. How can i achieve this.</p>
<p>Kindly help me </p>
<p>Thanks </p>
|
<ul>
<li>If the file size is small, you can simply use <strong>FileInputFormat</strong>, and hadoop will internally spawn a <strong>separate mapper task for every file</strong>, which will eventually generate output file for corresponding input file (if there are no reducers involved).</li>
<li>If the file is huge, you need to write a custominput format, and specify <code>isSplittable(false)</code>. It will ensure that hadoop does not split your file across mappers and will not generate multiple output files per input file</li>
</ul>
|
java|python|hadoop|mapreduce
| 1 |
1,903,719 | 4,107,996 |
Access to class attributes of parent classes
|
<p>I would like to know what is the best way to get all the attributes of a class when I don't know the name of them.</p>
<p>Let's say I have:</p>
<pre><code>#!/usr/bin/python2.4
class A(object):
outerA = "foobar outerA"
def __init__(self):
self.innerA = "foobar innerA"
class B(A):
outerB = "foobar outerB"
def __init__(self):
super(B, self).__init__()
self.innerB = "foobar innerB"
if __name__ == '__main__':
b = B()
</code></pre>
<p>Using hasattr/getattr to get the "outerA" class field of my b instance works fine:</p>
<pre><code>>>> print hasattr(b, "outerA")
>>> True
>>> print str(getattr(b, "outerA"))
>>> foobar outerA
</code></pre>
<p>Ok, that's good.</p>
<p>But what if I don't exactly know that b has inherited a field called "outerA" but I still want to get it?</p>
<p>To access b's inner fields, I usually use <code>b.__dict__</code> . To get <code>b.outerB</code>, I can use <code>b.__class__.__dict__</code> but that still doesn't show "outerA" among it fields:</p>
<pre><code>>>> print "-------"
>>> for key, val in b.__class__.__dict__.iteritems():
... print str(key) + " : " + str(val)
>>> print "-------\n"
</code></pre>
<p>Shows:</p>
<pre><code>-------
__module__ : __main__
__doc__ : None
__init__ : <function __init__ at 0xb752aaac>
outerB : foobar outerB
-------
</code></pre>
<p>Where's my <code>outerA</code>?? <strong>:D</strong></p>
<p>I am sure I can keep "climbing" the class hierarchy and get all the fields, but that doesn't seem like the greatest solution... </p>
<p>As there are hasattr(), getattr()... isn't there something like a <strong>listattr()</strong> that would give all the available attributes of an instance?</p>
<p>Thank you!</p>
|
<p>I think you're looking for <code>dir()</code> - it works just as well within code as in the shell.</p>
|
python|oop|inheritance|attributes
| 2 |
1,903,720 | 4,302,166 |
Format string dynamically
|
<p>If I want to make my formatted string dynamically adjustable, I can change the following code from</p>
<pre><code>print '%20s : %20s' % ("Python", "Very Good")
</code></pre>
<p>to</p>
<pre><code>width = 20
print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python", "Very Good")
</code></pre>
<p>However, it seems that string concatenation is cumbersome here. Any other way to simplify things?</p>
|
<p>You can do this using the <a href="https://docs.python.org/3/library/stdtypes.html#str.format" rel="noreferrer"><code>str.format()</code></a> method.</p>
<pre><code>>>> width = 20
>>> print("{:>{width}} : {:>{width}}".format("Python", "Very Good", width=width))
Python : Very Good
</code></pre>
<p>Starting from Python 3.6 you can use <a href="https://docs.python.org/3.6/reference/lexical_analysis.html#formatted-string-literals" rel="noreferrer"><code>f-string</code></a> to do this:</p>
<pre><code>In [579]: lang = 'Python'
In [580]: adj = 'Very Good'
In [581]: width = 20
In [582]: f'{lang:>{width}}: {adj:>{width}}'
Out[582]: ' Python: Very Good'
</code></pre>
|
python|string
| 114 |
1,903,721 | 69,556,023 |
compare tuple with array in them
|
<p>I am learning python and numpy. While trying to predict a result to check my understanding, I come across this :</p>
<pre><code>import numpy as np
x = np.arange(1,10).reshape(3,3)
np.where(x>5) == (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2]))
</code></pre>
<p>And the correlated error I now understand why.</p>
<pre><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></pre>
<p>And I came up with this:</p>
<pre><code>all(map(np.array_equal,
np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2])) ))
all([np.array_equal(v,t) for (v,t) in zip(
np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2]))) ])
all([(v==t).all() for (v,t) in zip(
np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2]))) ])
</code></pre>
<p>Which work, but seems to me a bit tedious and hard to read. Is there a more pythonic or numpy way to test arrays within a tuple ?</p>
|
<p>You were pretty close. The following works:</p>
<pre><code>np.array_equal(np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2])))
</code></pre>
<p><code>np.array_equal</code> has the ability to broadcast over tuples. It also treats arrays and sequences as equivalent, so you could just use if you'd prefer:</p>
<pre><code>np.array_equal(np.where(x>5), ([1, 2, 2, 2], [2, 0, 1, 2]))
</code></pre>
|
python|numpy|numpy-ndarray
| 0 |
1,903,722 | 48,405,608 |
save printed results from a loop to a dataframe
|
<p>How can I save loops from a print in a for loop to a dataframe?</p>
<p>Code I want to save</p>
<pre><code>for div in soup.select('[id^=post_message]'):
print(div.get_text("\n", strip=True))
</code></pre>
|
<p>Create a dataframe and append into it for each iteration. Or better still create a list, append into list for each step and then create a dataframe</p>
<pre><code>import pandas as pd
df = list()
for div in soup.select('[id^=post_message]'):
df.append(div.get_text("\n", strip=True))
df = pd.Dataframe(df)
</code></pre>
|
python|pandas|loops
| 0 |
1,903,723 | 51,466,445 |
Dice Roller in Python Not Random
|
<p>I made a dice roller in python recently. However, the outputs seem to be fairly non-random (e.g. numbers coming up regularly twice in a row). Is this to do with my poor code or is the random.randint function not as random as it seems?</p>
<pre><code>import random
print('Welcome to Dice Rolling simulator! \
Type "Roll" to start.')
def DiceRoll():
if input() == (str('Roll')):
print(spam)
print('Roll again?')
for i in range (50):
spam = random.randint(1,6)
DiceRoll()
</code></pre>
|
<p>One way to verify the randomness of your function is to call it enough times, and verify the output distribution. The following code does so.</p>
<pre><code>import random
def DiceRoll():
return random.randint(1,6)
hist = []
for i in range(100000):
hist.append(DiceRoll())
for j in range(1,7):
print("Pr({}) = {}".format(j,hist.count(j)/len(hist)))
</code></pre>
<p>This yields :</p>
<pre><code>Pr(1) = 0.16546
Pr(2) = 0.16777
Pr(3) = 0.16613
Pr(4) = 0.16534
Pr(5) = 0.1675
Pr(6) = 0.1678
</code></pre>
<p>Which seems to be perfectly random. </p>
|
python
| 3 |
1,903,724 | 64,274,464 |
Set currently logged in user as the user in the model when creating an object in Django
|
<p>I've tried to implement the solutions offered by some of the other posts I see on here, but nothing seems to be working. I'm brand new to django and backend in general, so I may just be lacking in skill.</p>
<p>The situation is that I'm letting users generate a <code>listing</code> based on a django model <code>Listings</code> using a ModelForm. Everything seems to be working except for the fact that I can't set the currently logged in user as the user for the <code>listing</code>. I understand that the user is stored in <code>request.user</code>, but I can't seem to set it within my form and I consistently get this error:</p>
<p><code>IntegrityError at /create</code></p>
<p><code>NOT NULL constraint failed: auctions_listings.listing_user_id</code></p>
<p>Here's the code for my User and Listings model:</p>
<pre><code>class User(AbstractUser):
pass
class Listings(models.Model):
title = models.CharField(max_length=64, default="")
description = models.TextField(default="")
image = models.URLField(blank=True, null=True)
initial_bid = models.DecimalField(max_digits=8, decimal_places=2)
category = models.CharField(max_length=64, default="Misc")
listing_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listing_user")
# listing.bid.all()????
</code></pre>
<p>and here is my form:</p>
<pre><code>from .models import Listings
class ListingsForm(forms.ModelForm):
class Meta:
model = Listings
exclude = ('listing_user')
fields = [
'title',
'description',
'image',
'initial_bid',
'category'
]
</code></pre>
<p>Some of the suggestions I've found have figured out that I can excluse the user requirement and then set it myself in my view, but whenever I try to exclude the <code>listing_user</code>, I get hit with this error:</p>
<p><code>TypeError: ListingsForm.Meta.exclude cannot be a string. Did you mean to type: ('listing_user',)?</code></p>
<p>Trying what is suggested is no help either.</p>
<p>Finally, here is my view:</p>
<pre><code>def create(request):
form = ListingsForm(request.POST or None)
if form.is_valid():
form.save()
form = ListingsForm()
context = {
'form': form
}
return render(request, "auctions/create.html", context)
</code></pre>
|
<p><strong>exclude</strong> should be a <strong>list</strong> or <strong>tuple</strong>. You have two options:</p>
<pre><code>exclude = ('listing_user',)
or
exclude = ['listing_user']
</code></pre>
<p>forms:</p>
<pre><code>from .models import Listings
class ListingsForm(forms.ModelForm):
class Meta:
model = Listings
exclude = ('listing_user',)
fields = [
'title',
'description',
'image',
'initial_bid',
'category'
]
</code></pre>
<p>views:</p>
<pre><code>def create(request):
form = ListingsForm(request.POST or None)
if form.is_valid():
form.instance.listing_user = request.user
form.save()
form = ListingsForm()
context = {
'form': form
}
return render(request, "auctions/create.html", context)
</code></pre>
|
python|django|django-models|django-forms|modelform
| 1 |
1,903,725 | 64,617,469 |
Anaconda Jupyter Notebook is suddenly not starting kernel
|
<p>I am trying to open Jupyter notebook, but everytime I got the message that <code>the kernel is dead</code>. I tried <code>conda update --all</code>, and after it was done, <strong>I could not even open anaconda</strong>. Then I uninstalled anaconda, and installed anaconda python 3.8 again. Now I get this message:</p>
<pre><code>Connection failed: A connection to the notebook server could not be
established. The notebook will continue trying to reconnect. Check your
network connection or notebook server configuration."
</code></pre>
<p>Yesterday I ran the command <code>conda update scipy</code> which was unsuccessful because I wasn't an administrator. Then I tried running as administrator, then ran <code>conda update --all</code>. Would that have caused the issue?</p>
|
<p><strong>As a last case scenario, if nothing else works, you could format your computer.</strong></p>
<p>In the future, just make sure to never use <code>conda</code> to install anything unless you are running in a virtual environment. If you want to read more about them check this out:</p>
<p><a href="https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/20/conda/" rel="nofollow noreferrer">https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/20/conda/</a></p>
|
python|jupyter-notebook|anaconda
| 0 |
1,903,726 | 64,329,330 |
RuntimeError: Data is outside [0.0, 1.0] and clamp is not set
|
<pre><code>def ContrastNBrightness1(img_array):
img_cv2 = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
img = copy.deepcopy(img_cv2)
st.write("Contrast and Brightness Settings")
orig = img.copy()
contrast = st.slider('Contrast', 0.0, 10.0, 1.0)
brightness = st.slider('brightness', 0.0, 500.0, 0.0)
img = np.clip(img * contrast + brightness, 0, 255)
img = imutils.resize(img, height=650)
st.image(img)
</code></pre>
<p>when i try to show the image using st.image(img) it is giving me the error. as it shows data is outside the range of [0,1]. so i try to divide the img with 255 <code>img = np.divide(img, 255)</code> . Again it shows the same error.</p>
<p>if i try like this:</p>
<pre><code>def ContrastNBrightness1(img_array):
img_cv2 = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
img = copy.deepcopy(img_cv2)
st.write("Contrast and Brightness Settings")
orig = img.copy()
contrast = st.slider('Contrast', 0.0, 10.0, 1.0)
brightness = st.slider('brightness', 0.0, 500.0, 0.0)
img = np.clip(img * contrast + brightness, 0, 255)
img = imutils.resize(img, height=650)
cv2.imwrite('tempImage.jpg', img)
st.image('tempImage.jpg')
</code></pre>
<p>Above code runs perfectly and able to show the image. But in this case image is saved in the local storage and i want directly to show image using <code>st.image(img)</code>. How to handle this?</p>
|
<p>Use <code>sk.image(...,clamp=True)</code>. For more information refer to : <a href="https://discuss.streamlit.io/t/runtimeerror-data-is-outside-0-0-1-0-and-clamp-is-not-set/12910" rel="nofollow noreferrer">https://discuss.streamlit.io/t/runtimeerror-data-is-outside-0-0-1-0-and-clamp-is-not-set/12910</a></p>
|
python|opencv|streamlit
| 0 |
1,903,727 | 70,633,593 |
How to display the grid when multiple matplotlib charts are created at the same time?
|
<p>I would like to use the grid in multiple matplotlib figures, but if I just use <code>plt.grid()</code> the grid would only show up in one of the charts.</p>
<p>How can I change the code below, so that the grid shows up in both figures, please?</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(19680801)
N_points = 100000
dist1 = rng.standard_normal(N_points)
fig = plt.figure()
axis = fig.add_subplot(1,1,1)
fig1 = plt.figure()
ax = fig1.add_subplot(1,1,1)
axis.hist(dist1)
ax.hist(dist1)
plt.grid()
plt.show()
</code></pre>
|
<pre><code>import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(19680801)
N_points = 100000
dist1 = rng.standard_normal(N_points)
fig = plt.figure()
axis = fig.add_subplot(1,1,1)
axis.grid()
fig1 = plt.figure()
ax = fig1.add_subplot(1,1,1)
ax.grid()
axis.hist(dist1)
ax.hist(dist1)
# plt.grid()
plt.show()
</code></pre>
|
python|matplotlib
| 2 |
1,903,728 | 55,940,823 |
Is there any possibility to move label position from top to bottom?
|
<p>I'm using tensorflow object detection api to find some objects inside some images. This objects are very close one to other.</p>
<p>Is there any possibility to move the label of the class and score from top of the box to the bottom? I can't see clearly the scores and I always need to check them in the log file.</p>
<p>This are the <strong>detection boxes</strong> that I'm talking about and as you can see the <strong>label is on top</strong>.</p>
<p><a href="https://i.stack.imgur.com/s70dX.jpg" rel="nofollow noreferrer">Link to image</a></p>
|
<p>Yes, you can move the label to the bottom by just modifying the plot function.</p>
<p>Specifically the function you need to modify is this <a href="https://github.com/tensorflow/models/blob/62ed862ef2c8f59ac1d6333ddfddf3a16e549b3b/research/object_detection/utils/visualization_utils.py#L132" rel="nofollow noreferrer">one</a>. </p>
<pre><code>if top > total_display_str_height:
text_bottom = top
else:
text_bottom = bottom + total_display_str_height
</code></pre>
<p>Modify the above line to</p>
<pre><code>text_bottom = bottom + total_display_str_height
</code></pre>
<p>And you will see the labels printed at the bottom of the bounding box.</p>
<p>I've tried it myself and here is the result.</p>
<p><a href="https://i.stack.imgur.com/HvrLa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HvrLa.png" alt="enter image description here"></a></p>
|
tensorflow|label|object-detection-api
| 1 |
1,903,729 | 64,072,764 |
Merging Dictionary to Dataframe where both dictionary values are scalar
|
<p>I have a dictionary that looks like this</p>
<pre><code>my_dict = {0:45,1:89.9,2:7.65}
</code></pre>
<p>I wanna merge it to my DataFrame, where my Dataframe looks like this:</p>
<pre><code>my_df = pd.DataFrame({'score':[11.7,99.8,83.5],'color':['pink','red','green']})
</code></pre>
<p><a href="https://i.stack.imgur.com/n82pT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n82pT.png" alt="enter image description here" /></a></p>
<p>I would like my final merged dataframe to look like this:</p>
<pre><code> my_df_final = pd.DataFrame({'score':[11.7,99.8,83.5],'color':['pink','red','green'], dict_values:[45,89.9,7.56]})
</code></pre>
<p><a href="https://i.stack.imgur.com/xRqR0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xRqR0.png" alt="enter image description here" /></a></p>
<p><code>pd.DataFrame(caption_count_dict</code>)
But when I try to create a dataframe from my dictionary, I get the message that "If using all scalar values, you must pass an index". I am not able to figure out how to supply the index or how to merge this dictionary with my dataframe as a new column.</p>
|
<p>Use <code>pandas.Series</code> to convert before concat:</p>
<pre><code>my_df["dict_values"] = pd.Series(my_dict)
print(my_df)
</code></pre>
<p>Output:</p>
<pre><code> score color dict_values
0 11.7 pink 45.00
1 99.8 red 89.90
2 83.5 green 7.65
</code></pre>
|
python|dataframe|dictionary
| 3 |
1,903,730 | 53,339,641 |
django rest framework check if serializer received None object
|
<p>Our endpoint can return from multiple models, all have something in common so they are mapped to an uniform response, e.g.:</p>
<pre><code>{
"reference": "November15-Inbound-1",
"note": null,
"inbound_date": "2018-11-14",
"inbound_lines": [
{
"article_code": "VBP_A",
"quantity": 1
}
]
</code></pre>
<p>}</p>
<p>Now it is possible that when doing a retrieve or update call that the object does not exist:</p>
<pre><code>try:
return AppInbound.objects.filter(customer__code=self.customer.code).get(**kwargs)
except AppInbound.DoesNotExist:
return None
</code></pre>
<p>This 'None' is then returned to our serializer, which yields the following result:</p>
<pre><code>{
"reference": "",
"note": "",
"inbound_date": null,
"inbound_lines": []
}
</code></pre>
<p>Is there a way I can check whether or not the serializer received a None object as input? Without having to do specific code per endpoint like:</p>
<pre><code>if serialized_data['reference'] == "":
raise Http404
</code></pre>
|
<p>You could override <code>get_initial()</code> in your serializer and check whether the instance is <code>None</code>. This method is responsible for returning the initial state of each field.</p>
<pre><code>def get_initial(self):
if self.instance is None:
raise Http404
return super().get_initial()
</code></pre>
|
python|django|django-rest-framework
| 0 |
1,903,731 | 72,115,808 |
CMD file opens when I launch Spyder
|
<p>I have recently installed Anaconda version 4.12.0 and created a virtual environment which I launched in Spyder 5 using Python 3.6. The problem is that every time I launch Spyder, a CMD file opens simultaneously. When I try to close the CMD, Spyder also closes. What can I do to stop the CMD file appearing? I have no experience with Anaconda, so any help would be higly appreciated!</p>
|
<p>Reset the configuration: File > Preferences > Configure navegator / Configure conda > Reset to defaults</p>
|
python|anaconda|spyder
| 0 |
1,903,732 | 68,541,813 |
Pandas - appending data to dataframe lead to more rows than the file source has
|
<p>I'm dealing with a situation here and I cannot tell what's the issue.</p>
<p>I have my source file which has two lines and looks as below:</p>
<pre><code>Jul 26, 2021 12:12:12 AM CEST INFO, create test, execution-c9d549fc-7c1e-4f27-887c-bd3ab0dc21ec-2021.07.26, Create fake XML document, Preparing to collect data
Jul 26, 2021 1:12:12 PM CEST INFO, create test, execution-c9d549fc-7c1e-4f27-887c-bd3ab0dc21ec-2021.07.26, Create fake XML document, Preparing to collect data
</code></pre>
<p>I use the below code to load the file, read and append the source data to the dataframe:</p>
<pre><code>data = []
months = (
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Sept',
'Oct',
'Nov',
'Dec'
)
for file in os.listdir():
if file.endswith(dt.now().strftime('%Y_%m_%d.log')):
LogFile = r'path\test.2021_07_27.log'
with open(LogFile, 'r') as f:
for line in map(str.strip, f):
if not line or not line.startswith(months):
continue
line = line.split(maxsplit=6)
logdate = " ".join(line[:6])
logstatus = line[-1].split(maxsplit=1)[0]
loginfo = line[-1].split(maxsplit=1)[-1]
data.append({"LogDate": logdate, "LogStatus": logstatus, "LogInfo": loginfo})
tzmapping = {
'CEST': dateutil.tz.gettz('UTC'),
}
df = pd.DataFrame(data)
print(df)
df['LogDate'] = df['LogDate'].apply(dateutil.parser.parse, ignoretz=True)
</code></pre>
<p>So far, so good (I guess). However, when I print the dataframe the result is displayed twice: once for the first row, including the column names appended and the second time, with both rows and also the column names:</p>
<pre><code> LogDate LogStatus LogInfo
0 Jul 26, 2021 12:12:12 AM CEST INFO, create test, execution-c9d549fc-7c1e-4f...
LogDate LogStatus LogInfo
0 Jul 26, 2021 12:12:12 AM CEST INFO, create test, execution-c9d549fc-7c1e-4f...
1 Jul 26, 2021 1:12:12 PM CEST INFO, create test, execution-c9d549fc-7c1e-4f...
</code></pre>
<p>What am I missing here? Could you give me a hint what might be wrong with my code? Thanks</p>
|
<p>With <code>print(df)</code> you print a new <code>DataFrame</code> tha is created based on <code>data</code>.</p>
<p>However, <code>data</code> resides outside of your loop and can be considered as a global variable here. You append each line to <code>data</code> in each iteration.</p>
<p>Basically, you print all the processed line in each step, not just the current line.</p>
|
python|pandas
| 1 |
1,903,733 | 68,863,050 |
Pyinstaller loading splash screen
|
<p>Pyinstaller recently added a splash screen option (yay!) but the splash stays open the entire time the exe is running. I need it because my file opens very slowly and I want to warn the user not to close the window. Is there a way I can get the splash screen to close when the gui opens?</p>
|
<p>from pyinstaller docs:</p>
<pre><code>import pyi_splash
# Update the text on the splash screen
pyi_splash.update_text("PyInstaller is a great software!")
pyi_splash.update_text("Second time's a charm!")
# Close the splash screen. It does not matter when the call
# to this function is made, the splash screen remains open until
# this function is called or the Python program is terminated.
pyi_splash.close()
</code></pre>
|
python|pyinstaller|splash-screen
| 3 |
1,903,734 | 62,600,404 |
Execute Python Program line-by-line automatically
|
<p>I'm doing a python script with selenium. To do tests I use command promp, this way i know if my line of command is working without needing to execute the program over and over to correct line by line. The thing is, i need a way to automatically start this lines so i don't need to keep retype it everytime i want to do some tests.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
options = webdriver.ChromeOptions()
options.add_argument('lang=pt-br')
driver = webdriver.Chrome(executable_path=r'./chromedriver.exe', options=options
</code></pre>
|
<p>From the command line, running <code>python -m pdb <yourscript.py></code> should open the <a href="https://docs.python.org/3/library/pdb.html" rel="nofollow noreferrer">Python Debugger</a> and allow you to step through. Each line is run by entering <code>n</code> and returning.</p>
|
python|selenium|line-by-line
| 1 |
1,903,735 | 70,190,246 |
How to make a sprite carry on moving after they key has been released
|
<p>I have a sprite that moves around when a one of the arrow keys is pressed however I would like the sprite to carry on moving in the direction of the key for a small amount of time after the key has been released, as if it was sliding around on ice.</p>
<p>'''</p>
<pre><code> mv_speed = 5
def move(self):
global mv_speed
keys = pg.key.get_pressed()
self.pos_x += (mv_speed * (keys[pg.K_RIGHT] - keys[pg.K_LEFT]))
self.pos_y += (mv_speed * (keys[pg.K_DOWN] - keys[pg.K_UP]))
if keys == False:
self.pos_x += 50 * (keys[pg.K_RIGHT] - keys[pg.K_LEFT])
self.pos_y += 50 * (keys[pg.K_DOWN] - keys[pg.K_UP])
self.rect.center = [self.pos_x,self.pos_y]
</code></pre>
<p>'''</p>
|
<p>Add an attribute that indicates the direction and speed of movement. Increase the speed a small amount for each frame that the button is pressed. Scale the speed in every frame by a friction factor:</p>
<pre class="lang-py prettyprint-override"><code>class Player:
def __init__(self):
# [...]
self.speed_x = 0
self.speed_y = 0
self.acceleration = 0.1
self.friction = 0.98
self.max_speed = 5
def move(self):
self.speed_x += self.acceleration * (keys[pg.K_RIGHT] - keys[pg.K_LEFT])
self.speed_y += self.acceleration * (keys[pg.K_DOWN] - keys[pg.K_UP])
self.speed_x = max(-self.max_speed, min(self.max_speed, self.speed_x))
self.speed_y = max(-self.max_speed, min(self.max_speed, self.speed_y))
self.pos_x += self.speed_x
self.pos_y += self.speed_y
self.rect.center = round(self.pos_x), round(self.pos_y)
self.speed_x *= self.friction
self.speed_y *= self.friction
</code></pre>
|
python|python-3.x|pygame
| 0 |
1,903,736 | 63,550,167 |
Dataframe contains nullss, but after filtering no nulls are shown. Python - Preparing data for ML
|
<p>I am pretty new to the field of machine learning and I am currently trying to predict returns using a random forest.</p>
<p>I have already built my model, but everytime I want to predict the returns in my test set, I get the following error:
ValueError: Input contains NaN, infinity or a value too large for dtype('float32')</p>
<p>So I tried to look for NaN's in my test set.
<a href="https://i.stack.imgur.com/uUVzy.png" rel="nofollow noreferrer">Example of test set</a></p>
<p>When I count all nulls, python tells me i have 103. But after filtering there is no null at all?</p>
<p>What am I missing here?</p>
|
<p>What do you mean by <code>outcome_test[outcome_test['bh1m'] == 0]?</code><br>
If you want to check if an element is empty, for your case, do the following:</p>
<pre><code>outcome_test[outcome_test['bh1m'].isnull()]
</code></pre>
<p>It will return datapoints which their <code>bhm1</code> feature is <code>NAN</code>. For your case something like this:</p>
<pre><code> bh1m
190 NaN
4354 NaN
... NaN
</code></pre>
<p>Also, if you want change <code>NaN</code> values to <code>0</code> do this: <code>outcome_test['bh1m'].fillna(0, inplace=True)</code></p>
|
python|pandas|dataframe
| 0 |
1,903,737 | 63,642,689 |
wxpython - wx.EVT_COMBOBOX event and GetSelection method: manual vs user triggering
|
<p>It is known that in wxpython setting in the code the value of a combobox doesn't trigger the EVT_COMBOBOX event as instead it does when the user select an item with the mouse. So, if needed, you have to trigger manually the event.</p>
<p>In my program, in the handler function, I need to use the value returned by the method event.GetSelection(), where event is the event object passed in to the handler function.</p>
<p>Now, the problem is that if I set in the code the value of the combo box and then trigger manually the EVT_COMBOBOX event, the method event.GetSelection() doesn't return the same value as if the event was rised by the user selecting the same item with the mouse.</p>
<p>The problem is shown by the following code.</p>
<p>As you can see executing the code, when the event is triggered by the code, the event.GetSelection() method returns always the value 0 (i.e. the first item in the combo box list, so that the item 'a' is displayed in the text box) instead of the value 1 setted in the code which would display the item 'b'.</p>
<p>Why this happen? Thank you for any answer.</p>
<pre><code>import wx
class ManualEventFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Manual Event Rising',size=(550, 200))
self.panel = wx.Panel(self)
self.st=wx.StaticText(self.panel, label='Select an item', pos=(10,10))
self.cb=wx.ComboBox(self.panel,pos=(110,10),choices=['a','b','c'])
self.st2 = wx.StaticText(self.panel, label='You choosed item', pos=(10, 75))
self.tc=wx.TextCtrl(self.panel,pos=(110,75))
self.button = wx.Button(self.panel,label="Select item 'b' and rise\nmanually the EVT_COMBOBOX event", pos=(300, 40))
self.button.Bind(wx.EVT_BUTTON,self.onButton)
self.cb.Bind(wx.EVT_COMBOBOX, self.onSelect)
def onSelect(self,event):
self.tc.SetValue(self.cb.GetString(event.GetSelection()))
def onButton(self, event):
self.cb.SetSelection(1)
myevent = wx.CommandEvent(wx.EVT_COMBOBOX._getEvtType(), self.cb.GetId())
myevent.SetEventObject(self.cb)
self.cb.GetEventHandler().ProcessEvent(myevent)
if __name__ == '__main__':
app = wx.App()
frame = ManualEventFrame(parent=None, id=-1)
frame.Show()
app.MainLoop()
</code></pre>
|
<p>I'm not sure why <code>event.GetSelection</code> in this scenario continues to return <code>0</code> but the way around your issue, is to get the value from the "horse's mouth" so to speak.<br />
Use:<br />
<code>self.tc.SetValue(self.cb.GetStringSelection())</code><br />
or:<br />
<code>self.tc.SetValue(self.cb.GetValue())</code></p>
|
combobox|event-handling|wxpython|getselection
| 0 |
1,903,738 | 60,768,347 |
Why I merge two dataframes and get an NaN column
|
<p>What I'm doing is like:</p>
<pre><code>df1['column1'] = df1.merge(df2,
how = 'left',
left_on = 'column2',
right_on = 'column3')['column4']
</code></pre>
<p>I don't want to save the merge because there are too many columns in df2 and I don't want to manually drop them. But the problem is that this operation results in a lot of NaN in <code>df1['column1']</code>. I haven't figured out the reason, but I find that after I do the following change there will not be any NaN.</p>
<pre><code>df1['column1'] = df1.merge(df2,
how = 'left',
left_on = 'column2',
right_on = 'column3')['column4'].tolist()
</code></pre>
<p>Does anyone have any idea about this?</p>
|
<p>You are using left join where entire left dataframe will be there and only the ones common with right dataframe will be added. The <code>NAN</code> is present because the key is matching in both the tables but other columns in that row contains blank values.</p>
<p>If you only want the common/intersection rows in both the dataframes, you should use <code>how = 'inner'</code> inside your <code>df1.merge()</code> function.</p>
|
python|pandas
| 1 |
1,903,739 | 60,944,216 |
Why is my python code to convert an number to binary using stack not working?
|
<p>The following is my code to convert a number to binary using stacks written in Python3.
Whenever I run it, <code>None</code> is produced as the output. What might be causing this? Thanks in advance.</p>
<pre><code>class Stack():
def __init__(self):
self.stack = []
self.top = -1
def push(self, val):
self.stack.append(val)
self.top += 1
def pop(self):
if self.top == -1:
print('Underflow')
else:
del self.stack[self.top]
self.top -= 1
def empty(self):
return self.stack == []
def peek(self):
return self.top
def display(self):
return self.stack
def binary(n):
b = Stack()
while n > 0:
r = n%2
b.push(r)
n = n//2
bn = ''
while not b.empty():
bn += str(b.pop())
return bn
print(binary(242))
</code></pre>
|
<p>This line just pops the elements from the stack and does not return anything.It returns None.</p>
<pre><code>bn += str(b.pop())
</code></pre>
<p>You must store the top element in a variable and then pop the stack after it.</p>
<p>Try this below in your binary function :</p>
<pre><code>def binary(n):
b = Stack()
while n > 0:
r = n % 2
b.push(r)
n = n//2
print(b.stack)
bn = ''
while not b.empty():
bn += str(b.stack[-1])
b.pop()
return bn
</code></pre>
|
python-3.x|binary|stack|decimal
| 0 |
1,903,740 | 59,339,103 |
Creating overlapping, square patches for rectangular images
|
<p>Given be a rectangular image <code>img</code> and patch <code>s</code>. Now I would like to cover the whole image with square patches of side length <code>s</code>, so that every pixel in <code>img</code> is in at least one patch using the minimal number of patches. Furthermore I want neighboured patches to have as little overlap as possible.</p>
<p>Thus far: I have included my code below and worked out an example. However it does not work yet perfectly. Hopefully, someone finds the error.</p>
<p>Example: Given is <code>img</code> of shape: <code>(4616, 3016)</code> and <code>s = 224</code>
That means I will 21 patches on the longer side, 14 patches on the smaller the width, 21*14 = 294 patches in total. </p>
<p>Now I try to figure out patches how to distribute the overlap between the patches.
My patches can cover an image of size: <code>(4704, 3136)</code>, thus my patches in the height have to cover 88 overlapping pixels <code>missing_h = ht * s - h</code>, width is analogous. </p>
<p>Now I try to figure out, how to distribute 88 pixels on 21 patches. 88 = 4* 21 + 4
Thus I will have <code>hso = 17</code> patches with overlap <code>shso = 4</code> and <code>hbo = 4</code> patches with overlap 5, width is analogous. </p>
<p>Now I simply loop over the whole image and keep track on my current position <code>(cur_h, cur_w)</code>. After each loop I adjust, <code>cur_h, cur_w</code>. I have <code>s</code>, my current patch number <code>i, j</code>, that indicates if the patch has a small or big overlap.</p>
<pre><code>import numpy as np
def part2(img, s):
h = len(img)
w = len(img[0])
ht = int(np.ceil(h / s))
wt = int(np.ceil(w / s))
missing_h = ht * s - h
missing_w = wt * s - w
hbo = missing_h % ht
wbo = missing_w % wt
hso = ht - hbo
wso = wt - wbo
shso = int(missing_h / ht)
swso = int(missing_w / wt)
patches = list()
cur_h = 0
for i in range(ht):
cur_w = 0
for j in range(wt):
patches.append(img[cur_h:cur_h + s, cur_w: cur_w + s])
cur_w = cur_w + s
if j < wbo:
cur_w = cur_w - swso - 1
else:
cur_w = cur_w - swso
cur_h = cur_h + s
if i < hbo:
cur_h = cur_h - shso - 1
else:
cur_h = cur_h - shso
if cur_h != h or cur_w != w:
print("expected (height, width)" + str((h, w)) + ", but got: " + str((cur_h, cur_w)))
if wt*ht != len(patches):
print("Expected number patches: " + str(wt*ht) + "but got: " + str(len(patches)) )
for patch in patches:
if patch.shape[0] != patch.shape[1] or patch.shape[0] != s:
print("expected shape " + str((s, s)) + ", but got: " + str(patch.shape))
return patches
def test1():
img = np.arange(0, 34 * 7).reshape((34, 7))
p = part2(img, 3)
print("Test1 successful")
def test2():
img = np.arange(0, 4616 * 3016).reshape((4616, 3016))
p = part2(img, 224)
print("Test2 successful")
test1()
test2()
</code></pre>
|
<p>Above problem can be fixed, making the following edits:</p>
<pre><code>hbo = missing_h % (ht-1)
wbo = missing_w % (wt-1)
shso = int(missing_h / (ht-1))
swso = int(missing_w / (wt-1))
</code></pre>
|
python|image-processing|sampling|subsampling
| 1 |
1,903,741 | 59,872,286 |
TypeError: unsupported operand typ
|
<p>i m just new to python and is trying to learn this language. i tried running a code in python but got an error can anyone help me
here is my code:</p>
<pre><code>def cel_to_fahr(c):
f = c * 9/5 + 32
return f
c = input("enter the temperature in celcius:")
print(cel_to_fahr(c))
</code></pre>
<p>the error i m getting is:</p>
<pre><code>File ".\prg.py", line 6, in <module>
print(cel_to_fahr(c))
File ".\prg.py", line 2, in cel_to_fahr
f = c * 9/5 + 32
TypeError: unsupported operand type(s) for /: 'str' and 'int
</code></pre>
<p>'</p>
|
<p>The function <code>input()</code> returns the string value. So convert it to either <code>int</code> or <code>float</code> </p>
<pre><code>c = int(input("enter the temperature in celcius:"))
</code></pre>
<p>OR</p>
<pre><code>c = float(input("enter the temperature in celcius:"))
</code></pre>
|
python|python-3.x
| 0 |
1,903,742 | 59,716,956 |
Can a python asycio coroutine have a code path with no await?
|
<p>Are there any problems or side effects with a coroutine having a code path that does not contain an await statement?</p>
<p>Consider this example where a callback is provided to a coroutine as an argument, but that callback may be a regular function or a coroutine:</p>
<pre><code>import asyncio
import inspect
async def foo(mycallback):
if inspect.iscoroutinefunction(mycallback):
await mycallback()
else:
mycallback()
...
</code></pre>
<p>Trying simple examples in the python console seem to suggest that there are no problems, but was wondering if there are more subtle issues that may arise.</p>
|
<p>If you don't await, then you block the other bits of code that should be running, because asynch is about sharing ressources. So if the regular code is running fast, it's not much of a problem, but if it can be slow, it's blocks everything.</p>
<p>In regular code, an alternative to asynch is thread based programming. Here Python interrupts your code when it feels like it to run other threads, so there you have less of a blocking problem.</p>
|
python|python-3.x|python-asyncio
| 2 |
1,903,743 | 72,395,299 |
Transforming multiple columns into a list of nested dictionaries in pandas
|
<p>I have a pandas dataframe that looks in the following way</p>
<pre><code>category sub_cat vitals value
HR EKG HR_EKG 136
SPO2 SPO2 SpO2_1 86
HR PPG HR_PPG_1 135
SPO2 PI PI_1 4.25
HR PPG HR_PULSED 135
NIBP SBP NIBPS 73
NIBP DBP NIBPD 25
NIBP MBP NIBPM 53
</code></pre>
<p>and I'd like to group by category and sub_cat columns and convert it into a list of nested dictionaries something like this</p>
<pre><code>[{
"HR":
{
"EKG":
{
"HR_EKG": 136
},
"PPG":
{
"HR_PPG_1": 135,
"HR_PULSED": 135
}
}
},
{
"NIBP":
{
"SBP":
{
"NIBPS": 73
},
"DBP":
{
"NIBPD": 25
},
"MBP":
{
"NIBPM": 53
}
}
},
{
"SPO2":
{
"SPO2":
{
"SpO2_1": 86
},
"PI":
{
"PI_1": 4.25
}
}
}]
</code></pre>
<p>I was able to either group by (category, vitals, and values), or (subcategory, vitals, and values) but was not able to group by all 4 columns. This is what I tried and works for 3 columns</p>
<pre><code>df = df.groupby(['sub_cat']).apply(lambda x: dict(zip(x['vitals'], x['value'])))
</code></pre>
|
<p>A series of nested <code>groupby</code> + <code>apply</code> + <code>to_dict</code> calls will do it:</p>
<pre><code>dct = df.groupby('category').apply(
lambda category: category.groupby('sub_cat').apply(
lambda sub_cat: sub_cat.set_index('vitals')['value'].to_dict()
).to_dict()
).to_dict()
</code></pre>
<p>Output:</p>
<pre><code>>>> import json
>>> print(json.dumps(dct, indent=4))
{
"HR": {
"EKG": {
"HR_EKG": 136.0
},
"PPG": {
"HR_PPG_1": 135.0,
"HR_PULSED": 135.0
}
},
"NIBP": {
"DBP": {
"NIBPD": 25.0
},
"MBP": {
"NIBPM": 53.0
},
"SBP": {
"NIBPS": 73.0
}
},
"SPO2": {
"PI": {
"PI_1": 4.25
},
"SPO2": {
"SpO2_1": 86.0
}
}
}
</code></pre>
|
python|json|pandas|dataframe
| 2 |
1,903,744 | 50,501,316 |
Python Turtle: the cursor is not moving
|
<p>I have a problem with my uni project's code, especially in the turtle module section. This program displays student marks and we are supposed to show a bar chart using the turtle module. The problem I am encountering is that even though the turtle workspace shows up, the cursor is not moving to draw the bar chart.</p>
<p>This is the code:</p>
<pre><code>def menu():
allStudentsMarks = {}
while True:
userinput = input("Enter 1 to store student details \n"+
"Enter 2 to display student report \n"+
"Enter 3 to exit \n")
if userinput == "1":
enterMarks(allStudentsMarks)
elif userinput == "2":
displayReports(allStudentsMarks)
elif userinput == "3":
print("You have left the program. Thank you.")
break
def enterMarks(allStudentsMarks):
studentName = input("Please enter the student's name: ")
while True:
DFMarks = input("Please enter the marks from 0-20: ")
DFMarks = float(DFMarks)
if DFMarks >= 0 and DFMarks <= 20:
break
while True:
ProjectMarks = input("Please enter the marks from 0-30: ")
ProjectMarks = float(ProjectMarks)
if ProjectMarks >= 0 and ProjectMarks <= 30:
break
while True:
FinalMarks = input("Please enter the marks from 0-50: ")
FinalMarks = float(FinalMarks)
if FinalMarks >= 0 and FinalMarks <= 50:
break
marksList = [DFMarks, ProjectMarks, FinalMarks]
allStudentsMarks[studentName] = marksList
studentDetails = sum(marksList)
def getBelowAvgDFMarks(studentDetails):
marks = list(studentDetails.values())
dfTot = 0
dfLen = 0
for marksList in marks:
dfTot += marksList[0]
dfLen += 1
dfAvg = dfTot / dfLen
print("Displaying the student(s) whose DF marks are below the average of", dfAvg)
belowAvgDF = {}
for student in studentDetails:
if studentDetails[student][0] < dfAvg:
belowAvgDF[student] = studentDetails[student][0]
print(belowAvgDF)
return
def getBelowAvgProjectMarks(studentDetails):
marks = list(studentDetails.values())
projectTot = 0
projectLen = 0
for marksList in marks:
projectTot = projectTot + marksList[1]
projectLen = projectLen + 1
projectAvg = projectTot / projectLen
print("Displaying the student(s) whose project marks are below the average of", projectAvg)
belowAvgProject = {}
for student in studentDetails:
if studentDetails[student][1] < projectAvg:
belowAvgProject[student] = studentDetails[student][1]
print(belowAvgProject)
return
def getBelowAvgFinalExamMarks(studentDetails):
marks = list(studentDetails.values())
finalTot = 0
finalLen = 0
for marksList in marks:
finalTot = finalTot + marksList[2]
finalLen = finalLen + 1
finalAvg = finalTot / finalLen
print("Displaying the student(s) whose final marks are below the average of", finalAvg)
belowAvgFinal = {}
for student in studentDetails:
if studentDetails[student][2] < finalAvg:
belowAvgFinal[student] = studentDetails[student][2]
print(belowAvgFinal)
return
def getBelowAvgOverallMarks(studentDetails):
marks = list(studentDetails.values())
overall = 0
overallLen = len(marks)
for marksList in marks:
for num in marksList:
overall += num
overallAvg = overall / overallLen
print(overallAvg)
print("Displaying the student(s) whose overall marks are below the average of", overallAvg)
belowAvgOverall = {}
for student in studentDetails:
if sum(studentDetails[student]) < overallAvg:
belowAvgOverall[student] = sum(studentDetails[student])
print(belowAvgOverall)
return
def getTotalMarks(studentDetails):
total = []
marks = list(studentDetails.values())
total = 0
for i in marks:
for num in i:
total = total + num
print(total)
total = 0
import turtle
wn = turtle.Screen()
turtle = turtle.Turtle()
turtle.color("blue", "lightblue")
for marks in range(total):
turtle.begin_fill()
turtle.forward(10)
turtle.left(90)
turtle.forward(marks)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(marks)
turtle.left(90)
turtle.end_fill()
turtle.forward(20)
wn.exitonclick()
def displayReports(allStudentsDetails):
userinput = input("Enter 1 to get the average DF report marks \n"+
"Enter 2 to get the average project report marks \n"+
"Enter 3 to get the average final exam marks \n"+
"Enter 4 to get the overall marks \n"+
"Enter 5 to get the selected student marks \n"+
"Enter 6 to get the bar chart of the total marks \n")
if userinput == "1":
getBelowAvgDFMarks(allStudentsDetails)
elif userinput == "2":
getBelowAvgProjectMarks(allStudentsDetails)
elif userinput == "3":
getBelowAvgFinalExamMarks(allStudentsDetails)
elif userinput == "4":
getBelowAvgOverallMarks(allStudentsDetails)
elif userinput == "5":
displaySelectedStudentsMarks(allStudentsDetails)
elif userinput == "6":
getTotalMarks(allStudentsDetails)
return
def displaySelectedStudentsMarks(selectedStudentsDetails):
for studentNameKey in selectedStudentsDetails:
displayAStudentsDetail(studentNameKey, selectedStudentsDetails[studentNameKey])
def displayAStudentsDetail(studentName, studentMarkList):
print("Student name: ", studentName)
print("DF marks: ", studentMarkList[0], "\tProject marks: ", studentMarkList[1], "\tFinal exam: ", studentMarkList[2], "\tTotal marks: ", sum(studentMarkList))
menu()
</code></pre>
<p>When you input the value '6' ("get the bar chart of the total marks"), in the second level "display student report" menu, it should be able to show the bar chart with the value of total exam for each student.</p>
<p>Thank you.</p>
|
<p>I believe your <code>getTotalMarks()</code> is a total mess. Not so much turtle-wise but Python-wise. One clue is that you have two different variables with the same name:</p>
<pre><code>total = []
marks = list(studentDetails.values())
total = 0
</code></pre>
<p>I'm going to suggest three changes. First, import turtle this way:</p>
<pre><code>from turtle import Turtle, Screen
</code></pre>
<p>Second, start up your <code>menu()</code> routine this way:</p>
<pre><code>wn = Screen()
menu()
wn.exitonclick()
</code></pre>
<p>I.e. don't put <code>exitonclick()</code> inside a function, make it the last thing your code does. Finally, replace <code>getTotalMarks()</code> with this rewrite:</p>
<pre><code>def getTotalMarks(studentDetails):
totals = [sum(scores) for scores in studentDetails.values()]
turtle = Turtle()
turtle.color("blue", "lightblue")
for total in totals:
turtle.begin_fill()
turtle.forward(10)
turtle.left(90)
turtle.forward(total)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(total)
turtle.left(90)
turtle.end_fill()
turtle.forward(20)
</code></pre>
<p>It's nothing fancy, but it should get you moving forward.</p>
|
python|turtle-graphics
| 0 |
1,903,745 | 57,445,244 |
Twint Module and creating a dataframe from tweets
|
<p>I have an issue converting twint results into a dataframe. I am unable to fetch the tweet results and store it into a dataframe. Everytime I set c.Pandas=True I get an error. Any ideas how to resolve this.</p>
<p>I know i can always store it to json/csv then port it back in but want to avoid doing that.</p>
<p>Code I am using:</p>
<pre><code>import twint
from datetime import datetime, timedelta
import nest_asyncio
import pandas as pd
nest_asyncio.apply()
c = twint.Config()
c.Limit=10
c.Username='ProtonMail'
c.Store_object=True
c.Pandas=True
twint.run.Search(c)
</code></pre>
<p>error Log below:</p>
<pre><code>Traceback (most recent call last):
File "<ipython-input-39-e0414b83fe16>", line 17, in <module>
twint.run.Search(c)
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\site-packages\twint\run.py", line 292, in Search
run(config, callback)
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\site-packages\twint\run.py", line 213, in run
get_event_loop().run_until_complete(Twint(config).main(callback))
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\site-packages\nest_asyncio.py", line 61, in run_until_complete
return f.result()
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\asyncio\futures.py", line 178, in result
raise self._exception
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\asyncio\tasks.py", line 251, in __step
result = coro.throw(exc)
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\site-packages\twint\run.py", line 154, in main
await task
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\asyncio\futures.py", line 260, in __await__
yield self # This tells Task to wait for completion.
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\asyncio\tasks.py", line 318, in __wakeup
future.result()
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\asyncio\futures.py", line 178, in result
raise self._exception
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\asyncio\tasks.py", line 249, in __step
result = coro.send(None)
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\site-packages\twint\run.py", line 198, in run
await self.tweets()
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\site-packages\twint\run.py", line 145, in tweets
await output.Tweets(tweet, self.config, self.conn)
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\site-packages\twint\output.py", line 142, in Tweets
await checkData(tweets, config, conn)
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\site-packages\twint\output.py", line 116, in checkData
panda.update(tweet, config)
File "c:\users\xx\appdata\local\programs\python\python37-32\lib\site-packages\twint\storage\panda.py", line 67, in update
day = weekdays[strftime("%A", localtime(Tweet.datetime))]
OSError: [Errno 22] Invalid argument`enter code here`
</code></pre>
|
<p>To use <code>twint.run.Search(c)</code>, fist you need to define <code>c.Search= ""</code>with the text you want to search. But if you are interested to scrape the tweet from the profile of <code>ProtonMail</code>, you should run <code>twint.run.Profile(c)</code> instead. Depending on the type of data you need, there are differnt options to run (Read more at this <a href="https://github.com/twintproject/twint/wiki/Tweet-attributes" rel="nofollow noreferrer">reference on github</a>.).</p>
|
python-3.x|twitter
| 0 |
1,903,746 | 57,453,803 |
How to get the date of a Twitter post (tweet) using BeautifulSoup?
|
<p>I am trying to extract posting dates from Twitter. I've already succeeded in extracting the name and text of the post, but the date is a hard rock for me. </p>
<p>As input I have a list of links like these: </p>
<ul>
<li><a href="https://twitter.com/BarackObama/status/1158764847800213507" rel="nofollow noreferrer">https://twitter.com/BarackObama/status/1158764847800213507</a>; </li>
<li><a href="https://twitter.com/Pravitelstvo_RF/status/1160613745208549377" rel="nofollow noreferrer">https://twitter.com/Pravitelstvo_RF/status/1160613745208549377</a></li>
<li><a href="https://twitter.com/BarackObama/status/1157016227681918981" rel="nofollow noreferrer">https://twitter.com/BarackObama/status/1157016227681918981</a></li>
</ul>
<p>I am using searching by class, but I think this is a problem. Sometimes it works with some links, sometimes not. I've already tried these solutions:</p>
<pre><code>soup.find("span",class_="_timestamp js-short-timestamp js-relative-timestamp")
soup.find('a', {'class': 'tweet-timestamp'})
soup.select("a.tweet-timestamp")
</code></pre>
<p>But none of these works every time.</p>
<p>My current code is: </p>
<pre><code>data = requests.get(url)
soup = BeautifulSoup(data.text, 'html.parser')
gdata = soup.find_all("script")
for item in gdata:
items2 = item.find('a', {'class': 'tweet-timestamp js-permalink js-nav js-tooltip'}, href=True)
if items2:
items21 = items2.get('href')
items22 = items2.get('title')
print(items21)
print(items22)
</code></pre>
<p>I need to have output with the posting date.</p>
|
<p>I believe twitter API would be best choice but regaring your code....</p>
<p>It's available via <code>title</code> attribute of element with class <code>tweet-timestamp</code>. This element is not within a <code>script</code> tag which seems to be where you are searching:</p>
<pre><code>gdata = soup.find_all("script")
for item in gdata:
items2 = item.find('a', {'class': 'tweet-timestamp js-permalink js-nav js-tooltip'}, href=True)
</code></pre>
<p>Instead, select by the class direct:</p>
<pre><code>data = requests.get(link)
soup = BeautifulSoup(data.text, 'html.parser')
tweets = soup.find_all('div' , {'class': 'content'})
for item in tweets:
items2 = item.find('a', {'class': 'tweet-timestamp js-permalink js-nav js-tooltip'}, href=True)
if items2:
items21 = items2.get('href')
items22 = items2.get('title')
print(items21)
print(items22.split('-')[1].strip())
</code></pre>
<p>I prefer css selectors and you only need one class out of the compound classes:</p>
<pre><code>data = requests.get(link)
soup = BeautifulSoup(data.text, 'html.parser')
tweets = soup.select(".content")
for item in tweets:
items2 = item.select_one('.tweet-timestamp')
if items2:
items21 = items2.get('href')
items22 = items2.get('title')
print(items21)
print(items22.split('-')[1].strip())
</code></pre>
|
python|twitter|beautifulsoup
| 1 |
1,903,747 | 41,633,774 |
Not able to run node-gyp rebuild
|
<p>i wanted to run node-gyp rebuild and i have installed pythod but after doing all steps its give error "can not find python env variable"</p>
<p><a href="https://i.stack.imgur.com/2weaW.png" rel="nofollow noreferrer">Error which am getting</a></p>
<p><a href="https://i.stack.imgur.com/9qLPp.png" rel="nofollow noreferrer">Environment variable</a></p>
|
<p>From, the error message it looks that the path you have specified is wrong. Crosscheck once again.</p>
<p>Find more help regarding this in the below link:</p>
<p><a href="https://stackoverflow.com/questions/31251367/node-js-npm-refuses-to-find-python-even-after-python-has-been-set">Node.js (npm) refuses to find python even after %PYTHON% has been set</a></p>
|
python|node.js|express
| 0 |
1,903,748 | 24,914,489 |
Best way to find the location of a config file based from launching directory?
|
<p>I'm developing a module right now that requires a configuration file. </p>
<p>The configuration file is optional and can be supplied when the module is launched, or (ideally) loaded from a <code>defaults.json</code> file located in the same directory as the application. The defaults.json file's purpose is also used to fill in missing keys with <code>setdefault</code>.</p>
<p>The problem comes from where the module is launched...</p>
<p><code>...\Application</code> = <code>python -m application.web.ApplicationServer</code></p>
<p><code>...\Application\application</code> = <code>python -m web.ApplicationServer</code></p>
<p><code>...\Application\application\web</code> = <code>python ApplicationServer.py</code></p>
<p>....read as, "If if I'm in the folder, I type this to launch the server."</p>
<p>How can I determine where the program was launched from (possibly using <code>os.getcwd()</code>) to determine what file path to pass to <code>json.load(open(<path>), 'r+b'))</code> such that it will always succeed?</p>
<p>Thanks.</p>
<p><em>Note: I strongly prefer to get a <strong>best practices</strong> answer, as I can "hack" a solution together already -- I just don't think my way is the best way. Thanks!</em></p>
|
<p>If you want to get the path to file that has your code relative to from where it was launched, then it is stored in the <code>__file__</code> of the module, which can be used if you:</p>
<ul>
<li>dont want your module(s) to be installed with a <code>setup.py</code>/<code>distutils</code>
scheme.</li>
<li>and want your code + configs contained in one location.</li>
</ul>
<p>So a <code>codeDir = os.path.dirname(os.path.abspath(__file__))</code> should always work.</p>
<p>If you want to make an installer, I would say it is customary to place the code in one place and things like configs somewhere else. And that would depend on your OS. On linux, one common place is in <code>/home/user/.local/share/yourmodule</code> or just directly under <code>/home/user/.yourmodule</code>. Windows have similar place for app-data.
For both, <code>os.environ['HOME']</code> / <code>os.getenv('HOME')</code> is a good starting point, and then you should probably detect the OS and place your stuff in the expected location with a nice foldername.</p>
<p>I can't swear that these are best practices, but they seem rather hack-free at least.</p>
|
python|configuration
| 3 |
1,903,749 | 52,447,548 |
AttributeError: module 'tox.config' has no attribute 'parseini'
|
<p>I recently get</p>
<pre><code>3.36s$ pip install coveralls tox-travis
0.31s$ tox
Matching undeclared envs is deprecated. Be sure all the envs that Tox should run are declared in the tox config.
Traceback (most recent call last):
File "/home/travis/virtualenv/python3.5.6/bin/tox", line 11, in <module>
sys.exit(cmdline())
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/tox/session.py", line 41, in cmdline
main(args)
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/tox/session.py", line 46, in main
config = prepare(args)
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/tox/session.py", line 28, in prepare
config = parseconfig(args)
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/tox/config.py", line 233, in parseconfig
pm.hook.tox_configure(config=config) # post process config object
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/pluggy/hooks.py", line 258, in __call__
return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/pluggy/manager.py", line 67, in _hookexec
return self._inner_hookexec(hook, methods, kwargs)
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/pluggy/manager.py", line 61, in <lambda>
firstresult=hook.spec_opts.get('firstresult'),
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/pluggy/callers.py", line 201, in _multicall
return outcome.get_result()
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/pluggy/callers.py", line 76, in get_result
raise ex[1].with_traceback(ex[2])
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/pluggy/callers.py", line 180, in _multicall
res = hook_impl.function(*args)
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/tox_travis/hooks.py", line 46, in tox_configure
autogen_envconfigs(config, undeclared)
File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/tox_travis/envlist.py", line 48, in autogen_envconfigs
make_envconfig = tox.config.parseini.make_envconfig
AttributeError: module 'tox.config' has no attribute 'parseini'
The command "tox" exited with 1.
</code></pre>
<p>for the <a href="https://github.com/MartinThoma/mpu" rel="nofollow noreferrer">mpu project</a> (<a href="https://travis-ci.org/MartinThoma/mpu/jobs/431564761" rel="nofollow noreferrer">travis link</a>)</p>
<p>The strange thing is that it works for Python 2.7 and Python 3.6 - so what is the issue?</p>
|
<p>Tox 3.4.0 (released yesterday) broke tox-travis: <a href="https://github.com/tox-dev/tox-travis/issues/114" rel="nofollow noreferrer">https://github.com/tox-dev/tox-travis/issues/114</a></p>
<p>The bug is already fixed and the new release <a href="https://pypi.org/project/tox-travis/0.11/" rel="nofollow noreferrer">0.11</a> just uploaded. Upgrade:</p>
<pre><code>pip install -U 'tox-travis>=0.11'
</code></pre>
|
python|travis-ci|python-3.5|tox
| 2 |
1,903,750 | 51,870,368 |
I am having a column like this 9(05),X(05),X(15). I want to separate this 9,X,X into one column and data in () into another column. How can I do that?
|
<p>I am having a column like this 9(05),X(05),X(15). I want to separate this 9,X,X into one column and data in () into another column. How can I do that?
input column is
9(05)
x(05)
x(15)
x(15)
s9(07)</p>
|
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>extract</code></a>:</p>
<pre><code>pat = r'(.*?)\((.*?)\)'
df[['a','b']] = df['col'].str.extract(pat, expand=True)
print (df)
col a b
0 9(05) 9 05
1 x(05) x 05
2 x(15) x 15
3 x(15) x 15
4 s9(07) s9 07
</code></pre>
|
python-3.x|pandas
| 1 |
1,903,751 | 51,948,295 |
Kivy unable to add text to button using ButtonBehavior
|
<p>I want to add text to the right of the circular image. I was told to use a label to do this, but I can not figure out how to actually do this. It has to be dynamic, so if you have to do this in the KV language could you show me how to keep the buttons dynamic even when making the buttons in the KV file. If it is possible I would like to keep this in the Python file, but if the KV way is better so be it. </p>
<pre><code>from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.clock import mainthread
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.properties import BooleanProperty, StringProperty
from kivy.uix.image import AsyncImage
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
Builder.load_file('main.kv')
login_plz = Popup(title='Please login',
content=Label(text='You need to login first'),
size_hint=(None, None), size=(400, 400),
auto_dismiss=True)
class Menu(BoxLayout):
access_denied = BooleanProperty(True)
class ScreenLogIn(Screen):
@mainthread
def verify_credentials(self):
popup = Popup(title='Try again',
content=Label(text='Wrong Email/Password'),
size_hint=(None, None), size=(400, 400),
auto_dismiss=True)
try:
if len(self.ids.login.text) > 20 or len(self.ids.passw.text) > 32:
popup.open()
elif self.ids.login.text == "a" and self.ids.passw.text == "a":
App.get_running_app().root.access_denied = False
self.manager.current = "match"
else:
App.get_running_app().root.access_denied = True
popup.open()
except Exception as e:
pass
class ScreenNearUsers(Screen):
@mainthread
def on_enter(self):
if App.get_running_app().root.access_denied is True:
self.manager.current = 'login'
login_plz.open()
else:
for i in xrange(31):
button = Button(text="B_" + str(i))
self.ids.grid.add_widget(button)
class ScreenMatch(Screen):
def on_enter(self, *args):
if App.get_running_app().root.access_denied is True:
self.manager.current = 'login'
login_plz.open()
else:
for i in range(10):
src = "http://placehold.it/480x270.png&text=slide-%d&.png" % i
image = AsyncImage(source=src, allow_stretch=True, keep_ratio=False, opacity=1, size_hint=(1, 1.3),
pos_hint={'center_x': 0.5, 'center_y': 0.75}, border=True)
self.ids.carousel.add_widget(image)
class ImageButton(ButtonBehavior, Image):
def __init__(self, **kwargs):
super(ImageButton, self).__init__(**kwargs)
class ScreenChats(Screen):
def on_enter(self, *args):
if App.get_running_app().root.access_denied is True:
self.manager.current = 'login'
login_plz.open()
else:
# This is the button with the image below
for i in range(4):
button = ImageButton(source=('Trifecta.png'), size=(200,200), size_hint=(None,None), text='some text')
self.ids.chat_layout.add_widget(button)
class ScreenUserProfile(Screen):
def on_enter(self, *args):
if App.get_running_app().root.access_denied is True:
self.manager.current = 'login'
login_plz.open()
else:
pass
class Manager(ScreenManager):
screen_log_in = ObjectProperty(None)
screen_near_user = ObjectProperty(None)
screen_match = ObjectProperty(None)
screen_chats = ObjectProperty(None)
screen_user_profile = ObjectProperty(None)
class MenuApp(App):
def build(self):
return Menu()
def on_start(self):
self.current_screen = 'login'
if __name__ == '__main__':
MenuApp().run()
</code></pre>
<p>The main Kv:</p>
<pre><code><Menu>:
manager: screen_manager
orientation: "vertical"
id: action
ActionBar:
size_hint_y: 0.1
background_color: 0, 0, 1000, 10
background_normal: ""
ActionView:
ActionPrevious:
app_icon:""
with_previous: False
markup:True
font_size:"16dp"
ActionButton:
id: near_users
size_hint: 1, 1
height: self.texture_size[ 1 ]
width: self.texture_size[ 0 ] + 40
minimum_width: self.texture_size[ 0 ] + 60
halign: "center"
icon: 'icons/internet.png'
disabled: True if root.access_denied else False
on_press: root.manager.current = 'near_users'
ActionButton:
id: matching_bar
size_hint: 1, 1
height: self.texture_size[ 1 ]
width: self.texture_size[ 0 ] + 40
minimum_width: -self.texture_size[ 0 ] + 60
halign: "center"
text: "Matching"
disabled: True if root.access_denied else False
on_press: root.manager.current= 'match'
ActionButton:
id: chat
size_hint: 1, 1
height: self.texture_size[ 1 ]
width: self.texture_size[ 0 ] + 40
minimum_width: self.texture_size[ 0 ] + 60
halign: "center"
text: "chat"
disabled: True if root.access_denied else False
on_press: root.manager.current = 'chats'
ActionButton:
id: profile
size_hint: 1, 1
height: self.texture_size[ 1 ]
width: self.texture_size[ 0 ] + 40
minimum_width: self.texture_size[ 0 ] + 60
halign: "center"
text: "Profile"
disabled: True if root.access_denied else False
on_press: root.manager.current = 'profile'
Manager:
id: screen_manager
<ScreenLogIn>:
id: login_screen
BoxLayout:
orientation: "vertical"
padding: 20, 20
spacing: 50
TextInput:
id: login
size_hint_y: None
multiline: False
TextInput:
id: passw
size_hint_y: None
multiline: False
password: True # hide password
Button:
text: "Log In"
on_release: root.verify_credentials()
<ScreenNearUsers>:
ScrollView:
GridLayout:
id: grid
size_hint_y: None
height: self.minimum_height
cols: 2
row_default_height: '20dp'
row_force_default: True
spacing: 0, 0
padding: 0, 0
<ScreenMatch>:
name: 'Carousel'
fullscreen: True
BoxLayout:
size_hint_y: None
height: '48dp'
Button:
text: 'last user'
id: last_user
Button:
text: 'like'
Button:
text: 'super like'
on_release: carousel.load_previous()
Button:
text: 'Dislike'
on_release: carousel.load_next()
AnchorLayout:
anchor_x: 'center'
anchor_y: 'center'
Carousel:
id: carousel
loop: last_user.state == 'down'
<ScreenChats>:
ScrollView:
GridLayout:
id: chat_layout
size_hint_y: None
height: self.minimum_height
cols: 1
row_default_height: '125dp'
row_force_default: True
spacing: 0, 0
padding: 0, 0
<ScreenUserProfile>:
Button:
text: "stuff4"
<Manager>:
id: screen_manager
screen_log_in: screen_log_in
screen_near_users: screen_near_users
screen_match: screen_match
screen_chats: screen_chats
screen_user_profile: screen_user_profile
ScreenLogIn:
id: screen_log_in
name: 'login'
manager: screen_manager
ScreenNearUsers:
id: screen_near_users
name: 'near_users'
manager: screen_manager
ScreenMatch:
id: screen_match
name: 'match'
manager: screen_manager
ScreenChats:
id: screen_chats
name: 'chats'
manager: screen_manager
ScreenUserProfile:
id: screen_user_profile
name: 'profile'
manger: screen_manager
</code></pre>
|
<p>I found the answer my self, you can only put a label inside the button in the KV language, when using ButtonBehavior. Then you can just use Factory to access the button from the python file. The "text = StringProperty()" in the ImageButton class is needed cause there is some sort of bug that causes the firs button to be generated with out text. </p>
<pre><code>from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.clock import mainthread
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.properties import BooleanProperty, StringProperty
from kivy.uix.image import AsyncImage
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
from kivy.factory import Factory
Builder.load_file('main.kv')
login_plz = Popup(title='Please login',
content=Label(text='You need to login first'),
size_hint=(None, None), size=(400, 400),
auto_dismiss=True)
class Menu(BoxLayout):
access_denied = BooleanProperty(True)
class ScreenLogIn(Screen):
def verify_credentials(self):
popup = Popup(title='Try again',
content=Label(text='Wrong Email/Password'),
size_hint=(None, None), size=(400, 400),
auto_dismiss=True)
try:
if len(self.ids.login.text) > 20 or len(self.ids.passw.text) > 32:
popup.open()
elif self.ids.login.text == "a" and self.ids.passw.text == "a":
App.get_running_app().root.access_denied = False
self.manager.current = "match"
else:
App.get_running_app().root.access_denied = True
popup.open()
except Exception as e:
pass
class ScreenNearUsers(Screen):
@mainthread
def on_enter(self):
if App.get_running_app().root.access_denied is True:
self.manager.current = 'login'
login_plz.open()
else:
for i in xrange(31):
button = Button(text="B_" + str(i))
self.ids.grid.add_widget(button)
class ScreenMatch(Screen):
def on_enter(self, *args):
if App.get_running_app().root.access_denied is True:
self.manager.current = 'login'
login_plz.open()
else:
for i in range(10):
src = "http://placehold.it/480x270.png&text=slide-%d&.png" % i
image = AsyncImage(source=src, allow_stretch=True, keep_ratio=False, opacity=1, size_hint=(1, 1.3),
pos_hint={'center_x': 0.5, 'center_y': 0.75}, border=True)
self.ids.carousel.add_widget(image)
class ImageButton(ButtonBehavior, Image):
text = StringProperty()
class ScreenChats(Screen):
def get_user_chat(self):
self.manager.current = 'match'
def on_enter(self, *args):
if App.get_running_app().root.access_denied is True:
self.manager.current = 'login'
login_plz.open()
else:
for i in range(4):
btn = Factory.ImageButton(text='sometxt', source='Trifecta.png')
self.ids.chat_layout.add_widget(btn)
class ScreenUserProfile(Screen):
def on_enter(self, *args):
if App.get_running_app().root.access_denied is True:
self.manager.current = 'login'
login_plz.open()
else:
pass
class Manager(ScreenManager):
screen_log_in = ObjectProperty(None)
screen_near_user = ObjectProperty(None)
screen_match = ObjectProperty(None)
screen_chats = ObjectProperty(None)
screen_user_profile = ObjectProperty(None)
class MenuApp(App):
def build(self):
return Menu()
def on_start(self):
self.current_screen = 'login'
if __name__ == '__main__':
MenuApp().run()
</code></pre>
<p>Kv:</p>
<pre><code><Menu>:
manager: screen_manager
orientation: "vertical"
id: action
ActionBar:
size_hint_y: 0.1
background_color: 0, 0, 1000, 10
background_normal: ""
ActionView:
ActionPrevious:
app_icon:""
with_previous: False
text:" [b]Dhobiwala.com[/b]"
markup:True
font_size:"16dp"
ActionButton:
id: near_users
size_hint: 1, 1
height: self.texture_size[ 1 ]
width: self.texture_size[ 0 ] + 40
minimum_width: self.texture_size[ 0 ] + 60
halign: "center"
icon: 'icons/internet.png'
disabled: True if root.access_denied else False
on_press: root.manager.current = 'near_users'
ActionButton:
id: matching_bar
size_hint: 1, 1
height: self.texture_size[ 1 ]
width: self.texture_size[ 0 ] + 40
minimum_width: -self.texture_size[ 0 ] + 60
halign: "center"
text: "Matching"
disabled: True if root.access_denied else False
on_press: root.manager.current= 'match'
ActionButton:
id: chat
size_hint: 1, 1
height: self.texture_size[ 1 ]
width: self.texture_size[ 0 ] + 40
minimum_width: self.texture_size[ 0 ] + 60
halign: "center"
text: "chat"
disabled: True if root.access_denied else False
on_press: root.manager.current = 'chats'
ActionButton:
id: profile
size_hint: 1, 1
height: self.texture_size[ 1 ]
width: self.texture_size[ 0 ] + 40
minimum_width: self.texture_size[ 0 ] + 60
halign: "center"
text: "Profile"
disabled: True if root.access_denied else False
on_press: root.manager.current = 'profile'
Manager:
id: screen_manager
<ScreenLogIn>:
id: login_screen
BoxLayout:
orientation: "vertical"
padding: 20, 20
spacing: 50
TextInput:
id: login
size_hint_y: None
multiline: False
TextInput:
id: passw
size_hint_y: None
multiline: False
password: True # hide password
Button:
text: "Log In"
on_release: root.verify_credentials()
<ScreenNearUsers>:
ScrollView:
GridLayout:
id: grid
size_hint_y: None
height: self.minimum_height
cols: 2
row_default_height: '20dp'
row_force_default: True
spacing: 0, 0
padding: 0, 0
<ScreenMatch>:
name: 'Carousel'
fullscreen: True
BoxLayout:
size_hint_y: None
height: '48dp'
Button:
text: 'last user'
id: last_user
Button:
text: 'like'
Button:
text: 'super like'
on_release: carousel.load_previous()
Button:
text: 'Dislike'
on_release: carousel.load_next()
AnchorLayout:
anchor_x: 'center'
anchor_y: 'center'
Carousel:
id: carousel
loop: last_user.state == 'down'
<ImageButton>:
size_hint: None, None
size: 200, 200
text: ''
Label:
Label:
text: root.text
pos: root.x - -75, root.y - 0
size: root.size
<ScreenChats>:
ScrollView:
GridLayout:
id: chat_layout
size_hint_y: None
height: self.minimum_height
cols: 1
row_default_height: '125dp'
row_force_default: True
spacing: 0, 0
padding: 0, 0
<ScreenUserProfile>:
Button:
text: "stuff4"
<Manager>:
id: screen_manager
screen_log_in: screen_log_in
screen_near_users: screen_near_users
screen_match: screen_match
screen_chats: screen_chats
screen_user_profile: screen_user_profile
ScreenLogIn:
id: screen_log_in
name: 'login'
manager: screen_manager
ScreenNearUsers:
id: screen_near_users
name: 'near_users'
manager: screen_manager
ScreenMatch:
id: screen_match
name: 'match'
manager: screen_manager
ScreenChats:
id: screen_chats
name: 'chats'
manager: screen_manager
ScreenUserProfile:
id: screen_user_profile
name: 'profile'
manger: screen_manager
</code></pre>
|
python|python-2.7|kivy|kivy-language
| 0 |
1,903,752 | 47,811,745 |
gevent fastcgi standalone not working?
|
<p>As shown in this page <a href="https://pypi.python.org/pypi/gevent-fastcgi" rel="nofollow noreferrer">https://pypi.python.org/pypi/gevent-fastcgi</a>,
we can use gevent-fastcgi in stand-alone mode.</p>
<pre><code>from gevent_fastcgi.server import FastCGIServer
from gevent_fastcgi.wsgi import WSGIRequestHandler
def wsgi_app(environ, start_response):
start_response('200 OK', [('Content-type', 'text/plain')])
yield 'Hello World!'
request_handler = WSGIRequestHandler(wsgi_app)
server = FastCGIServer(('127.0.0.1', 4000), request_handler, num_workers=4)
server.serve_forever()
</code></pre>
<p>However, when I tried it with wget, it get blocked.</p>
<pre><code>$ wget http://127.0.0.1:4000/ping
Connecting to 127.0.0.1:4000... connected.
HTTP request sent, awaiting response...
</code></pre>
<p>Python2.7.10, gevent-fastcgi==1.0.2.1, gevent==1.2.1</p>
<p>Is there anything wrong with the code? Thanks</p>
|
<p><code>gevent-fastcgi</code> is a library to serve WSGI app via fastcgi protocol, but <code>wget</code> is trying to talk with HTTP, you need another server in front of "127.0.0.1:4000" to translate HTTP to fastcgi, like <a href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_pass" rel="nofollow noreferrer">nginx</a>.</p>
|
python|cgi|fastcgi|gevent
| 1 |
1,903,753 | 26,172,790 |
Calling other class from inner class
|
<p>Hi guys i am planning to call the other class from other class parameter.The code i have tried</p>
<pre><code>class barber:
def __init__(self, age, money):
self.age = age
self.money = money
class Employee:
def __init__(self, name):
self.name = name
def displayCount(self):
print "Total Employee"
emp1 = Employee(barber(2,5))
print emp1.self.age
</code></pre>
<p>When i tried this code i got a blank page without any errors ..Can you guys point me where am going wrong ??..</p>
<p>Thanks in advance</p>
|
<p>You are mistaken in believing that the <code>emp1</code> instance of class <code>Employee</code> contains something called <code>self</code>. It contains something called <code>name</code> and that <code>name</code> member references an object of type <code>barber</code>.</p>
<p>Note that:</p>
<ul>
<li><p>It's a little odd to use the name <code>name</code> to refer to an object that isn't a string, isn't a name, and doesn't contain a name.</p></li>
<li><p>You have one class that starts with a capital letter and one that starts with a lower-case letter. It's more common to follow a regular pattern of naming classes.</p></li>
<li><p>While there are times in which you might want to have an <code>Employee</code> class that takes a specific type of employee in its constructor and "wraps" that object, it's more common to use <code>Employee</code> as a base class and <em>descend</em> other, more specific classes from that base class.</p></li>
</ul>
|
python
| 1 |
1,903,754 | 28,303,287 |
Django doesn't remember context
|
<p>I'm new to Django and i'm trying to set up an existing project on new server.</p>
<p>Django starts, but it behaves very strange. I have the following code:</p>
<pre class="lang-python prettyprint-override"><code>someVar = None
def first(request):
global someVar
someVar = 'modified'
def second(request):
return HttpResponse(someVar) # prints 'None'
</code></pre>
<p>I mapped this methods to URLs. When I call 'first' method and then 'second', the expected output is 'modified', but actually it is 'None'</p>
<p>It seems like Apache starts the application on each request, like if it was some cgi script. Any ideas why this is happening?</p>
<p>I'm using Apache2.2 with mod_wsgi and Django 1.5.9.
Django project is outside of Apache's document root. Here is Apache host configuration file:</p>
<pre><code>WSGIScriptAlias / /path/mysite/mysite/wsgi.py
WSGIPythonPath /path/mysite
<Directory /path/mysite/mysite>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
</code></pre>
|
<p>Module-level variables are only shared between requests that use the same process. Apache is almost certainly spinning up multiple processes to serve your site. If your subsequent requests happen to go to the same process that served the initial one, you will see the change; otherwise you won't.</p>
<p>If you really need to share data between requests no matter which process serves them, you should use a more persistent place, such as the session or the database.</p>
|
python|django|apache
| 2 |
1,903,755 | 44,339,574 |
how do I keep the center of my sphere in the actual center
|
<p>this is a tricky question, I made this little program:</p>
<pre><code>import pygame as pg
from math import *
import os
import sys
vec2 = pg.math.Vector2
vec3 = pg.math.Vector3
os.environ["SDL_VIDEO_CENTERED"] = "1"
width = 1000
height = 800
thickness = 2
pg.init()
screen = pg.display.set_mode((width, height))
clock = pg.time.Clock()
def p5map(n, start1, stop1, start2, stop2):
return ((float(n)-start1)/(stop1-start1))*(stop2-start2)+start2
def sphere(radius, point, xrot, yrot, yoffset):
for i in xrange(point):
lon = p5map(i, 0, point, -pi, pi)
for j in xrange(point):
lat = p5map(j, 0, point, -pi/2, pi/2)
x = int(radius * sin(lon) * cos(lat)) + width/2
y = int(radius * sin(lon) * sin(lat)) + height/2 + yoffset
z = int(radius * cos(lon))
pos = vec3(x,y,z)
alpha = int(p5map(z, -radius, radius, 0, 255))
pos.rotate_x_ip(xrot)
pos.rotate_y_ip(yrot)
x = int(pos.x)
y = int(pos.y)
screen.set_at((x, y), (0,0,0, alpha))
def run():
running = True
point = 100
radius = 300
yoffset = 0
xangle = 0
yangle = 0
while running:
clock.tick(0)
mouse_pos = vec2(pg.mouse.get_pos())
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
pg.quit()
sys.exit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
running = False
pg.quit()
sys.exit()
if event.key == pg.K_UP:
yoffset += -50
if event.key == pg.K_DOWN:
yoffset += 50
if event.key == pg.K_w:
xangle += 10
print xangle
if event.key == pg.K_s:
xangle += -10
print xangle
if event.key == pg.K_a:
yangle += 10
print yangle
if event.key == pg.K_d:
yangle += -10
print yangle
pg.display.set_caption("{:.2f}".format(clock.get_fps()))
screen.fill((255, 255, 255))
sphere(radius, point, xangle, yangle, yoffset)
pg.display.flip()
run()
</code></pre>
<p>you can play around with the keys "wasd" to rotate the sphere and you will rapidly encounter the problem; the sphere doesnt stay centered, it can even go out of the screen!
here is an exemple of how the sphere rotate:
<a href="https://i.stack.imgur.com/eB9JT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eB9JT.png" alt="sphere"></a></p>
<p>and this is how it should:<a href="https://i.stack.imgur.com/FiD5y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FiD5y.png" alt="sphere"></a></p>
<p>see how in the first exemple it isnt centered? how do I fix that so it stay centered?</p>
<p>the sphere doesnt rotate on itself but rather orbit around the 0,0,0 point of my screen. if anyone knows what I am doing wrong I would like to hear it!</p>
<p>another exemple of the sphere rotated(by 120 degrees):<a href="https://i.stack.imgur.com/yJfPw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yJfPw.png" alt="sphere"></a></p>
<p>and how it should be(fixed by hand):<a href="https://i.stack.imgur.com/P1CBz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P1CBz.png" alt="sphere"></a></p>
|
<p>well nevermind I find a solution, in the sphere function:</p>
<pre><code>def sphere(radius, point, xrot, yrot, yoffset):
for i in xrange(point):
lon = p5map(i, 0, point, -pi, pi)
for j in xrange(point):
lat = p5map(j, 0, point, -pi/2, pi/2)
x = int(radius * sin(lon) * cos(lat))# + width/2
y = int(radius * sin(lon) * sin(lat))# + height/2 + yoffset
z = int(radius * cos(lon))
pos = vec3(x,y,z)
alpha = int(p5map(z, -radius, radius, 0, 255))
pos.rotate_x_ip(xrot)
pos.rotate_y_ip(yrot)
x = int(pos.x)
y = int(pos.y)
x += width/2
y += height/2
screen.set_at((x, y), (0,0,0, alpha))
</code></pre>
<p>I commented out the + width/2 and + height/2 (which was the offset) and applied the offset after the rotation</p>
|
python|vector|3d|pygame
| 0 |
1,903,756 | 34,586,012 |
#include <Python.h> - compilation terminated on Linux Mint
|
<p>I am trying to install 4Suite-XML 1.02 on my Linux Mint 17.2 Cinnamon. I downloaded the tar.gz, extracted it, opened a terminal in the extracted directory, shifted to root shell with <code>sudo su</code>, and ran <code>python setup.py install</code>. I get this as output:</p>
<pre><code>running install
running build
running config
running build_py
running build_ext
building 'Ft.Lib.number' extension
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c Ft/Lib/src/number.c -o build/temp.linux-x86_64-2.7/Ft/Lib/src/number.o
Ft/Lib/src/number.c:7:20: fatal error: Python.h: No such file or directory
#include <Python.h>
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
</code></pre>
|
<p>Usually Linux distributions split programming language run-times to two packages and Python is no exception.</p>
<ul>
<li><p><code>python</code> - Python code runtime</p></li>
<li><p><code>python-dev</code> - Development files, libraries and headers. Needed to install any native extensions. Aimed for developers. Something that integrates Python to "native" C libraries. Python code is portable across operating systems, C code is not. C code must be recompiled to every operating system.</p></li>
</ul>
<p>You need to install related <code>python-dev</code> package which contains C headers necessary to compile Python native extensions. This command is usually <code>sudo apt install python-dev</code> on Debian based distributions. I have not checked the actual command for Mint Linux, but I assume it to be the same.</p>
<p>Also please read the official Python package installation guide <a href="https://packaging.python.org/en/latest/installing.html" rel="nofollow">https://packaging.python.org/en/latest/installing.html</a> - usually <code>sudo</code> installations and <code>python setup.py install</code> are unnecessary. <code>pip install --user</code> command should be able to download, extract and install the package for you.</p>
|
python|linux|linux-mint
| 4 |
1,903,757 | 48,568,555 |
Python wrapper to run requests on the endpoint of overpass-API
|
<p>we have with Overpass API python wrapper a thin Python wrapper around the OpenStreetMap Overpass API <a href="https://github.com/mvexel/overpass-api-python-wrapper" rel="nofollow noreferrer">https://github.com/mvexel/overpass-api-python-wrapper</a></p>
<p>we have some Simple example:</p>
<pre><code>import overpass
api = overpass.API()
response = api.Get('node["name"="Salt Lake City"]')
</code></pre>
<p>Note that you don't have to include any of the output meta statements. The wrapper will, well, wrap those.
we will get our result as a dictionary, which represents the JSON output you would get from the Overpass API directly.</p>
<pre><code>print [(feature['tags']['name'], feature['id']) for feature in response['elements']]
[(u'Salt Lake City', 150935219), (u'Salt Lake City', 585370637), (u'Salt Lake City', 1615721573)]
</code></pre>
<p>we can specify the format of the response. By default, we will get GeoJSON using the responseformat parameter. Alternatives are plain JSON (json) and OSM XML (xml), as ouput directly by the Overpass API.</p>
<pre><code>response = api.Get('node["name"="Salt Lake City"]', responseformat="xml")
</code></pre>
<p><strong>updated question:</strong> can we also get cvs - can we perform a request like below with the python wrapper to the endpoint of overpass turbo?</p>
<pre><code>[out:csv(::id,::type,"name","addr:postcode","addr:city",
"addr:street","addr:housenumber","website"," contact:email=*")][timeout:30];
area[name="Madrid"]->.a;
( node(area.a)[amenity=hospital];
way(area.a)[amenity=hospital];
rel(area.a)[amenity=hospital];);
out;
</code></pre>
<p>by the way: i have encountered that the example code in the readme-text is unfortunatly broken: When I try the following: </p>
<pre><code>print( [(feature['tags']['name'], feature['id']) for feature in response['elements']] )
</code></pre>
<p>I get the error</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'elements'
This works, though:
print( [(feature['properties']['name'], feature['id']) for feature in response['features']] )
</code></pre>
<p>What do you think?</p>
|
<p>You can try this.</p>
<pre><code>import overpass
api = overpass.API()
query = """
[out:csv(::id,::type,"name","addr:postcode","addr:city",
"addr:street","addr:housenumber","website"," contact:email=*")][timeout:30];
area[name="Madrid"]->.a;
( node(area.a)[amenity=hospital];
way(area.a)[amenity=hospital];
rel(area.a)[amenity=hospital];);
out;
"""
resp = api._get_from_overpass(query)
data = [row.split('\t') for row in resp.text.split('\n')]
</code></pre>
<p>Output:</p>
<pre><code>for x in data[:5]:
print(x)
# ['@id', '@type', 'name', 'addr:postcode', 'addr:city', 'addr:street', 'addr:housenumber', 'website', ' contact:email=*']
# ['597375537', 'node', 'Centro de especialidades Emigrantes', '', '', '', '', '', '']
# ['1437313175', 'node', '', '', '', '', '', '', '']
# ['1595068136', 'node', '', '', '', '', '', '', '']
# ['2320596216', 'node', '', '', '', '', '', '', '']
</code></pre>
<hr>
<p>Or</p>
<pre><code>api = overpass.API()
query = """
area[name="Madrid"]->.a;
( node(area.a)[amenity=hospital];
way(area.a)[amenity=hospital];
rel(area.a)[amenity=hospital];);
"""
fmt = 'csv(::id,::type,"name","addr:postcode","addr:city","addr:street","addr:housenumber","website"," contact:email=*")'
data = api.get(query, responseformat=fmt)
</code></pre>
<p>Output:</p>
<pre><code>for x in data[:5]:
print(x)
# ['@id', '@type', 'name', 'addr:postcode', 'addr:city', 'addr:street', 'addr:housenumber', 'website', ' contact:email=*']
# ['597375537', 'node', 'Centro de especialidades Emigrantes', '', '', '', '', '', '']
# ['1437313175', 'node', '', '', '', '', '', '', '']
# ['1595068136', 'node', '', '', '', '', '', '', '']
# ['2320596216', 'node', '', '', '', '', '', '', '']
</code></pre>
|
python|json|linux|openstreetmap|overpass-api
| 2 |
1,903,758 | 48,831,970 |
Am I able to create a form that is able to add a new django.contrib.auth User without logging in to the admin panel?
|
<p>Have created a form but unsure if is right and also unable to add a user, it will show TypeError/
<a href="https://i.stack.imgur.com/sx1Ns.jpg" rel="nofollow noreferrer">This is how the form I want it to look like</a></p>
<p>The following is my coding:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>class Form_Add_User(forms.Form):
name=forms.CharField(label="Name", max_length=50)
dateofbirth=forms.DateField(label="Date of Birth", widget=forms.widgets.DateInput(format="%m/%d/%Y"))
contactnum=forms.CharField(label="Contact Number", max_length=9)
def adduser(request):
if len(request.POST)>0:
form=Form_Add_User(request.POST)
if(form.is_valid()):
name=form.cleaned_data['name']
dateofbirth=form.cleaned_data['dateofbirth']
contactnum=form.cleaned_data['contactnum']
new_user=User(name=name,dateofbirth=dateofbirth,contactnum=contactnum)
new_user.save()
return redirect('/adduser')
else:
return render(request,'adduser.html',{'form':form})
else:
form=Form_Add_User
return render(request,'adduser.html',{'form':form})</code></pre>
</div>
</div>
</p>
|
<p>First off: it's always <strong>very</strong> useful to also post a full error message if you have one. The more info you give us, the easier (and quicker!) is answering your question.</p>
<p>I assume, your <code>User</code> model is not actually django's auth User model (see, if you had posted the model, I wouldn't have to guess).
The form you pass to your template was not instantiated:</p>
<pre><code>#...
else:
form=Form_Add_User() #!!
return render(request,'adduser.html',{'form':form})
</code></pre>
|
python|django|django-forms
| 0 |
1,903,759 | 51,399,150 |
Get column names including index name from pandas data frame
|
<p>Assuming that we have a data frame with an index that might have a name:</p>
<pre><code>df = pd.DataFrame({'a':[1,2,3],'b':[3,6,1], 'c':[2,6,0]})
df = df.set_index(['a'])
b c
a
1 3 2
2 6 6
</code></pre>
<p>What is the best way to get the column names that will include the index name if it is present.</p>
<p>Calling <code>df.columns.tolist()</code> do not include the index name and return <code>['b', 'c']</code> in this case, and I would like to obtain <code>['a', 'b', 'c']</code>.</p>
|
<p>The index can be temporarily reset for the call:</p>
<pre><code>df.reset_index().columns.tolist()
</code></pre>
<p>If an empty index name is not to appear in the list, do the <code>reset_index()</code> conditionally:</p>
<pre><code>(df.reset_index() if df.index.name else df).columns.tolist()
</code></pre>
|
python|pandas|dataframe
| 4 |
1,903,760 | 64,256,790 |
How do I Web Scrape a Wikipedia Infobox Table?
|
<p>I am trying to scrape a Wiki infobox and put the data into a dictionary where the first column of the infobox is the key and the second column is the value. I also have to ignore all rows that do not have 2 columns. I am having trouble understanding how to get the value associated to the key. The Wikipedia page I am trying to scrape is <a href="https://en.wikipedia.org/w/index.php?title=Titanic&oldid=981851347" rel="nofollow noreferrer">https://en.wikipedia.org/w/index.php?title=Titanic&oldid=981851347</a> where I am trying to pull the information from the first infobox.</p>
<p>The results should look like:
{"Name": "RMS Titanic", "Owner": "White Star Line", "Operator": "White Star Line", "Port of registry": "Liverpool, UK", "Route": "Southampton to New York City".....}</p>
<p>Here's what I've tried:</p>
<pre><code> import requests
from bs4 import BeautifulSoup
def get_infobox(url):
response = requests.get(url)
bs = BeautifulSoup(response.text)
table = bs.find('table', {'class' :'infobox'})
result = {}
row_count = 0
if table is None:
pass
else:
for tr in table.find_all('tr'):
if tr.find('th'):
pass
else:
row_count += 1
if row_count > 1:
if tr is not None:
result[tr.find('td').text.strip()] = tr.find('td').text
return result
print(get_infobox("https://en.wikipedia.org/w/index.php?title=Titanic&oldid=981851347"))
</code></pre>
<p>Any help would be greatly appreciated!</p>
|
<p>If you do not need or want to use a scraper, you could use the API</p>
<p><a href="https://www.mediawiki.org/wiki/API:Main_page/de" rel="nofollow noreferrer">https://www.mediawiki.org/wiki/API:Main_page/de</a></p>
<p>The english endpoint is <a href="https://en.wikipedia.org/w/api.php" rel="nofollow noreferrer">https://en.wikipedia.org/w/api.php</a></p>
<p>E.g.:</p>
<p><a href="https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=Titanic&rvsection=0" rel="nofollow noreferrer">https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=Titanic&rvsection=0</a></p>
|
python|web-scraping|beautifulsoup|wikipedia|infobox
| 0 |
1,903,761 | 70,005,545 |
storing the value of a tuple in a variable that is randomized
|
<pre><code>colours = [('green', 1.4), ('blue', 4.067), ('yellow', 6.56), ('black', 9.056), ('red', 10.23)]
</code></pre>
<p>I have randomized one of these values thorough the following code and got the index of that value in the list:</p>
<pre><code>colour_name = random.choice(colours)[0]
colour_number = [i for i, t in enumerate(colours) if t[0] == colour_name][0] + 1
</code></pre>
<p>Lets say I have randomized the colour green with the index 0. How do I also get the value 1.4 that belongs to green?</p>
<p>To be clear, I want the value 1.4 to be stored in a separate variable, just like "green" is stored in the variable "colour_name".</p>
<p>Thanks!</p>
|
<p><code>random.choice</code> is already returning both the name and the value; you are just discarding the value. You don't need to know the index of the choice; you just need to unpack the returned tuple.</p>
<pre><code>colour_name, colour_value = random.choice(colours)
</code></pre>
|
python|tuples
| 2 |
1,903,762 | 73,170,744 |
Value error: cannot reindex an axis with duplicated labels
|
<p>I'm having a little issue with a code:</p>
<p>I'm trying to create new columns on an existing df with some other df with % for different stock tickers as index. These tickers can repeat since one index can have more than one %, and the values can repeat too.</p>
<p>So my problem is that I can create new columns with a "df2", which has repeated indices and repeated values (even for the same index), but for some reason I cannot do that with a "df3" with the same structure. Then, I can do it again with a "df4" but not with a "df5".</p>
<p>Again, these "df2", "df3", "df4", "df5", etc, are basically the same df's and have the same length, have repeated indices, repeated values, etc.
I cannot print the df's because it's confidential, but here's the code.</p>
<p>To end this questions, df1,df2,df3 and df4 have the same indices in the same order, with different values but have repeated of everything.</p>
<pre><code>df['new column 1'] = df1 # (This one works)
df['new column 2'] = df2 # (This one doesn't)
df['new column 3'] = df3 # (This one works)
df['new column 4'] = df4 # (This one doesn't)
</code></pre>
|
<p>You can try to keep only one instance of index:</p>
<pre><code>df['new column 2'] = df2[~df2.index.duplicated()]
</code></pre>
|
python|pandas|dataframe|numpy|label
| 0 |
1,903,763 | 55,818,547 |
How to add computation (eg log and sqrt root) to keras vgg16 before softmax layer
|
<p>I am implementing the improved bilinear pooling (<a href="http://vis-www.cs.umass.edu/bcnn/docs/improved_bcnn.pdf" rel="nofollow noreferrer">http://vis-www.cs.umass.edu/bcnn/docs/improved_bcnn.pdf</a>) and I want to add computation (eg log and square root) before softmax layer to my model, which is fine tuned from keras vgg16 .
How can I do that?</p>
<pre><code>vgg_16 = keras.applications.vgg16.VGG16(weights='imagenet',include_top=False, input_shape=(224, 224, 3))
vgg_16.layers.pop()
My_Model = Sequential()
for layer in vgg_16.layers:
My_Model.add(layer)
for layer in My_Model.layers:
layer.trainable = False
# I want to add this function on top of my model then feed the result to a softmax layer
#
def BILINEAR_POOLING(bottom1, bottom2, sum_pool=True):
assert(np.all(bottom1.shape[:3] == bottom2.shape[:3]))
batch_size, height, width = bottom1.shape[:3]
output_dim = bottom1.shape[-1] * bottom2.shape[-1]
bottom1_flat = bottom1.reshape((-1, bottom1.shape[-1]))
bottom2_flat = bottom2.reshape((-1, bottom2.shape[-1]))
output = np.empty((batch_size*height*width, output_dim), np.float32)
for n in range(len(output)):
output[n, ...] = np.outer(bottom1_flat[n], bottom2_flat[n]).reshape(-1)
output = output.reshape((batch_size, height, width, output_dim))
if sum_pool:
output = np.sum(output, axis=(1, 2))
return output
</code></pre>
|
<p>The solution was only adding a keras lambda layer
as follow</p>
<pre><code>My_Model.add(Lambda(BILINEAR_POOLING,output_shape=[512,512]))
</code></pre>
|
python-3.x|tensorflow|keras|jupyter-notebook
| 0 |
1,903,764 | 73,257,138 |
Pandas method chaining with str.contains and str.split
|
<p>I'm learning Pandas method chaining and having trouble using str.conains and str.split in a chain. The data is one week's worth of information scraped from a Wikipedia page, I will be scraping several years worth of weekly data.</p>
<p>This code without chaining works:</p>
<pre><code>#list of data scraped from web:
list = ['Unnamed: 0','Preseason-Aug 11','Week 1-Aug 26','Week 2-Sep 2',
'Week 3-Sep 9','Week 4-Sep 23','Week 5-Sep 30','eek 6-Oct 7','Week 7-Oct 14',
'Week 8-Oct 21','Week 9-Oct 28','Week 10-Nov 4','Week 11-Nov 11','Week 12-Nov 18',
'Week 13-Nov 25','Week 14Dec 2','Week 15-Dec 9','Week 16 (Final)-Jan 4','Unnamed: 18']
#load to dataframe:
df = pd.DataFrame(list)
#rename column 0 to text:
df = df.rename(columns = {0:"text"})
#remove ros that contain "Unnamed":
df = df[~df['text'].str.contains("Unnamed")]
#split column 0 into 'week' and 'released' at the hyphen:
df[['week', 'released']] = df["text"].str.split(pat = '-', expand = True)
</code></pre>
<p>Here's my attempt to rewrite it as a chain:</p>
<pre><code>#load to dataframe:
df = pd.DataFrame(list)
#function to remove rows that contain "Unnamed"
def filter_unnamed(df):
df = df[~df["text"].str.contains("Unnamed")]
return df
clean_df = (df
.rename(columns = {0:"text"})
.pipe(filter_unnamed)
#[['week','released']] = lambda df_:df_["text"].str.split('-', expand = True)
)
</code></pre>
<p>The first line of the clean_df chain to rename column 0 works.</p>
<p>The second line removes rows that contain "Unnamed"; it works, but is there a better way than using pipe and a function?</p>
<p>I'm having the most trouble with str.split in the 3rd row (doesn't work, commented out). I tried assign for this and think it should work, but I don't know how to pass in the new column names ("week" and "released") with the str.split function.</p>
<p>Thanks for the help.</p>
|
<p>I also couldn't figure out how to create two columns in one go from the split... but I was able to do it by splitting twice and accessing parts 1 and 2 in succession (not ideal), <code>df.assign(week = ...[0], released = ...[1])</code>.</p>
<p>Note also I reset the index.</p>
<pre><code>df.assign(week = df[0].str.split(pat = '-', expand=True)[0], released = df[0].str.split(pat = '-', expand=True)[1])[~df[0].str.contains("Unnamed")].reset_index(drop=True).rename(columns = {0: "text"})
</code></pre>
<p>I'm sure there's a sleeker way, but this may help.</p>
|
python|pandas|dataframe|assign
| 0 |
1,903,765 | 66,393,087 |
TypeError with undefined amount of parameters
|
<p>I'm building a Discord Bot and I want to call the the first play function from class 1, that you can see below, from another class. I made another function for that down below, but when I run it, I get a TypeError:</p>
<blockquote>
<p>TypeError: play() takes 2 positional arguments but 3 were given.</p>
</blockquote>
<p>I think it gives me an error because I'm giving the function an undefined amount of parameters because it worked with a defined amount. Thanks for helping me already!</p>
<pre><code>
class1:
@commands.command()
async def play(self, ctx, *, url):
class2:
@commands.command()
async def play(self, ctx, *, url):
instance = class1()
await instance.play(instance, ctx, url) #place where the error occurs
</code></pre>
|
<p>From the python documentation:</p>
<pre><code># The second syntactical change is to allow the argument name to be omitted for a varargs argument.
# The meaning of this is to allow for keyword-only arguments for functions that would not otherwise take a varargs argument:
def compare(a, b, *, key=None):
...
</code></pre>
<p>When you use <code>(args1, args2, ... argsn, *, more_args)</code> that means that args1..n are positional while <code>more_args</code> can only be passed as a keyword argument with the form <code>more_args=something</code></p>
<p>Therefore you must do something like this:</p>
<pre><code>await instance.play(instance, ctx, url=url)
</code></pre>
|
python|discord.py
| 3 |
1,903,766 | 66,386,505 |
How can I Create a quest menu for my Text-RPG
|
<p>i want to create a quest menu for my text rpg, it should be a list of all quests and after completion the finished quest should be removed fromt the menu. I tried it with a class but i get this error:</p>
<p>IndexError: list assignment index out of range
<<strong>main</strong>.quest_menu object at 0x000001D4F8EC3FD0></p>
<p>#generate a class for my quest menu</p>
<pre><code> class quest_menu():
def __init__(self, quests):
self.quests = quests
</code></pre>
<h1>generate functions to remove single quests from the menu</h1>
<pre><code> def delete_quest_1(self):
del self.quests[0]
def delete_quest_2(self):
del self.quests[1]
</code></pre>
<h1>generate quests in a list</h1>
<pre><code> quests = quest_menu( ["Quest: Murder: kill Rottger = exp: 100, gold 100",
"\nQuest: Ring of strenght: Find the ring of strenght= : exp 50"])
</code></pre>
<h1>commands to delete quest from inventory when quest is completed</h1>
<pre><code> quests.delete_quest_1()
print(quests)
quests.delete_quest_2()
print(quests)
</code></pre>
<p>What am I doing wrong? Does anybody have some tips to improve the code?
Thx in advance!</p>
|
<p>I think what's wrong is that, You deleted a quest first then the only Quest that remains is the second one, this makes that quest first item in the list so using the function to delete the quest will result in IndexError as the quest is now at Index 0. Try to this instead.</p>
<pre><code>class quest_menu():
def __init__(self, quests):
self.quests = quests
def delete_quest_1(self):
del self.quests[0]
def delete_quest_2(self):
del self.quests[1]
quests = quest_menu( ["Quest: Murder: kill Rottger = exp: 100, gold 100", "\nQuest: Ring of strenght: Find the ring of strenght= : exp 50"])
quests.delete_quest_1()
print(quests.quests)
quests.delete_quest_1()
print(quests.quests)
</code></pre>
|
python|class
| 0 |
1,903,767 | 64,838,984 |
Flask Sessions - Session isn't always removed on logout (Works sometimes)
|
<p>I have a javascript fetch call to an api (on a different domain) and I'm passing along credentials. On the other Python Flask API, I have CORS and 'Access-Control-Allow-Credentials' set to true on all requests.</p>
<p>Python Webservice</p>
<pre class="lang-py prettyprint-override"><code>app = Flask(__name__)
app.secret_key = os.getenv('SESSION_SECRET')
app.config.from_object(__name__)
CORS(app)
@app.after_request
def add_header(response):
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response
@app.route('/login', methods=['POST'])
@captcha_check
def login():
data = request.get_json(force=True) # Force body to be read as JSON
email = data.get('email')
password = data.get('password')
# Authenticate users account and password
if auth.verify_password(email, password):
# Password is correct, return temporary session ID
username_query = db.get_username_by_email(email)
if username_query['found']:
session['email'] = email
return jsonify({'status': 200, 'email': email}), 200
else:
return jsonify({'status': 404, 'error': 'user-email-not-found'}), 404
else:
# Incorrect password specified, return Unauthorized Code
return jsonify({'status': 401, 'error': 'incorrect-password'}), 401
@app.route('/logout', methods=['POST'])
def logout():
print(session, file=sys.stdout)
session.clear()
print(session.pop('email', None), file=sys.stdout)
return jsonify({'status': 200}), 200
</code></pre>
<p>Javascript fetch call</p>
<pre class="lang-js prettyprint-override"><code>async function signInPost(data) {
const response = await fetch(serverAddress + '/login', {
method: 'POST',
credentials: 'include',
headers: {
'Access-Control-Allow-Origin': 'http://localhost:5000',
'Access-Control-Allow-Credentials': 'true'
},
body: JSON.stringify(data)
});
// Wait for response from server, then parse the body of the response in json format
return await response.json();
}
async function signOutPost() {
const response = await fetch(serverAddress + '/logout', {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': 'http://localhost:5000',
'Access-Control-Allow-Credentials': 'true'
},
credentials: 'include'
});
return await response.json();
}
</code></pre>
<p>I know the cookie is being set with login becuase I have other endpoints that check the status of the cookie to see if a person is signed in or not. What I'm confused about is why this doesn't always invalidate the cookie. On chrome the network syas the status of the first api call is "(cancled)", but then sometimes if I click it one or two more times it will eventually sign out. On Firefox and Safari it will esentially never sign me out.</p>
<p>Flask is getting the api calls and returning a 200 status, but the browsers are not respecting what is being returned.</p>
<p>My current assumption is that it has something to do with the OPTIONS method that get's called in advance blocking the request, but I'm not sure how to get around this.</p>
|
<p>Why dont you pass in your config.py file something like this</p>
<pre><code>CORS_SUPPORTS_CREDENTIALS = True
</code></pre>
<p>instead of passing in the requests?</p>
|
python|flask
| 1 |
1,903,768 | 64,732,468 |
python: can't open file '.manage.py': [Errno 2] No such file or directory
|
<p>Im learning django and i get this error:</p>
<pre><code>python: can't open file '.manage.py': [Errno 2] No such file or directory
</code></pre>
<p>when running</p>
<pre><code>python .\manage.py makemigrations
</code></pre>
<p>I know im running the command in the same folder as my manage.py file, so what can be the issue?</p>
<p>This is my directory tree:</p>
<pre><code>.
├── api
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── manage.py
└── music_controller
├── asgi.py
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
</code></pre>
<p>Here is the pwd where i run above command:</p>
<pre><code>(djangotut) ether@ether:~/Documents/django-react-tutorial/music_controller$
</code></pre>
|
<p>You don't need to use a backslash in the path.
The correct command would be: <code>python manage.py makemigrations</code></p>
<p>Naturally you will be using this in the directory where manage.py resides.</p>
|
python|django
| 3 |
1,903,769 | 64,089,292 |
Python: conversion from requests library to urllib3
|
<p>I need to convert the following CURL command into an http request in Python:</p>
<pre><code>curl -X POST https://some/url
-H 'api-key: {api_key}'
-H 'Content-Type: application/json'
-H 'Accept: application/json'
-d '{ "data": { "dirname": "{dirname}", "basename": "{filename}", "contentType": "application/octet-stream" } }'
</code></pre>
<p>I initially successfully implemented the request using Python's requests library.</p>
<pre><code>import requests
url = 'https://some/url'
api_key = ...
dirname = ...
filename = ...
headers = {
'api-key': f'{api_key}',
'Content-Type': 'application/json',
'Accept': 'application/json',
}
payload = json.dumps({
'data': {
'dirname': f'{dirname}',
'basename': f'{filename}',
'contentType': 'application/octet-stream'
}
})
response = requests.post(url, headers=headers, data=payload)
</code></pre>
<p>The customer later asked not to use pip to install the requests library. For this I am trying to use the urllib3 library as follows:</p>
<pre><code>import urllib3
url = 'https://some/url'
api_key = ...
dirname = ...
filename = ...
headers = {
'api-key': f'{api_key}',
'Content-Type': 'application/json',
'Accept': 'application/json',
}
payload = json.dumps({
'data': {
'dirname': f'{dirname}',
'basename': f'{filename}',
'contentType': 'application/octet-stream'
}
})
http = urllib3.PoolManager()
response = http.request('POST', url, headers=headers, body=payload)
</code></pre>
<p>The problem is that now the request returns me an error 400 and I don't understand why.</p>
|
<p>Try calling <code>.encode('utf-8')</code> on <code>payload</code> before passing as a parameter.</p>
<p>Alternatively, try to pass payload as <code>fields</code> without manually converting it to JSON:</p>
<pre class="lang-py prettyprint-override"><code>payload = {
'data': {
'dirname': f'{dirname}',
'basename': f'{filename}',
'contentType': 'application/octet-stream'
}
}
http = urllib3.PoolManager()
response = http.request('POST', url, headers=headers, fields=payload)
</code></pre>
|
python|curl|python-requests|urllib3
| 1 |
1,903,770 | 63,926,323 |
How do I make code in this function repeat? (python)
|
<p>I am writing a game and I want a certain part of the code to redo. The comments in the code show what I want to redo.</p>
<pre><code>import random
def getRandom():
#this is the code I want to rerun (guess code) but I don't want to reset "players" and "lives"
players = 10
lives = 5
myGuess = input("What number do you choose")
compGuess = random.randint(1,5)
compGuess = int(compGuess)
print(f"Computer chose {compGuess}")
if compGuess == myGuess:
players = players - compGuess
print(f"You took out {compGuess} players")
print(f"There are {players} players left")
#run guess code
else:
lives -= 1
print(f"You lost a life! You now have {lives} lives remaining")
#run guess
getRandom()
</code></pre>
|
<p>Yeah, I think you should create a mental model first.</p>
<p>What do you want to happen and how do you want it to happen.</p>
<p>If you want to "redo" some stuff, it sounds like a loop, try to create a function that is "self callable" at it's own end with a way of getting out.</p>
<p>If you create a function, you can call it inside itself.</p>
<p>example:</p>
<pre class="lang-py prettyprint-override"><code>def testfunction(value):
a = value
b = 2
c = a + b
testfunction(c)
</code></pre>
<p>But it would be interesting to add some method of getting out of this loop..</p>
|
python|loops
| 1 |
1,903,771 | 63,751,516 |
JavaScript heap out of memory when building react project in python subprocess
|
<p>I want to automate the deployment of a react app on my server. I have a github webhook event that hits a python Flask endpoint where I then run <code>npm run build:stage</code> in a subprocess.</p>
<p><strong>If I run the build command in an ssh login session, it works fine</strong> and the build generates but when the webhook fires and the command is run through the python subprocess, I see the following error:</p>
<p>Python code that executes the command:</p>
<pre><code>p = subprocess.Popen(command,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
</code></pre>
<pre><code>09/05/2020 02:42:59 PM +08 : INFO : Process Output:
> laravel-app@0.1.0 build:stage /home/user/reactapp
> env-cmd -f .env.prod react-scripts build
Creating an optimized production build...
<--- Last few GCs --->
[5541:0x2bc1760] 19190 ms: Scavenge 524.4 (551.5) -> 516.9 (554.2) MB, 10.4 / 0.0 ms (average mu = 0.989, current mu = 0.988) allocation failure
[5541:0x2bc1760] 19217 ms: Scavenge 528.1 (555.1) -> 528.0 (559.4) MB, 16.6 / 0.0 ms (average mu = 0.989, current mu = 0.988) allocation failure
[5541:0x2bc1760] 19432 ms: Scavenge 533.1 (560.0) -> 532.7 (563.7) MB, 209.0 / 0.0 ms (average mu = 0.989, current mu = 0.988) allocation failure
<--- JS stacktrace --->
Cannot get stack trace in GC.
09/05/2020 02:42:59 PM +08 : ERROR : Process Error: FATAL ERROR: Scavenger: semi-space copy Allocation failed - JavaScript heap out of memory
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! laravel-app@0.1.0 build:stage: `env-cmd -f .env.prod react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the laravel-app@0.1.0 build:stage script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/user/.npm/_logs/2020-09-05T06_42_59_795Z-debug.log
</code></pre>
<p>After going through <a href="https://stackoverflow.com/questions/62469659/scavenger-allocation-failed-javascript-heap-out-of-memory">Link 1</a>, <a href="https://stackoverflow.com/a/57924320/1783688">Link 2</a>, <a href="https://stackoverflow.com/a/61263408/1783688">Link 3</a></p>
<p>I added the following to my bashrc<br />
<code>export NODE_OPTIONS=--max_old_space_size=4096 --max-semi-space-size=4096000</code></p>
<p>and updated my build command to:<br />
<code>"build:stage": "env-cmd -f .env.prod react-scripts --max_old_space_size=4096 --max-semi-space-size=4096000 build"</code></p>
<p>The error changed to:</p>
<pre><code>09/05/2020 03:10:16 PM +08 : INFO : Process Output:
> laravel-app@0.1.0 build:stage /home/user/reactapp
> env-cmd -f .env.prod react-scripts --max_old_space_size=4096 --max-semi-space-size=4096000 build
Creating an optimized production build...
<--- Last few GCs --->
[7923:0x2e1d950] 33699 ms: Scavenge 415.5 (451.4) -> 412.5 (535.7) MB, 37.8 / 0.0 ms (average mu = 0.858, current mu = 0.000) allocation failure
[7923:0x2e1d950] 33913 ms: Scavenge 474.0 (542.3) -> 438.2 (546.6) MB, 36.2 / 0.0 ms (average mu = 0.858, current mu = 0.000) allocation failure
[7923:0x2e1d950] 34236 ms: Scavenge 480.8 (549.1) -> 454.3 (567.2) MB, 77.7 / 0.0 ms (average mu = 0.858, current mu = 0.000) allocation failure
<--- JS stacktrace --->
Cannot get stack trace in GC.
09/05/2020 03:10:16 PM +08 : ERROR : Process Error: FATAL ERROR: NewSpace::Rebalance Allocation failed - JavaScript heap out of memory
1: 0x9d8da0 node::Abort() [node]
2: 0x9d9f56 node::OnFatalError(char const*, char const*) [node]
3: 0xb37dbe v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]
4: 0xb38139 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
5: 0xce34f5 [node]
6: 0xd2a8ae [node]
7: 0xd2e627 v8::internal::MarkCompactCollector::CollectGarbage() [node]
8: 0xcef049 v8::internal::Heap::MarkCompact() [node]
9: 0xcefdb3 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [node]
10: 0xcf0925 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
11: 0xcf1fcf v8::internal::Heap::HandleGCRequest() [node]
12: 0xca0fb4 v8::internal::StackGuard::HandleInterrupts() [node]
13: 0xfef887 v8::internal::Runtime_StackGuard(int, unsigned long*, v8::internal::Isolate*) [node]
14: 0x13725d9 [node]
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! laravel-app@0.1.0 build:stage: `env-cmd -f .env.prod react-scripts --max_old_space_size=4096 --max-semi-space-size=4096000 build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the laravel-app@0.1.0 build:stage script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/user/.npm/_logs/2020-09-05T07_10_16_341Z-debug.log
</code></pre>
<pre><code># npm -v
6.12.0
# node -v
v12.13.0
</code></pre>
<p>Server: CentOS Linux release 7.6.1810 (Core)</p>
<p>No clue how to proceed further</p>
<p>UPDATE:</p>
<p>I upgraded my hosting plan to increase the RAM from 4GB to 6GB. Now if I run the python snipper in a python console, the build generates fine but when it runs via the webhook throught flask app, I still see it fail with the above error.</p>
|
<p>I had exactly the same problem running "npm audit fix" via python subprocess.run. I got it fixed via moving this part into a script and executing the shell (bash in my case) with the script from within my Python script.</p>
|
python|node.js|npm|subprocess
| 1 |
1,903,772 | 52,956,384 |
Python3/Django - QuerySet not updating
|
<p>I'm creating a website that allows for the creation of events, and those events will be shown on both the home page, and on the events list, so that people can click on the events on view the descriptions of them, as well as check in at the event. I'm having an issue getting a query set within a class to update when a new event is added.</p>
<p>So this function is for our main home page. The query_set updates every time you go back to the page, so when a new event is added, it is shown on this page. </p>
<pre><code>def index(request):
num_future_events = Event.objects.filter(date__gte=today).filter(approved=True).count()
query_set = Event.objects.filter(date__gte=today).filter(approved=True).order_by('date', 'time')[:3]
context = {
'num_future_events': num_future_events,
'query_set': query_set
}
return render(request, 'index.html', context=context)
</code></pre>
<p>This is a class for the events list page on my site. It uses a query set but since the class is only ever called once, the query set will only update with the class's initialization. </p>
<pre><code>class EventListView(generic.ListView):
model = Event
query_set = Event.objects.filter(date__gte=today).exclude(approved=False).order_by('date', 'time')[:21]
template_name = 'listPage.html'
def get_queryset(self):
return self.query_set
</code></pre>
<p>I was hoping to get some help with making it so when a new event is added, the query set in the EventListView class updates automatically so that it will be displayed on this page.</p>
<p>Any help will be greatly appreciated.</p>
|
<p>If we take a look at <a href="https://ccbv.co.uk/projects/Django/2.0/django.views.generic.list/ListView/#get_queryset" rel="nofollow noreferrer">Django's source code for a <code>ListView</code></a>, we see:</p>
<blockquote><pre><code>def get_queryset(self):
"""
Return the list of items for this view.
The return value must be an iterable and may be an instance of
`QuerySet` in which case `QuerySet` specific behavior will be enabled.
"""
if self.queryset is not None:
queryset = self.queryset
if isinstance(queryset, QuerySet):
<b>queryset = queryset.all()</b>
elif self.model is not None:
queryset = self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset, or override "
"%(cls)s.get_queryset()." % {
'cls': self.__class__.__name__
}
)
ordering = self.get_ordering()
if ordering:
if isinstance(ordering, str):
ordering = (ordering,)
queryset = queryset.order_by(*ordering)
return queryset</code></pre></blockquote>
<p>Django thus each time construct a <em>new</em> queryset, by calling <code>.all()</code> it makes a <em>unevaluated</em> clone of the queryset, such that this is forced to get reevaluated.</p>
<p>In this case, I thus propose that you do <em>not</em> overwrite <code>get_queryset</code>, but simply use the <code>queryset</code> attribute, like:</p>
<pre><code>class EventListView(generic.ListView):
model = Event
<b>queryset</b> = Event.objects.filter(
date__gte=today
).exclude(
approved=False
).order_by('date', 'time')[:21]
template_name = 'listPage.html'</code></pre>
<p>Or if you really want to override the <code>get_queryset</code> function you can use:</p>
<pre><code>class EventListView(generic.ListView):
model = Event
template_name = 'listPage.html'
def get_queryset(self):
return Event.objects.filter(
date__gte=today
).exclude(approved=False).order_by('date', 'time')[:21]</code></pre>
<p>or:</p>
<pre><code>class EventListView(generic.ListView):
model = Event
template_name = 'listPage.html'
query_set = Event.objects.filter(
date__gte=today
).exclude(approved=False).order_by('date', 'time')[:21]
def get_queryset(self):
return self.query_set.all()</code></pre>
|
python|django|django-queryset
| 5 |
1,903,773 | 72,076,003 |
Check for a column in pandas dataframe for all elements if they are in a set of values
|
<p>We have a pandas DataFrame <code>df</code> and a set of values <code>set_vals</code>.</p>
<p>For a particular column (let's say <code>'name'</code>), I would now like to compute a new column which is <code>True</code> whenever the value of <code>df['name']</code> is in <code>set_vals</code> and <code>False</code> otherwise.</p>
<p>One way to do this is to write:</p>
<p><code>df['name'].apply(lambda x : x in set_vals)</code></p>
<p>but when both <code>df</code> and <code>set_vals</code> become large this method is very slow. Is there a more efficient way of creating this new column?</p>
|
<p>The real problem is the complexity of <code>df['name'].apply(lambda x : x in set_vals)</code> is O(M*N) where M is the length of <code>df</code> and N is the length of <code>set_vals</code> if <code>set_vals</code> is a list (or another type for which the search complexity is linear).</p>
<p>The complexity can be improved to O(M) if <code>set_vals</code> is hashed (turned into <code>dict</code> type) and the search complexity will be O(1).</p>
|
python|pandas|dataframe
| 1 |
1,903,774 | 71,953,565 |
Python Web Scraping error - Reading from JSON- IndexError: list index out of range - how do I ignore
|
<p>I am performing web scraping via Python \ Selenium \ Chrome headless driver. I am reading the results from JSON - here is my code:</p>
<pre><code>CustId=500
while (CustId<=510):
print(CustId)
# Part 1: Customer REST call:
urlg = f'https://mywebsite/customerRest/show/?id={CustId}'
driver.get(urlg)
soup = BeautifulSoup(driver.page_source,"lxml")
dict_from_json = json.loads(soup.find("body").text)
# print(dict_from_json)
#try:
CustID = (dict_from_json['customerAddressCreateCommand']['customerId'])
# Addr = (dict_from_json['customerShowCommand']['customerAddressShowCommandSet'][0]['addressDisplayName'])
writefunction()
CustId = CustId+1
</code></pre>
<p>The issue is sometimes 'addressDisplayName' will be present in the result set and sometimes not. If its not, it errors with the error:</p>
<pre><code>IndexError: list index out of range
</code></pre>
<p>Which makes sense, as it doesn't exist. How do I ignore this though - so if 'addressDisplayName' doesn't exist just continue with the loop? I've tried using a TRY but the code still stops executing.</p>
|
<p>If you get an IndexError (with an index of '0') it means that your list is empty. So it is one step in the path earlier (otherwise you'd get a KeyError if 'addressDisplayName' was missing from the dict).</p>
<p>You can check if the list has elements:</p>
<pre><code>if dict_from_json['customerShowCommand']['customerAddressShowCommandSet']:
# get the data
</code></pre>
<p>Otherwise you can indeed use try..except:</p>
<pre><code>try:
# get the data
except IndexError, KeyError:
# handle missing data
</code></pre>
|
python|json|selenium|selenium-webdriver|web-scraping
| 1 |
1,903,775 | 72,096,144 |
Get feature names for best_estimator in GridsearchCV
|
<p>I've tried to use <code>GridsearchCV</code> on a Ridge model, where I use <code>PolynomialFeatures</code> in my preprocessing pipeline. When I have trained/fitted the model I can access the coefficients for the best model via:</p>
<pre><code>pipe = Pipeline(
[
("column_preprocessor", preprocessor),
("estimator", Ridge(max_iter=10000)),
]
)
gridsearch = GridSearchCV(pipe, param_grid, n_jobs=-1)
gridsearch.best_estimator_.named_steps.estimator.coef_
</code></pre>
<p>And this gives an array of values. However, since I have been using <code>PolynomialFeatures</code> I would actually like to know which feature each of these values corresponds to. I've tried something like:</p>
<pre><code>gridsearch.best_estimator_.feature_names_in_
</code></pre>
<p>But this just gives the names of the original data frame, i.e. not with the interaction and polynomial terms.</p>
<p>So, is there any way to get out ALL the features for my best estimator ?</p>
|
<p>scikit-learn preprocessors provide a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html#sklearn.preprocessing.PolynomialFeatures.get_feature_names_out" rel="nofollow noreferrer"><code>get_feature_names_out</code></a> (or <code>get_feature_names</code> in older versions, now deprecated) which returns the names of the generated features in a format like <code>['x0', 'x1', 'x0^2', 'x1^2', 'x0 x1']</code>. Optionally, a list of input names can be passed as argument to use them in returned output names.</p>
<pre><code>gridsearch.best_estimator_.named_steps.column_preprocessor.get_feature_names_out()
</code></pre>
|
python|scikit-learn
| 2 |
1,903,776 | 68,696,549 |
Django: How to automatically generate the USERNAME_FIELD of a custom user model?
|
<p>This is a learning project and I've been trying to create a custom user model with the possibility of having multiple accounts with the same <em>nickname</em>. The <code>USERNAME_FIELD</code> would be <code>username = f"{nickname}#{random_number}"</code> (just like the Blizzard and Discord format), but I can't figure out at which step I should include the function that would automatically create the username.</p>
<p>I tried generating the username in the <code>CustomAccountManager.create_user()</code> method but it doesn't seem to be called while filling the <code>RegistrationForm</code> from the view and it fails to create the superuser with <code>manage.py createsuperuser</code> (<code>TypeError: create_superuser() got an unexpected keyword argument 'username'</code>). I'd be glad if someone could explain how to procede in this case or link a resource, I couldn't find one with this kind of example. Any additional insight on the code will be appreciated.</p>
<p>I have registered the model in admin.py with <code>admin.site.register(Account)</code>, included the accounts app in the settings and set <code>AUTH_USER_MODEL = 'account.Account'</code></p>
<p>account/models.py</p>
<pre><code>from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from random import randint
from django.contrib.auth import get_user_model
### ACCOUNT
class CustomAccountManager(BaseUserManager):
def create_user(self, email, nick, password = None):
if not email:
raise ValueError("Email was not provided during user creation. (account/models.py/CustomAccountManager.create_user)")
if not nick:
raise ValueError("Username was not provided during user creation. (account/models.py/CustomAccountManager.create_user)")
if len(nick) >= 20:
raise ValueError("Username cannot be longer than 20 characters")
user_id = self.generate_id(nick)
user = self.model(
nick = nick,
username = f"{nick}#{user_id}",
user_id = user_id,
email = self.normalize_email(email),
)
user.set_password(password)
user.save(using = self._db)
return user
def create_superuser(self, nick, email, password = None):
user = self.create_user(
email = self.normalize_email(email),
nick = nick,
password = password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using = self._db)
return user
def generate_id(self, nick: str) -> int: # I want this to be a random number
database = []
accounts = self.model.objects.filter(nick = nick)
if len(accounts) > 995:
raise ValueError("Cannot create an account with this username, please choose another one. (account/models.py/CustomAccountManager.generate_id)")
for account in accounts:
database.append(int(getattr(account, "user_id")))
while True:
potential_id = randint(0, 999)
if potential_id not in database:
return potential_id
class Account(AbstractBaseUser):
### PERSONAL INFO
first_name = models.CharField(max_length = 20, blank = True, null = True)
second_name = models.CharField(max_length = 40, blank = True, null = True)
last_name = models.CharField(max_length = 20, blank = True, null = True)
### FUNCTIONAL PERSONAL INFO
email = models.EmailField(max_length = 60) #/#
username = models.CharField(max_length = 25, unique = True) #/# = f"{self.nick}#{self.user_id}"
nick = models.CharField(max_length = 20, default = "")
user_id = models.IntegerField(default = 777)
### FUNCTIONAL DJANGO
USERNAME_FIELD = "username" #/#
REQUIRED_FIELDS = ["email",]
is_active = models.BooleanField(default = True) #/#
is_admin = models.BooleanField(default = False) #/#
is_staff = models.BooleanField(default = False) #/#
is_superuser = models.BooleanField(default = False) #/#
objects = CustomAccountManager()
### LOGS
date_joined = models.DateTimeField(auto_now_add = True) #when account was made
last_login = models.DateTimeField(blank = True, null = True) #/#
rehabilitate = models.DateTimeField(blank = True, null = True) #date when user gets unbanned
banned_amount = models.IntegerField(default = 0) #collective hours banned
banned_times = models.IntegerField(default = 0) #amount of times someone was banned
logins = models.JSONField(default = dict)
logouts = models.JSONField(default = dict)
bans = models.JSONField(default = dict)
unbans = models.JSONField(default = dict)
### PERMISSIONS - REQUIRED
def has_perm(self, perm, obj) -> bool:
return self.is_admin
def has_module_perms(self, app_label) -> bool:
return self.is_admin
</code></pre>
<p>account/views.py:</p>
<pre><code>from django.http.request import HttpRequest
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, get_user_model
from account.forms import RegistrationForm
from account.models import Account
def RegistrationView(request):
context = {}
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
context['registration_form'] = form
elif request.method == 'GET':
form = RegistrationForm()
context['registration_form'] = form
return render(request, 'account/registration.html', context)
</code></pre>
<p>account/forms.py</p>
<pre><code>from django.contrib.auth.forms import UserCreationForm
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from .models import Account
class RegistrationForm(UserCreationForm):
class Meta:
model = Account
fields = ("email", "nick", 'password1', 'password2',
"first_name", "second_name", "last_name")
</code></pre>
|
<p>I have overwritten the <code>save()</code> method in the Account model this way:</p>
<pre><code> def save(self, *args, **kwargs):
if not int(self.user_id):
self.user_id = self.generate_id(self.nick) # moved from CustomAccountManager class
self.username = f"{self.nick}#{self.user_id}"
super().save(*args, **kwargs)
</code></pre>
<p>I'm still not sure this is the best way, but it seems to work.</p>
|
python|django|django-models
| 0 |
1,903,777 | 10,258,509 |
How to use Google application-specific password in script?
|
<p>Since enabling 2-factor authentication (aka. 2-step verification) on Google, my <a href="https://github.com/l0b0/export" rel="nofollow noreferrer">Google export scripts</a> no longer work. The computer is verified and trusted, but somehow the scripts are not. In effect, every time the cron job is run I receive a new "Google verification code" and the script fails. I assume it should be a simple matter to authenticate such scripts once and for all with <code>wget</code> or <code>curl</code>, but I couldn't find any documentation for how to do it.</p>
<hr>
<p>Google authentication schemes have gone through many iterations, and I can no longer seem to log in using <code>curl</code> or <code>mechanicalsoup</code>. I've tried using URLs like <code>https://accounts.google.com/ServiceLogin?continue=https://calendar.google.com/calendar/exporticalzip&Email=username@gmail.com&Passwd=application-specific-password</code>, and I always get redirected to a login page, usually with the message "Please use your account password instead of an application-specific password."</p>
|
<p>Are you absolutely sure that you want to use 2-factor auth with the shell scripts? If so, you don't need to try to get your computer or script as "trusted". You just do the full 2-factor auth every time you run the script.</p>
<p>If the target is to skip the manual second factor auth, I'd suggest using application-specific password instead (as already suggested by other answers). <strong>Just pretend that you're not using 2-factor auth at all</strong> and use your real login name but set password to one generated at <a href="https://accounts.google.com/b/0/IssuedAuthSubTokens?hl=en" rel="noreferrer">https://accounts.google.com/b/0/IssuedAuthSubTokens?hl=en</a> (subpage of <a href="https://www.google.com/settings/security" rel="noreferrer">https://www.google.com/settings/security</a>).</p>
<p>The intent is to set Application-specific password "Name" to a value that is meaningful to you. For example, I have passwords labeled "Pidgin at work", "My Android Phone", "Thunderbird Google Address Book Extension at Work" etc. You could have one for "Calendar and Reader Export Script". If you ever believe that this Application-specific password is compromised ("leaked"), just hit the "Revoke" link on the same page and then generate a new password for your script.</p>
<p>For the code, just use the last version that worked with Google single factor auth. <strong>Update:</strong> because the original question used URL <code>https://accounts.google.com/ServiceLogin</code> for initiating the session login it's practically faking browser login. However, Google does not officially support this and as I'm writing this, it seems that using application specific password for normal login will end up with error message "Please use your account password instead of an application-specific password".</p>
<p>One thing to understand about the Google 2-factor auth and "trusted computer" is that the actual implementation just adds a permanent cookie with 30 days expiry time to your browser. Trusted computer does not mean your IP address were trusted or some other magical connection were created. Unless your scripts capture the "trusted computer" cookie from your browser of choice, it does not matter at all if you've ever marked your computer as trusted. (The Google form should not say "Remember this computer for 30 days" but "Trust this browser and user account combination for 30 days (save permanent cookie)". However, I guess that was considered too technical...)</p>
<p><strong>Update:</strong> (copied from my comment below) The only officially supported method (Server to Server applications) is documented at <a href="https://developers.google.com/accounts/docs/OAuth2ServiceAccount" rel="noreferrer">https://developers.google.com/accounts/docs/OAuth2ServiceAccount</a>. It requires OAuth/JWT encoding the request and using Service Account private key created at <a href="https://code.google.com/apis/console" rel="noreferrer">https://code.google.com/apis/console</a>. As an alternative you could use ClientLogin authentication (already deprecated, best effort service until 2015).</p>
<p>If you decide to go with OAuth, you might want to look at <a href="http://blog.yjl.im/2010/05/bash-oauth.html" rel="noreferrer">http://blog.yjl.im/2010/05/bash-oauth.html</a> and <a href="https://github.com/oxys-net/curl-oauth" rel="noreferrer">https://github.com/oxys-net/curl-oauth</a></p>
|
python|bash|security|google-authentication
| 6 |
1,903,778 | 67,206,004 |
Why do I get an error when I put a question inside an if statement
|
<p>I use Python and I’m a beginner. I keep getting an error with this code:</p>
<pre><code> if(answer == “yes”):
question = input(“What do you like painting?”)
else:
print(“May I suggest sculpting?”)
</code></pre>
|
<p>It would be helpful to see the error to know how to help you. Without seeing the full code two things come to mind.</p>
<ol>
<li><p>is answer defined? In this code the variable "answer" is never defined. If you are hoping to get the input from your question "what do you like painting", that will be returned to the variable "question" once the user inputs it.</p>
</li>
<li><p>Your quotation marks look a bit odd. I'm guessing that is just from how you typed it into stackoverflow, but if not try replacing them with either <code>'</code> or <code>"</code></p>
</li>
</ol>
<p>This works for me:</p>
<pre><code>answer = input("Do you like painting?")
if(answer == "yes"):
question = input("What do you like painting?")
else:
print("May I suggest sculpting?")
</code></pre>
<p>As does this:</p>
<pre><code>if(input("What do you like painting?") == "yes"):
print("May I suggest sculpting?")
</code></pre>
|
python|input|syntax|conditional-statements
| 0 |
1,903,779 | 60,410,707 |
How can I extract the rate of my pandas timeseries data?
|
<p>Consider for example,</p>
<pre><code> Temp Hum WS
DateTime
2019-08-01 00:00:00 35.9615 20.51460 1.287225
2019-08-01 00:20:00 36.5795 21.92870 2.213225
2019-08-01 00:40:00 36.2885 22.62970 2.331175
2019-08-01 01:00:00 36.1095 22.76075 2.532800
</code></pre>
<p>The interval is clearly 20 minutes but is there a function to extract it?
I am writing a script to resample to lower resolution using df.resample(rate).mean()
I want to ensure that we run the script only when rate is larger than the rate of the df. It does not make sense to convert lower resolution data to a higher resolution. In this example, rate of '60T' will be acceptable because it will convert the 20 minute data to hourly data. But, a rate of '10T' should not be acceptable.</p>
|
<p>Try:</p>
<pre><code># if index not datetime object, then
# df.index = pd.to_datetime(df.index)
>>> pd.Series(df.index).diff().mean().components.minutes
20
#or,
>>> pd.Series(df.index).diff().iloc[-1].components.minutes
20
</code></pre>
|
python|pandas|dataframe|time-series|data-cleaning
| 2 |
1,903,780 | 64,390,026 |
I couldn't install discord.py
|
<p>So I was running this command</p>
<pre><code>py -3 -m pip install -U discord.py[voice]
</code></pre>
<p>in PyCharm (using latest version) but it couldn't let me install it. It gave me this exception:</p>
<blockquote>
<p>ERROR: The 'make' utility is missing from PATH</p>
<p>ERROR: Failed building wheel for PyNaCl Failed to build PyNaCl</p>
<p>ERROR: Could not build wheels for PyNaCl which use PEP 517 and cannot be installed directly</p>
</blockquote>
|
<p>if you are in linux run,</p>
<pre><code>sudo pip3 install discord.py[voice] -U
</code></pre>
<p>or if you are on windows run,</p>
<pre><code>pip install discord.py[voice] -U
</code></pre>
|
python|path|pycharm|discord.py|pynacl
| 0 |
1,903,781 | 70,110,424 |
Anyone knows how to create an attribute of a Class which will be a '''set''' of all instances of that class?
|
<p>I know that each instance will inherit that attribute, but I want a <strong>function</strong> or should I call it a <strong>method</strong> of that class to return the set of all instances created of that class.</p>
<p>So let's say I created 3 instances and call a method from the last one that will return all the previously created instances as well as the one that I am calling it from.</p>
<p>I was able to achieve it by making a list, but would it be possible to return a set?</p>
<p>Is there some kind of constructor that I am missing for it?</p>
<pre><code>class Bee():
instances = []
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
def __str__(self):
self.instances.append(f"{self.identifier} {self.name}")
return f"{self.identifier} {self.name}"
def get_hive(self):
return self.instances
</code></pre>
|
<p>Normally you would create <code>Hive</code> as a separate class and put the <code>Bees</code> inside. You then have a clear and explicit data structure whose job includes keeping track of all Bees created.</p>
<p>Something like:</p>
<pre><code>class Hive:
def __init__(self):
self.bees = []
def add_bee(self, bee):
self.bees.append(bee)
class Bee:
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
def __str__(self):
return f"Bee({self.name}, {self.identifier})"
def __repr__(self):
return str(self)
# User code example
hive = Hive()
b1 = Bee('My Bee', 0)
b2 = Bee('Some Other Bee', 1)
hive.add_bee(b1)
hive.add_bee(b2)
print(hive.bees) # display all bees inside the hive
</code></pre>
|
python|class|object|constructor|set
| 0 |
1,903,782 | 11,333,903 |
NLTK Named Entity Recognition with Custom Data
|
<p>I'm trying to extract named entities from my text using NLTK. I find that NLTK NER is not very accurate for my purpose and I want to add some more tags of my own as well. I've been trying to find a way to train my own NER, but I don't seem to be able to find the right resources.
I have a couple of questions regarding NLTK-</p>
<ol>
<li>Can I use my own data to train an Named Entity Recognizer in NLTK?</li>
<li>If I can train using my own data, is the named_entity.py the file to be modified?</li>
<li>Does the input file format have to be in IOB eg. Eric NNP B-PERSON ?</li>
<li>Are there any resources - apart from the nltk cookbook and nlp with python that I can use?</li>
</ol>
<p>I would really appreciate help in this regard</p>
|
<p>Are you committed to using NLTK/Python? I ran into the same problems as you, and had much better results using Stanford's named-entity recognizer: <a href="http://nlp.stanford.edu/software/CRF-NER.shtml" rel="noreferrer">http://nlp.stanford.edu/software/CRF-NER.shtml</a>. The process for training the classifier using your own data is very well-documented in the FAQ. </p>
<p>If you really need to use NLTK, I'd hit up the mailing list for some advice from other users: <a href="http://groups.google.com/group/nltk-users" rel="noreferrer">http://groups.google.com/group/nltk-users</a>. </p>
<p>Hope this helps!</p>
|
python|nlp|nltk|named-entity-recognition
| 24 |
1,903,783 | 10,876,258 |
Python Shelve could not retrieve object
|
<p>I tried to store objects and was able to do it successfully..But I have problems, while treiving it..Error is given below</p>
<p>person.py</p>
<pre><code>class Person:
def __init__(self, name, age, pay=0, job=None):
self.name = name
self.age = age
self.pay = pay
self.job = job
def lastname(self):
return self.name.split()[-1]
def giveraise(self,percent):
#return self.pay *= (1.0 + percent)
self.pay *= (1.0 + percent)
return self.pay
</code></pre>
<p>Manager.py</p>
<pre><code>from Person import Person
class Manager(Person):
def giveRaise(self, percent, bonus=0.1):
self.pay *= (1.0 + percent + bonus)
return self.pay
</code></pre>
<p>update_db_classes.py</p>
<pre><code>import shelve
from Person import Person
from Manager import Manager
bob = Person('Bob Smith', 42, 30000, 'software')
sue = Person('Sue Jones', 45, 40000, 'hardware')
tom = Manager('Tom Doe', 50, 50000)
db = shelve.open('class-shelve')
db['bob'] = bob
db['sue'] = sue
db['tom'] = tom
db.close()
</code></pre>
<p>Code to retrieve the objects..
dump_db_classes.py</p>
<pre><code>import shelve
db = shelve.open('class-shelve')
for key in db:
print(key, '=>\n ', db[key].name, db[key].pay)
bob = db['bob']
print(bob.lastName())
print(db['tom'].lastName())
</code></pre>
<p>Error:
C:\Python27\Basics>dump_db_classes.py
bob =>
Bob Smith 30000
sue =>
Sue Jones 40000
tom =>
Tom Doe 50000
Traceback (most recent call last):
File "C:\Python27\Basics\dump_db_classes.py", line 8, in
print(bob.lastName())
AttributeError: 'Person' object has no attribute 'lastName'</p>
|
<p>Python is case-sensitive. You call <code>bob.lastName()</code> but the <code>Person</code> method is <code>.lastname()</code>. The error message is trying to tell you this:</p>
<pre><code>AttributeError: 'Person' object has no attribute 'lastName'
</code></pre>
|
python
| 1 |
1,903,784 | 70,591,437 |
Json response error when yielding with Scrapy
|
<p>I'm trying to yield some data from the response of a webpage, so that I know that I have implemented the code correctly. Unfortunately, this is not the case as I'm getting the following error:</p>
<blockquote>
<p>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)</p>
</blockquote>
<p>I know this appears in the function <code>parse</code> when I'm trying to get a response from the data. However, I cannot understand why it won't work.</p>
<p>Here's my script:</p>
<pre><code>import scrapy
from scrapy_splash import SplashFormRequest
headers = {
'authority': 'www.etsy.com',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
'x-csrf-token': '3:1641383062:Exn8HMFDcc0UtitU6NOM3o3x8BGB:864dc90d926383d90686f37be56f69685b939f0f306b10a99bcd9016209f15d4',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'accept': '*/*',
'x-requested-with': 'XMLHttpRequest',
'x-page-guid': 'eeda48b359a.aa23cce28f31baac6f24.00',
'x-detected-locale': 'GBP|en-GB|GB',
'sec-ch-ua-platform': '"Linux"',
'origin': 'https://www.etsy.com',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://www.etsy.com/search/clothing/womens-clothing?q=20s&explicit=1&ship_to=GB&page=2&ref=pagination',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'cookie': 'uaid=G-_aWcvXqYHevnNO3ane9nOUmwNjZACCxCuVe2B0tVJpYmaKkpVSaVpUSoBZaGZVQL6Lj4mRv7ObrmmRR3F-aLyHp1ItAwA.; user_prefs=bNwL2wOEkWxqOSu2A1-CWlR6cr9jZACCxCuVe2B0tJK7U4CSTl5pTo6OUmqerruTko4SiACLGEEoXEQsAwA.; fve=1641314748.0; utm_lps=google__cpc; ua=531227642bc86f3b5fd7103a0c0b4fd6; p=eyJnZHByX3RwIjoxLCJnZHByX3AiOjF9; _gcl_au=1.1.1757627174.1641314793; _gid=GA1.2.1898390797.1641314793; __adal_cw=1641314793715; _pin_unauth=dWlkPVltVmtZemxoTldNdFpURXdPQzAwWkRWbUxXRTJOV1l0TTJGaE9URXdZVEEwTlRBeQ; last_browse_page=https%3A%2F%2Fwww.etsy.com%2Fuk%2F; __adal_ses=*; __adal_ca=so%3DGoogle%26me%3Dorganic%26ca%3D%28not%2520set%29%26co%3D%28not%2520set%29%26ke%3D%28not%2520set%29; search_options={"prev_search_term":"20s","item_language":null,"language_carousel":null}; _ga=GA1.2.559839679.1641314793; tsd=%7B%7D; __adal_id=952d43d7-5b80-4907-99d7-6f6baa9f4fe1.1641314794.3.1641383063.1641383059.2fe7a338-93bd-441f-b295-80549adbef7b; _tq_id.TV-27270909-1.a4d5=e2f6af8c27dee5e4.1641314794.0.1641383063..; _uetsid=dff577e06d7d11ec9617cbf4cc51b5b2; _uetvid=dff5f2706d7d11ec932fd3c5b816ab20; granify.uuid=bfd14e46-e8fa-4e7b-bce7-6f05dcb4b215; pla_spr=1; _ga_KR3J610VYM=GS1.1.1641383058.3.1.1641383118.60; exp_hangover=qk2fpkLi1lphuLsCKeq4gAe9BvxjZACCxCuVe8D01Zbb1UrlqUnxiUUlmWmZyZmJOfE5iSWpecmV8YUm8UYGhpZKVkqZeak5memZSTmpSrUMAA..; granify.session.QrsCf=-1',
}
class EtsySpider(scrapy.Spider):
name = 'etit'
start_urls = ['https://www.etsy.com/api/v3/ajax/bespoke/member/neu/specs/async_search_results']
custom_settings = {
'USER_AGENT':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'
}
def start_requests(self):
for url in self.start_urls:
yield SplashFormRequest(
url,
method = "POST",
formdata = {
'log_performance_metrics': 'true',
'specs[async_search_results][]': 'Search2_ApiSpecs_WebSearch',
'specs[async_search_results][1][search_request_params][detected_locale][language]': 'en-GB',
'specs[async_search_results][1][search_request_params][detected_locale][currency_code]': 'GBP',
'specs[async_search_results][1][search_request_params][detected_locale][region]': 'GB',
'specs[async_search_results][1][search_request_params][locale][language]': 'en-GB',
'specs[async_search_results][1][search_request_params][locale][currency_code]': 'GBP',
'specs[async_search_results][1][search_request_params][locale][region]': 'GB',
'specs[async_search_results][1][search_request_params][name_map][query]': 'q',
'specs[async_search_results][1][search_request_params][name_map][query_type]': 'qt',
'specs[async_search_results][1][search_request_params][name_map][results_per_page]': 'result_count',
'specs[async_search_results][1][search_request_params][name_map][min_price]': 'min',
'specs[async_search_results][1][search_request_params][name_map][max_price]': 'max',
'specs[async_search_results][1][search_request_params][parameters][q]': '30s',
'specs[async_search_results][1][search_request_params][parameters][explicit]': '1',
'specs[async_search_results][1][search_request_params][parameters][locationQuery]': '2635167',
'specs[async_search_results][1][search_request_params][parameters][ship_to]': 'GB',
'specs[async_search_results][1][search_request_params][parameters][page]': '4',
'specs[async_search_results][1][search_request_params][parameters][ref]': 'pagination',
'specs[async_search_results][1][search_request_params][parameters][facet]': 'clothing/womens-clothing',
'specs[async_search_results][1][search_request_params][parameters][referrer]': 'https://www.etsy.com/search/clothing/womens-clothing?q=30s&explicit=1locationQuery=2635167&ship_to=GB&page=3&ref=pagination',
'specs[async_search_results][1][search_request_params][user_id]': '',
'specs[async_search_results][1][request_type]': 'pagination_preact',
'specs[async_search_results][1][is_eligible_for_spa_reformulations]': 'false',
'view_data_event_name': 'search_async_pagination_specview_rendered'
},
headers=headers,
callback = self.parse
)
def parse(self, response):
stuff = response.json().get('cssFiles')
yield {
'stuff':stuff
}
</code></pre>
<p>I have tried with requests, and it works:</p>
<pre><code>import requests
headers = {
'authority': 'www.etsy.com',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
'x-csrf-token': '3:1641383062:Exn8HMFDcc0UtitU6NOM3o3x8BGB:864dc90d926383d90686f37be56f69685b939f0f306b10a99bcd9016209f15d4',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'accept': '*/*',
'x-requested-with': 'XMLHttpRequest',
'x-page-guid': 'eeda48b359a.aa23cce28f31baac6f24.00',
'x-detected-locale': 'GBP|en-GB|GB',
'sec-ch-ua-platform': '"Linux"',
'origin': 'https://www.etsy.com',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://www.etsy.com/search/clothing/womens-clothing?q=20s&explicit=1&ship_to=GB&page=2&ref=pagination',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'cookie': 'uaid=G-_aWcvXqYHevnNO3ane9nOUmwNjZACCxCuVe2B0tVJpYmaKkpVSaVpUSoBZaGZVQL6Lj4mRv7ObrmmRR3F-aLyHp1ItAwA.; user_prefs=bNwL2wOEkWxqOSu2A1-CWlR6cr9jZACCxCuVe2B0tJK7U4CSTl5pTo6OUmqerruTko4SiACLGEEoXEQsAwA.; fve=1641314748.0; utm_lps=google__cpc; ua=531227642bc86f3b5fd7103a0c0b4fd6; p=eyJnZHByX3RwIjoxLCJnZHByX3AiOjF9; _gcl_au=1.1.1757627174.1641314793; _gid=GA1.2.1898390797.1641314793; __adal_cw=1641314793715; _pin_unauth=dWlkPVltVmtZemxoTldNdFpURXdPQzAwWkRWbUxXRTJOV1l0TTJGaE9URXdZVEEwTlRBeQ; last_browse_page=https%3A%2F%2Fwww.etsy.com%2Fuk%2F; __adal_ses=*; __adal_ca=so%3DGoogle%26me%3Dorganic%26ca%3D%28not%2520set%29%26co%3D%28not%2520set%29%26ke%3D%28not%2520set%29; search_options={"prev_search_term":"20s","item_language":null,"language_carousel":null}; _ga=GA1.2.559839679.1641314793; tsd=%7B%7D; __adal_id=952d43d7-5b80-4907-99d7-6f6baa9f4fe1.1641314794.3.1641383063.1641383059.2fe7a338-93bd-441f-b295-80549adbef7b; _tq_id.TV-27270909-1.a4d5=e2f6af8c27dee5e4.1641314794.0.1641383063..; _uetsid=dff577e06d7d11ec9617cbf4cc51b5b2; _uetvid=dff5f2706d7d11ec932fd3c5b816ab20; granify.uuid=bfd14e46-e8fa-4e7b-bce7-6f05dcb4b215; pla_spr=1; _ga_KR3J610VYM=GS1.1.1641383058.3.1.1641383118.60; exp_hangover=qk2fpkLi1lphuLsCKeq4gAe9BvxjZACCxCuVe8D01Zbb1UrlqUnxiUUlmWmZyZmJOfE5iSWpecmV8YUm8UYGhpZKVkqZeak5memZSTmpSrUMAA..; granify.session.QrsCf=-1',
}
data = {
'log_performance_metrics': 'true',
'specs[async_search_results][]': 'Search2_ApiSpecs_WebSearch',
'specs[async_search_results][1][search_request_params][detected_locale][language]': 'en-GB',
'specs[async_search_results][1][search_request_params][detected_locale][currency_code]': 'GBP',
'specs[async_search_results][1][search_request_params][detected_locale][region]': 'GB',
'specs[async_search_results][1][search_request_params][locale][language]': 'en-GB',
'specs[async_search_results][1][search_request_params][locale][currency_code]': 'GBP',
'specs[async_search_results][1][search_request_params][locale][region]': 'GB',
'specs[async_search_results][1][search_request_params][name_map][query]': 'q',
'specs[async_search_results][1][search_request_params][name_map][query_type]': 'qt',
'specs[async_search_results][1][search_request_params][name_map][results_per_page]': 'result_count',
'specs[async_search_results][1][search_request_params][name_map][min_price]': 'min',
'specs[async_search_results][1][search_request_params][name_map][max_price]': 'max',
'specs[async_search_results][1][search_request_params][parameters][q]': '20s',
'specs[async_search_results][1][search_request_params][parameters][explicit]': '1',
'specs[async_search_results][1][search_request_params][parameters][ship_to]': 'GB',
'specs[async_search_results][1][search_request_params][parameters][page]': '2',
'specs[async_search_results][1][search_request_params][parameters][ref]': 'pagination',
'specs[async_search_results][1][search_request_params][parameters][facet]': 'clothing/womens-clothing',
'specs[async_search_results][1][search_request_params][parameters][referrer]': 'https://www.etsy.com/search/clothing/womens-clothing?q=20s&explicit=1&ship_to=GB',
'specs[async_search_results][1][search_request_params][user_id]': '',
'specs[async_search_results][1][request_type]': 'pagination_preact',
'specs[async_search_results][1][is_eligible_for_spa_reformulations]': 'false',
'view_data_event_name': 'search_async_pagination_specview_rendered'
}
requests.post('https://www.etsy.com/api/v3/ajax/bespoke/member/neu/specs/async_search_results', headers=headers, data=data)
#<Response [200]>
</code></pre>
|
<p>we need to use <code>cookies</code> to get required data, instead of using it in headers we need to move them into <code>cookies</code></p>
<pre class="lang-py prettyprint-override"><code> def start_requests(self):
headers = {
'authority': 'www.etsy.com',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
'x-csrf-token': '3:1641390466:3d9EJ5Y1lwN6z_d3nn2qROS-IK6z:476df27e75d2b310bb79d565bbb3fa66b6c6d1ec26c137e6b98a8265a8447b4c',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'accept': '*/*',
'x-requested-with': 'XMLHttpRequest',
'x-page-guid': 'eeda8f50e2a.c5a8a0ae59e2ab4a8635.00',
'x-detected-locale': 'USD|en-US|UA',
'sec-ch-ua-platform': '"Windows"',
'origin': 'https://www.etsy.com',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://www.etsy.com/search/clothing/womens-clothing?q=20s&explicit=1&ship_to=GB&page=3&ref=pagination',
'accept-language': 'en-US,en;q=0.9,ru-RU;q=0.8,ru;q=0.7,uk;q=0.6,en-GB;q=0.5',
# 'cookie': 'user_prefs=2sjEL59UUglDjNIW6TKc04MvLTVjZACCxJMbvsPoaKXQYBclnbzSnBwdpdQ83dBgJR2lUEeoiBGEwkXEMgAA; fve=1640607991.0; ua=531227642bc86f3b5fd7103a0c0b4fd6; _gcl_au=1.1.717562651.1640607992; uaid=E7bYwrWVwTy7YGe_b_ipYT3Avd9jZACCxJMbvoPpqwvzqpVKEzNTlKyUnLJ9Io3DTQt1k53MwiojXTLzvZPCS31yCoPC_JRqGQA.; pla_spr=0; _gid=GA1.2.1425785976.1641390447; _dc_gtm_UA-2409779-1=1; _pin_unauth=dWlkPU0yVTRaamxoTWpjdFlqTTVZUzAwT0RJeExXRmpNamt0WlROalpXTTVNREE0WkRVNQ; _ga=GA1.1.1730759327.1640607993; _uetsid=052ece906e2e11ecb56a0390ed629376; _uetvid=39de7550671011ec80d2dbfaa05c901b; exp_hangover=pB4zSokzfzMIT9Jzi7zIwmXybCJjZACCxJMbvoPpqwt7qpXKU5PiE4tKMtMykzMTc-JzEktS85Ir4wtN4o0MDC2VrJQy81JzMtMzk3JSlWoZAA..; _ga_KR3J610VYM=GS1.1.1641390446.2.1.1641390474.32',
}
data = {
'log_performance_metrics': 'true',
'specs[async_search_results][]': 'Search2_ApiSpecs_WebSearch',
'specs[async_search_results][1][search_request_params][detected_locale][language]': 'en-US',
'specs[async_search_results][1][search_request_params][detected_locale][currency_code]': 'USD',
'specs[async_search_results][1][search_request_params][detected_locale][region]': 'UA',
'specs[async_search_results][1][search_request_params][locale][language]': 'en-US',
'specs[async_search_results][1][search_request_params][locale][currency_code]': 'USD',
'specs[async_search_results][1][search_request_params][locale][region]': 'UA',
'specs[async_search_results][1][search_request_params][name_map][query]': 'q',
'specs[async_search_results][1][search_request_params][name_map][query_type]': 'qt',
'specs[async_search_results][1][search_request_params][name_map][results_per_page]': 'result_count',
'specs[async_search_results][1][search_request_params][name_map][min_price]': 'min',
'specs[async_search_results][1][search_request_params][name_map][max_price]': 'max',
'specs[async_search_results][1][search_request_params][parameters][q]': '20s',
'specs[async_search_results][1][search_request_params][parameters][explicit]': '1',
'specs[async_search_results][1][search_request_params][parameters][ship_to]': 'GB',
'specs[async_search_results][1][search_request_params][parameters][page]': '3',
'specs[async_search_results][1][search_request_params][parameters][ref]': 'pagination',
'specs[async_search_results][1][search_request_params][parameters][facet]': 'clothing/womens-clothing',
'specs[async_search_results][1][search_request_params][parameters][referrer]': 'https://www.etsy.com/search/clothing/womens-clothing?q=20s&explicit=1&ship_to=GB&page=2&ref=pagination',
'specs[async_search_results][1][search_request_params][user_id]': '',
'specs[async_search_results][1][request_type]': 'pagination_preact',
'specs[async_search_results][1][is_eligible_for_spa_reformulations]': 'true',
'view_data_event_name': 'search_async_pagination_specview_rendered'
}
cookies = {
"user_prefs": "2sjEL59UUglDjNIW6TKc04MvLTVjZACCxJMbvsPoaKXQYBclnbzSnBwdpdQ83dBgJR2lUEeoiBGEwkXEMgAA",
"fve": "1640607991.0",
"ua": "531227642bc86f3b5fd7103a0c0b4fd6",
"_gcl_au": "1.1.717562651.1640607992",
"uaid": "E7bYwrWVwTy7YGe_b_ipYT3Avd9jZACCxJMbvoPpqwvzqpVKEzNTlKyUnLJ9Io3DTQt1k53MwiojXTLzvZPCS31yCoPC_JRqGQA.",
"pla_spr": "0",
"_gid": "GA1.2.1425785976.1641390447",
"_dc_gtm_UA-2409779-1": "1",
"_pin_unauth": "dWlkPU0yVTRaamxoTWpjdFlqTTVZUzAwT0RJeExXRmpNamt0WlROalpXTTVNREE0WkRVNQ",
"_ga": "GA1.1.1730759327.1640607993",
"_uetsid": "052ece906e2e11ecb56a0390ed629376",
"_uetvid": "39de7550671011ec80d2dbfaa05c901b",
"exp_hangover": "pB4zSokzfzMIT9Jzi7zIwmXybCJjZACCxJMbvoPpqwt7qpXKU5PiE4tKMtMykzMTc-JzEktS85Ir4wtN4o0MDC2VrJQy81JzMtMzk3JSlWoZAA..",
"_ga_KR3J610VYM": "GS1.1.1641390446.2.1.1641390474.32"
}
for url in self.start_urls:
yield scrapy.FormRequest(
'https://www.etsy.com/api/v3/ajax/bespoke/member/neu/specs/async_search_results',
headers=headers,
cookies=cookies,
method="POST",
formdata=data,
callback = self.parse_res
)
</code></pre>
|
python|json|scrapy
| 1 |
1,903,785 | 63,639,247 |
iterating over a set and list simultaneously using single for loop, how does it work?
|
<p>here is a piece of code, print(B) gives set([0, 2, 3, 4, 5, 6]) which i am unable to understand.</p>
<pre><code>M=[2,2,0,5,3,5,7,4]
A=set(range(len(M)))
B=set(M[i] for i in A)
print(B)
</code></pre>
|
<p>No iteration over a set and list is being done simultaneously, rather a set is being created with the len of a list <code>M</code>, later another set is created using the previous ones element as <code>indices</code> to the original list <code>M</code>:</p>
<pre><code>M=[2,2,0,5,3,5,7,4]
print(len(M)) # prints 8 as the len of M
A=set(range(len(M)))
print(A) # prints a unique set with the len(M) i.e. 8 > range 0-7, {0,1,2,3,4,5,6,7}
B=set(M[i] for i in A)
print(B) # prints the unique set using elements of A as index in the M list, i.e. {0, 2, 3, 4, 5, 7}
</code></pre>
|
python-3.x|list|algorithm|for-loop|set
| 1 |
1,903,786 | 56,847,015 |
Cannot import name 'imread', 'imresize', 'imsave' anaconda (windows)
|
<p>I am trying to import image to python but end up getting the same error again and again.</p>
<p>I have tried most of the solutions mentioned about this problem on multiple discussion threads but none of them have solved this issue of mine.
I have installed Pillow but still the error prevails. Would really appreciate some guidance on how to resolve this issue.</p>
<pre><code>from scipy.misc import imread, imresize, imsave
import numpy as np
</code></pre>
<pre><code>ImportError Traceback (most recent call last)
<ipython-input-6-c8bc16b68368> in <module>
----> 1 from scipy.misc import imread, imresize, imsave
2 import numpy as np
ImportError: cannot import name 'imread'
</code></pre>
|
<p>The library you're looking scipy.misc.imread is deprecated. You can use imageio. First install Pillow and then install imageio</p>
<pre><code>pip install Pillow imageio
</code></pre>
<p>Then you can use,</p>
<pre><code>imageio.imread('image1.png')
imageio.imread('image2.png', array)
</code></pre>
<p>But you cannot resize in imageio. Use numpy for that.</p>
|
python|windows|jupyter-notebook|anaconda|python-imaging-library
| 3 |
1,903,787 | 17,707,002 |
Understanding Python 3 lists printing None value for each element
|
<p>As a very noob with in Python I'm printing all elements of a list in version 3, and after a comprehensive research I couldn't find an explanation for this kind of behavior. </p>
<p>However, I know every function must return some value and when it's not defined the function returns "Null" (or "None" in Python). But why in this case, after printing all elements correctly it prints "None" for each element in another list?</p>
<pre><code>>>> a_list = [1,2]
>>> a_list
[1, 2]
>>> [print(f) for f in a_list]
1
2
[None, None]
</code></pre>
|
<p><code>None</code> is the return value of the <code>print</code> function.</p>
<p>Don't use <code>[print(f) for f in a_list]</code> when you mean <code>for f in a_list: print(f)</code>.</p>
|
python|python-3.x|list
| 5 |
1,903,788 | 61,042,353 |
NMAP nse script using python3
|
<p>How will i pass the nse to the command?</p>
<p>import os
domain = "example.com"
nse = ["vulscan","vulners","xmpp-brute","xmpp-info","xmlrpc-methods","xdmcp-discover","unusual-port"]
os.system("nmap -v --script= nse " + domain)</p>
|
<p>There are a few choices:</p>
<pre><code>import os
domain = "example.com"
nse = ["vulscan","vulners","xmpp-brute","xmpp-info","xmlrpc-methods","xdmcp-discover","unusual-port"]
for each_script in nse:
os.system("nmap -v --script={} {}".format(each_script, domain)
</code></pre>
<p>But using <code>os.system</code> the command isn't cleaned. (Tip: read more on 'os' and 'sys' modules)</p>
<p>An safer alternative would be <code>subprocess</code>:
Sample:</p>
<pre><code>import subprocess
subprocess.call('nmap', '-sS', 'example.com')
</code></pre>
<p>However, the best approach I would say, is to use the nmap library from Python.
Example:</p>
<pre><code>import nmap #OR nmap3
nm=nmap.PortScanner()
nm.scan('example.com', '445',
arguments='--script=/usr/local/share/nmap/scripts/smb-os-discovery.nse')
</code></pre>
<p>Starting point <a href="https://pypi.org/project/python3-nmap/" rel="nofollow noreferrer">here</a>.</p>
|
python-3.x|nmap
| 0 |
1,903,789 | 61,046,613 |
Matplotlib variable frequency y-axis scale
|
<p>Does anyone know how to alter the y-axis scale of matplotlib figures to have different spacing and different steps between yticks.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
x_data = np.arange(0, 1000, 10)
y_data = np.random.rand(100)
fig, ax = plt.subplots(figsize=(7,2))
plt.plot(x_data,y_data, color='black', linewidth=1)
plt.scatter(x_data,y_data, marker='o', facecolors='none', edgecolors='black', linewidth=1, s=20)
rect = patches.Rectangle((450,0), 100, 14,facecolor='blue', zorder=3)
ax.add_patch(rect)
ax.set_ylim(0,20)
ax.minorticks_on()
ax.yaxis.grid(True, linestyle='-', which='major', linewidth='0.75', alpha=.9)
ax.yaxis.grid(True, linestyle='--', which='minor', linewidth='0.75', alpha=0.6)
plt.show()
</code></pre>
<p>This creates a figure as such:</p>
<p><a href="https://i.stack.imgur.com/axJm0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/axJm0.png" alt="enter image description here"></a></p>
<p>However, I am trying to alter the y-axis to be something like this (below) so that I can better visualize the distribution of the line graph, but can still showcase the height of the rectangle. </p>
<p><a href="https://i.stack.imgur.com/K90xR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K90xR.png" alt="enter image description here"></a></p>
<p>I am trying to have the first tick spacing (0 to 0.1) be the same spacing as the next tick distance (0.1 to 1), a larger gap between 1 to 5, and then reduced spacing for ticks past 5.</p>
|
<p>No sure of the etiquette for answering my own question, but wanted to post this in case others were interested. </p>
<p>Turns out all I needed was a x<sup>1/2</sup> function as was provided in an example here <a href="https://matplotlib.org/3.1.1/gallery/scales/scales.html#sphx-glr-gallery-scales-scales-py" rel="nofollow noreferrer">https://matplotlib.org/3.1.1/gallery/scales/scales.html#sphx-glr-gallery-scales-scales-py</a> </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
x_data = np.arange(0, 1000, 10)
y_data = np.random.rand(100)
fig, ax = plt.subplots(figsize=(7,2))
plt.plot(x_data,y_data, color='black', linewidth=1)
plt.scatter(x_data,y_data, marker='o', facecolors='none', edgecolors='black', linewidth=1, s=20)
rect = patches.Rectangle((450,0), 100, 14,facecolor='blue', zorder=3)
ax.add_patch(rect)
ax.set_ylim(0,20)
ax.minorticks_on()
ax.yaxis.grid(True, linestyle='-', which='major', linewidth='0.75', alpha=.9)
ax.yaxis.grid(True, linestyle='--', which='minor', linewidth='0.75', alpha=0.6)
def forward(x):
return x**(1/2)
def inverse(x):
return x**2
ax.set_yscale('function', functions=(forward, inverse))
ax.set_yticks([0,0.1,1,5,10,15,20])
ax.yaxis.set_minor_locator(plt.MultipleLocator(2.5))
plt.show()
</code></pre>
<p>Which produces:</p>
<p><a href="https://i.stack.imgur.com/ZymzZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZymzZ.png" alt="enter image description here"></a></p>
|
python-3.x|matplotlib
| 3 |
1,903,790 | 66,022,443 |
How can I make an android application using Pydroid 3?
|
<p>Good day, I'm a beginner and I made this program with my android phone using Pydroid 3. I wanted to ask how can I make it into an android application ? Thank you in advance.</p>
<pre><code>print("This program calculates the residential electricity bill in leyeco V per day, month and year.")
sum = 0
n = 2
for E in range(0,n):
P_string = input("Enter the powerr consumption in ilowattsss): ")
P = float(P_string)
T_string = input("Enter the hourss of usage per day: ")
T = float(T_string)
C = 6.8753
E = P*T*C
E1 = E*30
E2 = E1*12
print("The appliance has "+str(E)+" electricity cost per day in pesos.")
print("The appliance has "+str(E1)+" electricity cost per month in pesos.")
print("The appliance has "+str(E2)+" electricity cost per year in pesos.")
sum = sum+E
E3 = sum*30
E4 = E3*12
print("The total power consumption cost "+str(sum)+" cost per day in pesos.")
print("The total power consumption cost "+str(E3)+" cost per month in pesos.")
print("The total power consumption cost "+str(E4)+" cost per year in pesos.")
</code></pre>
|
<p>You mean create an app directly from your phone ? If yes, I don't know if it possible.</p>
<p>Even if possible, it is not the easy way. You can use kivy and buildozer packages on a PC instead : <a href="https://realpython.com/mobile-app-kivy-python/" rel="nofollow noreferrer">https://realpython.com/mobile-app-kivy-python/</a></p>
|
python
| 0 |
1,903,791 | 66,001,276 |
delete specific files with extention in bulk with user input
|
<p>I need to delete files with a specific extension but IT HAS TO TAKE THE USERS INPUT and the script I have does that but it does it one by one but not in bulk and I have honestly been very confused on how to complete this can I get some help on this please I have been struggling, the script below I appreciate all help:</p>
<pre><code>for root, dirnames, filenames in os.walk('path'):
for xml in filenames:
if xml.lower().endswith('.xml'):
if input('remove exisiting xml files? y/n: ') == "y":
os.remove(os.path.join(root, XML))
print('the file has been deleted succesfully')
else:
print('the file has not been deleted')
</code></pre>
|
<p>It sounds like you want to ask for user input right at the beginning:</p>
<pre><code>if input('remove exisiting xml files? y/n: ') == "y":
for root, dirnames, filenames in os.walk('path'):
for xml in filenames:
if xml.lower().endswith('.xml'):
os.remove(os.path.join(root, xml)) # notice the lowercase variable name. Python is case-sensitive
else:
print('the file has not been deleted')
</code></pre>
|
python|python-3.x
| 0 |
1,903,792 | 66,298,575 |
Connect face recognition model to database efficiently
|
<p>I'm having a hard time connecting my facial recognition system (realtime) to the database.</p>
<p>I am using python language here. Try to imagine, when the system is doing REAL-TIME face detection and recognition, it will certainly form frame by frame during the process (looping logic), and I want if that face is recognized then the system will write 'known face' in the database. But this is the problem, because what if the upload to the database is done repeatedly because the same frame is continuously formed?</p>
<p>the question is, how do you make the system only upload 1 data to the database and if the other frames have the same image, the system doesn't need to upload data to the database?</p>
|
<p>you dont show any code, but to do what you're asking you want to have a flag that detects when a face is found and sets the variable. Then clear the variable once the flag leaves the frame. to account for false positives you can wait 4-5 frames before clear the flags and see if the face is still in the frame (i.e someone turns their head and the tracking looses the face)</p>
|
python|face-recognition|yolo
| 0 |
1,903,793 | 66,213,843 |
Listing folder content from google drive, returns removed files too
|
<p>I use below function to get folder content (files list) from google drive (API V3):</p>
<pre><code>def get_gdrive_content(folder_id):
ret_val = []
page_token = None
while True:
response = service.files().list(q=f"parents = '{folder_id}'",
fields='nextPageToken, files(id, name, mimeType)',
pageToken=page_token
).execute()
for file in response.get('files', []):
ret_inner = {'file_name': file.get('name'), 'mime_type': file.get('mimeType'), 'file_id': file.get('id')}
ret_val.append(ret_inner)
page_token = response.get('nextPageToken', None)
if page_token is None:
break
return ret_val
</code></pre>
<p>This works and I get files list, just with one problem: if I remove file on google drive, this function still returns that removed file(s).</p>
<p>May be there is some timeout on Gdrive for removed files? I just can't found about this: <a href="https://developers.google.com/drive/api/v3/search-files" rel="nofollow noreferrer">here</a></p>
<p>I didn't searched good enough in docs? or I have something wrong in code?
Any help very appreciated!</p>
|
<p>According to the documentation, you might want to add and <code>thrashed = false</code> to your query:</p>
<pre><code>def get_gdrive_content(folder_id):
ret_val = []
page_token = None
while True:
response = service.files().list(
q=f"parents = '{folder_id}' and thrashed = false",
fields='nextPageToken, files(id, name, mimeType)',
pageToken=page_token
).execute()
for file in response.get('files', []):
ret_inner = {
'file_name': file.get('name'),
'mime_type': file.get('mimeType'),
'file_id': file.get('id')
}
ret_val.append(ret_inner)
page_token = response.get('nextPageToken', None)
if page_token is None:
break
return ret_val
</code></pre>
|
python|python-3.x|google-drive-api
| 3 |
1,903,794 | 72,814,996 |
ImportError : No module named ryu.cmd.manager
|
<p>I wanted to try the command: pythonpath=. ./bin/ryu-manager ryu/app/simple_switch.py in ryu controller and this is the error message i got :</p>
<pre><code> Traceback (most recent call last):
File "./bin/ryu-manager", line 18, in <module>
from ryu.cmd.manager import main
ImportError: No module named ryu.cmd.manager
</code></pre>
<p>I am using Ubuntu 18.04.4 LTS, python 2.7.17 and ryu 4.34</p>
|
<p>I don't know if this will help, I am new to this too.
try running not using python, but run ryu-manager command directly.</p>
<p>Like:
May Be you are running like this</p>
<pre><code>~/ryu/$ python ryu-manager ryu/app/simple_switch.py
</code></pre>
<p><strong>But try running ryu-manager directly like this:</strong></p>
<pre><code>~/ryu/$ ryu-manager ryu/app/simple_switch.py
</code></pre>
|
python|import|controller|sdn|ryu
| 0 |
1,903,795 | 68,256,701 |
How can i fix Pandas DataReader Errors
|
<p>I'm trying to learn how to make a python finance app. I tried to code an app that shows me data about a stock but I got errors.
This is my code:</p>
<pre><code>import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
style.use('ggplot')
start = dt.datetime(2000,1,1)
end = dt.datetime(2021,1,1)
df = web.DataReader('TSLA', 'yahoo', start, end)
print(df.head())
</code></pre>
<p>and these are the errors I get:</p>
<pre><code>File "D:/StocksBot/main.py", line 9, in <module>
df = web.DataReader('TSLA', 'yahoo', start, end)
File "D:\StocksBot\venv\lib\site-packages\pandas\util\_decorators.py", line 207, in wrapper
return func(*args, **kwargs)
File "D:\StocksBot\venv\lib\site-packages\pandas_datareader\data.py", line 376, in DataReader
return YahooDailyReader(
File "D:\StocksBot\venv\lib\site-packages\pandas_datareader\base.py", line 253, in read
df = self._read_one_data(self.url, params=self._get_params(self.symbols))
File "D:\StocksBot\venv\lib\site-packages\pandas_datareader\yahoo\daily.py", line 153, in _read_one_data
resp = self._get_response(url, params=params)
File "D:\StocksBot\venv\lib\site-packages\pandas_datareader\base.py", line 181, in _get_response
raise RemoteDataError(msg)
pandas_datareader._utils.RemoteDataError: Unable to read URL: https://finance.yahoo.com/quote/TSLA/history?period1=946692000&period2=1609552799&interval=1d&frequency=1d&filter=history
</code></pre>
|
<p>I got the same error message when running your code, and I checked that with curl it is possible to get that page, so the Yahoo service is ok.</p>
<p>I have this alternative code that works for me:</p>
<pre><code>import pandas as pd
import datetime as dt
import pandas_datareader.data as web
import yfinance as yf
yf.pdr_override()
start = dt.datetime(2020,1,1)
end = dt.datetime(2021,1,1)
df = web.get_data_yahoo('TSLA', start, end)
print(df.head())
</code></pre>
<p>This outputs the following:</p>
<pre><code>[*********************100%***********************] 1 of 1 completed
Open High Low Close Adj Close Volume
Date
2019-12-31 81.000000 84.258003 80.416000 83.666000 83.666000 51428500
2020-01-02 84.900002 86.139999 84.342003 86.052002 86.052002 47660500
2020-01-03 88.099998 90.800003 87.384003 88.601997 88.601997 88892500
2020-01-06 88.094002 90.311996 88.000000 90.307999 90.307999 50665000
2020-01-07 92.279999 94.325996 90.671997 93.811996 93.811996 89410500
</code></pre>
|
python|pandas|pandas-datareader
| 2 |
1,903,796 | 68,245,766 |
Python Discord Bot Scheduled Task Blocks The Rest Of The Code
|
<p>I build a Discord bot in Python. The bot has some tasks that needs to be run at scheduled different times of the day and some commands that needs to be ran on call.</p>
<pre><code>@bot.command(name = "how_are_you", help = "Asks: How Are You?")
async def ask_how_are_you(ctx):
await ctx.send("How are you?")
@tasks.loop(hours = 24)
async def say_hello():
channel = bot.get_channel(int(CHANNEL))
await channel.send("Hello World")
@say_hello.before_loop
async def before():
now = datetime.datetime.now()
start_time = datetime.datetime(now.year, now.month, now.day, 20, 00)
delta = start_time - now
time.sleep(delta.total_seconds())
await bot.wait_until_ready()
print("Finished waiting")
</code></pre>
<p>I then run the bot as follows:</p>
<pre><code>say_hello.start()
bot.run(TOKEN)
</code></pre>
<p>How it works: I want <code>say_hello()</code> to run every day @ 20.00. The <code>before()</code> function takes the current time and checks how many seconds miss before 20.00, it then waits for that amount of seconds.
The issue is that before being able to send commands to the bot, I will need to wait that the <code>before()</code> function finishes waiting. This may take a while because if now is 17.00, I'd need to wait until 20.00 before <code>before()</code> finishes waiting.
Even worse, if I have a weekly task that runs, let's say, every Friday @ 20.00 and today is Tuesday, I'd need to wait 3 days before being able to send commands.</p>
<p>How can I make the tasks wait in the background and be able in the meanwhile to send the commands to the bot? Thanks in advance.</p>
|
<p>I actually managed to solve the issue. The <code>before()</code> function needs to be changed as follows:</p>
<pre><code>@say_hello.before_loop
async def before():
now = datetime.datetime.now()
start_time = datetime.datetime(now.year, now.month, now.day, 20, 00)
delta = start_time - now
await asyncio.sleep(delta.total_seconds()) #THIS CHANGED
await bot.wait_until_ready()
print("Finished waiting")
</code></pre>
<p>What is important, and I didn't do it before, is to remember to <code>import asyncio</code> as if you don't do that, the code won't give you any error but it won't work.</p>
|
python|discord|discord.py|python-asyncio
| 0 |
1,903,797 | 59,155,219 |
How can I convert a string to the idna coded, encoding with 'idna' coded failed
|
<p>I have a string, which should be a stmp server in a later step for python.</p>
<p>The string is (little anonymized):</p>
<p><code>outlook-stg.d-a-tf.de/mapi/emsmdb/?MailboxId=cf27be4f-8605-40e4-94ab-d8cea3cc03bc@test.com</code></p>
<p>For sure the error is:</p>
<blockquote>
<p>UnicodeError: encoding with 'idna' codec failed (UnicodeError: label
empty or too long)</p>
</blockquote>
<p>Which I understand is a problem with the name how I want to adress the server: <a href="https://stackoverflow.com/questions/25103126/label-empty-or-too-long-python-urllib2">label empty or too long - python urllib2</a></p>
<p>But how can I convert it in the right format? I also tried: <a href="https://stackoverflow.com/questions/39465259/encoding-with-idna-codec-failed-in-rethinkdb">Encoding with 'idna' codec failed in RethinkDB</a></p>
<p>With this code: <code>.encode("idna")</code> but this also is the same error.</p>
|
<p>IDNA is an algorithm used to encode domain names, or hostnames. What you provide as example is an URL, so it includes characters that can not work in a domain name and hence can not be encoded and hence your error.</p>
<p>You need to separate the domain (host) name from the rest, apply IDNA only to it (but useless in your example as your hostname is purely ASCII already), and reconstruct your URL.</p>
<p>The specific error you quote comes from the following fact: as IDNA deals with names, per the DNS definition, it works at the label level. A label is somethings between dots, so first step is to split things.
Your string is then handled that way:</p>
<ol>
<li><code>outlook-stg</code></li>
<li><code>d-a-tf</code></li>
<li><code>de/mapi/emsmdb/?MailboxId=cf27be4f-8605-40e4-94ab-d8cea3cc03bc@test</code></li>
<li><code>com</code></li>
</ol>
<p>And a label in the DNS can not be more than 63 bytes. Your third string, even for now not considering that it has disallowed characters (like <code>@</code>) that can never happen in a domain name, even with IDNA encoding, is 68 bytes long, hence the exact error you get.</p>
<p>If I artificially shrink it I then get another error, as expected based on above explanations:</p>
<pre><code>>>> print(idna.encode('outlook-stg.d-a-tf.de/mapi/emsmdb/?MId=cf27be4f-8605-40e4-94ab-d8cea3cc03bc@test.com'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.7/site-packages/idna/core.py", line 358, in encode
s = alabel(label)
File "/usr/local/lib/python3.7/site-packages/idna/core.py", line 270, in alabel
ulabel(label)
File "/usr/local/lib/python3.7/site-packages/idna/core.py", line 304, in ulabel
check_label(label)
File "/usr/local/lib/python3.7/site-packages/idna/core.py", line 261, in check_label
raise InvalidCodepoint('Codepoint {0} at position {1} of {2} not allowed'.format(_unot(cp_value), pos+1, repr(label)))
idna.core.InvalidCodepoint: Codepoint U+002F at position 3 of 'de/mapi/emsmdb/?mid=cf27be4f-8605-40e4-94ab-d8cea3cc03bc@test' not allowed
</code></pre>
<p>(U+002F is <code>/</code> of course, another character disallowed in a domain name, hence rejected during IDNA encoding)</p>
<p>Note that there are rules also to encoding "non ascii characters" in other parts of the URL, that is the path, which is why the top governing standard is now IRI: RFC 3987
It says, even if in a convoluted way, exactly the above:</p>
<blockquote>
<p>Replace the ireg-name part of the IRI by the part converted using
the ToASCII operation specified in section 4.1 of [RFC3490] on each
dot-separated label, and by using U+002E (FULL STOP) as a label<br>
separator, with the flag UseSTD3ASCIIRules set to TRUE, and with the<br>
flag AllowUnassigned set to FALSE for creating IRIs and set to TRUE<br>
otherwise.</p>
</blockquote>
<p>So, depending on your needs, you should:</p>
<ol>
<li>Parse your string as an URI/IRI (with a proper library, do not expect to do it properly with a regex yourself)</li>
<li>Now that you have the hostname part, you can apply IDNA on it, as needed (but the URI/IRI parsing library may do the work for you in fact already, so double check)</li>
<li>And reconstruct the full URI/IRI if you want after that.</li>
</ol>
|
python|encoding|smtp
| 0 |
1,903,798 | 59,122,912 |
How to check if all numbers in a nested list are equal to n
|
<p>So I want to encode a secret image in another b&w image.
This image must have the same size as the original image that we are trying to hide the secret image in, so we have a correspondence of pixels for the two images. </p>
<p>To encode the secret image: </p>
<p>If a pixel in the secret image is white (so, with RGB values of [255, 255, 255]), add 1 to the blue component (last number). </p>
<p>Otherwise, leave the
blue component untouched. </p>
<p>So basically the coloured image is hidden in the b&w image by using an altered blue component from the original image. </p>
<p><em>Decoding the b&w image is done through reversal of the encoding process.</em></p>
<p>So lets say I currently have the following list of pixels:</p>
<pre class="lang-py prettyprint-override"><code>P = [[0, 0, 0], [255, 255, 255], [255, 184, 254], [255, 0, 254]]
</code></pre>
<p>Assuming that the width and height of both images are the same.</p>
<p>How would I check if any 'pixel' in P is equal to 255? So this means that all 3 numbers in the 'pixel' must be equal to 255.</p>
|
<p>You can use </p>
<pre><code>for idx,lst in enumerate(P):
if lst==[255,255,255]:
print(idx,lst)
</code></pre>
<p>or </p>
<pre><code>enc_P=[]
for lst in P:
if lst==[255,255,255]:
print(lst)
enc_P.append(lst)
</code></pre>
|
python|python-3.x|list|rgb|mutation
| 1 |
1,903,799 | 73,066,290 |
Drawing on jupyter notebooks on DataSpell
|
<p>I know this is "seeking for recommendations", but I have no experience with this.</p>
<p>I'm looking for a library for basic drawing in jupyter notebooks.<br />
In particular I don't want libraries like <code>plotly</code> or <code>matplotlib</code>, since I don't need to draw graphs.</p>
<p>I'm looking for something like Canvas for JS.</p>
<p>I've already tested <code>ipycanvas</code> and <code>tkinter</code> but they don't work on DataSpell:
<a href="https://i.stack.imgur.com/bP5E8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bP5E8.png" alt="enter image description here" /></a></p>
|
<p>You can use the package <code>turtle</code> to produce drawings in Python.</p>
|
python|canvas|jupyter-notebook|dataspell
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.