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,907,100 | 35,607,641 |
Finding out unknown matched words
|
<p>I have a regex pattern:</p>
<pre><code>import regex as re
re.sub(r'(.*)\bHello (.*) BGC$\b', "OTR", 'Hello People BGC')
</code></pre>
<p>This will replace to give <code>OTR</code>, but how do I find out what the matched characters are within the <code>(.*)</code>?</p>
<p>Using <code>regex==2016.1.10</code>, <code>Python 3.5.1</code></p>
|
<p>Compile the pattern and then call <code>match()</code> and <code>sub()</code> separately:</p>
<pre><code>>>> pattern = re.compile(r'^Hello (.*?) BGC$')
>>> s = 'Hello People BGC'
>>> pattern.match(s).group(1)
'People'
>>> pattern.sub("OTR", s)
'OTR'
</code></pre>
|
regex|python-3.x
| 2 |
1,907,101 | 59,841,817 |
Recursively calling function on certain condition
|
<p>I have a function that extracts the content from a random website every time using beautifulsoup library where I get random content every time. I'm successfully able to extract the content..... but let's say (if the output text is 'abc'). I want to re-call the function again and again until I get a different output. I added an if condition to make it done but somehow it's not working as I thought:</p>
<pre><code>class MyClass:
def get_comment(self):
source = requests.get('https://www.example.com/random').text
soup = BeautifulSoup(source, 'lxml')
comment = soup.find('div', class_='commentMessage').span.text
if comment == "abc":
logging.warning('Executing again....')
self.get_comment() #Problem here....Not executing again
return comment
mine = MyClass()
mine.get_comment() # I get 'abc' output
</code></pre>
|
<p>When you call your function recursively you aren't doing anything with the output:</p>
<pre><code>class MyClass:
def get_comment(self):
source = requests.get('https://www.example.com/random').text
soup = BeautifulSoup(source, 'lxml')
comment = soup.find('div', class_='commentMessage').span.text
if comment == "abc":
logging.warning('Executing again....')
return self.get_comment() #Call the method again, AND return result from that call
else:
return comment #return unchanged
mine = MyClass()
mine.get_comment()
</code></pre>
<p>I think this should be more like what you're after.</p>
|
python|recursion
| 1 |
1,907,102 | 58,001,987 |
Bayesian Inference with dropout, validation set
|
<p>I have implemented the Bayesian SegNet using Keras (<a href="https://github.com/keras-team/keras/issues/9412" rel="nofollow noreferrer">1</a>). To do so, I used the following custom loss function, which performs Bayesian inference for validation loss:</p>
<pre><code>def custom_loss_Bayesian(y_true, y_pred):
train_loss = K.categorical_crossentropy(y_true, y_pred)
output_list = []
for i in range(n_MoteCarlo_Samples):
output_list.append(K.categorical_crossentropy(y_true, y_pred))
Monty_sample_bin = K.stack(output_list,axis=0)
val_loss_Bayesian=K.mean(Monty_sample_bin,axis=0)
return K.in_train_phase(train_loss, val_loss_Bayesian)
</code></pre>
<p>It works fine, but this approach has a big problem. By increasing the number of Monte Carlo samples, the training process takes a lot longer. This is probably due to the fact that the loop for validation loss is calculated for each training batch, but it is not used anywhere. I only need <code>val_loss_Bayesian</code> after the end of each epoch. Is there a smarter way to do this? Please note, that I want to use <code>ModelCheckpoint</code> to save the set of weights with the lowest <code>val_loss_Bayesian</code>. I tried to implement the solution by lovecambi as in <a href="https://github.com/keras-team/keras/issues/3155" rel="nofollow noreferrer">2</a>, such that <code>n_MonteCarlo_Samples</code> is selected based on batch number, but it did not work. It appears that when you compile a model, the properties inside the loss function cannot be changed. Any suggestions are much appreciated.</p>
|
<p>Based on the discussion in <a href="https://github.com/keras-team/keras/issues/10426" rel="nofollow noreferrer">1</a>, it seems that Keras calculates the validation loss for each batch at the same time as the training loss. However, during the training process, only a running average is constantly being reported in the log for training. Therefore, the code snippet given above is doing its job as it is supposed to. It is taking log because validation loss is being calculated for each mini-batch. If I need Bayesian inference monitored in each epoch, I have to pay the computational price. </p>
|
python|validation|keras
| 0 |
1,907,103 | 36,161,632 |
python nested dictionary comprehension in static class scope: variable not defined
|
<p>I've got this code:</p>
<pre><code>class Chars:
char_to_number = {
'a': ['1'],
'b': ['2'],
'c': ['3', '6'],
'd': ['4', '5'],
}
number_to_char = {
number: char
for char in char_to_number
for number in char_to_number[char]
}
</code></pre>
<p>Now this code returns an error as such:
<code>name 'char_to_number' is not defined</code></p>
<p>Now it looks like python could not parse the nested dictionary comprehension. It looks like the inner scope was not updated with the outer scope, which defined the <code>char_to_number</code> variable.</p>
<p>I've solved this code with this implementation:</p>
<pre><code>class Chars:
char_to_number = {
'a': ['1'],
'b': ['2'],
'c': ['3', '6'],
'd': ['4', '5'],
}
number_to_char = {
number: char
for char, optional_numbers in char_to_number.items()
for number in optional_numbers
}
</code></pre>
<p>Here I'm not using the char_to_number variable in the inner loop, and python succeeded to parse this code.</p>
<p>Of course, all of that happens in the global scope of the class.
In the global python scope, it doesn't happen:</p>
<pre><code>char_to_number = {
'a': ['1'],
'b': ['2'],
'c': ['3', '6'],
'd': ['4', '5'],
}
number_to_char = {
number: char
for char in char_to_number
for number in char_to_number[char]
}
</code></pre>
<p>Does anyone have any clue about that?</p>
|
<p>The essence of the problem is not the nesting. It's the fact that there's a flaw in the scope in comprehensions used within classes. To understand why this looks like a flaw, take the code from the original question by @gal-ben-david and put it in a function (print statement and function call added to generate output and confirm that this code works, at least in Python 3.6.6):</p>
<pre><code>def Chars():
char_to_number = {
'a': ['1'],
'b': ['2'],
'c': ['3', '6'],
'd': ['4', '5'],
}
number_to_char = {
number: char
for char in char_to_number
for number in char_to_number[char]
}
print(number_to_char)
</code></pre>
<p>To understand why nesting is not the problem, take a look at the example in the explanation for this "limitation", <a href="https://docs.python.org/3/reference/executionmodel.html#resolution-of-names" rel="nofollow noreferrer">in the section on the execution model of the Python language reference</a>:</p>
<pre><code>class A:
a = 42
b = list(a + i for i in range(10))
</code></pre>
<p>The variable "a" is not in the scope of the comprehension if these two lines appear in a class, but it would be in a function or module. I call that a bug. To formalize the limitation a bit: when a comprehension is used in a class, only the outermost iterator in the for loop(s) is accessible inside the comprehension, but no other variables from outside the comprehension are accessible.</p>
<p>Comprehensions are presented as being equivalent to for loops, but obviously they aren't. While the nature of this flaw is being debated (bug or not bug), I've submitted a ticket to the developers about the documentation of comprehensions, which really should mention this problem prominently.</p>
<p>I don't have enough points to comment on @armatita's response, but note that it's a workaround and not equivalent to what the original code is trying to do, because it makes char_to_number and number_to_char attributes of each class instance and not of the class itself. I landed on this page because I was trying to assign class attributes.</p>
|
python|dictionary|static-classes
| 2 |
1,907,104 | 49,707,018 |
Python: How to append a file in python using inputs?
|
<p>I am fairly new to python, and have been trying to create a program where I create a file from user inputs. However, I cannot seem to get it to work, and keep getting the error:</p>
<pre><code>Traceback (most recent call last):
File "my_program.py", line 7, in <module>
my_file.append(x)
AttributeError: '_io.TextIOWrapper' object has no attribute 'append'
</code></pre>
<p>I think this means that I cannot append the file, but I am not sure at all why. Here is the relevant part of my program:</p>
<pre><code>my_file = "my_file"
with open(my_file, 'a') as my_file:
lines = True
counting_variable = 0
while lines:
x = input()
my_file.append(x)
</code></pre>
<p>Thank you very much for any help in advance!</p>
|
<p>Not able to comment yet (anyone mind converting?), but I think there are quite a few questions similar to this on SO. Try <a href="https://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file">Python Append</a></p>
|
python
| 0 |
1,907,105 | 54,769,699 |
How to delete an string from a list if it has an specific word in it
|
<p>I'm trying to write a piece of code that helps me choose what to eat for breakfast according to how hungry I feel and how much time I got left (newbie personal project :p).</p>
<p>The thing is that if I'm really hungry but have little to no time, I want to delete a few options that have the word "avena" in it.</p>
<p>Here's the code (I'm not going to write it all down here, just the part that I have problems with):</p>
<pre><code>ptiempo_bebi = ["Leche fría con punchao", "Leche fría con avena", "Leche
fría con cereal", "Yogurt con cereal", "Yogurt solo"]
mtiempo_bebi = ["Té", "Agua hervida con punchao", "Leche caliente con avena", "Yogurt con avena cocida"]
bebi = [ptiempo_bebi, mtiempo_bebi]
</code></pre>
<p>So, if I input "I'm really hungry" but "Have little time", the list should be edited, deleting every string with the word "avena" in it.</p>
<p>I tried lots of things, but I've been 3 days stuck with this problem :(.</p>
<p>Tried using functions and .remove</p>
<pre><code>def searchword(lists, word):
for element in lists:
for palabra in element:
if palabra == word:
lists = lists.remove(element)
return lists
print(searchword(ptiempo_bebi, "avena"))
</code></pre>
<p>Tried using a similar function but with del and append</p>
<pre><code>for element in ptiempo_bebi:
for palabra in element:
if palabra == "avena":
del(element)
else:
ptiempoedit_bebi.append(element)
</code></pre>
<p>I even tried (understanding and) using List Comprehension</p>
<pre><code>ptiempobebiedit = [ptiempo_bebi.remove(element) for palabra in element for element in list if palabra == "avena"]
</code></pre>
<p>And</p>
<pre><code>ptiempo_bebi = [ elem for elem in ptiempo_bebi if elem == "avena"]
</code></pre>
<p>Sorry if my code looks horrible or if I really messed up any syntax.
I'd be really grateful to receive any answer and an explanation of why it works and in which part I messed up.</p>
|
<p>You can filter your list to exclude strings that contain a particular word or phrase using list comprehension. For example:</p>
<pre><code>phrases = ['Té', 'Agua hervida con punchao', 'Leche caliente con avena', 'Yogurt con avena cocida']
filtered = [phrase for phrase in phrases if 'avena' not in phrase]
# ['Té', 'Agua hervida con punchao']
</code></pre>
|
string|list|python-3.7
| 0 |
1,907,106 | 54,974,872 |
Subtract consecutive timeframes in a pandas dataframe given the values of another column
|
<p>I have a pandas dataframe like this:</p>
<pre><code> CustomerId Timestamp
0. a 01-09-2018 00:08:00
1. a 01-09-2018 00:09:00
2. b 01-09-2018 00:11:00
3. b 01-09-2018 00:15:00
</code></pre>
<p>I need to calculate the difference in minutes between consecutive timestamps for each customer so that in the end I have something that looks a little like this: </p>
<pre><code> CustomerId Timestamp Difference
0. a 01-09-2018 00:08:00 -
1. a 01-09-2018 00:09:00 1
2. b 01-09-2018 00:11:00 -
3. b 01-09-2018 00:15:00 4
</code></pre>
<p>I have been trying some loops but nothing seems to be working out. I would really appreciate it if someone could help me out :)</p>
|
<p>Using <code>groupby</code> with <code>diff</code> </p>
<pre><code>df.groupby('CustomerId').Timestamp.diff().dt.total_seconds()/60
Out[10]:
0.0 NaN
1.0 1.0
2.0 NaN
3.0 4.0
Name: Timestamp, dtype: float64
df['Different']=df.groupby('CustomerId').Timestamp.diff().dt.total_seconds()/60
</code></pre>
|
python|pandas
| 3 |
1,907,107 | 44,257,141 |
qml doesn't work with vispy
|
<p>In the process of studying Qt and Qt, Quick encountered a very interesting problem. I wanted to add to my application a widget on which something would be rendered using an OpenGl. I found a small example using vispy and decided to try it. And then something very interesting is happening. The fact is that one of my widgets is written in QML, and when I launch my application, the widget with OpenGL worked. A black square appears instead of the QML-widget. Also in the log the following is written: </p>
<blockquote>
<p>WARNING: QQuickWidget cannot be used as a native child widget.
Consider setting Qt::AA_DontCreateNativeWidgetSiblings</p>
</blockquote>
<p>Here my code:</p>
<pre><code>import QtQuick 2.7
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.0
Rectangle {
width: 200
height: 200
color: 'white'
Rectangle {
id: lef_rec
width: parent.width / 2
height: parent.height
color: "green"
}
Rectangle {
width: parent.width / 2
height: parent.height
anchors.left: lef_rec.right
color: "blue"
}
}
</code></pre>
<p>In Python:</p>
<pre><code>self.qml_wdg = QQuickWidget()
self.qml_wdg.setSource(QtCore.QUrl("main.qml"))
canvas = Canvas(keys='interactive', vsync=False).native
layout = QtWidgets.QVBoxLayout()
layout.addWidget(canvas)
layout.addWidget(self.qml_wdg)
self.centralwidget.setLayout(layout)
</code></pre>
<p>Separately everything works, together there is this error. I'm wondering what this problem is?</p>
|
<p>You must place the attribute with <code>setAttribute()</code>:</p>
<pre><code>{your QApplication}.setAttribute(QtCore.Qt.AA_DontCreateNativeWidgetSiblings)
</code></pre>
<p>Complete code:</p>
<pre><code>import sys
from PyQt5 import QtWidgets, QtCore, QtQuickWidgets
from vispy.app import Canvas
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent=parent)
self.centralwidget = QtWidgets.QWidget()
self.setCentralWidget(self.centralwidget)
self.qml_wdg = QtQuickWidgets.QQuickWidget()
self.qml_wdg.setSource(QtCore.QUrl("main.qml"))
canvas = Canvas(keys='interactive', vsync=False).native
layout = QtWidgets.QVBoxLayout()
layout.addWidget(canvas)
layout.addWidget(self.qml_wdg)
self.centralwidget.setLayout(layout)
app = QtWidgets.QApplication(sys.argv)
app.setAttribute(QtCore.Qt.AA_DontCreateNativeWidgetSiblings)
w = MainWindow()
w.show()
sys.exit(app.exec_())
</code></pre>
<p><a href="https://i.stack.imgur.com/NPYRV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NPYRV.png" alt="enter image description here"></a></p>
|
python|pyqt|qml|pyqt5|vispy
| 0 |
1,907,108 | 51,366,538 |
why is psychopy.visual.MovieStim3 so slow in my use case?
|
<p>Currently I would like to continually play movies in a loop from different filepaths using python 3.6, psychopy 1.90.2. The filepaths are listed in a csv file and each filepath has common ancestors but has a different parent directory and filename. e.g. '/media/michael/shared_network_drive/dataset/training/jumping/man_jumps_through_hoop3342.mp4' and '/media/michael/shared_network_drive/dataset/training/shouting/h555502.mp4'.</p>
<p>Currently there is a very large delay when creating the visual.MovieStim3 object which results in a large delay before every video. Here is the code so far:</p>
<pre><code>def play_videos(csv_file, vid_location='/media/michael/shared_network_drive/dataset/training/'):
# Open a window
win = visual.Window([400,400])
#open csv file and cycle through each video
for vid, label, val1, val2 in csv.reader(open(csv_file, 'r')):
glob_vid_path = vid_location + vid
# Define a MovieStim3 object
mov = visual.MovieStim3(win, glob_vid_path, flipVert=False, flipHoriz=False)
# Loop through each frame of the video
while mov.status != visual.FINISHED:
mov.draw()
win.flip()
win.close()
</code></pre>
<p>Why is the delay so long and how can I overcome this?</p>
|
<p>For those with similar problems; the delay is caused by the location of the videos in a shared drive. Placing the videos on the home drive, or even an external hard-drive solved the problem.</p>
|
python|python-3.x|psychopy
| 4 |
1,907,109 | 69,748,179 |
Using scrapy to scrape multiple pages and multiple URLs
|
<p>I have previously done a small project on scraping a real estate website using BeautifulSoup, but it took a long time to scrape around 5,000 data points. I was thinking of learning multithread processing and implementing it with BS, but someone informed me that web-crawling with Scrapy might be faster and easier. Additionally, I have switched from using a Spyder to Pycharm as my IDE. It is still jarring experience but I am trying to get used to it.</p>
<p>I have gone over the documentation once, and followed some scraping examples using Scrapy, but I am still experiencing difficulties. I was planning to use my previously created BS scraping script as a base, and create a new Scrapy project to web-scrape real estate data. However, I don't know how and where I can start. Any and all help is much appreciated. Thank you.</p>
<p><strong>Desired Result:</strong>
Scrape multiple pages from multiple URLs using Scrapy. Scrape multiple values by entering into the apartment listing links and getting data from each.</p>
<p><strong>Scrapy Script (so far):</strong></p>
<pre><code># -*- coding: utf-8 -*-
# Import library
import scrapy
# Create Spider class
class UneguiApartmentSpider(scrapy.Spider):
name = 'apartments'
allowed_domains = ['www.unegui.mn']
start_urls = [
'https://www.unegui.mn/l-hdlh/l-hdlh-zarna/oron-suuts-zarna/'
]
# headers
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36"
}
def parse(self, response):
for listings in response.xpath("//div[@class='list-announcement']"):
item = ApartmentsItem()
item['name'] = listings.xpath('text()').extract()
item['link'] = listings.xpath('href').extract()
yield item
</code></pre>
<p><strong>BeautifulSoup Script:</strong></p>
<p>This script still has some issues I am trying to address such as scraping city and price. For example, for 4 bedroom apartments url (/4-r/) it creates an error or empty value because there are VIP listings</p>
<pre><code># -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup as BS
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from timeit import default_timer as timer
import pandas as pd
import re
import csv
dt_today = datetime.today()
date_today = dt_today.strftime('%Y-%m-%d')
date_today2 = dt_today.strftime('%Y%m%d')
date_yesterday = (dt_today-relativedelta(day=1)).strftime('%Y-%m-%d')
def main():
page = 0
name = []
date = []
address = []
district = []
city = []
price = []
area_sqm = []
rooms = []
floor = []
commission_year = []
building_floors = []
garage = []
balcony = []
windows = []
window_type = []
floor_type = []
door_type = []
leasing = []
description = []
link = []
for i in range (5,6):
BASE = 'https://www.unegui.mn'
URL = f'{BASE}/l-hdlh/l-hdlh-zarna/oron-suuts-zarna/{i}-r/?page='
COLUMNS=['Name','Date','Address','District','City','Price','Area_sqm','Rooms','Floor','Commission_year',
'Building_floors','Garage', 'Balcony','Windows','Window_type','Floor_type','door_type','Leasing','Description','Link']
with requests.Session() as session:
while True:
(r := session.get(f'{URL}{page+1}')).raise_for_status()
m = re.search('.*page=(\d+)$', r.url)
if m and int(m.group(1)) == page:
break
page += 1
start = timer()
print(f'Scraping {i} bedroom apartments page {page}')
soup = BS(r.text, 'lxml')
for tag in soup.findAll('div', class_='list-announcement-block'):
_name = tag.find('a', attrs={'itemprop': 'name'})
name.append(_name.get('content', 'N/A'))
if (_link := _name.get('href', None)):
link.append(f'{BASE}{_link}')
(_r := session.get(link[-1])).raise_for_status()
_spanlist = BS(_r.text, 'lxml').find_all('span', class_='value-chars')
floor_type.append(_spanlist[0].get_text().strip())
balcony.append(_spanlist[1].get_text().strip())
garage.append(_spanlist[2].get_text().strip())
window_type.append(_spanlist[3].get_text().strip())
door_type.append(_spanlist[4].get_text().strip())
windows.append(_spanlist[5].get_text().strip())
_alist = BS(_r.text, 'lxml').find_all('a', class_='value-chars')
commission_year.append(_alist[0].get_text().strip())
building_floors.append(_alist[1].get_text().strip())
area_sqm.append(_alist[2].get_text().strip())
floor.append(_alist[3].get_text().strip())
leasing.append(_alist[4].get_text().strip())
district.append(_alist[5].get_text().strip())
address.append(_alist[6].get_text().strip())
rooms.append(tag.find('div', attrs={'announcement-block__breadcrumbs'}).get_text().split('»')[1].strip())
description.append(tag.find('div', class_='announcement-block__description').get_text().strip())
date.append(tag.find('div', class_='announcement-block__date').get_text().split(',')[0].strip())
city.append(tag.find('div', class_='announcement-block__date').get_text().split(',')[1].strip())
# if ( _price := tag.find('div', class_='announcement-block__price _premium')) is None:
# _price = tag.find('meta', attrs={'itemprop': 'price'})['content']
# price.append(_price)
end = timer()
print(timedelta(seconds=end-start))
df = pd.DataFrame(zip(name, date, address, district, city,
price, area_sqm, rooms, floor, commission_year,
building_floors, garage, balcony, windows, window_type,
floor_type, door_type, leasing, description, link), columns=COLUMNS)
return(df)
df['Date'] = df['Date'].replace('Өнөөдөр', date_today)
df['Date'] = df['Date'].replace('Өчигдөр', date_yesterday)
df['Area_sqm'] = df['Area_sqm'].replace('м²', '')
df['Balcony'] = df['Balcony'].replace('тагттай', '')
if __name__ == '__main__':
df = main()
df.to_csv(f'{date_today2}HPD.csv', index=False)
</code></pre>
|
<p>this is an example of scraping multiple URLs to the same website
for example
the website is amazon
the first URL for the baby category
the second for another category</p>
<pre><code>import scrapy
class spiders(scrapy.Spider):
name = "try"
start_urls = ["https://www.amazon.sg/gp/bestsellers/baby/ref=zg_bs_nav_0",'https://www.amazon.sg/gp/browse.html?node=6537678051&ref_=nav_em__home_appliances_0_2_4_4']
def parse(self, response):
for url in response.css('.mr-directory-item a::attr(href)').getall(): #loop for each href
yield scrapy.Request(f'https://muckrack.com{url}', callback=self.parse_products,
dont_filter=True)
def parse_products(self, response):
#these are for another website
full_name = response.css('.mr-font-family-2.top-none::text').get()
Media_outlet = response.css('.mr-person-job-item a::text').get()
yield {'Full Name': full_name, 'Media outlet':Media_outlet,'URL': response.url}
</code></pre>
<p>if you want to do the different processes for each URL
you should use</p>
<pre><code>import scrapy
class spiders(scrapy.Spider):
name = "try"
def start_requests(self):
yield scrapy.Request('url1',callback=self.parse1)
yield scrapy.Request('url2',callback=self.parse2)
def parse1(self, response):
for url in response.css('.mr-directory-item a::attr(href)').getall():#loop for each href
yield scrapy.Request(f'https://muckrack.com{url}', callback=self.parse_products,
dont_filter=True)
def parse2(self, response):
for url in response.css('.mr-directory-item a::attr(href)').getall():#loop for each href
yield scrapy.Request(f'https://muckrack.com{url}', callback=self.parse_products,
dont_filter=True)
def parse_products(self, response):
#these are for another website
full_name = response.css('.mr-font-family-2.top-none::text').get()
Media_outlet = response.css('.mr-person-job-item a::text').get()
#yield {'header':'data'}
yield {'Full Name': full_name, 'Media outlet':Media_outlet,'URL': response.url}```
</code></pre>
|
python|html|loops|web-scraping|scrapy
| 2 |
1,907,110 | 69,991,894 |
Scraping an additional link and appending it to the list
|
<p>I have run into a problem and I can´t figure out how to get any further.</p>
<p>I have scraped multiple pages for a companies name, location and province, along with a link to additional information on another page. The link which I have collected provides 3 more pieces of information that I require.</p>
<p>I need to access the link, and take out the address, phone number (if it has one) and a CNAE code, and append that to the previous data.</p>
<p>The working script for the first scrape I currently have is as follows:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
baseurl = ["https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/index.html"]
urls = [f'https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/{i}.html'.format(i) for i in range(2,65)]
allurls = baseurl + urls
print(allurls)
for url in allurls:
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
lists = soup.select("div#simulacion_tabla ul")
#scrape the pages
for lis in lists:
title = lis.find('li', class_="col1").text
location = lis.find('li', class_="col2").text
province = lis.find('li', class_="col3").text
link = lis.select("li.col1 a")[0]['href']
info = [title, location, province, link]
print(info)
</code></pre>
<p>On the second page the data is in a table with the id names below. This is the code I thought I would need to use but it isn´t working and I am going round in circles trying to figure out why:</p>
<pre><code>section = soup.select("section#datos_empresa")
lslinks = link
for ls in lslinks
location = lis.find('tr', id_="tamano_empresa").text
cnae = lis.find('tr', id_="cnae_codigo_empresa").text
phone = lis.find('tr', id_="telefono_empresa").text
addinfo = [location, cnae, phone]
info.append(addinfo)
</code></pre>
<p>Here´s an example of one of the <a href="https://www.expansion.com/directorio-empresas/a-cortina-dos-acivros-sl_9163006_A02_27.html" rel="nofollow noreferrer">links</a></p>
<p>Ideally the output would be: <br>
['AGRICOLA CALLEJA SL', 'CARPIO', 'VALLADOLID', 'https://www.expansion.com/directorio-empresas/agricola-calleja-sl_1480101_A02_47.html', C/ LA TORRE, 2., 150, 983863247]</p>
<p>which I would write to a text file so I can import it to excel.</p>
<p>Any help would be greatly appreciated!</p>
<p>Cheers!</p>
|
<p>Here is the minimal working solution so far.</p>
<p>Code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
baseurl = ["https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/index.html"]
urls = [f'https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/{i}.html'.format(i) for i in range(2,5)]#range(2,65)]
allurls = baseurl + urls
#print(allurls)
data = []
for url in allurls:
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
lists = soup.select("div#simulacion_tabla ul")
#scrape the pages
for lis in lists:
title = lis.find('li', class_="col1").text
location = lis.find('li', class_="col2").text
province = lis.find('li', class_="col3").text
link = lis.select_one("li.col1 a")['href']
#info = [title, location, province, link]
#print(info)
sub_page = requests.get(link)
soup2 = BeautifulSoup(sub_page.content, "html.parser")
direction = soup2.select_one('#direccion_empresa').text
cnae = soup2.select_one('#cnae_codigo_empresa').text
phone=soup2.select_one('#telefono_empresa')
telephoe = phone.text if phone else None
print([title,location,province,link,direction,cnae,telephoe])
#data.append([title, location, province,link, direction, cnae, telephoe])
#cols = ["title", "location", "province","link", "direction", "cnae", "telephoe"]
#df = pd.DataFrame(data, columns=cols)
#print(df)
#df.to_csv('info.csv',index = False)
</code></pre>
<p>Output:</p>
<pre><code>['A CORTIÑA DOS ACIVROS SL', 'LUGO', 'LUGO', 'https://www.expansion.com/directorio-empresas/a-cortina-dos-acivros-sl_9163006_A02_27.html', 'CRTA. A CORUÑA, 16.', '150', '']
['A CORTIÑA DOS ACIVROS SL', 'LUGO', 'LUGO', 'https://www.expansion.com/directorio-empresas/a-cortina-dos-acivros-sl_9163006_A02_27.html', 'CRTA. A CORUÑA, 16.', '150', '']
['A P V 19 32 SL', 'VALENCIA', 'VALENCIA', 'https://www.expansion.com/directorio-empresas/a-p-v-19-32-sl_672893_A02_46.html', 'CALLE SALVA, 8 1 2B.', '150', '']
['ABADIA DE JABUGO SL', 'CARTAYA', 'HUELVA', 'https://www.expansion.com/directorio-empresas/abadia-de-jabugo-sl_5442689_A02_21.html', 'URB. MARINA EL ROMPIDO, 31 VILLA M-31. CRTA. EL RO.', '150', '']
['ABALOS REAL SLL', 'CARBONERAS DE GUADAZAON', 'CUENCA', 'https://www.expansion.com/directorio-empresas/abalos-real-sll_1239004_A02_16.html', 'C/ DON CRUZ, 23.', '150', '969142092']
</code></pre>
<p>... so on</p>
|
python|loops|web-scraping|beautifulsoup
| 1 |
1,907,111 | 72,897,624 |
gmail is not sending from django web application
|
<p>I have created a Python-Django web application.
I tried to send an email to a user, but it is not working. How Can I solve it ?</p>
<pre><code>#SMTP Configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_POSRT = 587
EMAIL_USE_TLS =True
EMAIL_HOST_USER = 'fhcollege@gmail.com'
EMAIL_HOST_PASSWORD = ''
</code></pre>
<p>This from my settings.py file</p>
<p>My views.py file is</p>
<pre><code>email=EmailMessage(
'PAYMENT SUCCESSFULL',
'welcome',
settings.EMAIL_HOST_USER,
['fhcollege@google.com']
)
email.fail_silently = False
email.send()
</code></pre>
<p>How can I solve the issue ?</p>
<p>The Error showing is</p>
<pre><code>TimeoutError at /payments/4
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Request Method: POST
Request URL: http://127.0.0.1:9000/payments/4
Django Version: 4.0.2
Exception Type: TimeoutError
</code></pre>
|
<ol>
<li>In settings.py make</li>
</ol>
<p>`EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'</p>
<p>DEFAULT_FROM_EMAIL = EMAIL_HOST_USER`</p>
<ol>
<li>Import the EmailMessage module, <code>from django.core.mail import EmailMessage</code></li>
<li>Send the email,<code>email = EmailMessage('Subject', 'Body', to=['deneme.deneme@gmail.com']) email.send()</code></li>
</ol>
<p><strong>Specifically for Gmail, you may need to turn on "enable less secure apps" in your Google account..</strong></p>
<p><a href="https://support.google.com/accounts/answer/6010255?hl=en" rel="nofollow noreferrer">Less secure apps & your Google Account</a></p>
|
python|django|email|gmail
| 0 |
1,907,112 | 73,521,580 |
python script gets stuck on keylogger listner
|
<p>the keylogger is getting stuck on listening for keys i tried putting the listening part in another script but it wasnt practical, is it possible to utilise threading for this?</p>
<pre><code>log_dir = ""
logging.basicConfig(filename=(log_dir + 'keylogs.txt'), \
level=logging.DEBUG, format='%(asctime)s: %(message)s')
def on_press(key):
logging.info(str(key))
with Listener(on_press=on_press) as lister:
lister.join()
path = r'C:\Users\Jacob\Desktop\keylogger\keylogs.txt'
f = open((path), 'r', encoding = 'utf-8')
file = f.readlines()
</code></pre>
|
<p>If you want to do something when <code>Listener</code> is running then you have to do before <code>.join()</code> because it waits for end of listener.</p>
<pre><code>with Listener(on_press=on_press) as lister:
# ... your code ...
lister.join()
</code></pre>
<p><code>Listener</code> already uses <code>threading</code> to run code so you don't have to run it in <code>Thread</code> and you can write it in similar way to <code>threading</code></p>
<pre><code>lister = Listener(on_press=on_press) # create thread
lister.start() # start thread
# ... your code ...
lister.join() # wait for end of thread
</code></pre>
<hr />
<p><strong>BTW:</strong></p>
<p>It has also all other functions from normal <code>Thread</code> - ie. <code>lister.is_alive()</code> to check if <code>Listener</code> is still running.</p>
<p>In opposite to normal <code>Thread</code> it has also command <code>lister.stop()</code> to stop this <code>Listener</code></p>
|
python|keylogger
| 1 |
1,907,113 | 64,065,205 |
Matplotlib Line Plot not indicating Labels
|
<p>I have the following Dataset from which I want to obtain the line plot. The plot is correct but the labels are missing although I provide the label name in the code. Please provide me a method to include the labels. Also if I try to include xlabel and ylabel in the code it gives me an error <code>AttributeError: 'Line2D' object has no property 'xlabel'</code></p>
<p><strong>Dataframe res</strong></p>
<pre><code>UserId | date |-7|-6|-5|-4|-3|-2|-1|0 |1 |2 |3 |4 |5 |6 |7
1 2009-10-17 17:38:32.590 |0 |0 |0 |0 |0 |0 |1 |0 |1 |0 |0 |0 |0 |0 |0
2 2009-10-19 00:37:23.067 |0 |0 |0 |0 |0 |1 |1 |0 |1 |0 |0 |0 |0 |0 |0
3 2009-10-20 08:37:14.143 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0
4 2009-10-21 18:07:51.247 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0
5 2009-10-22 21:25:24.483 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0
</code></pre>
<p><strong>Code</strong></p>
<pre><code>badges = ["A", "B", "C"]
for badge in badges:
res.iloc[:,2:].mean().plot(kind='line', label = badge)
</code></pre>
<p><strong>Output</strong></p>
<p><a href="https://i.stack.imgur.com/pCnzq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pCnzq.png" alt="Output Obtained" /></a></p>
<p>This is the output obtained from this code. I want the labels for all the three lines to be present in the graph. Along with that I want to add xlabel = "Week" and ylabel = "Mean Posts" on the axis.</p>
|
<p>The xlabel or ylabel argument is only available in pandas version 1.1.0. or above.
refer Documentation <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html#pandas.DataFrame.plot" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html#pandas.DataFrame.plot</a></p>
<p>The reason you are getting <strong>AttributeError: 'Line2D' object has no property 'xlabel'</strong> is because you might have lower version of pandas.</p>
<p>you can check pandas version by running following command</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
print(pd.__version__)
</code></pre>
<p>Now for putting x_label / y_label you can do the following:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
for badge in badges:
res.iloc[:,2:].mean().plot(kind='line', label = badge, ax=ax)
ax.set_ylabel('y')
ax.set_xlabel('x')
ax.legend()
plt.show()
</code></pre>
|
python|dataframe|matplotlib|seaborn
| 1 |
1,907,114 | 64,118,493 |
File not found when running a file in JupiterLab console
|
<p>Every time when I try to run a file in the JupiterLab console I get the following message:</p>
<p>ERROR:root:File <code>'thing.py'</code> not found.</p>
<p>In this case, my file is called <em>thing.py</em> and I try to run it with the trivial <em>run thing.py</em> command in the console. The code is running and it gives me correct results when executed in the console, but I wanted to have it saved, so I put it in a JupiterLab text file and changed the extension to <em>.py</em> instead of <em>.txt</em>. But I get the aforementioned message regardless of which file I try to run. I am new to JupiterLab and admit that I might have missed something important. Every help is much appreciated.</p>
|
<p>If you're running Jupyterlab you should be able:</p>
<ol>
<li>to create a new file & paste in your commands</li>
</ol>
<p><a href="https://i.stack.imgur.com/AITyl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AITyl.png" alt="enter image description here" /></a></p>
<ol start="2">
<li>Rename that file to "thing.py"</li>
</ol>
<p><a href="https://i.stack.imgur.com/GqEud.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GqEud.png" alt="enter image description here" /></a></p>
<ol start="3">
<li>And then open a console in the same Jupyterlab instance and run that file. Notice that you can see "thing.py" in the file explorer on the left:</li>
</ol>
<p><a href="https://i.stack.imgur.com/aFZ7H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aFZ7H.png" alt="enter image description here" /></a></p>
<ol start="4">
<li>Alternatively, you can use the <code>%load</code> magic command in a notebook to dynamically load the code into a notebook's cell.</li>
</ol>
<p><a href="https://i.stack.imgur.com/RPC7J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RPC7J.png" alt="enter image description here" /></a></p>
|
python|jupyter|jupyter-lab
| 0 |
1,907,115 | 52,921,209 |
Finding Median in Large Integer File of Integers
|
<p>I was asked in an interview the following. I didn't get it but trying to solve it at home. I believe we have to use the Median of Median algorithm...</p>
<blockquote>
<p>Q: Finding Median in Large Integer File of Integers </p>
<p>Find the median from a large file of integers. You can not access the
numbers by index, can only access it sequentially. And the numbers
cannot fit in memory.</p>
</blockquote>
<p>I found a solution online (rewrote in Python) but there are a few things I do not understand.. I kind of get the algorithm but not 100% sure.</p>
<p>a) Why do we check <code>left >= right</code>?</p>
<p>b) When <code>count < k</code>, we call <code>self.findMedianInLargeFile(numbers,k,max(result+1,guess),right)</code>. Why do we call <code>max(result+1, guess)</code> as <code>left</code>?</p>
<p>c) when <code>count > k</code>, why do we use <code>result</code> as <code>right</code>?</p>
<pre><code>class Solution:
def findMedianInLargeFile(self, numbers,k,left,right):
if left >= right:
return left
result = left
guess = (left + right ) // 2
count = 0
# count the number that is less than guess
for i in numbers:
if i <= guess:
count+=1
result = max(result,i)
if count == k:
return result
elif count < k: # if the number of items < guess is < K
return self.findMedianInLargeFile(numbers,k,max(result+1,guess),right)
else:
return self.findMedianInLargeFile(numbers,k,left,result)
def findMedian(self, numbers):
length = len(numbers)
if length % 2 == 1: # odd
return self.findMedianInLargeFile(numbers,length//2 + 1,-999999999,999999999)
else:
return (self.findMedianInLargeFile(numbers,length//2,-999999999,999999999) + self.findMedianInLargeFile(numbers,length//2 +1 ,-999999999,999999999)) / 2
</code></pre>
|
<p>This is just <a href="https://en.wikipedia.org/wiki/Binary_search_algorithm" rel="nofollow noreferrer">binary search</a> by median value</p>
<p>Compare with example code </p>
<pre><code>function binary_search(A, n, T):
L := 0
R := n − 1
while L <= R:
m := floor((L + R) / 2)
if A[m] < T:
L := m + 1
else if A[m] > T:
R := m - 1
else:
return m
return unsuccessful
</code></pre>
<ul>
<li><p><code>if left >= right:</code> stops iterations when borders
collide</p></li>
<li><p>when <code>count < k</code>, we call <code>self.findMedianInLargeFile(numbers,k,max(result+1,guess),right)</code> because our guess was too small, and median value is bigger than quessed value.</p></li>
<li>similar but reversed situation for <code>else</code> case</li>
</ul>
|
python|algorithm|sorting
| 2 |
1,907,116 | 65,243,745 |
Why slightly changing the function caused so much difference in exponential curve fitting in scipy?
|
<p>With the curve_fit function in scipy, I got some very werid result. A slight change in my function will make it better. But I don't know why.
This is the code doens't work:</p>
<pre><code>def func(x, A1, t1, y0):
return A1 * np.exp(x/t1) + y0
x_data = np.array(data['tau'])
y_data = np.array(data['magnitude'])
p0 = [1000, 4, 0]
popt, pcov = curve_fit(func, x_data, y_data, p0)
print(popt)
y_fited = func(x_data, *popt)
plt.plot(x_data, y_data, 'b-', label='data')
plt.plot(x_data, y_fited, 'r-', label='fited')
</code></pre>
<p>The output plot is like this:</p>
<p><a href="https://i.stack.imgur.com/C93Ze.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C93Ze.png" alt="enter image description here" /></a></p>
<p>And after I changed the t1 of func from dividing to multiplication, everything seems better.</p>
<pre><code>def func(x, A1, t1, y0):
return A1 * np.exp(x*t1) + y0
</code></pre>
<p><a href="https://i.stack.imgur.com/G67Ag.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G67Ag.png" alt="enter image description here" /></a></p>
<p>Why is this happenning? I can't understand why my first func can't work well, it is not a linear function, which I borrow it from Origin's exponential fitting tool. Thanks in advance!</p>
<p>Here is my x_data:</p>
<blockquote>
<p>[4.9063e-03 4.5800e-03 4.2538e-03 3.9275e-03 3.6012e-03 3.2750e-03
2.9487e-03 2.6224e-03 2.2961e-03 1.9699e-03 1.6436e-03 1.3173e-03
9.9107e-04 6.6480e-04 3.3853e-04 1.2266e-05]</p>
</blockquote>
<p>and y_data:</p>
<blockquote>
<p>[1038.3 921.93 865.19 878.07 1141.9 1043.3 1167.2 1030.5
1174.8
1331.5 1549.7 1379.8 2134.8 1992.5 2218.8 2505.7 ]</p>
</blockquote>
|
<p>There are a few issues here. Clearly it is a non-linear fit, so there is always the possibility of local minima. Obviously one is found here. The question then is: why? One has to see what the underlying algorithm is doing. Just looking at the <code>t1</code> we see that if we would start with <code>t1=1</code> both versions would give the same answer. Now the data clearly shows that this is decay, so the result should be negative. The case of <code>...* t1</code> hence, needs to get smaller and get negative. This is controlled by the gradient of the local error. Now it is likely that the <code>.../ t1</code> case also wants to go in directions of smaller factors, but this means increasing <code>t1</code>, it will, therefore, go in the wrong direction. If One prints the values of <code>t1</code> throughout the fitting process, one can observe this behavior. Actually at some point it overcomes the "barrier" to negative numbers. However, at that point, the other parameters have already such abnormal values that it goes back to positive.</p>
<p>In detail it depends on the starting parameters and <code>[5000,1,0]</code> would work.</p>
<p>At the end I think that <strong>this example is a great lesson</strong> on how to prepare your fit function:</p>
<ul>
<li>Try to get the sign correct i.e. <code>exp( -x * t1 )</code> would have been better, as it is obviously decay</li>
<li>if a parameter may chande sign, take care that nothing diverges if the parameter becomes zero. This is somewhat what happened here.</li>
<li>If possible rescale such that all parameters on the scale of <code>1</code>. This to some extend equivalent to providing good starting values. Here a fit-function like <code> 1000 * a * exp( -1000 * t * x ) + 1000 * c</code> would converge fast without providing starting values.</li>
</ul>
|
python|scipy|curve-fitting
| 0 |
1,907,117 | 71,813,903 |
regex : Read number and character from end until space is encountered
|
<p>I want to divide the line into a date, description, and amount. The last digits are the amount that can contain Cr. I have a line like the following:</p>
<pre class="lang-py prettyprint-override"><code>Date Description Amount
13/03/2021 XYZ ABC 428.00 31,408.37 Cr
17/03/2021 ZOOM.US 111-222-333 WWW.ZOOM.U USD 5.29 841.18
</code></pre>
<p>The regex that I used is:</p>
<pre><code>regex_filter = re.compile(r'(\d{2}/\d{2}/\d{4}) (.*?) ([\d,]+\.\d{2}) ')**
</code></pre>
<p>And what I got is:</p>
<pre><code>Date - 13/03/2021
Description - XYZ ABC
Amount - 428.00
</code></pre>
<p>I want the amount to be <code>31,408.37 Cr</code> and for the second one amount should be <code>841.18</code>. So I want digits and characters up to a space reading from the end.</p>
<p>How can I get this?</p>
|
<p>You may use this regex with anchors and optional group:</p>
<pre class="lang-py prettyprint-override"><code>^(\d{2}/\d{2}/\d{4})\s+(.*?)\s+((?:\d+(?:,\d+)*\.\d{2})(?: Cr)?)$
</code></pre>
<p><a href="https://regex101.com/r/Y6Zlb8/1" rel="nofollow noreferrer">RegEx Demo</a></p>
<p><strong>RegEx Details:</strong></p>
<ul>
<li><code>^</code>: Start</li>
<li><code>(\d{2}/\d{2}/\d{4})</code>: 1st capture group to match date</li>
<li><code>\s+</code>: 1+ whitespaces</li>
<li><code>(.*?)</code>: 2nd capture group to match anything lazily for description</li>
<li><code>\s+</code>: 1+ whitespaces</li>
<li><code>((?:\d+(?:,\d+)*\.\d{2})(?: Cr)?)</code>: 3rd capture group to match amount. Inside, we are matching ending <code>Cr</code> in an optional non-capture group</li>
<li><code>$</code>: End</li>
</ul>
|
python|regex
| 2 |
1,907,118 | 72,076,579 |
Way to Get Information from Website With Discord Bot
|
<p>i'm working on coding a discord bot using python and i'm trying to figure out a way to access a website via a bot command.</p>
<p>in theory, i'll have a command link the bot to the site, grab information, and then put that specific information in the chat.</p>
<p>this is what i'm trying to use: <a href="https://api.quotable.io/random" rel="nofollow noreferrer">https://api.quotable.io/random</a>, and have it be like !quote and then the bot will grab the 'content' and the 'author' bits of it.</p>
<p>is there a way to do this? i can't find anything written in the documentation online.</p>
<p>apologies if this is confusing, i'm not 100% sure what i'm doing.</p>
|
<p>You can do this by using the <code>requests</code> library. The code below imports the library, creates the query for the api and then makes the requests and then finally prints the response.</p>
<pre><code>import requests
query = "https://api.quotable.io/random"
response = requests.get(query)
print(respsonse)
</code></pre>
<p>To output specific parts of the response, you will need to use JSON formatting. The code below only outputs the content of the message from the api request that you have made.</p>
<pre><code>import requests
query = "https://api.quotable.io/random"
response = requests.get(query)
print(response["content"])
</code></pre>
<p>To implement this is discord instead of printing the response you can use <code>message.send</code> which is already built in. An example is below. This code makes the same request and instead outputs the content from the api request.</p>
<pre><code>import discord
import requests
@commands.command()
async def search(ctx):
query = "https://api.quotable.io/random"
response = requests.get(query)
output = "The quote is " + response["content"]
await ctx.send(output)
</code></pre>
|
python|discord|command|bots
| 1 |
1,907,119 | 68,726,083 |
Clustering on Python and Bokeh; select widget which allows user to change clustering algorithm
|
<p>I am trying to build a feature in a Bokeh dashboard which allows the user to cluster data. I am using the following example as a template, here is the link:-
<a href="https://github.com/bokeh/bokeh/blob/branch-2.4/examples/webgl/clustering.py" rel="nofollow noreferrer">Clustering in Bokeh example</a></p>
<p>Here is the code from this example:-</p>
<pre><code>import numpy as np
from sklearn import cluster, datasets
from sklearn.preprocessing import StandardScaler
from bokeh.layouts import column, row
from bokeh.plotting import figure, output_file, show
print("\n\n*** This example may take several seconds to run before displaying. ***\n\n")
N = 50000
PLOT_SIZE = 400
# generate datasets.
np.random.seed(0)
noisy_circles = datasets.make_circles(n_samples=N, factor=.5, noise=.04)
noisy_moons = datasets.make_moons(n_samples=N, noise=.05)
centers = [(-2, 3), (2, 3), (-2, -3), (2, -3)]
blobs1 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.4, random_state=8)
blobs2 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.7, random_state=8)
colors = np.array([x for x in ('#00f', '#0f0', '#f00', '#0ff', '#f0f', '#ff0')])
colors = np.hstack([colors] * 20)
# create clustering algorithms
dbscan = cluster.DBSCAN(eps=.2)
birch = cluster.Birch(n_clusters=2)
means = cluster.MiniBatchKMeans(n_clusters=2)
spectral = cluster.SpectralClustering(n_clusters=2, eigen_solver='arpack', affinity="nearest_neighbors")
affinity = cluster.AffinityPropagation(damping=.9, preference=-200)
# change here, to select clustering algorithm (note: spectral is slow)
algorithm = dbscan # <- SELECT ALG
plots =[]
for dataset in (noisy_circles, noisy_moons, blobs1, blobs2):
X, y = dataset
X = StandardScaler().fit_transform(X)
# predict cluster memberships
algorithm.fit(X)
if hasattr(algorithm, 'labels_'):
y_pred = algorithm.labels_.astype(int)
else:
y_pred = algorithm.predict(X)
p = figure(output_backend="webgl", title=algorithm.__class__.__name__,
width=PLOT_SIZE, height=PLOT_SIZE)
p.circle(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), alpha=0.1,)
plots.append(p)
# generate layout for the plots
layout = column(row(plots[:2]), row(plots[2:]))
output_file("clustering.html", title="clustering with sklearn")
show(layout)
</code></pre>
<p>The example allows the user to cluster data. Within the code, you can specify which algorithm to use; in the code pasted above, the algorithm is dbscan. I tried to modify the code so that I can add in a widget which would allow the user to specify the algorithm to use :-</p>
<pre><code>
from bokeh.models.annotations import Label
import numpy as np
from sklearn import cluster, datasets
from sklearn.preprocessing import StandardScaler
from bokeh.layouts import column, row
from bokeh.plotting import figure, output_file, show
from bokeh.models import CustomJS, Select
print("\n\n*** This example may take several seconds to run before displaying. ***\n\n")
N = 50000
PLOT_SIZE = 400
# generate datasets.
np.random.seed(0)
noisy_circles = datasets.make_circles(n_samples=N, factor=.5, noise=.04)
noisy_moons = datasets.make_moons(n_samples=N, noise=.05)
centers = [(-2, 3), (2, 3), (-2, -3), (2, -3)]
blobs1 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.4, random_state=8)
blobs2 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.7, random_state=8)
colors = np.array([x for x in ('#00f', '#0f0', '#f00', '#0ff', '#f0f', '#ff0')])
colors = np.hstack([colors] * 20)
# create clustering algorithms
dbscan = cluster.DBSCAN(eps=.2)
birch = cluster.Birch(n_clusters=2)
means = cluster.MiniBatchKMeans(n_clusters=2)
spectral = cluster.SpectralClustering(n_clusters=2, eigen_solver='arpack', affinity="nearest_neighbors")
affinity = cluster.AffinityPropagation(damping=.9, preference=-200)
kmeans = cluster.KMeans(n_clusters=2)
############################select widget for different clustering algorithms############
menu =[('DBSCAN','dbscan'),('Birch','birch'),('MiniBatchKmeans','means'),('Spectral','spectral'),('Affinity','affinity'),('K-means','kmeans')]
select = Select(title="Option:", value="DBSCAN", options=menu)
select.js_on_change("value", CustomJS(code="""
console.log('select: value=' + this.value, this.toString())
"""))
# change here, to select clustering algorithm (note: spectral is slow)
algorithm = select.value
############################################################
plots =[]
for dataset in (noisy_circles, noisy_moons, blobs1, blobs2):
X, y = dataset
X = StandardScaler().fit_transform(X)
# predict cluster memberships
algorithm.fit(X)
if hasattr(algorithm, 'labels_'):
y_pred = algorithm.labels_.astype(int)
else:
y_pred = algorithm.predict(X)
p = figure(output_backend="webgl", title=algorithm.__class__.__name__,
width=PLOT_SIZE, height=PLOT_SIZE)
p.circle(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), alpha=0.1,)
plots.append(p)
# generate layout for the plots
layout = column(select,row(plots[:2]), row(plots[2:]))
output_file("clustering.html", title="clustering with sklearn")
show(layout)
</code></pre>
<p>However, I get this error when I try to run it:-</p>
<pre><code>AttributeError: 'str' object has no attribute 'fit'
</code></pre>
<p>Can anyone tell me what I am missing in order to fix this?</p>
<p>Also, and if not too hard to do, I would like to add in a numeric input widget which allows the user to select the number of clusters for each algorithm to find. Suggestions?</p>
<p>Many thanks :)</p>
<p><strong>EDIT</strong></p>
<p>Here is the current state of the code with @Tony solution.</p>
<pre><code>''' Example inspired by an example from the scikit-learn project:
http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_comparison.html
'''
#https://github.com/bokeh/bokeh/blob/branch-2.4/examples/webgl/clustering.py
from bokeh.models.annotations import Label
import numpy as np
from sklearn import cluster, datasets
from sklearn.preprocessing import StandardScaler
from bokeh.layouts import column, row
from bokeh.plotting import figure, output_file, show
from bokeh.models import CustomJS, Select
print("\n\n*** This example may take several seconds to run before displaying. ***\n\n")
N = 50000
PLOT_SIZE = 400
# generate datasets.
np.random.seed(0)
noisy_circles = datasets.make_circles(n_samples=N, factor=.5, noise=.04)
noisy_moons = datasets.make_moons(n_samples=N, noise=.05)
centers = [(-2, 3), (2, 3), (-2, -3), (2, -3)]
blobs1 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.4, random_state=8)
blobs2 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.7, random_state=8)
colors = np.array([x for x in ('#00f', '#0f0', '#f00', '#0ff', '#f0f', '#ff0')])
colors = np.hstack([colors] * 20)
# create clustering algorithms
dbscan = cluster.DBSCAN(eps=.2)
birch = cluster.Birch(n_clusters=2)
means = cluster.MiniBatchKMeans(n_clusters=2)
spectral = cluster.SpectralClustering(n_clusters=2, eigen_solver='arpack', affinity="nearest_neighbors")
affinity = cluster.AffinityPropagation(damping=.9, preference=-200)
kmeans = cluster.KMeans(n_clusters=2)
menu =[('DBSCAN','dbscan'),('Birch','birch'),('MiniBatchKmeans','means'),('Spectral','spectral'),('Affinity','affinity'),('K-means','kmeans')]
select = Select(title="Option:", value="DBSCAN", options=menu)
select.js_on_change("value", CustomJS(code="""
console.log('select: value=' + this.value, this.toString())
"""))
# change here, to select clustering algorithm (note: spectral is slow)
#algorithm = select.value
algorithm = None
if select.value == 'dbscan':
algorithm = dbscan # use dbscan algorithm function
elif select.value == 'birch':
algorithm = birch # use birch algorithm function
elif select.value == 'means':
algorithm = means # use means algorithm function
elif select.value == 'spectral':
algorithm = spectral
elif select.value == 'affinity':
algorithm = affinity
elif select.value == 'kmeans':
algorithm = 'kmeans'
if algorithm is not None:
plots =[]
for dataset in (noisy_circles, noisy_moons, blobs1, blobs2):
X, y = dataset
X = StandardScaler().fit_transform(X)
# predict cluster memberships
algorithm.fit(X) ######################This is what appears to be the problem######################
if hasattr(algorithm, 'labels_'):
y_pred = algorithm.labels_.astype(int)
else:
y_pred = algorithm.predict(X)
p = figure(output_backend="webgl", title=algorithm.__class__.__name__,
width=PLOT_SIZE, height=PLOT_SIZE)
p.circle(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), alpha=0.1,)
plots.append(p)
else:
print('Please select an algorithm first')
# generate layout for the plots
layout = column(select,row(plots[:2]), row(plots[2:]))
output_file("clustering.html", title="clustering with sklearn")
show(layout)
</code></pre>
<p>See <code>algorithm.fit(X)</code> this is where the error occurs.
Error message:-</p>
<pre><code>AttributeError: 'NoneType' object has no attribute 'fit'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
m:\bokehdash\clusteringbokeh.py in
67
68 # predict cluster memberships
---> 69 algorithm.fit(X)
70 if hasattr(algorithm, 'labels_'):
71 y_pred = algorithm.labels_.astype(int)
AttributeError: 'NoneType' object has no attribute 'fit'
</code></pre>
|
<p>I don't know <code>sklearn</code> but comparing both your examples I can see the following:</p>
<ol>
<li>the <code>Select</code> is a Bokeh model which has <code>value</code> attribute of type <code>string</code>. So <code>select.value</code> is a <strong>string</strong></li>
<li>the <code>dbscan</code> is an <strong>algorithm function</strong></li>
</ol>
<p>So when you do <code>algorithm = dbscan</code> you assign an algorithm function to your <code>algorithm</code> variable and when you do <code>algorithm = select.value</code> in your second example you assign just a string to it so it won't work because <code>string</code> doesn't have the <code>fit()</code> function. You should do something like this:</p>
<pre><code>algorithm = None
if select.value == 'DBSCAN':
algorithm = dbscan # use dbscan algorithm function
elif select.value == 'Birch':
algorithm = birch # use birch algorithm function
elif select.value == 'MiniBatchKmeans':
algorithm = means # use means algorithm function
etc...
if algorithm is not None:
plots =[]
for dataset in (noisy_circles, noisy_moons, blobs1, blobs2):
...
else:
print('Please select an algorithm first')
</code></pre>
|
python|numpy|scikit-learn|cluster-analysis|bokeh
| 1 |
1,907,120 | 10,847,703 |
Check if pyodbc connection is open or closed
|
<p>I often get this error: <code>ProgrammingError: The cursor's connection has been closed.</code> </p>
<p>Is there a way to check whether the connection I am using has been closed before I attempt to execute a query?</p>
<p>I'm thinking of writing a wrapper to execute queries. First it would check whether the connection is closed, if it is, it would reconnect. Is this an advisable way of doing this?</p>
|
<p>The wrapper is a good idea but I don't know any API to reliably check whether the connection is closed or not.</p>
<p>So the solution would be something along these lines:</p>
<pre><code>for retry in range(3):
try:
... execute query ...
return # Stop on success
except e:
if is_connection_broken_error(e):
reconnect()
continue
raise
raise # throw if the retry fails too often
</code></pre>
|
python|mysql|odbc|pyodbc
| 6 |
1,907,121 | 5,086,789 |
Python: Is there an inverse for ndarray.flatten('F')?
|
<p>For example:</p>
<pre><code>from numpy import *
x = array([[1,2], [3, 4], [5, 6]])
print x.flatten('F')
>>>[1 3 5 2 4 6]
</code></pre>
<p>Is it possible to get <code>[[1,2], [3, 4], [5, 6]]</code> from <code>[1 3 5 2 4 6]</code>?</p>
|
<pre><code>>>> a = numpy.array((1, 3, 5, 2 ,4, 6))
>>> a.reshape(2, -1).T
array([[1, 2],
[3, 4],
[5, 6]])
>>>
</code></pre>
|
python|arrays|numpy
| 21 |
1,907,122 | 67,402,228 |
How can I apply multiple filter using pandas?
|
<p>How can I apply multiple filter using pandas for 100 values easily?
There are two columns (column/column2), and 500000 rows.
My aim is: find some values such as value-1, value-2, etc. in the sample.xlsx file (should be include all of them). Then extract unique values from column2 to another xlsx file.</p>
<pre><code>import pandas as pd
df=pd.read_excel('sample.xlsx')
filtered_list = df[(df['column']=='value-1')|
(df['column']=='value-2')]
(df['column']=='value-3')]
.......
(df['column']=='value-100')]
print(filtered_list)
</code></pre>
<pre><code> list = ['value-1', 'value-2', ..., 'value-100']
**Sample Dataset**
column column2
value-1 gene1
value-2 gene1
value-3 gene2
value-4 gene2
value-5 gene2
..... ....
value-100 gene3
value-102 gene3
value-105 gene4
</code></pre>
<pre><code>**1. Desired Output**
column column2
value-1 gene1
value-2 gene1
value-3 gene2
value-4 gene2
value-5 gene2
..... ....
value-100 gene3
</code></pre>
<pre><code>**2. Desired Output**
column2
gene1
gene2
gene3
</code></pre>
<p>@domiziano</p>
|
<p>If you have a list of all the values you want you can do</p>
<pre><code>list = ['value-1', 'value-2', ..., 'value-100']
filtered_list = df[df['column'].isin(list)]
</code></pre>
<p>Then to see all unique values from column2</p>
<pre><code>filtered_list['column2'].unique()
</code></pre>
|
python|python-3.x|pandas
| 0 |
1,907,123 | 60,720,451 |
Openvino-opencv videocapture abnormal behaviour
|
<p>I have been using IP camera's rtsp stream for video capturing. For capturing and display,I've found <code>openvino-opencv</code> is almost 10x faster than system <code>python-opencv</code>. BUT some abnormal things is going on which doesn't make sense to me:</p>
<p>Average time taken by <code>openvino-opencv</code> to read and display image is <code>0.01 sec approx.</code>except every once in a while (approxly after every 250 frame) it takes <code>4.5 sec approx</code>.</p>
<p><strong>NOTES</strong>:</p>
<pre><code>CAMERA MODEL: FLIR AX8
CAMERA FRAME_RATE = 30
Average time taken by system-python to read and display is 0.11
I tested with UCAM, both performs similar
I tested with static video, system-python runs faster.```
</code></pre>
|
<p>It is possible that the IP camera has some sort of buffering to avoid a non-continuous streaming.</p>
<p>I would recommend to match your consuming frames speed to the IP camera framerate and that shouldn't be a problem anymore.</p>
|
python|opencv|openvino
| 0 |
1,907,124 | 71,343,561 |
Access dict objects from json dict
|
<p>I have a json that includes a dict and a list. I want to loop only the dict objects and stop the loop.</p>
<pre><code>json_res = {
"abc": "123",
"Students": [
{
"Sub1": {
"Name":"Amit Goenka"
},
"Sub2": {
"Major":"Physics" ,
"Name2":"Smita Pallod"
},
"Sub3": {
"Major2":"Chemistry" ,
"Name3":"Rajeev Sen" ,
"Major3":"Mathematics"
}
},
[
[
"Name",
0,
"Student",
1
]
]
]
}
</code></pre>
<p>Here is what I tried:</p>
<pre><code>for data in json_res['Students']:
val = data.get('Sub3')
</code></pre>
<p>this results:</p>
<pre><code>{
"Major2":"Chemistry" ,
"Name3":"Rajeev Sen" ,
"Major3":"Mathematics"
}
</code></pre>
<p>and fails. I want to consider the loop only from "Sub1" till "Sub3".</p>
|
<p>You need to add the isinstance to check for dict.</p>
<pre><code>for data in json_res['Students']:
if isinstance(data, dict):
val = data.get('Sub3')
print(val)
</code></pre>
|
python|json|dictionary
| 0 |
1,907,125 | 55,696,957 |
Text Pre-processing Error: ['Errno 21] Is a directory
|
<p>I am trying to get all files from my directory and then run them through a series of def functions (python 3) and outputting each processed file into a certain directory. Below is my code:</p>
<pre><code> import re
import glob
import sys
import string
#Create Stop_word Corpora
file1=open("/home/file/corps/stopwords.txt", 'rt', encoding='latin-1')
line= file1.read()
theWords=line.split()
stop_words=sorted(set(theWords)) # Stop Word Corpora
#Gather txt files to be processed
folder_path = "/home/file"
file_pattern = "/*txt"
folder_contents = glob.glob(folder_path + file_pattern)
#Read in the Txt Files
for file in folder_contents:
print("Checking", file)
words= []
for file in folder_contents:
read_file = open(file, 'rt', encoding='latin-1').read()
words.extend(read_file.split())
def to_lowercase(words):
#"""Convert all characters to lowercase from list of tokenized words"""
new_words=[]
for word in words:
new_word=word.lower()
new_words.append(new_word)
return new_words
def remove_punctuation(words):
#"""Remove punctuation from list of tokenized words"""
new_words=[]
for word in words:
new_word = re.sub(r'[^\w\s]', '', word)
if new_word != '':
new_words.append(new_word)
return new_words
def replace_numbers(words):
#""""""Replace all interger occurrences in list of tokenized words with textual representation"
new_words=[]
for word in words:
new_word= re.sub(" \d+", " ", word)
if new_word !='':
new_words.append(new_word)
return new_words
def remove_stopwords(words):
#"""Remove stop words from list of tokenized words"""
new_words=[]
for word in words:
if not word in stop_words:
new_words.append(word)
return new_words
def normalize(words):
words = to_lowercase(words)
words = remove_punctuation(words)
words = replace_numbers(words)
words = remove_stopwords(words)
return words
words = normalize(words)
# Write the new procssed file to a different location
append_file=open("/home/file/Processed_Files",'a')
append_file.write("\n".join(words))
</code></pre>
<p>This is the error I keep receiving:</p>
<p><a href="https://i.stack.imgur.com/oKxKq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oKxKq.png" alt="enter image description here"></a></p>
<p>I want the new text files to be sent to the directory above, after they have been ran through the def functions. So there should be 5 new files in the Processed_files directory above.</p>
|
<p>The traceback you present doesn't agree with the error reported in your question title.</p>
<p>But your code does this twice:</p>
<pre><code>for word in words:
new_word = re.sub(r'[^\w\s]', '', word)
if new_word != '':
new_words.append(new_word)
</code></pre>
<p>If <code>words</code> is empty, then the <code>for word in words</code> loop never gets executed, even once. And if it doesn't get executed even once then no value ever gets assigned to <code>new_word</code>. So, in that case, when your code does <code>if new_word != '':</code> you will get the error <code>new_word referenced before assignment</code>. That is because your code is asking what is in <code>new_word</code> but it is unassigned.</p>
<p>This problem will go away if you code it like this:</p>
<pre><code>for word in words:
new_word = re.sub(r'[^\w\s]', '', word)
if new_word != '':
new_words.append(new_word)
</code></pre>
<p>which I suspect is what you meant, anyway.</p>
|
python|python-3.x
| 2 |
1,907,126 | 69,994,895 |
Python Pandas: Get the two largest values from a set of numbers but ensure they are x amount of values apart
|
<p>Is it possible to use .nlargest to get the two highest numbers in a set of number, but ensure that they are x amount of rows apart?</p>
<p>For examples, in the following code I would want to find the largest values but ensure that they are more than 5 values apart from each other. Is there an easy way to do this?</p>
<pre><code> data = {'Pressure' : [100,112,114,120,123,420,1222,132,123,333,123,1230,132,1,23,13,13,13,123,13,123,3,222,2303,1233,1233,1,1,30,20,40,401,10,40,12,122,1,12,333],
}
</code></pre>
|
<p>If I understand the question correctly, you need to output the largest value, and then the next largest value that's at least X rows apart from it (based on the index).</p>
<p>First value is just <code>data.Pressure.max()</code>. Its index is <code>data.Pressure.idxmax()</code></p>
<p>Second value is either before or after the first value's index:</p>
<pre class="lang-py prettyprint-override"><code>max_before = df.Pressure.loc[:df.Pressure.idxmax() - X].max()
max_after = df.Pressure.loc[df.Pressure.idxmax() + X:].max()
second_value = max(max_before, max_after)
</code></pre>
|
python|pandas
| 0 |
1,907,127 | 17,753,019 |
Typing Text into the Tkinter Canvas Widget
|
<p>I need to allow the users to type text into the Canvas Widget, making the canvas update as the user types new text.</p>
<p>Here's what I have tried so far, but am not getting it to work.</p>
<p>First I have a <code>mouseDown</code> method which is bound to Button-1 event</p>
<pre><code>widget.bind(self.canvas, "<Button-1>", self.mouseDown)
</code></pre>
<p>This <code>mouseDown</code> method returns the <code>startx, starty</code> positions to my method <code>drawText</code></p>
<pre><code>def drawText(self, x, y, fg):
self.currentObject = self.canvas.create_text(x,y,fill=fg,text=self.typedtext)
</code></pre>
<p>I also have a global binding on the canvas widget to capture any key press like this:</p>
<pre><code>Widget.bind(self.canvas, "<Any KeyPress>", self.currentTypedText)
def currentTypedText(self, event):
self.typedtext = str(event.keysym)
self.drawText(self, self.startx, self.starty,self.foreground)
</code></pre>
<p>However there's no error and nothing gets printed on the canvas.</p>
|
<p>What you want to do is pretty complex and will require quite a bit of code to get working nicely. You will need to handle click events, keypress events, special keypress events (such as "Shift" and "Ctrl"), "Backspace" and delete events, and a lot more.</p>
<p>Nevertheless, first is first and that is getting text to appear in the canvas as a user types. Now, since I don't have your full script, I can't really work with your stuff as is. However, I went and made my own little app that does exactly what you want. Hopefully, it will shine some light on where to go:</p>
<pre><code>from Tkinter import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
# self.x and self.y are the current mouse position
# They are set to None here because nobody has clicked anywhere yet.
self.x = None
self.y = None
self.makeCanvas()
self.bind("<Any KeyPress>", lambda event: self.drawText(event.keysym))
def makeCanvas(self):
self.canvas = Canvas(self)
self.canvas.pack()
self.canvas.bind("<Button-1>", self.mouseDown)
def mouseDown(self, event):
# Set self.x and self.y to the current mouse position
self.x = event.x
self.y = event.y
def drawText(self, newkey):
# The if statement makes sure we have clicked somewhere.
if None not in {self.x, self.y}:
self.canvas.create_text(self.x, self.y, text=newkey)
# I set x to increase by 5 each time (it looked the nicest).
# 4 smashed the letters and 6 left gaps.
self.x += 5
App().mainloop()
</code></pre>
<p>Once you click somewhere in the canvas and start typing, you will see text appear. Note however that I have not enabled this to handle deletion of text (that is a little tricky and beyond the scope of your question).</p>
|
python|python-2.7|tkinter
| 2 |
1,907,128 | 17,985,021 |
Returning a Unicode string vs. Returning a normal string encoded as UTF-8?
|
<p>On the <a href="https://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">tutorial page</a> for the Django web framework, the author explains why adding a <code>__unicode__()</code> method is preferred than a <code>__str__()</code> with the following reason:</p>
<blockquote>
<p>Django models have a default <code>__str__()</code> method that calls
<code>__unicode__()</code> and converts the result to a UTF-8 bytestring. <strong>This
means that <code>unicode(p)</code> will return a Unicode string, and <code>str(p)</code>
will return a normal string, with characters encoded as UTF-8.</strong></p>
</blockquote>
<p>I don't understand what's the difference between a Unicode string and a string with characters encoded as UTF-8. I thought UTF-8 is one of the encodings for Unicode?</p>
|
<p>Python Unicode objects are abstract - they represent a sequence of Unicode code points independent of any particular encoding. A UTF-8 encoded string, on the other hand, is a sequence of bytes that encodes a sequence of Unicode code points. They're different levels of abstraction.</p>
<p>You can think of code points as being like an abstract number, and an encoding as being like a particular binary representation of that number. A Unicode object represents the "number" (actually the codepoints), while a string represents the binary. This analogy is not exact, but if you're already used to the idea that, say, an object to represent the integer "8" is different from an object to represent the specific bit sequence "00001000" it may prove clarifying. Especially if you've worked with systems like twos-complement, where the bit sequence that represents the abstract integer "8" would be different.</p>
<p><a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">This essay</a>, while now almost ten years old, is still one of the clearest and most comprehensive explanations of the concepts I've ever run into.</p>
<p><a href="https://stackoverflow.com/questions/22149/unicode-vs-utf-8-confusion-in-python-django?rq=1">This answer</a> is pretty good on the Python-specific details.</p>
|
python|django|unicode|django-models|utf-8
| 3 |
1,907,129 | 60,966,981 |
Extracting the values from dictionary with tuple
|
<p>I'm working on support vector machine where I extracted the best parameters for polynomial, linear and RBF using <strong>gridsearchcv</strong> . I wanted to separate C and degree values so that I can call the best parameters for my dataset for the fit function where I can compute the accuracy with the tuned parameters. </p>
<p>The dictionary with tuple is </p>
<p>({'C': 1, 'degree': 1}, {'C': 0.1, 'degree': 1}, {'C': 1, 'degree': 1})</p>
<p>I tried using</p>
<pre><code>for i in c.items():
value=i
print(value)
</code></pre>
<p>But got error:
AttributeError: 'tuple' object has no attribute 'items'</p>
<p>The progress of my code is:</p>
<pre><code> def svc_param_selection(self, X, y, nfolds):
#We tune two hyperparameters C and d using svc_param_selection
#the slack penalty hyperparameter
Cs = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]
#degrees of polynomial kernel of svc
degrees = [1, 2, 3, 4, 5]
#initialize the paremeter grid as dictionary
param_grid = {'C': Cs, 'degree' : degrees}
#initialize search for best parameters using input nfold cross validation
search = grid_search.GridSearchCV(svm.SVC(kernel='poly'), param_grid, cv=nfolds)
search1 = grid_search.GridSearchCV(svm.SVC(kernel='linear'), param_grid, cv=nfolds)
search2 = grid_search.GridSearchCV(svm.SVC(kernel='rbf'), param_grid, cv=nfolds)
#fit the search object to input training data
search.fit(X, y)
search1.fit(X, y)
search2.fit(X, y)
#return the best parameters
search.best_params_
search1.best_params_
search2.best_params_
print("[*] Searching for the best parameters for fitting the data.......")
print("Parameters are :")
#print(search.best_params_)
#print(search1.best_params_)
#print(search2.best_params_)
return search.best_params_,search1.best_params_,search2.best_params_
def param_sel(self):
X_train,y_train,X_test,y_test=self.norm()
#self.svc_param_selection(X_train, y_train, 10)
degree=np.array([])
c= self.svc_param_selection(X_train, y_train, 10)
print(c)
for i in c.items():
value=i
print(value)
def fit(self):
X_train,y_train,X_test,y_test=self.norm()
final_svc_poly1 = svm.SVC(C=1, degree=1, kernel='poly')
final_svc_poly2 = svm.SVC(C=1, degree=1, kernel='linear')
final_svc_poly3 = svm.SVC(C=1, degree=1, kernel='rbf')
final_svc_poly1.fit(X_train, y_train)
final_svc_poly2.fit(X_train, y_train)
final_svc_poly3.fit(X_train, y_train)
print("[*] Computing accuracy of test dataset")
print("Accuracy with polynomial kernel",final_svc_poly1.score(X_test, y_test))
print("Accuracy with linear kernel",final_svc_poly2.score(X_test, y_test))
print("Accuracy with RBF kernel",final_svc_poly3.score(X_test, y_test))
</code></pre>
<p>Output:</p>
<pre><code>[*] Searching for the best parameters for fitting the data.......
Parameters are :
({'C': 1, 'degree': 1}, {'C': 0.1, 'degree': 1}, {'C': 1, 'degree': 1})
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-106-4be4dd58a851> in <module>
1 if __name__=='__main__':
----> 2 main()
<ipython-input-105-7b466d716ef5> in main()
7 #X_train,y_train=first.split_data()
8 #print(X_train)
----> 9 param=second.param_sel()
10 second.fit()
<ipython-input-104-57f0d958ed41> in param_sel(self)
69 c= self.svc_param_selection(X_train, y_train, 10)
70 print(c)
---> 71 for i in c.items():
72 value=i
73 print(value)
</code></pre>
<p>AttributeError: 'tuple' object has no attribute 'items'</p>
|
<p>Your value - <code>C=({'C': 1, 'degree': 1}, {'C': 0.1, 'degree': 1}, {'C': 1, 'degree': 1})</code> is a tuple of dictionaries, hence it has no attribute <code>items</code>.</p>
<p>You can iterate over the tuple with - </p>
<pre><code>for item in C:
print(item)
</code></pre>
<p>So, fixing according to the clarification - </p>
<pre><code>c_values = []
degrees = []
for item in C:
c_values.append(item['C'])
degrees.append(item['degree'])
</code></pre>
<p>btw - in your loop you override value in each iteration any print it outside the loop.</p>
|
python|machine-learning|deep-learning|tuples|svm
| 1 |
1,907,130 | 66,001,665 |
Python gzip and Java GZIPOutputStream give different results
|
<p>I'm trying to take hash of gzipped string in Python and need it to be identical to Java's. But Python's <code>gzip</code> implementation seems to be different from Java's <code>GZIPOutputStream</code>.</p>
<p>Python <code>gzip</code>:</p>
<pre><code>import gzip
import hashlib
gzip_bytes = gzip.compress(bytes('test', 'utf-8'))
gzip_hex = gzip_bytes.hex().upper()
md5 = hashlib.md5(gzip_bytes).hexdigest().upper()
>>>gzip_hex
'1F8B0800678B186002FF2B492D2E01000C7E7FD804000000'
>>>md5
'C4C763E9A0143D36F52306CF4CCC84B8'
</code></pre>
<p>Java <code>GZIPOutputStream</code>:</p>
<pre><code>import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HelloWorld{
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
public static String md5(byte[] bytes) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytes);
return bytesToHex(thedigest);
}
catch (NoSuchAlgorithmException e){
new RuntimeException("MD5 Failed", e);
}
return new String();
}
public static void main(String []args){
String string = "test";
final byte[] bytes = string.getBytes();
try {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final GZIPOutputStream gout = new GZIPOutputStream(bos);
gout.write(bytes);
gout.close();
final byte[] encoded = bos.toByteArray();
System.out.println("gzip: " + bytesToHex(encoded));
System.out.println("md5: " + md5(encoded));
}
catch(IOException e) {
new RuntimeException("Failed", e);
}
}
}
</code></pre>
<p>Prints:</p>
<pre><code>gzip: 1F8B08000000000000002B492D2E01000C7E7FD804000000
md5: 1ED3B12D0249E2565B01B146026C389D
</code></pre>
<p>So, both gzip bytes outputs seem to be very similar, but slightly different.</p>
<p>1F8B0800<strong>678B186002FF</strong>2B492D2E01000C7E7FD804000000</p>
<p>1F8B0800<strong>000000000000</strong>2B492D2E01000C7E7FD804000000</p>
<p>Python <code>gzip.compress()</code> method accepts <code>compresslevel</code> argument in range of 0-9. Tried all of them, but none gives desired result.
Any way to get same result as Java's <code>GZIPOutputStream</code> in Python?</p>
|
<p>Your requirement "hash of gzipped string in Python and need it to be identical to Java's" cannot be met in general. You need to change your requirement, implementing your need differently. I would recommend requiring simply that the <em>decompressed</em> data have identical hashes. In fact, there is a 32-bit hash (a CRC-32) of the decompressed data already there in the two gzip strings, which are identical (<code>0xd87f7e0c</code>). If you want a longer hash, then you can append one. The last four bytes is the uncompressed length, modulo 2<sup>32</sup>, so you can compare those as well. Just compare the last eight bytes of the two strings and check that they are the same.</p>
<p>The difference between the two gzip strings in your question illustrates the issue. One has a time stamp in the header, and the other does not (set to zeros). Even if they both had time stamps, they would still very likely be different. They also have some other bytes in the header different, like the originating operating system.</p>
<p>Furthermore, the compressed data in your examples is extremely short, so it just so happens to be identical in this case. However for any reasonable amount of data, the compressed data generated by two gzippers will be different, <em>unless</em> they happen to made with exactly the same deflate code, the same version of that code, and the same memory size and compression level settings. If you are not in control of all of those, you will never be able to assure the same compressed data coming out of them, given identical uncompressed data.</p>
<p>In short, don't waste your time trying to get identical compressed strings.</p>
|
java|python|gzip|gzipoutputstream
| 1 |
1,907,131 | 66,253,559 |
Python: Function scope inside a class
|
<p>Let's consider the code below.</p>
<pre class="lang-py prettyprint-override"><code>name = "John"
class MyClass:
name = "Tom"
list_1 = [name] * 2
list_2 = [name for i in range(2)]
</code></pre>
<p>On first look, one might expect <code>list_1</code> and <code>list_2</code> to both have the same
content: <code>["Tom", "Tom"]</code>, but this is not the case. <code>list_1</code> evaluates to
<code>["Tom", "Tom"]</code>, whereas <code>list_2</code> evaluates to <code>["John", "John"]</code>.</p>
<p>I read that when a function is nested inside a class, Python will use variables defined in the module scope and not in the class scope. <code>list_1</code> is not a function, so it uses <code>name</code> from the class scope, whereas <code>list_2</code> is a function and, therefore, uses <code>name</code> from the module scope. I understand this is how it works, but it seems counter-intuitive. I don't understand the reason.</p>
|
<p>Scoping with list comprehensions takes some getting used to. In this case, the local scope within the list comprehension <code>list2 = [name for i in range(2)]</code> temporarily blocks class local scope. See: <a href="https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition">this answer</a>.</p>
|
python|function|class|oop|scope
| 0 |
1,907,132 | 66,104,957 |
How to read the file when that file was changed?
|
<p>I don't know how to use the watchdog script and read file script together.</p>
<pre><code>import sys
import time
import logging from watchdog.observers
import Observer from watchdog.events
import LoggingEventHandler
if name == "main":
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
path = "C:/watch"
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()
file = open('test.txt','r')
f = file.readlines()
newList = []
for line in f:
newList.append(line[:-1])
print(newList)
</code></pre>
|
<p>Your imports are incorrect (syntax error), and so is the <code>if name == "main":</code> test, take another look at the example in <a href="https://pypi.org/project/watchdog/" rel="nofollow noreferrer">https://pypi.org/project/watchdog/</a>. Here's a patched version, plus a couple of changes listed below:</p>
<pre><code>import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
def on_modified(event_handler):
print(f'event_handler.src_path={event_handler.src_path}')
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = "C:/watch"
event_handler = LoggingEventHandler()
event_handler.on_modified = on_modified
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()
</code></pre>
<p>I added a callback function <code>on_modified</code> (currently does just a print), assigned it to your event handler's on_modified function, removed the editing of the "test.txt" file at the end. You should now put this into the callback function.</p>
<p>You can see in the callback function that <code>event_handler.src_path</code> is the path to a file that was modified: at that point, you can put the code to read the file.</p>
|
python|python-watchdog
| 0 |
1,907,133 | 66,186,262 |
Can I get information on an S3 Bucket's public access bucket Settings from boto3?
|
<p>I am using boto3 to extract information about my S3 buckets.<br />
However, I am stuck at this point. I am trying to extract information about a bucket's public access (see attached screenshot).</p>
<p>How can I get this information? So far I have failed to find out any boto3 function that allows me to do so.</p>
<p><a href="https://i.stack.imgur.com/byANc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/byANc.png" alt="enter image description here" /></a></p>
|
<p>You can use <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.get_public_access_block" rel="nofollow noreferrer"><code>get_public_access_block()</code></a>:</p>
<blockquote>
<p>Retrieves the <code>PublicAccessBlock</code> configuration for an Amazon S3 bucket.</p>
<p>When Amazon S3 evaluates the <code>PublicAccessBlock</code> configuration for a bucket or an object, it checks the <code>PublicAccessBlock</code> configuration for both the bucket (or the bucket that contains the object) and the bucket owner's account. If the <code>PublicAccessBlock</code> settings are different between the bucket and the account, Amazon S3 uses the most restrictive combination of the bucket-level and account-level settings.</p>
</blockquote>
<p>If you wish to modify the settings, you can use: <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.put_public_access_block" rel="nofollow noreferrer"><code>put_public_access_block()</code></a></p>
|
python-3.x|amazon-web-services|amazon-s3|boto3
| 1 |
1,907,134 | 72,596,889 |
How can I make pynput.mouse do a task N times?
|
<p>How can I make Python do this task</p>
<pre><code>from pynput.mouse import Button, Controller
mouse = Controller()
mouse.position(660,226)
mouse.press(Button.left)
mouse.release(Button.left)
</code></pre>
<p>every 10 seconds, X amount of times?</p>
|
<p>You can wrap the thing you want to do multiple times in a <code>for</code> block, for example like this:</p>
<pre class="lang-py prettyprint-override"><code>for iteration in range(X):
# do the thing
</code></pre>
<p>Make sure to replace X by the amount of actions you want to do.</p>
<p>You can also add a <code>time.sleep(seconds)</code> to the end of the action inside the <code>for</code> block to make it sleep each time after completing the action.</p>
|
python|loops|task|pynput
| 1 |
1,907,135 | 59,330,884 |
How to find and replace all cells with an attribute in pandas/python
|
<p>I cant find any info specific to finding attribute within cells of a df. Below is a sample of the data without the real names/orgs but otherwise you can see its quite a mess. I am new to data cleaning and I need to find a way to select all 'cells' with a certain attribute in the df. I need to keep the data so to replace or drop them is not an option I dont think.
I am volunteering with a museum to help clean up their SalesForce account and for years they have been taking note of every donation (among other things) in a column called 'Important Notes'. I exported all the data to an .xls file and with a jupyter notebook using pandas I reduced the df to just 3 columns: the index, org name, and the 'important notes' column. Because this 'Important Notes' column has info that needs to be kept my plan is to try and filter all cells in the column WITHOUT a '$' and then change them all to Null as a place holder and then clean the rest to make them uniform entries to add up into a new total donations column. My plan is to do this then import it back into SF then apply a function to add the donations and give a running total of the amount a specific organization or donor has contributed.
If anyone could offer possible solutions or point me in a helpful direction it would be greatly appreciated.</p>
<p><a href="https://i.stack.imgur.com/M63uL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M63uL.png" alt="enter image description here"></a></p>
<p>Hoping to eventually have a column like this: </p>
<p><a href="https://i.stack.imgur.com/jImsl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jImsl.png" alt="enter image description here"></a></p>
|
<p>Your question is very cryptic, but if you want to filter the rows that do not contain a '$'. You can do this:</p>
<pre><code>import pandas as pd
# Dummy df
columns = ['org_name', 'important_notes']
data = [
['secret org', 'very shady'],
['very secret org', '$100000']
]
df = pd.DataFrame(data, columns=columns)
df
</code></pre>
<p>Output:</p>
<pre><code> org_name important_notes
0 secret org very shady
1 very secret org $100000
</code></pre>
<p>df without rows containing the dollar sign.</p>
<pre><code>df_no_dollars = df[~df['important_notes'].str.contains("\$")]
df_no_dollars
</code></pre>
<p>Output:</p>
<pre><code> org_name important_notes
0 secret org very shady
</code></pre>
|
python|pandas|jupyter-notebook|salesforce|data-cleaning
| 0 |
1,907,136 | 72,973,696 |
Using the Coverage Python API to get coverage results after a run
|
<p>I want to generate a Markdown report after a coverage run, so I tried to use the <a href="https://coverage.readthedocs.io/en/6.4.2/api.html" rel="nofollow noreferrer">Python API</a>, particularly the <code>CoverageData</code> class. I can get the lines covered with <code>CoverageData.lines(<file>)</code>, however I don't see how to get the percentage. Any pointers?</p>
|
<p>You should use the <code>coverage json</code> command to get a JSON data file, then process it however you like. It will be easier than using the API.</p>
|
python|markdown|coverage.py
| 1 |
1,907,137 | 63,113,956 |
Not getting an output of the OpenCV program in jupyter notebook
|
<p>I am trying to run this program in jupyter notebook, but it's not running at all. It's just showing the asterisk beside the program. Can anyone tell me why is that happening? I have also tried other programs of OpenCV as well, but the result was the same. None of them are running.</p>
<pre><code>import cv2
import numpy as np
image = cv2.imread('images/input.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Original image',image)
cv2.imshow('Gray image', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
|
<p>Try this following code, opencv <code>imshow</code> cause issues with notebook.</p>
<pre><code>from matplotlib import pyplot as plt
import cv2
image = cv2.imread('images/input.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
plt.imshow(gray)
plt.title('Gray image')
plt.show()
</code></pre>
|
python|opencv|opencv-python
| 0 |
1,907,138 | 58,747,368 |
How to compare Multiple columns in different Dataframes with Pandas
|
<p>I have two dataframes having 6000 rows and 20 columns. I want to compare these two dataframes on 3 columns so that if the values match then those matched rows go to a new dateframe and if the values do not match then they go to a second new dataframe. For this, I tried to use if statement but it is giving me error that "<em>The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</em>" and I checked everything online to tackle it but I failed.</p>
<p><a href="https://i.stack.imgur.com/r1Kis.jpg" rel="nofollow noreferrer">In datatype it shows boolean</a></p>
<p><a href="https://i.stack.imgur.com/vb0ib.jpg" rel="nofollow noreferrer">In if statement, it shows a error</a></p>
<p>Any help would be appreciated.</p>
|
<p>For the dataframe where the rows match you can do this with a inner join (rows that match in both dataframes come through into the new dataframe). See below something that should work</p>
<p><code>joined_df_match = df1.merge(df2, how = 'inner', left_on = ['col1','col2','col3'], right_on = ['col1','col2','col3'])</code></p>
<p>For when they don't match you could use an outer join</p>
<p><code>joined_df_non = df1.merge(df2, how = 'outer', left_on = ['col1','col2','col3'], right_on = ['col1','col2','col3'])</code></p>
|
python|pandas
| 0 |
1,907,139 | 58,706,132 |
statsmodels anova_lm returns PR>F 0.0: How to change the number of decimals?
|
<p>I'm performing ANOVA on a pandas dataframe using <code>statsmodels anova_lm</code>. </p>
<p>The returned significance level <code>PR>F</code> is <code>0.0</code>. I assume this is a rounded value, but rounded at how many decimal places?</p>
<p>Is there a way to specify the number of decimal places in <code>statsmodels</code>? </p>
<p>my code: </p>
<pre><code>from statsmodels.formula.api import ols
import statsmodels.api as sm
formula = 'consensus_rate ~ C(strategy) + np.power(nr_clues,' + str(exp) +') + shared_ratio + primacy_weight + edges_per_node '
lm = ols(formula, data=bigdf).fit()
sm.stats.anova_lm(lm, typ=2)
</code></pre>
<p>returns </p>
<pre><code>>>>> sum_sq df F PR(>F)
C(strategy) 1.909980e+06 3.0 15196.209763 0.0
np.power(nr_clues, 0.1) 5.159021e+05 1.0 12313.884367 0.0
shared_ratio 7.383109e+05 1.0 17622.480378 0.0
primacy_weight 2.099998e+05 1.0 5012.410347 0.0
edges_per_node 8.457493e+04 1.0 2018.689015 0.0
Residual 3.013158e+05 7192.0 NaN NaN
</code></pre>
|
<p><code>PR(>F)</code> is probably smaller than <code>0.000000</code></p>
<p>Looking at other <code>statsmodels</code> anova tables, it seems <code>statsmodels</code> displays floats with 6 decimals. </p>
<p>For example: </p>
<pre><code> df sum_sq mean_sq F PR(>F)
C(Fitness) 2.0 672.0 336.000000 16.961538 0.000041
Residual 21.0 416.0 19.809524 NaN NaN
</code></pre>
<p>sourced from: <a href="https://www.statsmodels.org/stable/examples/notebooks/generated/interactions_anova.html" rel="nofollow noreferrer">https://www.statsmodels.org/stable/examples/notebooks/generated/interactions_anova.html</a></p>
|
python|statsmodels|anova|p-value|significance
| 0 |
1,907,140 | 58,757,169 |
How to extract the entire decimal from a string?
|
<p>I am parsing an email and trying to get the numeric values from the email. My algorithm splits the email into an array split by spaces, and just extracts the values from that array. Problem is the html gets picked up, so an element in the array looks like this</p>
<pre><code> pre-wrap;">32.35</pre>
</td>
</tr>
</code></pre>
<p>
<p>I want to just extract the digit and tried to filter it out, but its ignoring the decimal</p>
<p>this is the method</p>
<pre><code>extractedValue = ''.join(filter(lambda i: i.isdigit(), firstString))
</code></pre>
<p>this returns 3235 and ignores the decimal.</p>
<p>What is the work around for this?</p>
|
<p>As in the comment, here is how to do it with regexps </p>
<pre class="lang-py prettyprint-override"><code>re.search(r'(\d+\.\d+)', firstString).group(1)
</code></pre>
<p>In fact we can use <code>.group()</code> to get the whole match, which save you some key strokes.</p>
<pre><code>foo = re.search("foo", sometring).group()
bar = re.search("bar", something).group()
</code></pre>
<p>If search didn't matched it returns None, so this expands to <code>None.group()</code> which raises <code>AttributeError</code>, so you can catch <code>AttributeError</code> for any non-match</p>
<pre><code>try:
foo = re.search("foo", sometring).group()
bar = re.search("bar", something).group()
except AttributeError:
pass
# something went wrong
</code></pre>
<p>So you can achieve the same result with <code>re.search(r'\d+\.\d+', firstString).group()</code></p>
<p>I hope this helps,
Regards</p>
|
python|parsing
| 0 |
1,907,141 | 31,321,872 |
Jira python runs very slowly, any ideas on why?
|
<p>I'm using jira-python to automate a bunch of tasks in Jira. One thing that I find weird is that jira-python takes a long time to run. It seems like it's loading or something before sending the requests. I'm new to python, so I'm a little confused as to what's actually going on. Before finding jira-python, I was sending requests to the Jira REST API using the requests library, and it was blazing fast (and still is, if I compare the two). Whenever I run the scripts that use jira-python, there's a good 15 second delay while 'loading' the library, and sometimes also a good 10-15 second delay sending each request. </p>
<p>Is there something I'm missing with python that could be causing this issue? Anyway to keep a python script running as a service so it doesn't need to 'load' the library each time it's ran?</p>
|
<p>@ThePavoIC, you seem to be correct. I notice MASSIVE changes in speed if Jira has been restarted and re-indexed recently. Scripts that would take a couple minutes to run would complete in seconds. Basically, you need to make sure Jira is tuned for performance and keep your indexes up to date.</p>
|
python|jira-rest-api
| 0 |
1,907,142 | 31,398,815 |
Sorting a dictionary based on values
|
<p>I searched for sorting a Python dictionary based on value and got various answers on the internet.Tried few of them and finally used Sorted function.
I have simplified the example to make it clear.
I have a dictionary,say:</p>
<pre><code>temp_dict = {'1': '40', '0': '109', '3': '37', '2': '42', '5': '26', '4': '45', '7': '109', '6': '42'}
</code></pre>
<p>Now ,to sort it out based on value,I did the following operation(using Operator module):</p>
<pre><code>sorted_temp_dict = sorted(temp_dict.items(), key=operator.itemgetter(1))
</code></pre>
<p>The result I'm getting is(The result is a tuple,which is fine for me):</p>
<pre><code>[('0', '109'), ('7', '109'), ('5', '26'), ('3', '37'), ('1', '40'), ('2', '42'), ('6', '42'), ('4', '45')]
</code></pre>
<p>The issue is,as you can see,the first two elements of the tuple is not sorted.The rest of the elements are sorted perfectly based on the value.
Not able to find the mistake here.Any help will be great.Thanks</p>
|
<p>Those are sorted. They are strings, and are sorted lexicographically: '1' is before '2', etc.</p>
<p>If you want to sort by numeric value, you'll need to convert to ints in the key function. For example:</p>
<pre><code>sorted(temp_dict.items(), key=lambda x: int(x[1]))
</code></pre>
|
python|sorting
| 3 |
1,907,143 | 31,619,813 |
iPython Notebook/Jupyter autosave failed
|
<p>I am working in iPython 3/Jupyter running multiple kernels and servers. As such, i often forget to personally save things as I jump around a lot. The autosave has failed for the past 3 hours.
The error says: "Last Checkpoint: 3 hours ago Autosave Failed!
I try to manually File>>Save and Checkpoint, and nothing changes. Help!
Next to my Python 2 kernel name, there is a yellow box that say forbidden instead of edit. It goes away when i click on it. I don't know if that has anything to do with the failure to save, but it doesn't change once clicked.</p>
|
<p>I had same problem and I found out I was logged out from Jupyter. I found that when I went to Jupyter home page and it asked me to enter password. After I entered password I could save my notebook (it was still running in other tab).</p>
|
ipython-notebook|autosave|jupyter
| 57 |
1,907,144 | 49,188,966 |
DB Driver for azure SQL Data ware house via python notebook in ML Studio
|
<p>I am trying to access my data warehouse azure, fetch some data in mlstudio-attached-notebook in python. Simple connection says driver not found.</p>
<p>[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 13 for SQL Server' : file not found (0) (SQLDriverConnect).</p>
<p>Now, I need to know, is it a firewall issue or the not right driver name issue.</p>
<p>I have tried multiple driver name/string. No effect.</p>
|
<p>By looking at issue with php, one of the guy suggested the driver name.</p>
<p><a href="https://github.com/Microsoft/msphpsql/issues/526" rel="nofollow noreferrer">https://github.com/Microsoft/msphpsql/issues/526</a></p>
<p>Driver is "ODBC Driver 17 for SQL Server"</p>
|
python|azure-sql-database|jupyter-notebook|sql-data-warehouse|ml-studio
| 0 |
1,907,145 | 48,994,844 |
Fill barchart with patterns
|
<p>I am currently working on plotting a bar chart. For easier readability and to make the different bars distinguishable after b&w-printing I want to plot the bars using different patterns and if at all possible different colors and patterns similar to <a href="http://www.burningcutlery.com/derek/bargraph/cluster-pattern.png" rel="nofollow noreferrer">this</a> or <a href="https://i.stack.imgur.com/OCJzr.png" rel="nofollow noreferrer">this</a>. Is this possible while using pandas or matplotlib? If so, are there pattern palettes similar to color palettes?
My current code looks like this</p>
<pre><code>df.transpose().plot.bar(width=0.8)
</code></pre>
|
<p>Google held the answer :) Try passing <code>hatch='/'</code> to <code>bar()</code>.</p>
<p>All hatch options (<a href="https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.bar.html" rel="nofollow noreferrer">from here</a>): <code>['/' | '' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*']</code></p>
<p>Demo:
<a href="https://matplotlib.org/examples/pylab_examples/hatch_demo.html" rel="nofollow noreferrer">https://matplotlib.org/examples/pylab_examples/hatch_demo.html</a></p>
|
python|pandas|matplotlib
| 1 |
1,907,146 | 48,895,963 |
How to resolve Django migrate stuck?
|
<p>After I tried to <code>makemigrations</code>/<code>migrate</code> a change (adding a default value to a <code>DateTimeField</code> for testing) on my <code>MySQL</code> database with <code>Django 2.0.2</code> it run into an error as I formatted the date wrong. Now after</p>
<ul>
<li>removing the default value</li>
<li>changing the default value</li>
<li>removing the table and recreating the model</li>
</ul>
<p><code>python manage.py migrate</code> still shows the following error (last line):</p>
<pre><code>django.core.exceptions.ValidationError: ["'02.02.2012' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
</code></pre>
<p>Like I said: I allready changed my code to (excerpt):</p>
<pre><code>class Task(models.Model):
uploaddate = models.DateTimeField(auto_now_add=True)
</code></pre>
<p>and run <code>makemigrations</code> several times.</p>
<p>Why does <code>migrate</code> keep on showing my former mistake and wont import the new attribute correctly? Is this possibly a bug? Can I sort of "reset" <code>migrate</code>?</p>
|
<p>It sounds like one of your migration files contains the invalid date that you specified <code>'02.02.2012'</code> when running <code>manage.py makemigrations</code>. </p>
<p>You can editing the migration file and change <code>'02.02.2012'</code> to <code>datetime(2012,2,2)</code>. You may have to add the import <code>from datetime import datetime</code> to the migration file as well.</p>
|
python|django
| 0 |
1,907,147 | 25,315,683 |
nested scope in python
|
<p>My question is regarding the rules of enclosing scope. In the snippet below if x=x is not passed to the header of F2 there will be an error</p>
<pre><code>def f1():
x = 88
def f2(x=x): # Remember enclosing scope X with defaults
print(x)
f2()
f1()
</code></pre>
<p>however I dont understand why "x=x" is not needed in the lambda in the below snippet</p>
<pre><code>def func():
x = 4
action = (lambda n: x ** n) # x remembered from enclosing def
return action
x = func()
print(x(2))
</code></pre>
|
<blockquote>
<p>In the snippet below if x=x is not passed to the header of F2 there will be an error</p>
</blockquote>
<p>No there won't:</p>
<pre><code>>>> def f1():
... x = 88
... def f2():
... print(x)
... f2()
...
>>> f1()
88
</code></pre>
<hr>
<p>You only need the default parameter value hack when you're trying to pass a value that might get changed later. <code>f2</code> as I've written it captures the variable <code>x</code> from the enclosing scope, so it will print whatever <code>x</code> happens to be at the time. As you've written it, it captures the current value of the variable <code>x</code>, not the variable itself.</p>
<p>For example:</p>
<pre><code>>>> def f1():
... x = 88
... def f2():
... print(x)
... x = 44
... f2()
...
>>> f1()
44
>>> def f1():
... x = 88
... def f2(x=x):
... print(x)
... x = 44
... f2()
...
>>> f1()
88
</code></pre>
<hr>
<p>For a very common real-life example of where this difference is important, see <a href="https://docs.python.org/3.4/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result" rel="nofollow">Why do lambdas defined in a loop with different values all return the same result?</a> in the official FAQ.</p>
|
python|lambda|scope
| 2 |
1,907,148 | 70,850,916 |
drop duplicates and exclude specific columns and take the lowest value
|
<p>I have this example dataset</p>
<pre><code>CPU_Sub_Series RAM Screen_Size Resolution Price
Intel i5 8 15.6 1920x1080 699
Intel i5 8 15.6 1920x1080 569
Intel i5 8 15.6 1920x1080 789
Ryzen 5 16 16.0 2560x1600 999
Ryzen 5 32 16.0 2560x1600 1299
</code></pre>
<p>All I want to do is, check and then drop the duplicate data, except in the price column, and then keep the lowest value in the price column.<br />
So, the output column is like this :</p>
<pre><code>CPU_Sub_Series RAM Screen_Size Resolution Price
Intel i5 8 15.6 1920x1080 569
Ryzen 5 16 16.0 2560x1600 999
Ryzen 5 32 16.0 2560x1600 1299
</code></pre>
<p>Should I sort it first by price? and then what?<br />
<code>df.sort_values('Price')</code> ? and then what?</p>
|
<pre><code>df.groupby(["CPU_Sub_Series","RAM","Screen_Size","Resolution"], as_index=False).min()
</code></pre>
|
python|pandas|duplicates
| 4 |
1,907,149 | 3,075,375 |
Optimizing operations on lists
|
<p>I need to process lots of data in lists and so have been looking at what the best way of doing this is using Python. </p>
<p>The main ways I've come up with are using:
- List comprehensions
- generator expressions
- functional style operations (map,filter etc.)</p>
<p>I know generally list comprehensions are probably the most "Pythonic" method, but what is best in terms of performance?</p>
|
<p>Inspired by this answer: <a href="https://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map">Python List Comprehension Vs. Map</a> , I've tweaked the questions to allow generator expressions to be compared:</p>
<p>For built-ins:</p>
<pre><code>$ python -mtimeit -s 'import math;xs=range(10)' 'sum(map(math.sqrt, xs))'
100000 loops, best of 3: 2.96 usec per loop
$ python -mtimeit -s 'import math;xs=range(10)' 'sum([math.sqrt(x) for x in xs)]'
100000 loops, best of 3: 3.75 usec per loop
$ python -mtimeit -s 'import math;xs=range(10)' 'sum(math.sqrt(x) for x in xs)'
100000 loops, best of 3: 3.71 usec per loop
</code></pre>
<p>For lambdas:</p>
<pre><code>$ python -mtimeit -s'xs=range(10)' 'sum(map(lambda x: x+2, xs))'
100000 loops, best of 3: 2.98 usec per loop
$ python -mtimeit -s'xs=range(10)' 'sum([x+2 for x in xs])'
100000 loops, best of 3: 1.66 usec per loop
$ python -mtimeit -s'xs=range(10)' 'sum(x+2 for x in xs)'
100000 loops, best of 3: 1.48 usec per loop
</code></pre>
<p>Making a list:</p>
<pre><code>$ python -mtimeit -s'xs=range(10)' 'list(map(lambda x: x+2, xs))'
100000 loops, best of 3: 3.19 usec per loop
$ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 1.21 usec per loop
$ python -mtimeit -s'xs=range(10)' 'list(x+2 for x in xs)'
100000 loops, best of 3: 3.36 usec per loop
</code></pre>
<p>It appears that <code>map</code> is best when paired with built-in functions, otherwise, generator expressions beat out list comprehensions. Along with slightly cleaner syntax, generator expressions also save much memory over list comprehensions because they are lazily evaluated. So in the absence of specific tests for your application, you should use <code>map</code> with builtins, a list comprehension when you require a list result, otherwise a generator. If you're really concerned with performance, you might take a look at whether you actually require lists at all points in your program.</p>
|
python|performance|list
| 1 |
1,907,150 | 67,923,281 |
How to paste a small png behind a template in PIL?
|
<p>Good evening! I have been trying to make a script in PIL that pastes an image behind another image, like a meme template. The thing is - i can't find a way to get it on the back layer. Here i will provide examples for what i <strong>want it to output</strong> and <strong>what it does</strong>:</p>
<p>What i want it to output:
<a href="https://i.stack.imgur.com/nuqVM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nuqVM.png" alt="An image of Scott Wozniak standing near a TV smiling with an image inside of the TV's display" /></a></p>
<p>What it outputs:
<a href="https://i.stack.imgur.com/bQSyP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bQSyP.jpg" alt="An image of Scott Wozniak standing near a TV smiling but the image from the example above is on the front layer" /></a></p>
<p>And here's the code i use to generate the bottom image:</p>
<pre class="lang-py prettyprint-override"><code>url = ctx.message.attachments[0].url # Getting the image from Discord
pic = requests.get(url, stream=True).raw # Putting that image into the pic variable
template = Image.open("./generators/scott.png") # Opening the template with Scott into PIL
pic = Image.open(pic) # Opening the image from Discord
pic = pic.resize((565,402)) # Resizing the image to the size of the TV screen
template.paste(pic,(200,278)) # Pasting the image where it belongs
template.save("./renderedcontent/scott.png") # Saving the image to send it
</code></pre>
<p><strong>What i have tried:</strong></p>
<p>I tried browsing the docs for other functions, tried some, couldn't get stuff done with them, tried playing with variables and masks. Nothing worked, even got some funny renders out of it.</p>
<p><strong>TL;DR:</strong></p>
<p>I need to paste the image onto the back layer so it gets behind the big png template.</p>
|
<p>The fastest way possible I can' think off, if you don't mind perspective, is:</p>
<ol>
<li>modify the big image template, cutting out with Photoshop or gimp the place where the image should be and saving it as PNG</li>
<li>Paste the meme on the canvas</li>
<li>Paste the big image on the canvas</li>
</ol>
|
python|python-imaging-library
| 0 |
1,907,151 | 66,796,379 |
Is tensorflow dataset 'prefetch' method add a dimension for my data? why?
|
<p>Here is an example, this func is used to cut time sequence into windows:</p>
<pre><code>def window_dataset(tensor, window_size, batch_size=32,
shuffle_buffer=1000):
dataset = tf.data.Dataset.from_tensor_slices(tensor)
print(dataset.element_spec)
dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
print(dataset.element_spec)
dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
print(dataset.element_spec)
dataset = dataset.shuffle(shuffle_buffer)
print(dataset.element_spec)
dataset = dataset.map(lambda window: (window[:-1], window[-1]))
print(dataset.element_spec)
dataset = dataset.batch(batch_size).prefetch(1)
print(dataset.element_spec)
return dataset
</code></pre>
<p>call && output:</p>
<pre><code>list_a = np.random.random(184)
window_dataset(list_a, 30)
</code></pre>
<pre><code>TensorSpec(shape=(), dtype=tf.float64, name=None)
DatasetSpec(TensorSpec(shape=(), dtype=tf.float64, name=None), TensorShape([]))
TensorSpec(shape=(None,), dtype=tf.float64, name=None)
TensorSpec(shape=(None,), dtype=tf.float64, name=None)
(TensorSpec(shape=(None,), dtype=tf.float64, name=None), TensorSpec(shape=(), dtype=tf.float64, name=None))
(TensorSpec(shape=(None, None), dtype=tf.float64, name=None), TensorSpec(shape=(None,), dtype=tf.float64, name=None))
</code></pre>
<p>It seemed that the dataset have one more rank after prefetch, is it?
I didn't find any doc to describe this phenomenon, i will be appreciate if anybody could offer help.</p>
<p>============================================================
updated at 2021-03-25 12:28:16 UTC+0</p>
<p>I found this to be a little embarrassing misunderstanding, thanks to @ Lescurel for pointing this out. In fact, <code>prefetch</code> does not affect the dimension, and <code>batch</code> will add a dimension. The modification example is as follows:</p>
<pre><code>def window_dataset(tensor, window_size, batch_size=32,
shuffle_buffer=1000):
dataset = tf.data.Dataset.from_tensor_slices(tensor)
print(dataset.element_spec)
dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
print(dataset.element_spec)
dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
print(dataset.element_spec)
dataset = dataset.shuffle(shuffle_buffer)
print(dataset.element_spec)
dataset = dataset.map(lambda window: (window[:-1], window[-1]))
print(dataset.element_spec)
dataset = dataset.batch(batch_size)
print(dataset.element_spec)
dataset = dataset.prefetch(1)
print(dataset.element_spec)
return dataset
</code></pre>
<p>call && output:</p>
<pre><code>list_a = np.random.random(184)
window_dataset(list_a, 30)
</code></pre>
<pre><code>TensorSpec(shape=(), dtype=tf.float64, name=None)
DatasetSpec(TensorSpec(shape=(), dtype=tf.float64, name=None), TensorShape([]))
TensorSpec(shape=(None,), dtype=tf.float64, name=None)
TensorSpec(shape=(None,), dtype=tf.float64, name=None)
(TensorSpec(shape=(None,), dtype=tf.float64, name=None), TensorSpec(shape=(), dtype=tf.float64, name=None))
# after batch
(TensorSpec(shape=(None, None), dtype=tf.float64, name=None), TensorSpec(shape=(None,), dtype=tf.float64, name=None))
# after prefetch
(TensorSpec(shape=(None, None), dtype=tf.float64, name=None), TensorSpec(shape=(None,), dtype=tf.float64, name=None))
</code></pre>
<p>It is clear now.</p>
|
<p><code>prefetch</code> allows later elements to be prepared while the current element is being processed. This often improves latency and throughput at the cost of using additional memory to store prefetched elements.</p>
<p>Where as <code>batch</code> is combines consecutive elements of dataset into batches based on <code>batch_size</code>.</p>
<p>It has no concept of examples vs. batches. <code>examples.prefetch(2)</code> will prefetch <code>two elements (2 examples)</code>, while <code>examples.batch(20).prefetch(2)</code> will prefetch <code>2 elements (2 batches, of 20 examples each)</code>.</p>
<p>For more details you can refer <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#methods_2" rel="nofollow noreferrer">methods</a> of tf.data.Dataset.</p>
|
tensorflow
| 0 |
1,907,152 | 42,701,118 |
Getting values from the lists in python
|
<p>I am having an input like the following type,</p>
<pre><code>[[ 34535.54 23514.54 43213.73 ]
[ 249.01976173 132.7836 26.05499407]
[ 87.26696285 107.90388887 148.68014509]]
</code></pre>
<p>I need to get the values from first,second and third rows separately
like </p>
<pre><code>a1=34535.54, a2=23514.54, a3= 43213.73
b1=249.01976173 ,b2=132.7836 ,b3=26.05499407
c1=87.26696285 ,c2=107.90388887 ,c3=148.68014509
</code></pre>
<p>How should i display the values in python?</p>
|
<p>You can break up lists in python like so:</p>
<pre><code>a, b, c = [1, 2, 3]
</code></pre>
<p>This can be extended to nested lists as well.</p>
|
python
| 1 |
1,907,153 | 66,386,127 |
Visual studio coderunner extension does not work. Nothing happens when clicking on run
|
<p>Coderunner extension for visual studio code used to work on my computer. Then, for no reason it stopped working. Whenever I press run, nothing happens. No execution, no output to the terminal, nothing. Absolutely nothing happens. I have searched the entire internet for my problem but no one has the same problem as me. I reinstalled visual studio code and coderunner extension but the issue persisted. Anyone with technical knowledge knows how to fix this ?</p>
<p><a href="https://i.stack.imgur.com/7yNY1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7yNY1.png" alt="Nothing happens when I click on run" /></a></p>
<p>There can't be anything wrong with the extension configurations because I imported the extension configurations from an account on another computer which the coderunner worked perfect on. So my computer has the same extension settings for coderunner as that other computer and it still does not work to run coderunner on my computer.</p>
|
<p>I finally solved this issue by installing an older version of coderunner.</p>
<p><a href="https://i.stack.imgur.com/cgMTI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cgMTI.png" alt="enter image description here" /></a></p>
<p>However, I am not satisfied with this solution. I should not have to use an outdated version of coderunner to make it able to work when there is newer better version of coderunner.
So if anyone knows how I can make it work with newer version of coderunner, feel free to answer.</p>
|
python|c|visual-studio-code|vscode-code-runner
| 1 |
1,907,154 | 72,377,016 |
Getting Rolling Sum per Group
|
<p>I have a dataframe like this:</p>
<pre><code>Product_ID Quantity Year Quarter
1 100 2021 1
1 100 2021 2
1 50 2021 3
1 100 2021 4
1 100 2022 1
2 100 2021 1
2 100 2021 2
3 100 2021 1
3 100 2021 2
</code></pre>
<p>I would like to get the Sum of the last three months (excluding the current month), per Product_ID.</p>
<p>Therefore I tried this:</p>
<pre><code>df['Qty_Sum_3qrts'] = (df.groupby('Product_ID'['Quantity'].shift(1,fill_value=0)
.rolling(3).sum().reset_index(0,drop=True)
)
# Shifting 1, because I want to exclude the current row.
# Rolling 3, because I want to have the 3 'rows' before
# Grouping by, because I want to have the calculation PER product
</code></pre>
<p>My code is failing, because it does not only calculate it per product, but it will give me also numbers for other products (let's say Product 2, quarter 1: gives me the 3 rows from product 1).</p>
<p>My proposed outcome:</p>
<pre><code>Product_ID Quantity Year Quarter Qty_Sum_3qrts
1 100 2021 1 0 # because we dont historical data for this id
1 100 2021 2 100 # sum of last month of this product
1 50 2021 3 200 # sum of last 2 months of this product
1 100 2021 4 250 # sum of last 3 months of this product
1 100 2022 1 250 # sum of last 3 months of this product
2 100 2021 1 0 # because we dont have hist data for this id
2 100 2021 2 100 # sum of last month of this product
3 100 2021 1 0 # etc
3 100 2021 2 100 # etc
</code></pre>
|
<p>You need to apply the rolling sum per group, you can use <code>apply</code> for this:</p>
<pre><code>df['Qty_Sum_3qrts'] = (df.groupby('Product_ID')['Quantity']
.apply(lambda s: s.shift(1,fill_value=0)
.rolling(3, min_periods=1).sum())
)
</code></pre>
<p>output:</p>
<pre><code> Product_ID Quantity Year Quarter Qty_Sum_3qrts
0 1 100 2021 1 0.0
1 1 100 2021 2 100.0
2 1 50 2021 3 200.0
3 1 100 2021 4 250.0
4 1 100 2022 1 250.0
5 2 100 2021 1 0.0
6 2 100 2021 2 100.0
7 3 100 2021 1 0.0
8 3 100 2021 2 100.0
</code></pre>
|
python|python-3.x|pandas|rolling-computation
| 5 |
1,907,155 | 72,306,873 |
How to set constant number of lags of a time series data inside sts.adfuller() function test?
|
<p>adfuller test gives each variable a different number of lags. hence different P-value.
How to get the same p-value, and how to set the no. of lags in each variable?</p>
<p>Theses are adfuller test results for two variables with same size but it shows different number and lags and different p-value!</p>
<pre class="lang-none prettyprint-override"><code>(-1.6111475029851472,
0.4773732658526479,
2,
1139,
{'1%': -3.4334108531807006,
'5%': -2.862892168387536,
'10%': -2.5674898285322496},
-8273.914480099738)
</code></pre>
<pre class="lang-none prettyprint-override"><code>(-25.304769346612073,
0.0,
1,
1140,
{'1%': -3.4334094211542983,
'5%': -2.8628915360971003,
'10%': -2.5674894918770197},
83264.08934179449)
</code></pre>
|
<p>To force <code>statsmodels.tsa.stattools.adfuller</code> to use the desired number of lags, you need to set <code>maxlag</code> argument to the desired number of lags and then also set <code>autolag</code> argument to <code>None</code> to force it to use whatever is passed as <code>maxlag</code> as the number of lags instead of performing automated lag order search routines.</p>
|
python|python-3.x|time-series|statsmodels
| 0 |
1,907,156 | 50,793,972 |
Django 1.11 admin: Create a OneToOne relationship and it's object in the admin
|
<p>I have a simple app (about QR codes) in which I have two models. The first one is for defining the QR Code and the second one is for giving it a function. (For those wondering: I split it up into two models because our QR codes are complex and sometimes lack functions and are read-only. I wanted to keep our database as normalized as possible).</p>
<p>Here is the model (models.py):</p>
<pre><code>from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils.translation import ugettext_lazy as _
from core.behaviors import QRCodeable, UniversallyUniqueIdentifiable
from core.utils import QR_CODE_FUNCTIONS
from model_utils.fields import StatusField
from model_utils.models import SoftDeletableModel, TimeStampedModel
QR_CODE_PREFIX = "QR Code"
QR_CODE_FUNCTION_PREFIX = "Function"
QR_CODE_FUNCTION_MIDFIX = "for"
class QRCode(
UniversallyUniqueIdentifiable,
SoftDeletableModel,
TimeStampedModel,
models.Model
):
@property
def function(self):
try:
return self.qrcodefunction.qr_code_function
except ObjectDoesNotExist:
return ""
class Meta:
verbose_name = _('QR code')
verbose_name_plural = _('QR codes')
def __str__(self):
return f'{QR_CODE_PREFIX} {self.uuid}'
class QRCodeFunction(
UniversallyUniqueIdentifiable,
SoftDeletableModel,
TimeStampedModel,
QRCodeable,
models.Model
):
QR_CODE_FUNCTIONS = QR_CODE_FUNCTIONS
qr_code_function = StatusField(choices_name="QR_CODE_FUNCTIONS")
class Meta:
verbose_name = _('QR code function')
verbose_name_plural = _('QR code functions')
def __str__(self):
return f'{QR_CODE_FUNCTION_PREFIX} {self.qr_code_function} {QR_CODE_FUNCTION_MIDFIX} {self.qr_code}'
</code></pre>
<p>The mixin QRCodeable is an abstract base class which gives the function a OneToOne relation to the QR code. The mixin UniversallyUniqueIdentifiable gives it a uuid. </p>
<p>Anyways, I now want to be able to create QR codes with functions within the Django admin. So I wrote my own admin class (admin.py):</p>
<pre><code>from django.contrib import admin
from .models import QRCode, QRCodeFunction
class QRCodeFunctionInline(admin.TabularInline):
model = QRCodeFunction
extra = 0
@admin.register(QRCode)
class QRCodeAdmin(admin.ModelAdmin):
save_on_top = True
search_fields = ['qrcodefunction__qr_code_function']
list_display = (
'__str__',
'function',
)
inlines = [
QRCodeFunctionInline,
]
</code></pre>
<p>This code results in the following admin interface:</p>
<p><a href="https://i.stack.imgur.com/lRnGE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lRnGE.png" alt="Admin interface of the QR code in the Django admin."></a></p>
<p>If I now click on <code>add another QR code function</code>, choose a function and hit save, the new instance of QR code function does <strong>NOT</strong> get created! Why is that? How can I write this model admin so that I can create functions for the QR code in the QR codes admin?</p>
|
<p>This is likely a duplicate of <a href="https://stackoverflow.com/questions/34355406/django-admin-not-saving-pre-populated-inline-fields-which-are-left-in-their-init">Django Admin not saving pre-populated inline fields which are left in their initial state</a>. Your inline will only use the defaults, but Django's admin by default won't actually create an instance if one or more of the fields have been changed. It's a painful experience, but Django errs on the side of caution here. Better to not create than to create and have to delete.</p>
<p>The answer in that question adjusted for your context would be:</p>
<pre><code>from django.contrib import admin
from django.forms.models import ModelForm
class AlwaysChangedModelForm(ModelForm):
def has_changed(self):
""" Should returns True if data differs from initial.
By always returning true even unchanged inlines will get validated and saved."""
return True
class QRCodeFunctionInline(admin.TabularInline):
model = QRCodeFunction
form = AlwaysChangedModelForm
extra = 0
</code></pre>
|
django|python-3.x|django-models|django-admin|django-1.11
| 0 |
1,907,157 | 3,757,326 |
findString program python
|
<p>I have an assignment said that to create a findString function that accept 2 string which are 'target' and 'query', and that returns
a
list
of
all
indices
in
target
where
query
appears.
If
target
does
not
contain
query,
return
an
empty
list.
</p>
<p>For example:
findString(‘attaggtttattgg’,’gg’)</p>
<p>return:</p>
<p>[4,12] </p>
<p>I dont know how to start off with this function writing at all. Please help me everyone. Thank you so much!!!</p>
|
<p>since an answer has already been given:</p>
<pre><code>def find_matches(strng, substrng):
substrg_len = len(substr)
return [i for i in range(len(strg) + 1 - substrg_len)
if strg[i:i+substrg_len] == substrg]
</code></pre>
|
python
| 1 |
1,907,158 | 50,295,510 |
Is "shadows name from outer scopes an error"?
|
<p>Hello I am writing a Python code and I am receiving the two variables underlined in green with "Shadows name 'value' from outer scope" and "Shadows name 'value1' from outer scope". Is this an error? And how can I solve this problem? My code should read two variables data from firebase realtime database. If both variables data are 1 then I should receive a notification on my phone. Is the code wrong?
Note that it was working normally and I was able to receive notification but when I added the second variable and modified the code I cant receive notifications anymore.</p>
<pre><code>value = 0
value1 = 0
def stream_handler(message):
print(message)
if message['data'] is 1:
value = 1 //here the variable is underlined in green
value = value //here the variable is underlined in green
return value
def stream_handler1(message1):
print(message1)
if message1['data'] is 1:
value1 = 1 //here the variable is underlined in green
value1 = value1 //here the variable is underlined in green
return value1
if value is 1 & value1 is 1:
response = pn_client.publish(
interests=['hello'],
publish_body={
'apns': {
'aps': {
'alert': 'Hello!',
},
},
'fcm': {
'notification': {
'title': 'Notification',
'body': 'Fall Detected !!',
},
},
},
)
print(response['publishId'])
my_stream = db.child("Fall_Detection_Status").stream(stream_handler)
my_stream1 = db.child("Fall_Detection_Status1").stream(stream_handler1)
</code></pre>
|
<p>You probably meant this:</p>
<pre><code>def stream_handler(message):
global value
print(message)
# rest of function elided
def stream_handler1(message1):
global value1
print(message1)
# rest of function elided
</code></pre>
<p>The <code>global</code> statements tell Python that you mean to use the global versions of the value variables and not have local versions.</p>
<p>Additionally you probably don't want statements like:</p>
<pre><code>value = value
</code></pre>
<p>as this doesn't mean anything.</p>
|
python|firebase|firebase-realtime-database|firebase-admin
| 2 |
1,907,159 | 26,812,978 |
Circular dependency in the class constructor
|
<p>I have the following class:</p>
<pre><code>class CustomDictionary(dict):
def __init__(self, val, *args, **kwargs):
self.wk = val
super(dict, self).__init__()
def __setattr__(self, key, value):
if key in self.wk:
raise Exception("Wrong key", "")
key = key.replace(" ", "_")
self.__dict__[key] = value
def main():
wrong_keys = ("r23", "fwfew", "s43t")
dictionary = CustomDictionary(wrong_keys)
dictionary["a1"] = 1
</code></pre>
<p>As you can see, I create the attribute <code>wk</code> in the <code>constructor</code>. But I have <code>__setattr__</code> function, in which I work with attribute <code>wk</code>. However, <code>CustomDictionary object</code> has no attribute <code>wk</code>.</p>
|
<p><code>__setattr__</code> is a pain that way, because it is called for every assignment to an instance member. Probably the easiest fix for your situation is to define an empty <code>wk</code> before <code>__init__</code>:</p>
<pre><code>class CustomDictionary(dict):
wk = []
def __init__(self, val, *args, **kwargs):
self.wk = val
...
</code></pre>
|
python-3.x|constructor|circular-dependency
| 1 |
1,907,160 | 64,780,343 |
Forbidden (CSRF token missing or incorrect.): /updatecart_index/
|
<p>in my html i have this code where the user updating the quantity from the database,why i am encounter this kind of error <code>Forbidden (CSRF token missing or incorrect.): /updatecart_index/</code> ? eventhought i have this in my form <code>{% csrf_token %}</code></p>
<pre><code><form method="POST" id="form" >{% csrf_token %}
<input type="hidden" value="{{bought.id}}" name="itemID">
<input type="submit" value="-" id="down" formaction="/updatecart_index/" onclick="setQuantity('down');" >
<input type="text" name="quantity" id="quantity" value="{{bought.quantity}}" onkeyup="multiplyBy()" style="width: 13%; text-align:left;" readonly>
<input type="submit" value="+" id="up" formaction="/updatecart_index/" onclick="setQuantity('up');" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function(){
event.preventDefault();
var form_id = $('#form')
$.ajax({
url: "{% url 'updatecart_index' %}",
type: 'POST',
data: form_id.serialize(),
header: {'X-CSRFToken': '{% csrf_token %}'},
dataType: "json",
success: function (response){
var success = response['success']
if(success){
alert("form submittend");
}else{
alert("got error");
}
},
failure: function (error){
alert("Error occured while calling Django view")
}
})
});
});
</script>
</code></pre>
<p>in views.py</p>
<pre><code>def updatecart_index(request):
item = request.POST.get("itemID")
print("dasdasd")
quantity = request.POST.get("quantity")
product = CustomerPurchaseOrderDetail.objects.get(id=item)
print("aa", CustomerPurchaseOrderDetail.objects.get(id=item))
product.quantity = quantity
product.save()
data = {}
data['success'] = True
return HttpResponse(json.dumps(data), content_type="application/json")
</code></pre>
<p><strong>UPDATE</strong></p>
<p>when i tried <code>@csrf_exempt</code> in views.py, the <strong>request.POST.get("item")</strong> didnt get the data from the html</p>
|
<p>You can simply do this to you Ajax</p>
<pre><code><script type="text/javascript">
$(document).ready(function(){
$('form').submit(function(){
event.preventDefault();
var that = $(this);
$.ajax({
url: "{% url 'updatecart_index' %}",
type: 'POST',
data: that.serialize()
,success: function(data){
console.log('Success!');
}
});
return false;
});
});
</script>
</code></pre>
<p>and dont use <code>csrf_exempt</code></p>
|
python|django|ajax
| 0 |
1,907,161 | 64,918,590 |
simple day converter? getting how many weeks and days are in a number python
|
<p>rewritten....</p>
<p>Im trying to get the number of weeks, and how many days extra, out of a number.
for example..</p>
<p>if the program has been running for 5 days, it will say week 1 day 5</p>
<p>if the program has been running for 14 days, it will say week 2 day 7</p>
<p>if the program has been running for 16 days, it will say week 3 day 2</p>
<p>I didnt upload my original code becuase as I was writing this question, i solved the HUGE mess i had, and didnt want to post a bunch of useless code. but still wanted to share my solution becuase I couldn't find another answer.</p>
<p>this code is what I got to work, but the answer to this question if a simplified version discovered after comments helped me understand a bit better.</p>
<pre><code>import math
totaldays = 77
week = totaldays / 7
if week <= 1:
week, day = 1, totaldays % 7
if day == 0:
day = 7
elif week >=1:
week, day = math.ceil(week), totaldays % 7
days = [1, 2, 3, 4, 5, 6, 7]
if day not in days:
day = 7
print("Total days: " + str(totaldays) + " (week: " + str(int(week)) + ", day: " + str(int(day)) + ")")
</code></pre>
|
<p>with help from @samwise i shortened the hell out of this.</p>
<pre><code>import math
totaldays = 5
day = totaldays % 7
days = [1, 2, 3, 4, 5, 6, 7]
if day not in days:
day = 7
print(f"Total days: {totaldays} (week: {math.ceil(totaldays / 7)}, day: {day})")
</code></pre>
|
python
| 0 |
1,907,162 | 64,846,201 |
What is the type of *args if args is not provided
|
<p>I was trying to implement map function in Python and I came across this:</p>
<pre class="lang-py prettyprint-override"><code>def map(func, iterable, *args):
for args2 in zip(iterable, *args):
yield func(*args2)
</code></pre>
<p>I wrote down a few tests to check if it's working correctly.</p>
<pre class="lang-py prettyprint-override"><code>from types import *
print(isinstance(_map(None, None), GeneratorType))
print(list(map(lambda x: x.upper(), 'just a line')) == list(_map(lambda x: x.upper(), 'just a line')))
print(list(map(lambda x,y: x+y, [1,2,3,4], [5,6,7,8])) == list(_map(lambda x,y: x+y, [1,2,3,4], [5,6,7,8])))
</code></pre>
<p>But this got me thinking, what is happening here:</p>
<pre class="lang-py prettyprint-override"><code>print(list(map(lambda x: x.upper(), 'just a line')) == list(_map(lambda x: x.upper(), 'just a line')))
</code></pre>
<p>I provided only iterable argument. So in this case:</p>
<pre class="lang-py prettyprint-override"><code>iterable = 'just a line'
args = Not provided
</code></pre>
<p>What in this case is the value of *args? Is it even an object? What it is? When I'm trying to print values</p>
<pre class="lang-py prettyprint-override"><code>print(args) - > ()
print(len(args)) -> 0
print(*args)) ->
print(len(*args)) -> TypeError: len() takes exactly one argument (0 given)
</code></pre>
|
<p>You can figure out the type by using <code>type</code> function, but the main problem here, I think, is that you're treating <code>*args</code> as an object which is certainly not the case.</p>
<p><code>*</code> is just an operator, so when you want to use function like <code>len</code> or <code>type</code> on it, you should use <code>args</code> without <code>*</code>.</p>
<p>To answer your question, it's always a <code>tuple</code>.</p>
|
python
| 1 |
1,907,163 | 61,336,814 |
Vectorizing a function with numpy arrays
|
<p>I am attempting to speed up some code that I wrote but am having a large amount of trouble doing so. I know that being able to remove for loops and using numpy can help to do this so that is what I have been attempting with little success.</p>
<p>The working function without any speedups is</p>
<pre><code>def acf(x, y, z, cutoff=0):
steps = x.shape[1]
natoms = x.shape[0]
z_x = np.zeros((steps,natoms))
z_y, z_z = np.zeros_like(z_x), np.zeros_like(z_x)
xmean = np.mean(x, axis=1)
ymean = np.mean(y, axis=1)
zmean = np.mean(z, axis=1)
for k in range(steps-cutoff): # x.shape[1]
xtemp, ytemp, ztemp = [], [], []
for i in range(x.shape[0]): # natoms
xtop, ytop, ztop = 0.0, 0.0, 0.0
xbot, ybot, zbot = 0.0, 0.0, 0.0
for j in range(steps-k): # x.shape[1]-k
xtop += (x[i][j] - xmean[i]) * (x[i][j+k] - xmean[i])
ytop += (y[i][j] - ymean[i]) * (y[i][j+k] - ymean[i])
ztop += (z[i][j] - zmean[i]) * (z[i][j+k] - zmean[i])
xbot += (x[i][j] - xmean[i])**2
ybot += (y[i][j] - ymean[i])**2
zbot += (z[i][j] - zmean[i])**2
xtemp.append(xtop/xbot)
ytemp.append(ytop/ybot)
ztemp.append(ztop/zbot)
z_x[k] = xtemp
z_y[k] = ytemp
z_z[k] = ztemp
z_x = np.mean(np.array(z_x), axis=1)
z_y = np.mean(np.array(z_y), axis=1)
z_z = np.mean(np.array(z_z), axis=1)
return z_x, z_y, z_z
</code></pre>
<p>The inputs x, y, and z for this function are numpy arrays of the same dimensions. An example of x (or y or z for that matter) is:</p>
<pre><code>x = np.array([[1,2,3],[4,5,6]])
</code></pre>
<p>So far what I have been able to do is</p>
<pre><code>def acf_quick(x, y, z, cutoff=0):
steps = x.shape[1]
natoms = x.shape[0]
z_x = np.zeros((steps,natoms))
z_y, z_z = np.zeros_like(z_x), np.zeros_like(z_x)
x -= np.mean(x, axis=1, keepdims=True)
y -= np.mean(y, axis=1, keepdims=True)
z -= np.mean(z, axis=1, keepdims=True)
for k in range(steps-cutoff): # x.shape[1]
for i in range(natoms):
xtop, ytop, ztop = 0.0, 0.0, 0.0
xbot, ybot, zbot = 0.0, 0.0, 0.0
for j in range(steps-k): # x.shape[1]-k
xtop += (x[i][j]) * (x[i][j+k])
ytop += (y[i][j]) * (y[i][j+k])
ztop += (z[i][j]) * (z[i][j+k])
xbot += (x[i][j])**2
ybot += (y[i][j])**2
zbot += (z[i][j])**2
z_x[k][i] = xtop/xbot
z_y[k][i] = ytop/xbot
z_z[k][i] = ztop/xbot
z_x = np.mean(np.array(z_x), axis=1)
z_y = np.mean(np.array(z_y), axis=1)
z_z = np.mean(np.array(z_z), axis=1)
return z_x, z_y, z_z
</code></pre>
<p>This speeds it up by about 33% but I believe there is a way to remove the <code>for i in range(natoms)</code> using something along the lines of <code>x[:][j]</code>. So far I have been unsuccessful and any help would be greatly appreciated.</p>
<p>Before anyone asks, I know that this is an autocorrelation function and there are several built into numpy, scipy, etc but I need to write my own.</p>
|
<p>Here is a vectorized form of your loop:</p>
<pre><code>def acf_quick_new(x, y, z, cutoff=0):
steps = x.shape[1]
natoms = x.shape[0]
lst_inputs = [x.copy(),y.copy(),z.copy()]
lst_outputs = []
for x_ in lst_inputs:
z_x_ = np.zeros((steps,natoms))
x_ -= np.mean(x_, axis=1, keepdims=True)
x_top = np.diag(np.dot(x_,x_.T))
x_bot = np.sum(x_**2, axis=1)
z_x_[0,:] = np.divide(x_top, x_bot)
for k in range(1,steps-cutoff): # x.shape[1]
x_top = np.diag(np.dot(x_[:,:-k],x_.T[k:,:]))
x_bot = np.sum(x_[:,:-k]**2, axis=1)
z_x_[k,:] = np.divide(x_top, x_bot)
z_x_ = np.mean(np.array(z_x_), axis=1)
lst_outputs.append(z_x_)
return lst_outputs
</code></pre>
<p>Note, that in your _quick-function there is a little bug: you always divide by xbot instead of xbot,ybot, and zbot. Moreover, my suggestion can be written a little nicer, but it should do the trick for your problem and speed up the calculations a lot :)</p>
|
python|arrays|python-3.x|numpy|vectorization
| 1 |
1,907,164 | 61,432,745 |
Django, TypeError: unhashable type: 'dict', where is the error?
|
<p>I'm new in django. I'm trying to run my code but give me the following error: <code>TypeError: unhashable type: 'dict'</code>.
I'm checking all code but I don't understand where is the mistake. Moreover I don't sure about the correctness of my code. Could you give me the necessary supports?</p>
<p>Here my models.py</p>
<pre><code>class MaterialeManager(models.Manager):
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).annotate(
total=F('quantita')*F('prezzo'),
)
def get_monthly_totals(self):
conto = dict((c.id, c) for c in Conto.objects.all())
return list(
(conto, datetime.date(year, month, 1), totale)
for conto_id, year, month, totale in (
self.values_list('conto__nome', 'data__year', 'data__month')
.annotate(totale=Sum(F('quantita') * F('prezzo')))
.values_list('conto__nome', 'data__year', 'data__month', 'totale')
))
class Conto(models.Model):
nome=models.CharField('Nome Conto', max_length=30, blank=True, default="")
def __str__(self):
return self.nome
class Materiale(models.Model):
conto = models.ForeignKey(Conto, on_delete=models.CASCADE,)
tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE,)
sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True)
um = models.CharField()
quantita=models.DecimalField()
prezzo=models.DecimalField()
data=models.DateField('Data di acquisto', default="GG/MM/YYYY")
objects=MaterialeManager()
def __str__(self):
return str(self.sottocategoria)
</code></pre>
<p>and here my views.py: </p>
<pre><code>def conto_economico(request):
defaults = list(0 for m in range(12))
elements = dict()
for conto, data, totale in Materiale.objects.get_monthly_totals():
if conto not in elements:
elements[conto.id] = list(defaults)
index = data.month - 1 # jan is one, but on index 0
elements[conto.id][index] = totale
context= {'elements': elements,}
return render(request, 'conto_economico/conto_economico.html', context)
</code></pre>
|
<p>You are trying to use a <code>dict:conto</code> as a key to your elements dictionary. That won't work because dictionary keys have to be hashable, which isn't the case. You can use other representative of cont as key, such as its name or id.</p>
|
django|python-3.x|django-models|django-forms|django-views
| 2 |
1,907,165 | 58,152,627 |
pandas: how to modify values in a column in dataframe by comparing other column values
|
<p>I have dataframe with the following structure:</p>
<pre><code>raw_data = {'website': ['bbc.com', 'cnn.com', 'google.com', 'facebook.com'],
'type': ['image', 'audio', 'image', 'video'],
'source': ['bbc','google','stackoverflow','facebook']}
df = pd.DataFrame(raw_data, columns = ['website', 'type', 'source'])
</code></pre>
<p><a href="https://i.stack.imgur.com/bQkFF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bQkFF.png" alt="enter image description here"></a></p>
<p>I would like to modify the values in column <code>type</code> with a condition that if the <code>source</code> exists in <code>website</code>, then suffix <code>type</code> with '_1stParty' else '_3rdParty'. The dataframe should eventually look like:</p>
<p><a href="https://i.stack.imgur.com/VCPtG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VCPtG.png" alt="enter image description here"></a> </p>
|
<p>Test values betwen rows with <code>in</code> and apply for processing each rows separately:</p>
<pre><code>m = df.apply(lambda x: x['source'] in x['website'], axis=1)
</code></pre>
<p>Or use <code>zip</code> with list comprehension:</p>
<pre><code>m = [a in b for a, b in zip(df['source'], df['website'])]
</code></pre>
<p>and then add new values by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p>
<pre><code>df['type'] += np.where(m, '_1stParty', '_3rdParty')
#'long' alternative
#df['type'] = df['type'] + np.where(m, '_1stParty', '_3rdParty')
print (df)
website type source
0 bbc.com image_1stParty bbc
1 cnn.com audio_3rdParty google
2 google.com image_3rdParty stackoverflow
3 facebook.com video_1stParty facebook
</code></pre>
|
python|pandas|dataframe
| 1 |
1,907,166 | 58,161,787 |
Iterate over each rows of a numpy array
|
<p>I have the following input which is 2D array. And I would like to iterate over each row to do some calculation but when I print the output it seems to iterate only on the first row of the array. Any contribution would be appreciated.</p>
<p>2D numpy array <code>corr_ret</code>: </p>
<pre><code>[[-6.33870149e-04 8.55011683e-04 -1.17983411e-03 7.91091491e-04
2.62196784e-04 -4.43688931e-05 -6.45968376e-06 -1.12538630e-03
2.15421763e-03 -3.16434832e-03 2.60707339e-03 1.50132673e-03
-1.26622898e-03 -6.60251486e-04 5.02396330e-04 2.11832581e-04
-7.69597583e-04 -3.29756120e-03 -1.24210577e-03 -4.62660468e-04
-3.49262651e-04 -3.43464642e-04 -2.55611240e-04 5.54536845e-04
-2.01366145e-03 -2.87531971e-04 -5.34641032e-04 1.72644604e-03
5.76858322e-04 -2.29174764e-03]
[ 4.70029370e-04 1.77020781e-03 -1.05050155e-03 -6.18841938e-04
1.16485579e-03 -6.00092725e-05 1.05676386e-04 -1.48243613e-03
3.72088647e-03 -1.75323439e-03 1.09075078e-03 9.89241541e-05
-1.59512783e-03 -7.11380812e-04 1.73537083e-03 8.78393781e-04
-9.29723278e-04 -1.53385019e-03 1.20444451e-04 -4.84107094e-04
-7.83347205e-04 1.18777621e-03 -1.54999170e-03 8.35286745e-05
-1.74472610e-03 9.83476064e-04 -8.82693488e-04 1.58099698e-03
3.15406396e-03 -1.26301009e-04]
[-1.06896577e-03 8.31379672e-04 1.54808513e-04 -1.35452237e-03
-2.19101603e-04 -7.26696656e-04 -2.93275089e-04 -6.88305530e-04
2.89300411e-03 -2.38832429e-03 -7.67452518e-04 -2.40866147e-04
-2.11929402e-03 -7.45901508e-04 5.02921628e-04 1.77651468e-04
-2.08574762e-03 -1.80218000e-03 -1.23287491e-03 -7.47521806e-04
-7.80485878e-04 6.15345860e-04 -1.40945995e-03 8.74548883e-04
-2.78711058e-03 1.92856732e-03 5.73070388e-04 1.29301575e-03
1.89158005e-03 8.65315240e-04]]
</code></pre>
<p>My code:</p>
<pre><code>for row in corr_ret:
seed = 1
So = corr_ret[0] #the first cell of the row
N = 30
mu = corr_ret.mean()/N
sigma = corr_ret.std()
print(sigma)
T = 1
</code></pre>
<p>My output: </p>
<pre><code> [-6.33870149e-04 8.55011683e-04 -1.17983411e-03 7.91091491e-04
2.62196784e-04 -4.43688931e-05 -6.45968376e-06 -1.12538630e-03
2.15421763e-03 -3.16434832e-03 2.60707339e-03 1.50132673e-03
-1.26622898e-03 -6.60251486e-04 5.02396330e-04 2.11832581e-04
-7.69597583e-04 -3.29756120e-03 -1.24210577e-03 -4.62660468e-04
-3.49262651e-04 -3.43464642e-04 -2.55611240e-04 5.54536845e-04
-2.01366145e-03 -2.87531971e-04 -5.34641032e-04 1.72644604e-03
5.76858322e-04 -2.29174764e-03]
-5.2605086588854405e-06
0.0013733187643799106
[-6.33870149e-04 8.55011683e-04 -1.17983411e-03 7.91091491e-04
2.62196784e-04 -4.43688931e-05 -6.45968376e-06 -1.12538630e-03
2.15421763e-03 -3.16434832e-03 2.60707339e-03 1.50132673e-03
-1.26622898e-03 -6.60251486e-04 5.02396330e-04 2.11832581e-04
-7.69597583e-04 -3.29756120e-03 -1.24210577e-03 -4.62660468e-04
-3.49262651e-04 -3.43464642e-04 -2.55611240e-04 5.54536845e-04
-2.01366145e-03 -2.87531971e-04 -5.34641032e-04 1.72644604e-03
5.76858322e-04 -2.29174764e-03]
-5.2605086588854405e-06
0.0013733187643799106
[-6.33870149e-04 8.55011683e-04 -1.17983411e-03 7.91091491e-04
2.62196784e-04 -4.43688931e-05 -6.45968376e-06 -1.12538630e-03
2.15421763e-03 -3.16434832e-03 2.60707339e-03 1.50132673e-03
-1.26622898e-03 -6.60251486e-04 5.02396330e-04 2.11832581e-04
-7.69597583e-04 -3.29756120e-03 -1.24210577e-03 -4.62660468e-04
-3.49262651e-04 -3.43464642e-04 -2.55611240e-04 5.54536845e-04
-2.01366145e-03 -2.87531971e-04 -5.34641032e-04 1.72644604e-03
5.76858322e-04 -2.29174764e-03]
-5.2605086588854405e-06
0.0013733187643799106
</code></pre>
|
<p>
To get the first cell you are using the corr_ret array, (the original array) which actually returns the first row of of the array.
To get the first element of each row, use So = row[0]
</p>
<pre><code>for row in corr_ret:
seed = 1
So = row[0] #the first cell of the row
N = 30
mu = corr_ret.mean()/N
sigma = corr_ret.std()
print(sigma)
T = 1
</code></pre>
|
python|numpy
| 0 |
1,907,167 | 57,845,551 |
Two figures with the x axis frame of exactly the same size
|
<p>I need to make two separate figures which will be than pasted together in such a way that they share the x axis. I don't want them to overlap, one must stay on the top and the other on the bottom, but with the same x axis. I tried to do it by setting the same <code>figsize</code>, then controlling the margins using <code>plt.subplots_adjust()</code>, for example</p>
<pre><code>import matplotlib.pyplot as plt
fig1=plt.figure('fig1',figsize=(6.4,4.8))
ax1=fig1.add_subplot(111)
plt.subplots_adjust(left=0.15, bottom=0.15, right=0.95, top=0.9, wspace=0, hspace=0.5)
fig2=plt.figure('fig2',figsize=(6.4,4.8))
ax2=fig2.add_subplot(111)
plt.subplots_adjust(left=0.15, bottom=0.15, right=0.95, top=0.9, wspace=0, hspace=0.5)
</code></pre>
<p>Then they might have different labels in the y axis. Unfortunately, when I try to paste them using GIMP, I see that their x axis size is very slightly different. How can I control the x axis size in such a way that there is no risk of having this problem? </p>
|
<p>Instead of using <code>add_subplot</code>, try <code>add_axes</code> as shown in the example below</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1,10,10)
y1 = x*x
y2 = np.exp(-x/3)
fig =plt.figure('fig1',figsize=(6.4,4.8))
ax1 = fig.add_axes((0.1,0.1,0.8,0.4))
ax2 = fig.add_axes((0.1,0.5,0.8,0.4))
ax1.plot(x,y1,color='Red')
ax1.set_xlim(0,10)
ax2.set_xlim(0,10)
ax2.plot(x,y2,color='Blue')
plt.savefig('example.png')
</code></pre>
<p><a href="https://i.stack.imgur.com/HRnhY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HRnhY.png" alt="enter image description here"></a></p>
|
python|matplotlib|plot
| 0 |
1,907,168 | 56,318,589 |
Trying to add Discord alerts/hooks to an existing python code
|
<p>So i want to monitor a webpage, and if a change occurs, i would like to be notified of that via Discord.</p>
<p>Searching google, i landed on this page <a href="https://www.adventuresintechland.com/detect-when-a-webpage-changes-with-python/" rel="nofollow noreferrer">https://www.adventuresintechland.com/detect-when-a-webpage-changes-with-python/</a></p>
<p>and it seems to work when i test it on my website.
But i would like to add Discord alerts to this code but seem to be stuck </p>
<p>i have looked into Dhooks on github and have been stuck trying to implement it</p>
<pre><code># Hunter Thornsberry
# http://www.adventuresintechland.com
# WebChange.py
# Alerts you when a webpage has changed it's content by comparing checksums of the html.
import hashlib
import urllib2
import random
import time
# url to be scraped
url = "http://raw.adventuresintechland.com/freedom.html"
# time between checks in seconds
sleeptime = 60
def getHash():
# random integer to select user agent
randomint = random.randint(0,7)
# User_Agents
# This helps skirt a bit around servers that detect repeaded requests from the same machine.
# This will not prevent your IP from getting banned but will help a bit by pretending to be different browsers
# and operating systems.
user_agents = [
'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
'Opera/9.25 (Windows NT 5.1; U; en)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:8.0.1) Gecko/20100101 Firefox/8.0.1',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19'
]
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', user_agents[randomint])]
response = opener.open(url)
the_page = response.read()
return hashlib.sha224(the_page).hexdigest()
current_hash = getHash() # Get the current hash, which is what the website is now
while 1: # Run forever
if getHash() == current_hash: # If nothing has changed
print "Not Changed"
else: # If something has changed
print "Changed"
break
time.sleep(sleeptime)
</code></pre>
|
<p>You will need to use the discord API connection: with python, use discord.py.</p>
<p>Have a look at the <a href="https://discordpy.readthedocs.io/en/latest/" rel="nofollow noreferrer">discord.py docs</a> and learn how to use it, then connect the two - just add the required discord.py imports and setup to the file in the appropriate places and add a prompt to send a message whenever the webpage changes (in this case, replacing the <code>print("changed")</code> with <code>yourChannel.send("webpage has changed!)"</code>.</p>
|
python|python-3.x|discord.py
| 0 |
1,907,169 | 56,264,563 |
How to wait for a shell script reboot in Fabric 2
|
<p>I'm using Fabric 2 and I'm trying to run a shell script on a number of hosts sequentially. In the script, it configures a few settings and reboots that host. When I run my task however it ends after the script has run on the first host (I'm guessing because the SSH connection terminates due to the reboot). I tried looking into setting 'warn_only' to True, but I don't see where to set this value on Fabric 2. </p>
<p>Adding:</p>
<pre><code>with settings(warn_only=True):
</code></pre>
<p>throws a "NameError: global name 'settings' is not defined" error. </p>
<p>Is there a correct format to warn_only? If not possible yet in Fabric 2, is there a way to continue running my task regardless of this reboot?</p>
<p>My script:</p>
<pre><code>from fabric import *
import time
import csv
@task
def test(ctx):
hosts = ['1.1.1.1', '2.2.2.2']
for host in hosts:
c = Connection(host=host, user="user", connect_kwargs={"password": "password"})
c.run("./shell_script.sh")
configured = False
while not configured:
result = c.run("cat /etc/hostname")
if result != "default": configured = True
time.sleep(10)
</code></pre>
|
<p>Looks like you can use the <code>config</code> argument to the connection class instead of the <code>with settings()</code> construction, and <code>warn_only</code> as been renamed to <code>warn</code>;</p>
<pre class="lang-py prettyprint-override"><code>with Connection(host=host, user="user", connect_kwargs={"password": "password"}) as c:
c.run("./shell_script.sh", warn=True)
</code></pre>
<p>More generally, you can get upgrade documentation at <a href="https://www.fabfile.org/upgrading.html#run" rel="nofollow noreferrer">https://www.fabfile.org/upgrading.html#run</a></p>
|
python|fabric
| 0 |
1,907,170 | 56,418,338 |
like button not doing anything, cant tell what the problem is
|
<p>I want users to be able to like my post so I implemented here. here's my code. It doesn't give any error which is frustrating.</p>
<pre><code>models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
url = models.URLField(max_length=250, blank=True, null=True)
views = models.IntegerField(default=0)
likes = models.ManyToManyField(User, related_name='likes')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
def total_likes(self):
return self.likes.count()
views.py
def like(request):
if request.method == 'POST':
user = request.user # bring login user
post_pk = request.POST.get('pk', None)
post = Post.objects.get(pk = post_pk) #bring the post object.
if post.likes.filter(id = user.id).exists(): #if exit
post.likes.remove(user) #likes deleted.
message = 'You disliked this'
else:
post.likes.add(user)
message = 'You liked this'
context = {'likes_count' : post.total_likes, 'message' : message}
return HttpResponse(json.dumps(context), content_type='application/json')
</code></pre>
<p>urls.py</p>
<pre><code>urlpatterns = [
path('', PostListView.as_view(), name='community-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/<int:post_pk>/comment/new',views.comment_new, name='comment_new'),
path('post/<int:post_pk>/comment/<int:pk>/edit',views.comment_edit, name='comment_edit'),
path('post/<int:post_pk>/comment/<int:pk>/delete',views.comment_delete, name='comment_delete'),
path('like/', views.like, name='like'),
</code></pre>
<p>my html</p>
<pre><code><input type="button" class="like" name="{{ memo.id }}" value="Like">
<p id="count{{ memo.id }}">count : {{ memo.total_likes }}</p>
<script type="text/javascript">
for(i = 0; i < $(".writer_name").length; i++){
if($("#user_name").text() == $(".writer_name")[i].innerHTML){
$("#control_id"+i).removeClass("hidden");
}
}
$('.like').click(function(){
var pk = $(this).attr('name')
$.ajax({
type: "POST",
url: "{% url 'like' %}",
data: {'pk': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response){
id = $(this).attr('name')
$('#count'+ pk).html("count : "+ response.likes_count);
alert(response.message);
alert("likes :" + response.likes_count);
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
}
});
})
</script>
</code></pre>
<p>I'm not sure if my ajax is wrong or my python is wrong. but to me the logic here makes sense. if anyone can tell what the problem is I would be really appreciated. Thanks</p>
|
<pre><code>def like(request):
response_json = request.POST
response_json = json.dumps(response_json)
data = json.loads(response_json)
post = Post.objects.get(pk =data['pk'])
if post.likes.filter(id = user.id).exists(): #if exit
post.likes.remove(user) #likes deleted.
message = 'You disliked this'
else:
post.likes.add(user)
message = 'You liked this'
context = {'likes_count' : post.total_likes, 'message' : message}
return JsonResponse(context, safe=False)
</code></pre>
<p>try like this. You are sending a JSON datatype so python has to interpret it as so.</p>
|
javascript|python|ajax|django
| 0 |
1,907,171 | 18,564,708 |
Course Builder 1.5.1 'ImportError: No module named html5lib'
|
<p>I just upgraded my coursebuilder course to Course builder version 1.5.1. I ran into an issue where html5lib isn't working. Has anyone dealt with this or know how to get around it? I noticed that when I downloaded the course-builder demo application, it also suffers the same problem. Below is the stacktrace I've run into.</p>
<pre><code>Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 196, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 255, in _LoadHandler
handler = __import__(path[0])
File "/Users/r351574nc3/projects/git/kfs-training/main.py", line 25, in <module>
from common import tags
File "/Users/r351574nc3/projects/git/kfs-training/common/tags.py", line 30, in <module>
import html5lib
ImportError: No module named html5lib
</code></pre>
|
<p>I figured the answer out. The problem is that the html5lib-0.95.zip I was using had within it a directory called html5lib-0.95. I think coursebuilder required that all files be in the root path of the zip. Recreating the zip fixed this for me.</p>
|
python|google-app-engine
| 0 |
1,907,172 | 18,689,292 |
How do I get a variable from another class?
|
<p>I have the following class:</p>
<pre><code>class Login():
#PROMPT THE OPERATOR TO LOGIN
def login(self):
self.usr = input("usr> ")
self.pwd = getpass.getpass("pwd> ")
self.check_login()
</code></pre>
<p>I also have this class:</p>
<pre><code>class Kernel(Login):
#THIS IS WHERE THE OPERATOR CAN ENTER STUFF AND SHIT.
def kernel(self):
obj = Login()
kernel_input = input(obj.login.self.usr + "@" + OS_NAME.lower() + ">")
</code></pre>
<p>However, I have no idea how to get the variable <em>self.usr</em> from the class <em>Login</em> to work on the class <em>Kernel</em> which is a child to the class <em>Login</em>.</p>
<p>As you can see, I have created the Login() object and stored it into the variable <em>obj</em>. In the Login class, there is a method called <em>login</em> which holds a self variable called <em>usr</em>.</p>
<p>I tried calling it in another class using:</p>
<pre><code>obj.usr
obj.self.usr
obj.login.usr
obj.login.self.usr
</code></pre>
<p>But none of that works.
How could I make this work?</p>
|
<p><code>obj.usr</code> is the correct way. However, that attribute will not exist until after the <code>login</code> method of the <code>Login</code> object is called. You would need to do something like:</p>
<pre><code>obj = Login()
obj.login()
# now you can use obj.usr
</code></pre>
<p>It's hard to know exactly when you should be calling <code>login()</code> without knowing exactly how your classes are meant to be used (e.g., when the Login object's login is "supposed" to happen). Another possibility is that you actually want to set <code>usr</code> and <code>pwd</code> during the Login class's <code>__init__</code>, so they exist as soon as the object is created.</p>
|
python|class|oop|variables
| 1 |
1,907,173 | 71,649,594 |
Is there possibility to enable file path autocompletion in PyCharm?
|
<p>I'm looking for an option to enable file path autocompletion in <em>Python</em> scripts for <em>PyCharm</em>. Is there such an option or a plug-in?</p>
<p>A similar feature exists already in <em>Jupyter Notebook</em>:
<a href="https://i.stack.imgur.com/kmGPO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kmGPO.png" alt="jupyter-example" /></a></p>
|
<p>Its possible, however you need to use plugin for that.
you can find it <a href="https://plugins.jetbrains.com/plugin/11088-file-path-autocomplete" rel="nofollow noreferrer">here</a></p>
|
python|path|pycharm
| 1 |
1,907,174 | 69,565,568 |
How will I convert data in csv file to dictionary format using python
|
<p>I have a CSV file which looks like below image:</p>
<p><img src="https://i.stack.imgur.com/8Pbwp.png" alt="image" /></p>
<p>I want to get this in dictionary format like this:</p>
<pre><code>{'Alcolohol - related liver disease': 'Jaundice Yellow Eye, pain, swelling,',
'Acquired Capillary Haemangioma of Eyelid': 'Raised red or blue lesion,',
'Acquired Immuno Deficiency Syndrome': 'Flu-like illness,',
'Acute encephalitis syndrome': 'Headache, fever, confusion, stiff neck,
vomiting,', .......... and so on}
</code></pre>
<p>Try using this in CSV file.</p>
|
<p>You might want to check if the <code>key</code> <em>(disease)</em> is already assigned and <code>append</code> the <code>value</code> <em>(symptoms)</em> to the <code>list</code>.</p>
<p>≈ Database DeNormalization</p>
<pre><code>import csv
csv_reader = csv.reader(open('./file.csv', 'r'))
next(csv_reader) # skip header
disease_dict = {}
for row in csv_reader:
disease, symptoms = row[0], row[1]
if disease not in disease_dict:
disease_dict[disease] = []
disease_dict[disease].append(symptoms)
print(disease_dict)
</code></pre>
<p>P.S.
To print the dictionary in your format:</p>
<pre><code>for key in disease_dict:
print(key, *disease_dict[key])
</code></pre>
|
python
| 1 |
1,907,175 | 69,521,272 |
Highlight new posts in django/react
|
<p>I have Post model in django which has Channel as foreign key. What I want to do is , whenever there is a new post in post model, that channel should get highlighted and that should be user specific. What I am thinking is whenever new post is created, there will be one flag <code>is_highlighted</code> which will be set to true. Is this the right way to do? any other better way? TIA</p>
<pre><code>class Post(models.Model):
user = models.ForeignKey(
User,
on_delete=models.DO_NOTHING,
blank=True,
null=True,
related_name="post_user_id")
channel = models.ForeignKey(
Channel,
on_delete=models.DO_NOTHING,
blank=False,
null=False,
related_name="post_channel_id")
</code></pre>
<p>and channel model is</p>
<pre><code>class Channel(models.Model):
channel_name = models.CharField(
max_length=250,
help_text="Channel channel_name")
</code></pre>
|
<p>I think the simplest solution in the long term would be to store the creation date of the record which can be done by adding the line</p>
<p><code>creation_date = models.DateField("creation_date", auto_now_add=True)</code> into the Post model that you would like this to apply to. If you are using a REST api to communicate between your Django backend and React frontend, you will then need to serialize this in order to have the date added to the json which the React app uses, then on your frontend code you can have a simple script that highlights the post when the difference between the current date and the creation_date is greater than a certain time period. This should fix your problem and automate the process of changing highlighting.</p>
|
python|reactjs|django|django-queryset
| 0 |
1,907,176 | 55,213,253 |
Using click.MultiCommand with classmethods
|
<p>How can I use <code>click.MultiCommand</code> together with commands defined as classmethods?</p>
<p>I'm trying to setup a plugin system for converters where users of the library can provide their own converters. For this system I'm setting up a CLI like the following:</p>
<pre><code>$ myproj convert {converter} INPUT OUTPUT {ARGS}
</code></pre>
<p>Each converter is its own class and all inherit from <code>BaseConverter</code>. In the <code>BaseConverter</code> is the most simple Click command which only takes input and output.</p>
<p>For the converters that don't need more than that, they don't have to override that method. If a converter needs more than that, or needs to provide additional documentation, then it needs to be overridden.</p>
<p>With the code below, I get the following error when trying to use the cli:</p>
<blockquote>
<p>TypeError: cli() missing 1 required positional argument: 'cls'</p>
</blockquote>
<pre><code>conversion/
├── __init__.py
└── backends/
├── __init__.py
├── base.py
├── bar.py
├── baz.py
└── foo.py
</code></pre>
<pre class="lang-py prettyprint-override"><code># cli.py
from pydoc import locate
import click
from proj.conversion import AVAILABLE_CONVERTERS
class ConversionCLI(click.MultiCommand):
def list_commands(self, ctx):
return sorted(list(AVAILABLE_CONVERTERS))
def get_command(self, ctx, name):
return locate(AVAILABLE_CONVERTERS[name] + '.cli')
@click.command(cls=ConversionCLI)
def convert():
"""Convert files using specified converter"""
pass
</code></pre>
<pre class="lang-py prettyprint-override"><code># conversion/__init__.py
from django.conf import settings
AVAILABLE_CONVERTERS = {
'bar': 'conversion.backends.bar.BarConverter',
'baz': 'conversion.backends.baz.BazConverter',
'foo': 'conversion.backends.foo.FooConverter',
}
extra_converters = getattr(settings, 'CONVERTERS', {})
AVAILABLE_CONVERTERS.update(extra_converters)
</code></pre>
<pre class="lang-py prettyprint-override"><code># conversion/backends/base.py
import click
class BaseConverter():
@classmethod
def convert(cls, infile, outfile):
raise NotImplementedError
@classmethod
@click.command()
@click.argument('infile')
@click.argument('outfile')
def cli(cls, infile, outfile):
return cls.convert(infile, outfile)
</code></pre>
<pre class="lang-py prettyprint-override"><code># conversion/backends/bar.py
from proj.conversion.base import BaseConverter
class BarConverter(BaseConverter):
@classmethod
def convert(cls, infile, outfile):
# do stuff
</code></pre>
<pre class="lang-py prettyprint-override"><code># conversion/backends/foo.py
import click
from proj.conversion.base import BaseConverter
class FooConverter(BaseConverter):
@classmethod
def convert(cls, infile, outfile, extra_arg):
# do stuff
@classmethod
@click.command()
@click.argument('infile')
@click.argument('outfile')
@click.argument('extra-arg')
def cli(cls, infile, outfile, extra_arg):
return cls.convert(infile, outfile, extra_arg)
</code></pre>
|
<p>To use a <code>classmethod</code> as a click command, you need to be able to populate the <code>cls</code> parameter when invoking the command. That can be done with a custom <code>click.Command</code> class like:</p>
<h3>Custom Class:</h3>
<pre><code>import click
class ClsMethodClickCommand(click.Command):
def __init__(self, *args, **kwargs):
self._cls = [None]
super(ClsMethodClickCommand, self).__init__(*args, **kwargs)
def main(self, *args, **kwargs):
self._cls[0] = args[0]
return super(ClsMethodClickCommand, self).main(*args[1:], **kwargs)
def invoke(self, ctx):
ctx.params['cls'] = self._cls[0]
return super(ClsMethodClickCommand, self).invoke(ctx)
</code></pre>
<h3>Using the Custom Class:</h3>
<pre><code>class MyClassWithAClickCommand:
@classmethod
@click.command(cls=ClsMethodClickCommand)
....
def cli(cls, ....):
....
</code></pre>
<p>And then in the <code>click.Multicommand</code> class you need to populate the <code>_cls</code> attribute since the <code>command.main</code> is not called in this case:</p>
<pre><code>def get_command(self, ctx, name):
# this is hard coded in this example but presumably
# would be done with a lookup via name
cmd = MyClassWithAClickCommand.cli
# Tell the click command which class it is associated with
cmd._cls[0] = MyClassWithAClickCommand
return cmd
</code></pre>
<h3>How does this work?</h3>
<p>This works because click is a well designed OO framework. The <code>@click.command()</code> decorator usually instantiates a <code>click.Command</code> object but allows this behavior to be over ridden with the <code>cls</code> parameter. So it is a relatively easy matter to inherit from <code>click.Command</code> in our own class and over ride desired methods.</p>
<p>In this case, we override <code>click.Command.invoke()</code> and then add the containing class to the <code>ctx.params</code> dict as <code>cls</code> before invoking the command handler.</p>
<h3>Test Code:</h3>
<pre><code>class MyClassWithAClickCommand:
@classmethod
@click.command(cls=ClsMethodClickCommand)
@click.argument('arg')
def cli(cls, arg):
click.echo('cls: {}'.format(cls.__name__))
click.echo('cli: {}'.format(arg))
class ConversionCLI(click.MultiCommand):
def list_commands(self, ctx):
return ['converter_x']
def get_command(self, ctx, name):
cmd = MyClassWithAClickCommand.cli
cmd._cls[0] = MyClassWithAClickCommand
return cmd
@click.command(cls=ConversionCLI)
def convert():
"""Convert files using specified converter"""
if __name__ == "__main__":
commands = (
'converter_x an_arg',
'converter_x --help',
'converter_x',
'--help',
'',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for cmd in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + cmd)
time.sleep(0.1)
convert(cmd.split())
except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise
</code></pre>
<h3>Results:</h3>
<pre><code>Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> converter_x an_arg
class: MyClassWithAClickCommand
cli: an_arg
-----------
> converter_x --help
Usage: test.py converter_x [OPTIONS] ARG
Options:
--help Show this message and exit.
-----------
> converter_x
Usage: test.py converter_x [OPTIONS] ARG
Error: Missing argument "arg".
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Convert files using specified converter
Options:
--help Show this message and exit.
Commands:
converter_x
-----------
>
Usage: test.py [OPTIONS] COMMAND [ARGS]...
Convert files using specified converter
Options:
--help Show this message and exit.
Commands:
converter_x
</code></pre>
|
python|command-line-interface|python-click
| 4 |
1,907,177 | 55,244,737 |
Check if a database connection is busy using python
|
<p>I want to create a Database class which can create cursors on demand.
It must be possible to use the cursors in parallel (two or more cursor can coexist) and, since we can only have one cursor per connection, the Database class must handle multiple connections. </p>
<p>For performance reasons we want to reuse connections as much as possible and avoid creating a new connection every time a cursor is created:
whenever a request is made the class will try to find, among the opened connections, the first non-busy connection and use it.</p>
<p>A connection is still busy as long as the cursor has not been consumed.</p>
<p>Here is an example of such class:</p>
<pre class="lang-py prettyprint-override"><code>class Database:
...
def get_cursos(self,query):
selected_connection = None
# Find usable connection
for con in self.connections:
if con.is_busy() == False: # <--- This is not PEP 249
selected_connection = con
break
# If all connections are busy, create a new one
if (selected_connection is None):
selected_connection = self._new_connection()
self.connections.append(selected_connection)
# Return cursor on query
cur = selected_connection.cursor()
cur.execute(query)
return cur
</code></pre>
<p>However looking at the <a href="https://www.python.org/dev/peps/pep-0249/#connection" rel="nofollow noreferrer">PEP 249</a> standard I cannot find any way to check whether a connection is actually being used or not. </p>
<p>Some implementations such as MySQL Connector offer ways to check whether a connection has still unread content (see <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-unread-results.html" rel="nofollow noreferrer">here</a>), however as far as I know those are not part of PEP 249.</p>
<p>Is there a way I can achieve what described before for any PEP 249 compliant python database API ?</p>
|
<p>Perhaps you could use the status of the cursor to tell you if a cursor is being used. Let's say you had the following cursor:</p>
<pre><code>new_cursor = new_connection.cursor()
cursor.execute(new_query)
</code></pre>
<p>and you wanted to see if that connection was available for another cursor to use. You <em>might</em> be able to do something like:</p>
<pre><code>if (new_cursor.rowcount == -1):
another_new_cursor = new_connection.cursor()
...
</code></pre>
<p>Of course, all this really tells you is that the cursor hasn't executed anything yet since the last time it was closed. It could point to a cursor that is done (and therefore a connection that has been closed) or it could point to a cursor that has just been created or attached to a connection. Another option is to use a try/catch loop, something along the lines of:</p>
<pre><code>try:
another_new_cursor = new_connection.cursor()
except ConnectionError?: //not actually sure which error would go here but you get the idea.
print("this connection is busy.")
</code></pre>
<p>Of course, you probably don't want to be spammed with printed messages but you can do whatever you want in that except block, sleep for 5 seconds, wait for some other variable to be passed, wait for user input, etc. If you are restricted to PEP 249, you are going to have to do a lot of things from scratch. Is there a reason you can't use external libraries?</p>
<p>EDIT: If you are willing to move outside of PEP 249, here is something that might work, but it may not be suitable for your purposes. If you make use of the <code>mysql</code> python library, you can take advantage of the <code>is_connected</code> method.</p>
<pre><code>new_connection = mysql.connector.connect(host='myhost',
database='myDB',
user='me',
password='myPassword')
...stuff happens...
if (new_connection.is_connected()):
pass
else:
another_new_cursor = new_connection.cursor()
...
</code></pre>
|
python|mysql|sql|pymysql|mysql-connector-python
| 1 |
1,907,178 | 57,691,614 |
Parse cookie string to array or something else in python
|
<p>i have many cookie strings that i get from a http response and save in a set. For example like this:</p>
<pre><code>cookies = set()
cookies.add("__cfduid=123456789101112131415116; expires=Thu, 27-Aug-20 10:10:10 GMT; path=/; domain=.example.com; HttpOnly; Secure")
cookies.add("MUID=16151413121110987654321; domain=.bing.com; expires=Mon, 21-Sep-2020 10:10:11 GMT; path=/;, MUIDB=478534957198492834; path=/; httponly; expires=Mon, 21-Sep-2020 10:10:11 GMT")
</code></pre>
<p>Now i would like to parse that strings to an array or something else to access the data (domain, expires, ...) easier. For example like this:</p>
<pre><code>cookie['MUID']['value']
cookie['MUID']['domain']
cookie['MUIDB']['path']
cookie['__cfduid']['Secure']
...
</code></pre>
<p>But i don't know how i do this. I try it with the <code>SimpleCookie</code> from <code>http.cookies</code> but i get not the expected result.</p>
|
<p>You should create a python dictionary for this.</p>
<pre><code>from collections import defaultdict
cookies = defaultdict(str)
list_of_strings = ["__cfduid=123456789101112131415116; expires=Thu, 27-Aug-20 10:10:10 GMT; path=/; domain=.example.com; HttpOnly; Secure"]# this is your list of strings you want to add
for string in list_of_strings:
parts = string.split(";")
for part in parts:
temp = part.split("=")
if len(temp) == 2:
cookies[temp[0]] = temp[1]
</code></pre>
|
python|cookies|http-headers
| 0 |
1,907,179 | 57,642,245 |
My custom mobilenet trained model is not showing any results. What am I doing wrong?
|
<p>I started to learn ML using Tensorflow/Deeplab. I tried to train my own model from scratch for clothes recognition using semantic segmentation with mobilenet_v2 model variant. But I don't get results.</p>
<p>I'm using <a href="https://github.com/tensorflow/models" rel="nofollow noreferrer">tensorflow/models</a> for tfrecord export and training. And <a href="https://colab.research.google.com/github/tensorflow/models/blob/master/research/deeplab/deeplab_demo.ipynb" rel="nofollow noreferrer">deeplab/example</a> code for visualization and testing purpose (renamed locally as main.py), I modify some lines so I can get the local models and testing image.</p>
<p>I'll show the process I followed:</p>
<ol>
<li>Download 100 JPEG images (I know is not that big, but I guess I can try it with this amount). Just for 1 class -> shirts</li>
<li>Create the segmentation class PNG for each image.</li>
<li>Create the files image sets definition for: train(85 filenames), trainval(100 filenames) and val(15 filenames).
<br>So my "pascal dataset" directory has: ImageSets, JPEGImages and SegmentationClassPNG folders.</li>
<li><p>Export the "pascal dataset" directory to tfrecord like this (I'm on "models-master/research/deeplab/datasets" folder):</p>
<pre><code>py build_voc2012_data.py --image_folder="pasc_imgs/JPEGImages" --semantic_segmentation_folder="pasc_imgs/SegmentationClassPNG" --list_folder="pasc_imgs/ImageSets" --image_format="jpg" --output_dir="train/tfrecord"
</code></pre>
<ul>
<li>this works fine, it generates *.tfrecord files on "train/tfrecord"</li>
</ul></li>
<li><p>I edited "models-master/research/deeplab/data_generator.py" like this: {'train': 85, 'trainval': 100, 'val': 15}, num_classes=2.</p></li>
<li>Now time to start the training, (I'm on "models-master/research/deeplab"). I used 10000 steps, why? I proved with 30000 and takes like 30 hours with no results, so I reduce it with new params. I guess 10000 steps could show me something:
<pre><code>py train.py --logtostderr --training_number_of_steps=10000 --train_split="train" --model_variant="mobilenet_v2" --output_stride=16 --decoder_output_stride=4 --train_batch_size=1 --dataset="pascal_voc_seg" --train_logdir="datasets/train/deeplab_model_mn" --dataset_dir="datasets/train/tfrecord"
</code></pre>
<ul>
<li>This step takes almost 8 hours (have a tiny GPU, so.. can't use it), and it generates the checkpoint, graph.pbtxt, and model.ckpt-XXX (10000 included) files. </li>
</ul></li>
<li>I exported the previous result with (I'm on "models-master/research/deeplab") this command line:
<pre><code>py export_model.py --checkpoint_path=datasets/train/deeplab_model_mn/model.ckpt-10000 --export_path=datasets/train/deeplab_inference_mn/frozen_inference_graph.pb --model_variant="mobilenet_v2" --output_stride=16 --num_classes=2
</code></pre>
<ul>
<li>It creates the frozen graph (frozen_inference_graph.pb).</li>
</ul></li>
<li>Now run: <b>py main.py</b> (proof image and frozen_inference_graph.pb already imported)</li>
<li>No results with my custom model. This last script works with pre-trained mobilenetv2_coco_voc_trainaug. Not with my custom model </li>
</ol>
<p><b>data_generator.py (edited lines):</b></p>
<pre class="lang-py prettyprint-override"><code>_PASCAL_VOC_SEG_INFORMATION = DatasetDescriptor(
splits_to_sizes={
'train': 85,
'trainval': 100,
'val': 15,
},
num_classes=2,# 0:background, 1:shirt
ignore_label=255,
)
</code></pre>
<p>Image example (1/100) that I'm using for training (I used the <a href="https://github.com/wkentaro/labelme" rel="nofollow noreferrer">labelMe</a> utility):
<br>
<a href="https://i.stack.imgur.com/YVIy3.jpg" rel="nofollow noreferrer">shirt_001.jpg</a>
<br>
<a href="https://i.stack.imgur.com/P4WKU.png" rel="nofollow noreferrer">shirt_001.png</a></p>
<p><br>
<b>main.py result for mobilenetv2_coco_voc_trainaug (shirt as a person, that's ok) and my custom model</b> :
<br>
<a href="https://i.stack.imgur.com/cBs5z.jpg" rel="nofollow noreferrer">mobilenetv2_coco_voc_trainaug result</a>
<br>
<a href="https://i.stack.imgur.com/42S7R.jpg" rel="nofollow noreferrer">my custom model result</a></p>
<p>As you can see, my model fails. I've been testing many combinations without success. <b>What should I do?</b> Thank you!</p>
|
<p>Ok, I had the same problem and after many attempts I've done it.
First, you should make correct masks. If you use one class you should create the masks with <strong>indexed color map</strong>, and <strong>all pixels should be 0 or 1</strong>, 0 - background, 1 - mask (there're 255 colors in the indexed color map).
Second, you need a bigger dataset. I tried training using a dataset with ~200 images and got no results (even with a correct dataset) even on checkpoint-30k. But when I tried training using a dataset with 450 images I had some results only from ~9000 epoch. There was no improvement after the ~18000 epoch, but the results were plausible (though far from ideal). Then I was training a model with 1100 images, but the results were the same.</p>
|
python|tensorflow|semantic-segmentation|deeplab|mobilenet
| 0 |
1,907,180 | 59,176,715 |
Python 3 // Printing an error if a string contains no vowels
|
<blockquote>
<p>Write a function which takes a string argument with no spaces in it, searches for vowels (the letters "a", "e", "i", "o", "u") in the string, replaces them by upper case characters, and prints out the new string with the upper cases as well as returns the new string from the function. You should verify it is a string argument using <code>isalpha</code> (so no spaces are allowed!) and return with an error if not (the error message should being with "Error:").</p>
<p>For instance, if the string input is "miscellaneous", then your program will print out and return "mIscEllAnEOUs". <strong>If nothing in the string is a vowel, print "Nothing to convert!" and return <code>None</code>.</strong></p>
</blockquote>
<p>This is what I have so far that is working, but I'm having trouble with the part in bold in the assignment.</p>
<pre><code>def uppercase(word):
vowels = "aeiou"
error_msg = "Error: not a string."
nothing_msg = "Nothing to convert!"
new_word = []
for letter in word:
if word.isalpha():
if letter in vowels:
new_word.append(letter.upper())
else:
new_word.append(letter.lower())
else:
print(error_msg)
return None
new_word = ''.join(new_word)
return new_word
</code></pre>
|
<p>To check that a string is all letters you can use <code>str.isalpha</code>. To check that there are vowels contained, you can use a generator expression within <code>any</code> to confirm that at least one of the letters is a vowel. Then lastly you can do the conversion with another generator expression within <code>join</code> to uppercase only the vowels, then return a new string.</p>
<pre><code>def uppercase(word):
if not word.isalpha():
return 'Error'
if not any(letter in 'aeiou' for letter in word):
return 'Nothing to convert!'
return ''.join(letter.upper() if letter in 'aeiou' else letter for letter in word)
</code></pre>
<p>Examples</p>
<pre><code>>>> uppercase('miscellaneous')
'mIscEllAnEOUs'
>>> uppercase('abc123')
'Error'
>>> uppercase('xyz')
'Nothing to convert!'
</code></pre>
|
python|string|function
| 1 |
1,907,181 | 59,132,514 |
Trouble importing third party Python packages to GIMP 2.10 so that they can be used to write GIMP plugins
|
<p>My goal is to import a couple third party Python packages for use with my GIMP installation. This will allow me to use these packages when developing a GIMP plugin. I noticed a few directories that may be of use. They are as follows: </p>
<p>C:\Program Files\GIMP 2\32\lib\python2.7</p>
<p>This directory contains a site-packages folder which contains packages such as requests and pip.</p>
<p>C:\Program Files\GIMP 2\32\bin</p>
<p>This directory contains a python.exe. When I run python --version in an elevated cmd at this directory path, the output is Python 2.7.16, which I assume is GIMP 2.10's version of Python. This is important because I have my own installation of Python 3.8.0 in my Program Files. If I'm anywhere outside of this path in the cmd, the version that outputs is 3.8.0.</p>
<p>I have added these directories to my PATH system variable and tried running pip install but the output tells me I have already installed the requested third party packages. The problem is that they are installed to my Python 3.8.0 installation. I'm trying to run pip install in the context of GIMP's Python environment. </p>
<p>Any advice would be much appreciated.</p>
|
<ul>
<li>Grab <code>get-pip.py</code> <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow noreferrer">here</a></li>
<li>Put it into your GIMP Python directory (C:\Program Files\GIMP 2\Python)</li>
<li>From a Windows Command Prompt Window <code>cd</code> to that directory</li>
<li>Run <code>get-pip</code> <strong>with this python instance</strong>: <code>.\python.exe get-pip.py</code>. You now have pip installed in the GIMP version of Python.</li>
<li>You can now use this pip instance with Gimp's Python runtime: <code>.\python.exe -m pip install --user <package></code></li>
</ul>
<p>Uplifted/adapted from <a href="https://www.gimp-forum.net/Thread-Gimp-python-and-numpy?pid=4385#pid4385" rel="nofollow noreferrer">here</a></p>
|
python|python-3.x|python-2.7|gimp|gimpfu
| 1 |
1,907,182 | 59,308,278 |
How to get Python support in Vim (not gVim) on Windows
|
<p>I read that Vim and gVim in the same installation are supposed to be identical, excluding the graphical interface obviously. However I was trying to figure out why some plugins wouldn't load into Vim (not gVim). I was following a tutorial that mentioned that Window's Vim already has Python support built in. After more checking I learned about <code>:version</code> and tried it in both Vim and gVim of the same installation.</p>
<p>gVim:</p>
<pre><code>:version
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Dec 12 2019 13:30:17)
MS-Windows 32-bit GUI version with OLE support
Compiled by mool@tororo
Huge version with GUI. Features included (+) or not (-):
+acl +cindent +cursorshape -farsi +jumplist +mksession +path_extra +rightleft +tag_binary +title +wildignore
+arabic +clientserver +dialog_con_gui +file_in_path +keymap +modify_fname +perl/dyn +ruby/dyn -tag_old_static +toolbar +wildmenu
+autocmd +clipboard +diff +find_in_path +lambda +mouse +persistent_undo +scrollbind -tag_any_white +user_commands +windows
+autochdir +cmdline_compl +digraphs +float +langmap +mouseshape +popupwin +signs +tcl/dyn +vartabs +writebackup
+autoservername +cmdline_hist +directx +folding +libcall +multi_byte_ime/dyn -postscript +smartindent -termguicolors +vertsplit -xfontset
+balloon_eval +cmdline_info -dnd -footer +linebreak +multi_lang +printer +sound +terminal +virtualedit -xim
-balloon_eval_term +comments -ebcdic +gettext/dyn +lispindent +mzscheme/dyn +profile +spell -termresponse +visual +xpm_w32
+browse +conceal +emacs_tags -hangul_input +listcmds +netbeans_intg +python/dyn +startuptime +textobjects +visualextra -xterm_save
++builtin_terms +cryptv +eval +iconv/dyn +localmap +num64 +python3/dyn +statusline +textprop +viminfo
+byte_offset +cscope +ex_extra +insert_expand +lua/dyn +ole +quickfix -sun_workshop -tgetent +vreplace
+channel +cursorbind +extra_search +job +menu +packages +reltime +syntax +timers -vtp
system vimrc file: "$VIM\vimrc"
user vimrc file: "$HOME\_vimrc"
2nd user vimrc file: "$HOME\vimfiles\vimrc"
3rd user vimrc file: "$VIM\_vimrc"
user exrc file: "$HOME\_exrc"
2nd user exrc file: "$VIM\_exrc"
system gvimrc file: "$VIM\gvimrc"
user gvimrc file: "$HOME\_gvimrc"
2nd user gvimrc file: "$HOME\vimfiles\gvimrc"
3rd user gvimrc file: "$VIM\_gvimrc"
defaults file: "$VIMRUNTIME\defaults.vim"
system menu file: "$VIMRUNTIME\menu.vim"
Compilation: cl -c /W3 /nologo -I. -Iproto -DHAVE_PATHDEF -DWIN32 -DFEAT_CSCOPE -DFEAT_TERMINAL -DFEAT_SOUND -DFEAT_NETBEANS_INTG -DFEAT_JOB_CHANNEL -DFEAT_XPM_W32 -DWINVER=0x0501 -D_WIN32_WINNT=0x0501 /MP -DHAVE_STDINT_H /Ox /GL -
DNDEBUG /arch:IA32 /Zl /MT -DFEAT_OLE -DFEAT_MBYTE_IME -DDYNAMIC_IME -DFEAT_GUI_MSWIN -DFEAT_DIRECTX -DDYNAMIC_DIRECTX -DFEAT_DIRECTX_COLOR_EMOJI -DDYNAMIC_ICONV -DDYNAMIC_GETTEXT -DFEAT_TCL -DDYNAMIC_TCL -DDYNAMIC_TCL_DLL=\"tcl86t.dll\"
-DDYNAMIC_TCL_VER=\"8.6\" -DFEAT_LUA -DDYNAMIC_LUA -DDYNAMIC_LUA_DLL=\"lua53.dll\" -DFEAT_PYTHON -DDYNAMIC_PYTHON -DDYNAMIC_PYTHON_DLL=\"python27.dll\" -DFEAT_PYTHON3 -DDYNAMIC_PYTHON3 -DDYNAMIC_PYTHON3_DLL=\"python36.dll\" -DFEAT_MZSCH
EME -I "E:\Racket\include" -DMZ_PRECISE_GC -DDYNAMIC_MZSCHEME -DDYNAMIC_MZSCH_DLL=\"libracket3m_a36fs8.dll\" -DDYNAMIC_MZGC_DLL=\"libracket3m_a36fs8.dll\" -DFEAT_PERL -DPERL_IMPLICIT_CONTEXT -DPERL_IMPLICIT_SYS -DDYNAMIC_PERL -DDYNAMIC_P
ERL_DLL=\"perl524.dll\" -DFEAT_RUBY -DDYNAMIC_RUBY -DDYNAMIC_RUBY_VER=24 -DDYNAMIC_RUBY_DLL=\"msvcrt-ruby240.dll\" -DFEAT_HUGE /Fd.\ObjGXOULYHTRZi386/ /Zi
Linking: link /nologo /opt:ref /LTCG:STATUS oldnames.lib kernel32.lib advapi32.lib shell32.lib gdi32.lib comdlg32.lib ole32.lib netapi32.lib uuid.lib /machine:i386 gdi32.lib version.lib winspool.lib comctl32.lib advapi32.lib shell32.
lib netapi32.lib /machine:i386 libcmt.lib oleaut32.lib user32.lib /nodefaultlib:lua53.lib /STACK:8388608 /nodefaultlib:python27.lib /nodefaultlib:python36.lib "E:\ActiveTcl\lib\tclstub86.lib" winmm.lib WSock32.lib xpm\x86\lib-vc14
\libXpm.lib /PDB:gvim.pdb -debug
</code></pre>
<p>Vim:</p>
<pre><code>:version
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Dec 12 2019 13:19:27)
MS-Windows 32-bit console version
Compiled by mool@tororo
Huge version without GUI. Features included (+) or not (-):
+acl +channel +cscope +ex_extra +iconv/dyn +listcmds -mzscheme +profile +sound +termguicolors +vartabs +windows
+arabic +cindent +cursorbind +extra_search +insert_expand +localmap -netbeans_intg -python +spell +terminal +vertsplit +writebackup
+autocmd +clientserver +cursorshape -farsi +job -lua +num64 -python3 +startuptime -termresponse +virtualedit -xfontset
+autochdir +clipboard +dialog_con +file_in_path +jumplist +menu +packages +quickfix +statusline +textobjects +visual -xim
+autoservername +cmdline_compl +diff +find_in_path +keymap +mksession +path_extra +reltime -sun_workshop +textprop +visualextra -xpm_w32
-balloon_eval +cmdline_hist +digraphs +float +lambda +modify_fname -perl +rightleft +syntax -tgetent +viminfo -xterm_save
+balloon_eval_term +cmdline_info -dnd +folding +langmap +mouse +persistent_undo -ruby +tag_binary +timers +vreplace
-browse +comments -ebcdic -footer +libcall -mouseshape +popupwin +scrollbind -tag_old_static +title +vtp
++builtin_terms +conceal +emacs_tags +gettext/dyn +linebreak +multi_byte -postscript +signs -tag_any_white -toolbar +wildignore
+byte_offset +cryptv +eval -hangul_input +lispindent +multi_lang +printer +smartindent -tcl +user_commands +wildmenu
system vimrc file: "$VIM\vimrc"
user vimrc file: "$HOME\_vimrc"
2nd user vimrc file: "$HOME\vimfiles\vimrc"
3rd user vimrc file: "$VIM\_vimrc"
user exrc file: "$HOME\_exrc"
2nd user exrc file: "$VIM\_exrc"
defaults file: "$VIMRUNTIME\defaults.vim"
Compilation: cl -c /W3 /nologo -I. -Iproto -DHAVE_PATHDEF -DWIN32 -DFEAT_CSCOPE -DFEAT_TERMINAL -DFEAT_SOUND -DFEAT_JOB_CHANNEL -DWINVER=0x0501 -D_WIN32_WINNT=0x0501 /MP -DHAVE_STDINT_H /Ox /GL -DNDEBUG /arch:IA32 /Zl /MT -DDYNAMIC_
ICONV -DDYNAMIC_GETTEXT -DFEAT_HUGE /Fd.\ObjCi386/ /Zi
Linking:
link /nologo /opt:ref /LTCG:STATUS oldnames.lib kernel32.lib advapi32.lib shell32.lib gdi32.lib comdlg32.lib ole32.lib netapi32.lib uuid.lib /machine:i386 libcmt.lib user32.lib winmm.lib WSock32.lib /PDB:vim.pdb -debug
</code></pre>
<p>From the <code>:version</code> details I see that gVim has the expected</p>
<pre><code>+python/dyn +python3/dyn
</code></pre>
<p>entries but Vim instead has</p>
<pre><code>-python -python3
</code></pre>
<p>Was I mistaken in thinking that these two should be identical in their build configuration? Do I need to rebuild vi from scratch to get the command line version of Vim to include Python support? or is there some simpler method? Or maybe should I report this discrepancy as a bug somewhere?</p>
<p>[EDIT]</p>
<p>Removed image of <code>:version</code> outputs and pasted their text directly into this post. Also switched to version 8.2 (was 8.1).</p>
|
<p>[UPDATE]</p>
<p>It turns out that vim-win32-installer repo has python capabilities in both gvim and vim. The releases can be found here: <a href="https://github.com/vim/vim-win32-installer/releases" rel="nofollow noreferrer">https://github.com/vim/vim-win32-installer/releases</a></p>
<p>[Original Answer]</p>
<p>It turns out that the vim installer build used for windows has a misconfiguration between the two separate builds used for gVim and vim. I tried to follow up on this here: github.com/vim/vim/issues/5355</p>
<p>At the present time the consensus seems to lean towards this not being a big enough issue and people can just build vim manually if they want another feature-set. While I disagree with this in general, I can definitely understand this is not a priority and hope that the powers that be get the two builds in sync in the future. Please contribute your own thoughts to that task.</p>
|
python|windows|vim
| 0 |
1,907,183 | 59,412,778 |
How to configure interpreter in PyCharm after downgrading python 3.8 to 3.7 on windows?
|
<p>I want to downgrade my python to 3.7 because the whl that i want to install(<a href="https://github.com/intxcc/pyaudio_portaudio/releases" rel="nofollow noreferrer">https://github.com/intxcc/pyaudio_portaudio/releases</a>) only supports python 3.7.
I tried uninstalling python 3.8 and installing 3.7.But now i can't configure the interpreter in pycharm.
Anyone can help with that?
Thanks<a href="https://i.stack.imgur.com/hT3WT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hT3WT.png" alt="enter image description here"></a></p>
|
<p>You didn't need to uninstall Python 3.8, because PyCharm supports multiple interpreters. You can have some project using 3.7 and others using 3.8.</p>
<p>To set the interpreter for a specific project, click <code>File</code> and select <code>Settings</code> from the drop down.</p>
<p>In the <code>settings</code> popup, find your project and then <code>Project Interpreter</code> :</p>
<p><a href="https://i.stack.imgur.com/jdDMA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jdDMA.png" alt="Project interpreter in Settings"></a></p>
<p>Click on the drop-down arrow circled in red, and you will get a list of interpreters available to choose from.</p>
<p>If none of them are correct ones, select <code>Show all</code>, and a new popup with the name <code>Project Interpreters</code> appears on top, listing more interpreters.</p>
<p>If none of those is correct one, click on the <code>+</code> in the upper right corner of the <code>Project Interpreters</code>, and get <code>Add Python Interpreter</code> popup.</p>
<p>It's a good idea to use virtual environments. If you already have a virtual environment inside your project, either delete it or create a new one with a different name (the default name is <code><your project path>/venv</code>). For example, instead of <code>venv</code>, use <code>venv37</code>.</p>
<p><a href="https://i.stack.imgur.com/dWd3y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dWd3y.png" alt="Add Project Interpreter"></a></p>
<p>The drop-down arrow I circled in green will show all the interpreters that PyCharm knows about.</p>
<p>If the new one doesn't show, click on <code>...</code> (circled in blue), and locate the newly installed interpreter in the file system. Then click <code>OK</code> to close <code>Add Python Interpreter</code> popup, and get back to <code>Project Interpreters</code>.</p>
<p>The new virtual environment will show on that list. Select it and click <code>OK</code>.</p>
<p>Now you should be back in Settings. Click <code>Apply</code> and then <code>OK</code>.</p>
<p>From now on, this PyCharm project will be using the new interpreter.</p>
|
python|pycharm
| 2 |
1,907,184 | 65,285,154 |
Django decorators to handle admin users redirection
|
<p>I want normal users to be redirected to <code><address>/panel</code> and need admins to be redirected to <code><adress>/admin</code>. So what I did in <code>views.py</code> is something like:</p>
<pre><code>from django.contrib.auth.decorators import login_required
@unauthenticated_user
def registration_view(request):
...
@unauthenticated_user
def login_view(request):
...
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def admin_home_view(request):
context = {}
return render(request, 'account/admin/home-page.html', context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['user'])
def user_home_view(request):
context = {}
return render(request, 'account/user/home-page.html', context)
</code></pre>
<h1>Update here</h1>
<p>And in <code>decorators.py</code> I have:</p>
<pre><code>from django.http import HttpResponse
from django.shortcuts import redirect
from groups_manager.models import Group, GroupMemberRole, Member
def unauthenticated_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('panel')
else:
return view_func(request, *args, **kwargs)
return wrapper_func
def allowed_users(allowed_roles=[]):
def decorator(view_func):
def wrapper_func(request, *args, **kwargs):
allowed_role = allowed_roles[0]
username = request.user.username
member = Member.objects.get(username=username)
roles = GroupMemberRole.objects.filter(groupmember__member=member)
member_roles = []
for role in roles:
member_roles.append(role.label)
if 'admin' in member_roles:
...
elif 'user' in member_roles:
...
else:
return HttpResponse('you are not allowed')
return wrapper_func
return decorator
</code></pre>
<p>I want to know how I can redirect <code>admin</code> users to <code><address>/admin</code> url. But admin users are redirected to <code>/panel</code> url.</p>
<p>My <code>urls.py</code> is:</p>
<pre><code>urlpatterns = [
path('admin', views.admin_home_view, name='admin'),
path('panel', views.user_home_view, name='panel'),
path('panel/register', views.registration_view, name='register'),
path('panel/logout', views.logout_view, name='logout'),
path('panel/login', views.login_view, name='login'),
]
</code></pre>
|
<p>I got the answer I think based on @markwalker_ help.</p>
<p>Now my <code>decorators.py</code> is:</p>
<pre><code>from django.shortcuts import redirect
def unauthenticated_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('panel')
else:
return view_func(request, *args, **kwargs)
return wrapper_func
</code></pre>
<p>and in my <code>login_view</code> I have:</p>
<pre><code>login(request, user)
member = Member.objects.get(username=username)
roles = GroupMemberRole.objects.filter(groupmember__member=member)
member_roles = []
for role in roles:
member_roles.append(role.label)
if 'admin' in member_roles:
return redirect('admin')
else:
return redirect('panel')
</code></pre>
<p>I think it could be a reliable way to work.</p>
|
python|django|python-decorators
| 0 |
1,907,185 | 45,641,646 |
Why doesn't Jupyter notebook command open notebook?
|
<p>When I write <code>jupyter notebook</code> in terminal it doesn't open notebook, it opens Jupyter tree. What can be the problem?</p>
|
<p><strong>Question</strong>: When I write <code>jupyter notebook</code> in terminal it doesn't open notebook, it opens Jupyter tree. What can be the problem?</p>
<p><strong>Answer</strong>: You missed the path for the notebook (say, notebook_to_open.ipynb).
Try again with command like this:</p>
<p>(windows)</p>
<pre><code>jupyter notebook c:/path/to/your/notebook_to_open.ipynb
</code></pre>
<p>(linux)</p>
<pre><code>jupyter notebook ~/path/to/your/notebook_to_open.ipynb
</code></pre>
|
python|ubuntu|jupyter-notebook|jupyter
| 0 |
1,907,186 | 28,762,116 |
Cannot construct tkinter.PhotoImage from PIL Image
|
<p>I try to show a image in a label when I push a button, but the image are too large and I have tried to resize the image. I have created this function:</p>
<pre><code>def image_resize(imageFile):
width = 500
height = 300
image = Image.open(imageFile)
im2 = image.resize((width, height), Image.ANTIALIAS)
return im2
</code></pre>
<p>To show the image I have created this function:</p>
<pre><code>def show_image():
label_originalimage ['image'] = image_tk
</code></pre>
<p>And the button with the <code>command=show_image</code>:</p>
<pre><code>filename = 'bild_1.jpg'
image_resize = image_resize(filename)
image_tk = PhotoImage(image_resize)
button_open = Button(frame_open, text='Open Image', command=show_image)
</code></pre>
<p>I get only this:</p>
<pre><code>TypeError : __str__ returned non-string (type instance)
</code></pre>
|
<p>The <a href="http://effbot.org/tkinterbook/photoimage.htm" rel="nofollow"><code>PhotoImage</code></a> class from <code>tkinter</code> takes a filename as an argument, and as it cannot convert the <code>image</code> into a string, it complains. Instead, use the <code>PhotoImage</code> class from the <code>PIL.ImageTk</code> module. This works for me:</p>
<pre><code>from tkinter import *
from PIL import ImageTk, Image
def image_resize(imageFile):
width = 500
height = 300
image = Image.open(imageFile)
im2 = image.resize((width,height), Image.ANTIALIAS)
return im2
def show_image():
label_originalimage ['image'] = image_tk
root = Tk()
filename = './Pictures/Space/AP923487321702.jpg'
image_resize = image_resize(filename)
image_tk = ImageTk.PhotoImage(image_resize)
label_originalimage = Label(root)
label_originalimage.pack()
button_open = Button(root, text='Open Image', command=show_image)
button_open.pack()
root.mainloop()
</code></pre>
<p>Notice the change from <code>image_tk = PhotoImage(image_resize)</code> to <code>image_tk = ImageTk.PhotoImage(image_resize)</code>.</p>
|
python|tkinter|resize|python-imaging-library|resize-image
| 2 |
1,907,187 | 57,154,751 |
is there a way to go through all the keys in two dictionarys and change all duplicate items so the dictionarys items are all different
|
<p>I am a new programmer and am writing some code for a personnel assignment and I need to make sure two dictionarys with identical keys has no identical items. I need to search for the identical items and change them.</p>
<p>Im using python 3 and have tried messing with for loops but have not gotten anything to work but Im guessing that is because of my only basic understanding of them.</p>
<p>In the code below it may seem as though i can just check through each variable and change the variables individually but for the purpose of learning and whats actually in my full script id like to do it the way i described.</p>
<pre><code>from random import choice
names = ['jacob', 'josh', 'alex', 'tyler']
weapons = ['swords', 'ax', 'rock', 'nothing']
armor = ['chest plate', 'none', 'vest', 'mask']
# I dont want to change values through these variables if possible
p1_name = choice(names)
p2_name = choice(names)
p1_weapon = choice(weapons)
p2_weapon = choice(weapons)
p1_armor = choice(armor)
p2_armor = choice(armor)
#here are the dictionarys I want to change
p1 = {'name': p1_name, 'weapon': p1_weapon, 'armor': p1_armor}
p2 = {'name': p2_name, 'weapon': p2_weapon, 'armor': p2_armor}
</code></pre>
<p>I also know I can probably go through every key manually i.e.:</p>
<pre><code>if p1['name'] == p2['name']:
</code></pre>
<p>but if its possible to do it through some sort of loop I'd prefer that because throughout my original code the dicts will change.</p>
|
<p>You could collect your lists also in a dict and then assuming your dictionaries have similar keys (as your example suggests) you could use a loop like so:</p>
<pre class="lang-py prettyprint-override"><code>database = {'name': ['jacob', 'josh', 'alex', 'tyler'],
'weapon': ['swords', 'ax', 'rock', 'nothing'],
'armor': ['chest plate', 'none', 'vest', 'mask']}
for key in p1.keys():
if p1[key] == p2[key]:
p2[key] = choice(database[key])
</code></pre>
<hr>
<p>To avoid that check at all, you could actually make sure from the start that no two similar items will be assigned by using <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow noreferrer"><code>random.sample</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>from random import sample
names = ['jacob', 'josh', 'alex', 'tyler']
weapons = ['swords', 'ax', 'rock', 'nothing']
armor = ['chest plate', 'none', 'vest', 'mask']
p1_name, p2_name = sample(names, 2)
p1_weapon, p2_weapon = sample(weapons, 2)
p1_armor, p2_armor = sample(armor, 2)
p1 = {'name': p1_name, 'weapon': p1_weapon, 'armor': p1_armor}
p2 = {'name': p2_name, 'weapon': p2_weapon, 'armor': p2_armor}
</code></pre>
|
python|dictionary|for-loop
| 0 |
1,907,188 | 25,435,777 |
returning a list in a single line in python
|
<p>I'm just curious if there is a simpler way to do this. If I want to print a list of items on one line I simply write </p>
<pre><code>for i in things:
print i,
</code></pre>
<p>but if I substitute print for return I'm obviously only going to get the first item of the list. I needed the list to comma and space separated as well so I ended up with a function that looks like this</p>
<pre><code>def returner(things):
thing = ""
n = 1
for i in things:
thing += i
if n < len(things):
thing += ", "
n += 1
return thing
</code></pre>
<p>Was there a better way to do this?</p>
|
<p>Use join</p>
<pre><code>return ", ".join([str(x) for x in things])
</code></pre>
|
python|list|for-loop|printing|return
| 4 |
1,907,189 | 44,496,838 |
Using chaos game representation for gene sequences [Python program]
|
<p>I need to represent many gene sequences using chaos game representation I got this python code from Boštjan Cigan's blog (<a href="https://bostjan-cigan.com/chaos-game-representation-of-gene-structure-in-python/" rel="nofollow noreferrer">https://bostjan-cigan.com/chaos-game-representation-of-gene-structure-in-python/</a>)</p>
<h1>Author: Bostjan Cigan</h1>
<h1><a href="https://bostjan-cigan.com" rel="nofollow noreferrer">https://bostjan-cigan.com</a></h1>
<pre><code> import collections
from collections import OrderedDict
from matplotlib import pyplot as plt
from matplotlib import cm
import pylab
import math
f = open("ensemblSeq.fa")
s1 = f.read()
data = "".join(s1.split("\n")[1:])
def count_kmers(sequence, k):
d = collections.defaultdict(int)
for i in xrange(len(data)-(k-1)):
d[sequence[i:i+k]] +=1
for key in d.keys():
if "N" in key:
del d[key]
return d
def probabilities(kmer_count, k):
probabilities = collections.defaultdict(float)
N = len(data)
for key, value in kmer_count.items():
probabilities[key] = float(value) / (N - k + 1)
return probabilities
def chaos_game_representation(probabilities, k):
array_size = int(math.sqrt(4**k))
chaos = []
for i in range(array_size):
chaos.append([0]*array_size)
maxx = array_size
maxy = array_size
posx = 1
posy = 1
for key, value in probabilities.items():
for char in key:
if char == "T":
posx += maxx / 2
elif char == "C":
posy += maxy / 2
elif char == "G":
posx += maxx / 2
posy += maxy / 2
maxx = maxx / 2
maxy /= 2
chaos[posy-1][posx-1] = value
maxx = array_size
maxy = array_size
posx = 1
posy = 1
return chaos
f3 = count_kmers(data, 3)
f4 = count_kmers(data, 4)
f3_prob = probabilities(f3, 3)
f4_prob = probabilities(f4, 4)
chaos_k3 = chaos_game_representation(f3_prob, 3)
pylab.title('Chaos game representation for 3-mers')
pylab.imshow(chaos_k3, interpolation='nearest', cmap=cm.gray_r)
pylab.show()
chaos_k4 = chaos_game_representation(f4_prob, 4)
pylab.title('Chaos game representation for 4-mers')
pylab.imshow(chaos_k4, interpolation='nearest', cmap=cm.gray_r)
pylab.show()
</code></pre>
<p>This code works fine but I have many sequence files I need to iterate through each fasta file in the folder and get individual plots stored in a folder with the name of the image file corresponding to the name of the fasta file how can I modify the code according to my need </p>
<p>I am new to python as well as StackOverflow if any mistake is there kindly ignore</p>
<p>Thanks in advance </p>
|
<p>So, if you want to apply your code on every file in your directory a very simple way to do this is calling all files inside of a <code>for</code>-loop. I suggest the following:</p>
<pre><code>import collections
import os
from collections import OrderedDict
from matplotlib import pyplot as plt
from matplotlib import cm
import pylab
import math
def count_kmers(sequence, k):
d = collections.defaultdict(int)
for i in xrange(len(data)-(k-1)):
d[sequence[i:i+k]] +=1
for key in d.keys():
if "N" in key:
del d[key]
return d
def probabilities(kmer_count, k):
probabilities = collections.defaultdict(float)
N = len(data)
for key, value in kmer_count.items():
probabilities[key] = float(value) / (N - k + 1)
return probabilities
def chaos_game_representation(probabilities, k):
array_size = int(math.sqrt(4**k))
chaos = []
for i in range(array_size):
chaos.append([0]*array_size)
maxx = array_size
maxy = array_size
posx = 1
posy = 1
for key, value in probabilities.items():
for char in key:
if char == "T":
posx += maxx / 2
elif char == "C":
posy += maxy / 2
elif char == "G":
posx += maxx / 2
posy += maxy / 2
maxx = maxx / 2
maxy /= 2
chaos[posy-1][posx-1] = value
maxx = array_size
maxy = array_size
posx = 1
posy = 1
return chaos
if __name__ == "__main__":
PATH = os.getcwd()
filelist = sorted([os.path.join(PATH, f) for f in os.listdir(PATH) if f.endswith('.fa')])
for file in filelist:
f = open(file)
s1 = f.read()
data = "".join(s1.split("\n")[1:])
f3 = count_kmers(data, 3)
f4 = count_kmers(data, 4)
f3_prob = probabilities(f3, 3)
f4_prob = probabilities(f4, 4)
chaos_k3 = chaos_game_representation(f3_prob, 3)
pylab.title('Chaos game representation for 3-mers')
pylab.imshow(chaos_k3, interpolation='nearest', cmap=cm.gray_r)
pylab.savefig(os.path.splitext(file)[0]+'chaos3.png')
pylab.show()
chaos_k4 = chaos_game_representation(f4_prob, 4)
pylab.title('Chaos game representation for 4-mers')
pylab.imshow(chaos_k4, interpolation='nearest', cmap=cm.gray_r)
pylab.savefig(os.path.splitext(file)[0]+'chaos4.png')
pylab.show()
</code></pre>
<p>I just wrapped a loop around and added a <code>pylab.savefig()</code> call. Furthermore I used <code>os</code> to get the filenames from your directory. It should work now.</p>
|
python|dna-sequence|representation|chaos
| 0 |
1,907,190 | 44,735,224 |
Printing a specific column using regex in Python 3
|
<p>I have a line which looks like this:</p>
<pre><code>line = "A1 33 #_ABCDBDBBD_# A8310810 _AJFA_AS_A__SA"
</code></pre>
<p>I want to extract fourth column from this line using re.search in python.</p>
<p>Currently I'm using</p>
<pre><code>re.search(r"\s+([A-F0-9])+\s", line).group()
</code></pre>
<p>This prints <code>33</code></p>
<p>Instead I'm expecting it to print <code>33 A8310810</code></p>
<p>And then later extract the second element from this using <code>group(2)</code>.</p>
<p>What is my mistake? How do I extract the fourth column?</p>
|
<p>If you want to match multiple columns, it would be simpler to split by whitespace than match on content.</p>
<p>For example:</p>
<pre><code>>>> import re
>>> line = "A1 33 #ABCDBDBBD# A8310810 _AJFA_AS_A__SA"
>>> cols = re.split('[\s]+', line)
>>> cols
['A1', '33', '#ABCDBDBBD#', 'A8310810', '_AJFA_AS_A__SA']
>>> cols[1]
'33'
>>> cols[3]
'A8310810'
</code></pre>
<hr>
<p>You can also use <code>line.split()</code>:</p>
<pre><code>>>> line.split()
['A1', '33', '#_ABCDBDBBD_#', 'A8310810', '_AJFA_AS_A__SA']
</code></pre>
<hr>
<p>Here's another way using <code>re.match</code> to get your groups.</p>
<pre><code>>>> m = re.match('^([\S]+)[\s]+([\S]+)[\s]+([\S]+)[\s]+([\S]+)[\s]+([\S]+)$', line)
>>> print(m.groups())
('A1', '33', '#_ABCDBDBBD_#', 'A8310810', '_AJFA_AS_A__SA')
>>> m.group(2)
'33'
>>> m.group(4)
'A8310810'
</code></pre>
|
python|regex
| 0 |
1,907,191 | 23,698,857 |
What is causing Flask to not start running?
|
<p>I have been working on some code for a while now, but haven't had a chance to look at it for two weeks. I've just come back to it, and really cannot figure out why it isn't working. I thought it was working when I left it (Not perfectly, as it isn't finished) but I keep getting errors for Flask itself, but only with this code. Please could someone take a look and see if there is anything glaringly obvious?</p>
<pre><code># add flask here
from flask import Flask
from flask import request
from flask import jsonify
app = Flask(__name__)
app.debug = True
# keep your code
import time
import cgi
import json
from tellcore.telldus import TelldusCore
core = TelldusCore()
devices = core.devices()
# define a "power ON api endpoint"
# START ENDPOINT DECLARATION
@app.route("/API/v1.0/power-on",methods=['POST'])
def powerOnDevice():
payload = {}
payload['success'] = False
payload['message'] = "An unspecified error occured"
#get the device by id somehow
# get some extra parameters
# let's say how long to stay on
# PARAMS MUST BE HERE
#params = request.json
jsonData = request.get_json()
print jsonData['deviceID']
device = -1
powerAction = "none"
time = 0
password = "none"
#checks to make sure the deviceId has been specified and is a valid number
try:
device = devices[int(jsonData['deviceID'])]
except:
payload['message'] = "Incorrect deviceId specified"
return jsonify(**payload)
#checks to make sure the powerAction has been specified and is valid text
try:
powerAction = jsonData['powerAction']
if (jsonData['powerAction'] == "on" or jsonData['powerAction'] == "off"):
powerAction = jsonData['powerAction']
except:
payload['message'] = "Incorrect powerAction specified"
return jsonify(**payload)
#check password is specified and is text
try:
password = jsonData['password']
if (jsonData['password']
#check time is number and is specified
if (jsonData['pass'] == "support"):
try:
device.turn_on()
payload['success'] = True
payload['message'] = ""
return jsonify(**payload)
except:
payload['success'] = False
# add an exception description here
return jsonify(**payload)
else:
payload['message'] = "Incorrect password"
# END ENDPOINT DECLARATION
return jsonify(**payload)
# define a "power OFF api endpoint"
@app.route("/API/v1.0/power-off/<deviceId>",methods=['POST'])
def powerOffDevice(deviceId):
payload = {}
#get the device by id somehow
device = devices[int(deviceId)]
try:
device.turn_off()
payload['success'] = True
return payload
except:
payload['success'] = False
# add an exception description here
return payload
app.run(host='0.0.0.0', port=81, debug=True)
</code></pre>
<p>When run, I get this:</p>
<pre><code>pi@FOR-PI-01 ~/FlaskTesting $ sudo python flaskao150514.py
File "flaskao150514.py", line 71
if (jsonData['pass'] == "support"):
^
SyntaxError: invalid syntax
</code></pre>
<p>Then deleting the whole if statement gives me errors with the app.run at the bottom. I know there may be Python mistakes in there, but why isn't Flask running?</p>
|
<p>You left an incomplete line <em>before</em> the line that throws the syntax error:</p>
<pre><code>if (jsonData['password']
</code></pre>
<p>Because there is no closing parenthesis there, Python is looking at following lines to see where the expression ends.</p>
<p>Note that Python does <em>not need</em> those parenthesis; the following is valid Python:</p>
<pre><code>if jsonData['pass'] == "support":
</code></pre>
<p>Go easy on the parenthesis and you'll create fewer opportunities for such errors.</p>
|
python|api|flask|raspberry-pi
| 0 |
1,907,192 | 23,868,338 |
sending a mail inside a django view gives NameError
|
<p>Trying to send mail inside django view</p>
<pre><code>from django.core.mail import send_mail
# Snippet inside a view
for ml in mls:
try:
l = Letter.objects.get(pk = ml.message_key)
except Exception as e:
mail_txt = _("sending mail failed " + str(e) + " " + str(ml.activity_org) + " " + str(ml.scheduled_time))
send_mail(mail_txt, "sending mail", "user@domain.com", ["sender@domain.com"], fail_silently=False)
</code></pre>
<p><strong>Error</strong> </p>
<pre><code>NameError: global name 'send_mail' is not defined
</code></pre>
|
<p>I recommend you tu use <code>EmailMultiAlternatives</code>. I use this, is easy to configure and use.
Example:</p>
<p><strong>Add this to Settings.py</strong></p>
<pre><code>EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'yourmail@gmail.com'
EMAIL_HOST_PASSWORD = 'yourpass'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
</code></pre>
<p>If you use different mail server change the shown data for your data</p>
<hr>
<p><strong>Function example</strong></p>
<pre><code>from django.core.mail import EmailMultiAlternatives
title = 'Test Email'
message_text = 'Test email message'
#email_to has to be a list, even if you're sending mail only to 1 address
mail = EmailMultiAlternatives(title, message_text, 'from@email.com', ['email_to1'])
mail.send()
</code></pre>
<p>You can attach files, or html code... More info in <a href="https://docs.djangoproject.com/en/dev/topics/email/" rel="nofollow">Django Documentation - Mail</a></p>
<p>Hope it helps! </p>
|
python|django|django-views|sendmail
| 0 |
1,907,193 | 15,002,085 |
How to get values from a "cell" of a "groupby" object?
|
<p>Assume that I have the following data frame:</p>
<pre><code> A B C D
0 foo one 1 10
1 bar one 2 20
2 foo two 3 30
3 bar one 4 40
4 foo two 5 50
5 bar two 6 60
6 foo one 7 70
7 foo two 8 80
</code></pre>
<p>Now I can group by the first column: <code>grouped = df.groupby('A')</code>. As a result I get the following <code>DataFrameGroupBy</code> object:</p>
<pre><code> A B C D
0 foo [one,two,two,one,two] [1,3,5,7,8] [10,30,50,70,80]
1 bar [one,one,two] [2,4,6] [20,40,60]
</code></pre>
<p>Now I would like to access the values from a particular cell. How can I do it? For example I want to get the values from the column 'D' and the row where <code>'A'=='foo'</code> (the first row). In other words I want to get <code>[10,30,50,70,80]</code>. Is it possible?</p>
|
<p>Are you thinking of something like this?</p>
<pre><code>>>> df
A B C D
0 foo one 1 10
1 bar one 2 20
2 foo two 3 30
3 bar one 4 40
4 foo two 5 50
5 bar two 6 60
6 foo one 7 70
7 foo two 8 80
>>> df.groupby("A").get_group("foo")["D"]
0 10
2 30
4 50
6 70
7 80
Name: D
>>> df.groupby("A").get_group("foo")["D"].tolist()
[10, 30, 50, 70, 80]
</code></pre>
|
python|group-by|pandas
| 15 |
1,907,194 | 29,452,875 |
return empty JSON by Flask
|
<p>I have a simple functions, which should returns JSON.</p>
<pre><code>@app.route('/storage/experiments', methods=['GET'])
def get_experiments():
if not request.json:
abort(400)
experiments = db['experiments']
cursor = experiments.find(request.get_json())
print(dumps(cursor))
resp = Response(response=dumps(cursor),
status=200, \
mimetype="application/json")
return resp
</code></pre>
<p>print(dumps(cursor)) shows</p>
<p><code>[{"current": "11", "date": "12.12.2001", "_id": {"$oid": "551c7b642349c517f5fa5223"}, "name": "xaxa", "voltage": "34"}]</code></p>
<p>but returns empty brackets []</p>
|
<p>I guess this is happneing because your database cursor (I don't know what database framework you use. <code>sqlalchemy</code>?) points at the end of your dataset when you want to return it, because your <code>print()</code>-statement was already iterating over it. It should work with this code when you just comment out the <code>print()</code> statement, because I can't see any other error in this code:</p>
<pre><code>@app.route('/storage/experiments', methods=['GET'])
def get_experiments():
if not request.json:
abort(400)
experiments = db['experiments']
cursor = experiments.find(request.get_json())
#print(dumps(cursor))
resp = Response(response=dumps(cursor),
status=200, \
mimetype="application/json")
return resp
</code></pre>
|
python|json|flask
| 0 |
1,907,195 | 64,543,406 |
pandas groupby with function as key
|
<p>I would like to calculate the mean with with a timespan of 3 years.
My data are like that :</p>
<pre><code>import pandas as pd
import numpy as np
N=120
data = {'p1': np.random.randint(50,100,N),
'p2': np.random.randint(0,100,N),
'p3': np.random.randint(10,70,N)
}
df = (pd.DataFrame(data, index=pd.bdate_range(start='20100101', periods=N, freq='BM'))
.stack()
.reset_index()
.rename(columns={'level_0': 'date', 'level_1': 'type', 0: 'price'})
.sort_values('date')
)
</code></pre>
<p>I tried :</p>
<pre><code>(df.sort_values('date')
.groupby(['type',
''.join([(df.date.dt.year-3), '-', (df.date.dt.year)]) #3 years time span
]
)
['price']
.apply(lambda x: x.mean())
)
</code></pre>
<p>but get an error message :</p>
<pre><code>TypeError: sequence item 0: expected str instance, Series found
</code></pre>
<p>I would like to calculate the mean (and others stat) on price with group by type/time period of 2010-2013, 2011-2014, 2012-2015...</p>
<p><strong>The label is important because I can use :</strong></p>
<pre><code>(df.sort_values('date')
.groupby(['type', df.date.dt.year//3]) #3 years time span
['price']
.apply(lambda x: x.mean())
)
</code></pre>
<p>any idea ?</p>
|
<p>I think I found the answer to my own question with (someone else could be interested) :</p>
<pre><code>(df.sort_values('date')
.groupby(['type', (df.date.dt.year-3).astype(str).str.cat((df.date.dt.year).astype(str), sep='-')
]
)
['price']
.apply(lambda x: x.mean())
)
</code></pre>
|
pandas|dataframe|group-by
| 1 |
1,907,196 | 70,404,461 |
Can't call with tpqoa
|
<p>can someone help me with this error?
Is there an error in my pyalgo file?
What type of other address I have to put into tpqoa call?</p>
<p>Thanks</p>
<p>CODE</p>
<p>pyalgo.cfg</p>
<pre><code> [oanda]
account_id = "101-012-21240417-001"
access_token = 'hidden'
account_type = practice
</code></pre>
<p>CODE</p>
<pre><code>import oandapyV20
import pandas as pd
import tpqoa
api = tpqoa.tpqoa('../pyalgo.cfg')
api.get.instruments()[:15]
</code></pre>
<p>Output</p>
<pre><code>KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5064/836215391.py in <module>
2 import pandas as pd
3 import tpqoa
----> 4 api = tpqoa.tpqoa('../pyalgo.cfg')
5 from oandapyV20 import API
6 import oandapyV20.endpoints.pricing as pricing
~\anaconda3\envs\PythonPC\lib\site-packages\tpqoa\tpqoa.py in __init__(self, conf_file)
111 self.config = configparser.ConfigParser()
112 self.config.read(conf_file)
--> 113 self.access_token = self.config['oanda']['access_token']
114 self.account_id = self.config['oanda']['account_id']
115 self.account_type = self.config['oanda']['account_type']
~\anaconda3\envs\PythonPC\lib\configparser.py in __getitem__(self, key)
958 def __getitem__(self, key):
959 if key != self.default_section and not self.has_section(key):
--> 960 raise KeyError(key)
961 return self._proxies[key]
962
KeyError: 'oanda'
</code></pre>
|
<p>you have indented the account_id, access_token and account_type.</p>
<p>unindent them then run it.</p>
|
python-3.x|api|rest|call|wrapper
| 0 |
1,907,197 | 69,764,973 |
What are the return values of the function GetTokenInformation() and how do I use it
|
<p>I tried this code:</p>
<pre><code>import win32security
import win32api
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32security.TOKEN_QUERY_SOURCE | win32security.TOKEN_QUERY)
for i in range(0x30):
try:
n = win32security.LookupPrivilegeName(None, i)
privs = win32security.GetTokenInformation(token, i)
except Exception as e:
pass
else:
print(privs)
print(i, n)
while True:
pass
</code></pre>
<p>I tried to get the information of each privilege(I mostly want the flags), but I can't understand the return values of GetTokenInformation() , it returns different types and I can't manage to extract any Info out of it, I searched on MSDN but I still didn't understand.</p>
|
<p>After reading more in MSDN I found out that the GetTokenInformation function receives a parameter called TOKEN_INFORMATION_CLASS that specify what the function will return, so in order to find about the privileges and on their flags I used the following code:</p>
<pre><code>import win32security
import win32api
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32security.TOKEN_QUERY_SOURCE | win32security.TOKEN_QUERY)
privs = win32security.GetTokenInformation(token, win32security.TokenPrivileges)
for i in range(len(privs)):
# name of privilege
name = win32security.LookupPrivilegeName(None, privs[i][0])
flag = privs[i][1]
# check the flag value
if flag == 0:
flag = 'Disabled'
elif flag == 3:
flag = 'Enabled'
print(name, flag)
while True:
pass
</code></pre>
|
python|security|winapi
| 0 |
1,907,198 | 69,831,882 |
Randomly replace values at a set frequency
|
<p>I am trying to replace values from a list. However, I would like to be able to set the frequency for which this occurs. I would like to provide values (max and min) for the number of values that are replaced. For example. I would like to be able to set the max number of values to be replaced a 5 and the minimum at 0, meaning that any given line, at most 5 values will be replaced but there is a possibility that none are replaced. The numbers could be anything values though, I don't want to just limit myself to 5 and 0 haha. I know this sounds bizarre but for the type of analysis I want to perform, the needs to be some kind of set frequency.</p>
<p>Based on previous posts, I have been able to find ways to randomly replace values but I haven't been able to find anything that talked about setting how frequent the random replacement occurs.</p>
<p>The code that I am using looks like this</p>
<pre><code>import random
vals = ['*','1','0']
with open("test2.txt","w") as out:
with open("test.txt", "rt") as f:
for line in f:
li=line.strip()
tabs = li.split("\t")
geno = tabs[1:]
print(geno)
for index, x in enumerate(geno):
if random.randint(0, 1):
geno[index] = random.choice(vals)
print(geno)
</code></pre>
<p>an example of a list that is being used looks like this</p>
<pre><code>['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
</code></pre>
<p>A few example lines from my data to help out with your answer</p>
<pre><code>AAD - - 0 - - - 0 - - 0 0 - 0 0 0 0 0 - 0 0 - 0 0 - 0 - 0 - - - - - - 0 - 0 0 0 0 - - 0 - 0 0 0 0 0 - 0 0 0 0 - 0 - 0 0 0 0 - - - 0 - 0 0 0 0 - 0 0 0 0 0 - 0 0 0 - 0 0 0 0 - - - 0 - 0 0 0 - 0 0 0 0 0 0 - 0 0 - 0 0 0 0 - 0 - 0 0 - - 0 0 0 0 0 - 0 0 0 0 - 0 0 0 0 - 0 0 0 0 - - 0 0 - 0 0 - 0 0 0 0 0 0 - - 0 0 0 0 0 - 0 - - 0 0 0 - 0 0 0 0 - 0 - - 0 0 0 0 0 0 0 - 0 - - - 0 - - 0 - 0 0 - 0 - - 0 - - - - - - - - 0 0 - 0 - - - - - - - - - - 0 0 - - - 0 0 0 - 0 0 - - - - - - - 0 0 - - - 0 - - 0 - - - - - 0 - - - - - - - 0 - - 0 0 0 0 - 0 - - 0 0 0 0 0 0 - - - - - 0 - 0 - 0 0 - - - 0 - - - - 0 - - - - - 0 - - - - 0 - 0 0 - - - - 0 - 0 - - - - 0 0 - 0 0 0 - 0 - 0 - - - - 0 - - 0 - 0 - - - 0 0 0 0 - 0 0 - - - 0 - - - - 0 0 - - - 0 - - - - - - - - - - - - - - - - - - - - - - 0 - - - - - - - - - 0 - - 0 - - - - - - - 0 - 0 - 0 - - 0 0 - - - - - - 0 - - - - - - - - - - - - - - 0 - - - - - - 0 - 0 - 0 - - - - - 0 0 - - - 0 - 0 - - 0 0 0 - - - - - - - - 0 - - 0 0 - - - - - - 0 0 - - - - 0 - 0 - - - - 0 - - 0 - - - - - - 0 - 0 - - - 0 - - - - - - - - - - - - - - - - - - 0 0 - - - 0 - - - - 0 - - 0 0 - - - - - - 0 - - 0 - 0 - - - - - - - - - - - 0 - 0 0 - - 0 - - - 0 - - - 0 - - - - - 0 - - - 0 - - - 0 - - - - - - - - - - - 0 - - - - - 0 0 - - - - 1 - 0 - 0 - - - - 0 - - - - 1 - - - - - - - - - - 0 - - - - - - - - - - - - - - - - 0 - 0 - - - - - - - - 0 - - - - - - - - - - - - - - - - - - 0 0 - 0 0 - - - - - - - - - - 0 - - 0 - - - - - - 0 - - - - - - - - - 0 1 - - - - - - - - - - - - - - - - 0 - - - - - - - - - - - 0 1 - - - - - - - - - 0 1 - - - - - - - - 1 0 - - - 0 - - - - - - - - - 0 - 0 - - - - - - - - - - - - 0 - - - 0 0 0 - - - 0 - - - 0 - - - - - - - - 0 - - - - 0 - - - - - 0 - 0 - - - - 0 - - - - - - - 0 - - 0 0 -
AAC 0 - 0 - - - 0 0 - - - 0 - - - - 0 0 0 - - - - 0 0 0 - 0 - - 0 0 0 0 - - - - 0 - 0 0 - 0 - 0 - 0 - - 0 - - 0 0 0 0 - 0 0 - 0 0 0 0 0 0 - 0 0 - - 0 0 0 0 - 0 0 0 0 - - - - - - - 0 0 - 0 - 0 - - 0 - 0 - 0 0 0 - - 0 0 0 - 0 - - - 0 0 0 0 0 0 - - 0 0 0 0 0 0 0 0 - 0 0 - 0 0 0 0 0 0 0 0 0 0 0 0 - 0 0 0 0 0 0 0 0 - 0 0 0 0 0 0 0 0 0 0 0 0 0 - - 0 0 0 - 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 - 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 - 0 0 0 - - 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 - 0 0 0 0 0 0 0 0 0 0 0 0 0 - - - 0 0 - 0 0 - - - 0 0 0 - 0 - 0 0 0 0 0 0 - - 0 - 0 0 0 0 0 - 0 0 0 0 0 - 0 0 - 0 - 0 0 0 - - - - 0 - 0 - 0 0 - - - - 0 0 - 0 - 0 - - - - - - - - - 0 0 - - 1 - 0 - 0 - 0 - 0 - 0 - 0 0 - - - - - - 0 0 0 0 0 0 0 - 0 0 0 - 0 0 0 - 0 0 0 0 0 0 - - 0 - - - - - - - 0 - - - 0 0 - - - - 0 - 0 - 0 0 - - 0 - 0 0 - 0 0 - - 0 - - - - 0 - 0 - 0 - - - - 0 0 0 0 0 0 0 0 - 0 - - 0 0 - - - 0 - 0 0 - 0 0 - 0 - - - 0 0 - - 0 0 - 0 - - - - 0 0 - 0 - 0 0 - - - - - - - - - 0 - - - 0 - - 0 - 0 - - - 0 - - 0 0 0 - - 0 0 - 0 0 - 0 - 0 0 0 0 - - 0 0 0 - 0 - - - 0 - - - 0 - - 0 - 0 - 0 - - - 0 0 0 - 0 - 0 - - - 0 - - - - 0 0 0 - 0 0 - - - 0 0 - 0 - 0 0 - - - - - 0 - 0 - 0 0 - - - - 0 - 0 0 - - - 0 - - - 0 - - - 0 - - - - - 0 - - - - 0 0 0 - - - 0 - 0 0 0 - - - - 0 - - - - - - 0 - 0 0 0 0 - 0 0 0 - 0 - 0 - - - - - - 0 - - 0 - 0 0 0 0 0 - - - - - 0 - - 0 - 0 0 - - - - 0 - - - - - - - - 0 0 - - - - 0 - - 0 - - - 0 - - 0 0 - - - - - - 0 0 - - - - - 0 - 0 0 - 0 0 - - - - - - - - - 0 0 0 - - 0 - - 0 0 - - - - 0 - 0 - - - - - - - 0 0 0 - - - - - 0 - - 0 0 - 0 - - 0 0 - - - - - - - 0 0 0 - 0 0 - - 0 - 0 - - - - 0 - 0 - - - - - - - - - - 0 - -
</code></pre>
|
<p>To elaborate on my comment:</p>
<pre><code>import random
def replace_random_indexes(lst, min_n, max_n, replacements):
# (1) Figure out how many indexes to change.
n = random.randint(min_n, max_n)
if n == 0: # No changes required? Return original list.
return lst
# (2) Get a random set of indexes to change.
indexes = set(random.sample(range(len(lst)), n))
# (3) Using a list comprehension, return a new list with the indexes
# from `indexes` changed to a random choice from `replacements`.
return [
random.choice(replacements)
if index in indexes
else value
for index, value
in enumerate(lst)
]
orig = [1, 2, 3, 4, 5, 6, 7]
for i in range(10):
print(replace_random_indexes(orig, 0, 3, ["a", "b", "c"]))
</code></pre>
<p>This prints out e.g.</p>
<pre><code>[1, 'a', 'a', 'c', 5, 6, 7]
['a', 2, 'c', 'a', 5, 6, 7]
[1, 2, 3, 4, 5, 6, 'a']
[1, 'a', 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 'a']
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 'c', 'c']
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 'b', 5, 'c', 'c']
</code></pre>
<p>You can note that no list has more than 3 items changed.</p>
<p>To plug that into your original program,</p>
<pre><code>vals = ["*", "1", "0"]
with open("test2.txt", "w") as out, open("test.txt", "rt") as f:
for line in f:
li = line.strip()
tabs = li.split("\t")
geno = tabs[1:]
new_geno = replace_random_indexes(geno, 0, 5, vals)
print(new_geno)
</code></pre>
<p>or similar should do the trick.</p>
|
python
| 1 |
1,907,199 | 66,380,044 |
How to plot multiple facet_col in pyhthon using plotly.express
|
<p>I have this plotly express scatter plot of imdb_rating vs runtime having facet columns of genre_1<a href="https://i.stack.imgur.com/SdEbz.png" rel="nofollow noreferrer">My output</a></p>
<p>But instead of all the genres I just want the plot to include three genres (namely 'Action,Drama and Biography),.What tweaks should I make to my code to achieve the desired output(shown in image)<a href="https://i.stack.imgur.com/wdABK.png" rel="nofollow noreferrer">Desired output</a></p>
|
<p>Using this page as a reference, I wrote some code that can produce the output you expect. To create multiple graphs with category variables, use <code>facet_col</code>.</p>
<p><strong>Important:</strong> Posting code or data as images is not recommended. It is not recommended to post code or data in images, because it is too much work for the respondents and they will be reluctant to answer. As a result, you will not get a quick answer.</p>
<pre><code>import random
import pandas as pd
import numpy as np
np.random.seed(20210226)
genre_1 = random.choices(['Action','Drama','Biography'], k=100)
rating = [random.uniform(7.0, 9.0) for i in range(100)]
runtime = [random.randint(85, 180) for n in range(100)]
df = pd.DataFrame({'genre_1':genre_1, 'rating':rating,'runtime':runtime})
import plotly.express as px
fig = px.scatter(df, x="runtime", y="rating", color="genre_1", facet_col="genre_1",
category_orders={"genre_1": ["Action", "Drama", "Biography"]})
fig.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/ift2L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ift2L.png" alt="enter image description here" /></a></p>
|
python|pandas|matplotlib|plotly|data-visualization
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.