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,909,200 | 40,831,081 |
match same pattern at begin and end twice
|
<p>I need to change words in upper case for a tag <code>'###'</code>. Let's suppouse a charset like this in all the text: <code>[a-zA-Z\s]</code></p>
<p>I'm doing this:</p>
<pre><code>re.sub(r'(^|\s)([A-Z]+)(\s|$)', r'\1###\3', 'Hello PYTHON WORLD')
</code></pre>
<p>but instead of getting <code>'Hello ### ###'</code>, it returns <code>'Hello ### WORLD'</code>.</p>
<p>The problem is that re.sub matches all occurrences, however, groups 1 and 3 are <em>equals</em>, but re.sub isn't using it twice to match PYTHON and WORLD.</p>
<p>How do I solve it? I'm using python 3.</p>
<p><em>equals</em>: almost equals, they differ in <code>^</code> and <code>$</code> in case of begin/end, but this isn't the problem.</p>
|
<p>To replace all <em>upper-case</em> words with <code>###</code> use the following approach:</p>
<pre><code>s = 'Hello PYTHON WORLD'
replaced = re.sub(r'\b([A-Z]+)\b', r'###', s)
print(replaced)
</code></pre>
<p>The output:</p>
<pre><code>Hello ### ###
</code></pre>
<p><em><code>\b</code> is defined as the boundary between a <code>\w</code> and a <code>\W</code> character (or vice versa), or between <code>\w</code> and the beginning/end of the string</em></p>
|
python|regex
| 4 |
1,909,201 | 40,302,670 |
lxml 3.6.4 installation error for python 3.5 on win 10
|
<p>When I try to install <strong>lxml</strong> for python 3.5 on Windows 10 by using <code>pip install lxml</code> I get the error message as follows:</p>
<pre><code>"b" 'xslt-config' is nor recognized as an external or internal command,
\r\noperable program or batch file.\r\n" ** make sure the developement
packages of libxml2 and libxslt are installed **
</code></pre>
<p>The problem is I cannot figure out how to install libxml2 since the setup files for libxml2 return <code>"failed to find headers for libxml2: update includes_dir"</code></p>
<p>Any suggestions on how I fix these issues?</p>
|
<p>You can't compile lxml from sources without having the dependent libs avaiable to link against, and a working toolchain (which requires a matching version of Visual Studio on windows for your python version)</p>
<p>download a pre-compiled binary wheel from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml" rel="nofollow">here</a>.</p>
<p>Install it with pip:</p>
<pre><code>pip install path-to-lxml-3.6.4-cp35-cp35m-win_amd64.whl
</code></pre>
|
python|python-3.x|windows-10|lxml|libxml2
| 0 |
1,909,202 | 40,013,529 |
I am not able get the sorted values from the input
|
<p>problem with sorting</p>
<pre><code>a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
while i <= n:
s = input()
total = total + int(s)
i = i + 1
s.sort()
print s
print('The sum is ' + str(total))
</code></pre>
|
<pre><code>n = int(input("Enter the number of inputs : "))
total = 0
i = 1
array = []
while i <= n:
s = int(input())
array.append(s)
total = total + int(s)
i = i + 1
array.sort()
print(array)
print('The sum is ' + str(total))
</code></pre>
<p>this will solve your problem, sort applies on list not on str object</p>
|
python
| 0 |
1,909,203 | 40,213,284 |
Python: Initiate a variable once in a program running every few minutes
|
<p>I have a program running every minutes. I want that when I'm executing it for the first time I do something and after something else; like this :</p>
<pre><code>def alarm_function (alarm):
first_time=0
if first_time==0:
send_on_website(message)
first_time+=1
alarm=0
else:
send_on_website(a_different_message)
if alarm==0:
#do nothing
if alarm==1:
alarm+=1
#do something
</code></pre>
<p>So basically after I executed once I want to erase the first line "first_time=0" because I don't want to initiate it again. Also, I want to make a counter on alarm variable which is initiate somewhere in the program. How can I do that ?</p>
|
<p>you would have to define a new function if you dont want the first_time any more. and for the counter you can put at the top of your program <code>import time</code> and where ever you want the counter to be you use <code>time.sleep(?) #change ? for a any number of seconds</code></p>
|
python|initialization
| 0 |
1,909,204 | 29,245,465 |
Mean and St Dev of indexed elements from a separate array
|
<p><strong><em>The Data:</em></strong> I have two numpy arrays. One represents spike or peak amplitudes and the other represents the corresponding peak time stamps in seconds. The zeros represent nothing, and can be changed to NaN if need be. I have copied a small subset of this data below.</p>
<p><strong><em>The goal:</em></strong> The goal is to find the average and standard deviation of certain elements of my amplitude array based on different windows of time; say, the first 4 minutes (0-240 seconds). In other words, I need to find the indices in my time array that satisfy that condition (0-240), and then apply those indices to the amplitude array in a way that outputs the mean and st dev.</p>
<p><strong><em>My attempt:</em></strong> Unfortunately, I am relatively new to python and have not been able to find much information concerning manipulation/application of 2D indices. I can say that I have been using very pathetic combinations of numpy.where and numpy.take.</p>
<pre><code>t = [[ 111 184 221 344 366 0 0 0 0 0 0]
[ 408 518 972 1165 1186 0 0 0 0 0 0]
[ 208 432 1290 1321 0 0 0 0 0 0 0]
[ 553 684 713 888 1012 1108 1134 0 0 0 0]
[ 285 552 1159 1183 0 0 0 0 0 0 0]
[ 304 812 852 0 0 0 0 0 0 0 0]
[ 192 616 654 724 1143 1290 0 0 0 0 0]]
</code></pre>
<p>and</p>
<pre><code>A = [[ 0.18573314 0.52252139 0.16042311 0.21260801 0.24919374 0. 0.
0. 0. 0. 0. ]
[ 0.16968141 0.18421777 0.16616463 0.19172084 0.15638406 0. 0.
0. 0. 0. 0. ]
[ 0.1740181 0.24890002 0.17237853 0.20274514 0. 0. 0.
0. 0. 0. 0. ]
[ 0.21144188 0.2076988 0.19915351 0.19803788 0.15826589 0.17068694
0.15190413 0. 0. 0. 0. ]
[ 0.15933248 0.17080178 0.15793379 0.15461262 0. 0. 0.
0. 0. 0. 0. ]
[ 0.19708434 0.1696343 0.26508617 0. 0. 0. 0.
0. 0. 0. 0. ]
[ 0.2893063 0.16306161 0.1529097 0.15348586 0.24668999 0.18140199
0. 0. 0. 0. 0. ]]
</code></pre>
|
<pre><code>import numpy as np
# get numpy.arrays in case t and A are not yet numpy.arrays
t = np.array(t)
A = np.array(A)
# find the indices of the timestamps you look for
idx = (t>0) & (t <= 240)
# get the standard deviation and the mean
# A[idx] consists of all those elements in A for which idx is true
np.std(A[idx])
np.mean(A[idx])
</code></pre>
|
python|arrays|python-2.7|numpy
| 0 |
1,909,205 | 52,372,425 |
Error: Unable to find conda binary. Is Anaconda installed? reticulate Rstudio
|
<p>I installed reticulate via Rstudio. Now i want to use <code>conda_create()</code> but I installed anaconda in another directory then the default. How can I change the directory in which Rstudio is searching for anaconda? </p>
<pre><code>Error: Unable to find conda binary. Is Anaconda installed?
</code></pre>
|
<p>The directory should be in your path. But you can check where it is like this:</p>
<p><code>Sys.which("python")</code></p>
<p>If you have multiple python versions (or it is not in your path), then you can specify a different location with <code>use_python</code> for where the python binary is located and <code>use_conda</code> for the conda environment. </p>
<p>More info can be found in <a href="https://cran.r-project.org/web/packages/reticulate/vignettes/versions.html" rel="nofollow noreferrer">this reticulate vignette</a></p>
|
python|r|anaconda|reticulate
| 2 |
1,909,206 | 52,390,123 |
Pandas Read Excel function convert index to list
|
<pre><code>## Summary: Analyze the data in each sheet and get the result
def analyze_data(project, sheet):
print(project_dict[project],'****'+sheet)
## Get data with specific finding type in validation sheet
sheet_df = pd.read_excel(project_dict[project],sheet, na_values=['NA'])
print(sheet_df['Feedback Report']=='S.No')
# Get index of tables
242 idx = sheet_df[sheet_df['Feedback Report']=='S.No'].index.tolist()[0]
243 head = idx - 1
245 header_df = sheet_df.iloc[0:head,:]
246 sheet_df = sheet_df.iloc[idx:,:]
## Replace the header
header = sheet_df.iloc[0]
sheet_df.columns = header.tolist()
sheet_df = sheet_df[1:]
####################################
## Get data from the time period
</code></pre>
<p>The above code is not written by me and I am supposed to make a complete windows executable for it. I am not able to understand what the code is trying to do in line 242.</p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File 37-32\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File QA_Review_Reporting.py", line 751, in sync
report.read(project_dict)
File reports.py", line 705, in read
process()
File reports.py", line 749, in process
get_valid_type(project)
File reports.py", line 185, in get_valid_type
counts = analyze_data(project, item)
File reports.py", line 242, in analyze_data
idx = sheet_df[sheet_df['Feedback Report']=='S.No'].index.tolist()[0]
IndexError: list index out of range
</code></pre>
|
<p>As I mentioned in my comment, Line 242 is filtering the dataframe <code>sheet_df</code> to rows where the <code>'Feedback Report'</code> column has a value of <code>'S.No'</code>. Then it is returning the corresponding index of the filtered <code>sheet_df</code> dataframe to a list and taking the first element in that list via <code>[0]</code>.</p>
<p>For example:</p>
<pre><code>sheet_df = pd.DataFrame([['No', 1, 2, 3], ['S.No', 4, 5, 6], ['S.No', 7, 8, 9], ['Yes', 10, 11, 12]], columns=['Feedback Report', 'Val 1', 'Val 2', 'Val 3'])
</code></pre>
<p>Which yields:</p>
<pre><code> Feedback Report Val 1 Val 2 Val 3
0 No 1 2 3
1 S.No 4 5 6
2 S.No 7 8 9
3 Yes 10 11 12
</code></pre>
<p>Filtering the dataframe via <code>sheet_df[sheet_df['Feedback Report']=='S.No']</code> will return:</p>
<pre><code> Feedback Report Val 1 Val 2 Val 3
1 S.No 4 5 6
2 S.No 7 8 9
</code></pre>
<p>Then taking the index and sending <code>tolist()</code>:</p>
<pre><code>[1, 2]
</code></pre>
<p>Finally, take the first element via <code>[0]</code> to return:</p>
<p><code>1</code></p>
|
python-3.x|pandas|tkinter|openpyxl|xlsxwriter
| 2 |
1,909,207 | 51,856,491 |
In a library that uses metaclasses a lot, how can I avoid annoying the user with metaclass conflicts?
|
<p>The library I'm writing makes heavy use of metaclasses. As an example, here is a basic singleton implementation:</p>
<pre><code>class SingletonMeta(type):
_instance = None
def __call__(self, *args, **kwargs):
if self._instance is None:
self._instance = super().__call__(*args, **kwargs)
return self._instance
class ExampleSingleton(metaclass=SingletonMeta):
pass
</code></pre>
<p>This works perfectly fine, but problems arise when multiple inheritance is used and the other class also has a metaclass. Metaclasses are fairly common in the standard library; the most notable is <a href="https://docs.python.org/3/library/abc.html#abc.ABCMeta" rel="nofollow noreferrer"><code>abc.ABCMeta</code></a>. A naive attempt to make an abstract singleton fails:</p>
<pre><code>class AbstractSingleton(ExampleSingleton, abc.ABC):
pass
Traceback (most recent call last):
File "untitled.py", line 25, in <module>
class AbstractSingleton(ExampleSingleton, abc.ABC):
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
</code></pre>
<p>The workaround is easy enough - create a new metaclass that inherits from <code>SingletonMeta</code> and <code>ABCMeta</code> - but it's really annoying for anyone who wants to use my library.</p>
<pre><code>class AbstractSingletonMeta(SingletonMeta, abc.ABCMeta):
pass
class AbstractSingleton(metaclass=AbstractSingletonMeta):
pass
# no metaclass conflict
</code></pre>
<p>What's the best way to deal with this problem?</p>
<p>Some of my ideas:</p>
<ol>
<li>Since abstract classes are fairly common, I could make <code>SingletonMeta</code> a subclass of <code>ABCMeta</code>.</li>
<li>I could implement <code>AbstractSingletonMeta</code> in my library for the user's convenience.</li>
<li>Since any callable can be used as a metaclass, I could implement a function that automatically merges the metaclasses of all parent classes. (The usage would be like <code>class AbstractSingleton(ExampleSingleton, abc.ABC, metaclass=auto_merge_metaclasses):</code>)</li>
<li>In the spirit of "explicit is better than implicit", I could do nothing and let the user sort out the metaclass conflicts.</li>
</ol>
|
<p>Since all the information about the needed metaclasses and what needs to be combined is already present in the base classes, and those are passed to the metaclass call, it is possible to have a callable that will inspect all the bases and their used metaclasses, and dynamically create a combining metaclass. </p>
<p>The <code>types</code> module have some callables that otherwise make it easy to pick the correct metaclass for a set of base classes. So, the function bellow should suffice to your needs, if all your used metaclasses are combinable in an arbitrary order:</p>
<pre><code>from types import prepare_class
def combine_meta(name, bases, namespace, **kwargs):
metaclasses = {prepare_class(name, (base,))[0] for base in bases}
metaclasses.discard(type)
if len(metaclasses) > 1:
meta_name = '_'.join(mcs.__name__ for mcs in metaclasses)
metaclass = combine_meta(meta_name, tuple(metaclasses), {})
elif len(metaclasses) == 1:
metaclass = metaclasses.pop()
else:
metaclass = type
return metaclass(name, bases, namespace, **kwargs)
</code></pre>
<p>I've tested this with this sequence in the interactive interpreter, and it worked that far:</p>
<pre><code>class M1(type): pass
class M2(type): pass
class A(metaclass=M1): pass
class B(metaclass=M2): pass
class C(A, B): pass # This raises a metaclassconflict
class C(A, B, metaclass=combine_meta): pass
</code></pre>
|
python|metaclass
| 2 |
1,909,208 | 51,995,182 |
Adding logo to a cat image in Python
|
<p>For the captioned, here's the code (courtesy Automate the Boring Stuff) and I'd tweaked it a bit. </p>
<pre><code>import os
from PIL import Image
SQUARE_FIT_SIZE = 300
LOGO_FILENAME = 'catlogo.png'
logoIm = Image.open(LOGO_FILENAME)
logoWidth, logoHeight = logoIm.size
# Loop over all files in the working directory.
for filename in os.listdir('.'):
if not (filename.endswith('.png') or filename.endswith('.jpg')) \
or filename == LOGO_FILENAME:
continue # skip non-image files and the logo file itself
im = Image.open(filename)
width, height = im.size
# Add logo.
print('Adding logo to %s...' % (filename))
im.paste(logoIm, (width - logoWidth, height - logoHeight), logoIm)
# Save changes.
im.save('Cat with Logo.png')
</code></pre>
<p><a href="https://i.stack.imgur.com/DTCra.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DTCra.png" alt="Cat Logo"></a></p>
<p><a href="https://i.stack.imgur.com/8hzGH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8hzGH.png" alt="Cat Image"></a></p>
<p>For some reason, the logo failed to be added at the end. Is something wrong with the <code>save</code> command? </p>
|
<p>I realized <code>resizeAndAddLogo.py</code> resizes the file to which the logo is pasted on, not the logo size proportioned to the file. We don't want that. So I changed the script to change logo size with the ratio of 1/5 to the image file.</p>
<pre><code>...
# Resize the logo.
print(f'Resizing logo to fit {filename}...')
sLogo = logoIm.resize((int(width / 5), int(height / 5)))
sLogoWidth, sLogoHeight = sLogo.size
# Add the logo.
print(f'Adding logo to {filename}...')
im.paste(sLogo, (width - sLogoWidth, height - sLogoHeight), sLogo)
...
</code></pre>
<p>At this point, I don't need <code>SQUARE_FIT_SIZE = 300</code>, so I deleted it and made the code shorter. Here's my full script.</p>
<pre><code>import os
from PIL import Image
LOGO_FILENAME = 'catlogo.png'
logoIm = Image.open(LOGO_FILENAME)
os.makedirs('withLogo', exist_ok=True)
# Loop over all files in the working directory.
for filename in os.listdir():
if not (filename.endswith('.png') or filename.endswith('.jpg')) or filename == LOGO_FILENAME:
continue
im = Image.open(filename)
width, height = im.size
# Resize the logo.
print(f'Resizing logo to fit {filename}...')
sLogo = logoIm.resize((int(width / 5), int(height / 5)))
sLogoWidth, sLogoHeight = sLogo.size
# Add the logo.
print(f'Adding logo to {filename}...')
im.paste(sLogo, (width - sLogoWidth, height - sLogoHeight), sLogo)
# Save changes.
im.save(os.path.join('withLogo', filename))
</code></pre>
<p>Note that resized logo should be assigned to be used in loop.</p>
<p>And this one of the resulted images. </p>
<p><a href="https://i.stack.imgur.com/taFHk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/taFHk.jpg" alt="enter image description here"></a></p>
|
python|image-processing
| 2 |
1,909,209 | 59,765,464 |
Python create dataframe from sql query result
|
<p>I have sql query with multiple temporary table creation and one final select statement.</p>
<p>Let's imagine query example:</p>
<pre><code>select
t1.Variable11,
t1.Variable12,
t2.Variable13
into #R1
from t1
join t2
on t1.Key1= t2.key1 and t1.Key2= t2.key2
where t1.Variable1 > 100
select
t3.Variable21,
t3.Variable22,
t4.Variable23
into #R2
from t3
join t4
on t3.Key1= t4.key1 and t3.Key2= t4.key2
where t3.Variable1 > 200
select
#R1.*,
#R2.*
from #R1
join #R2
on #R1.Variable11= #R2.Variable21
</code></pre>
<p>I connect to sql server with pyodbc connector:</p>
<pre><code>connection = pyodbc.connect(driver='{SQL Server Native Client 11.0}', server=server_name,
database=db_name, trusted_connection='yes', MARS_Connection='yes')
</code></pre>
<p>I do not want to re-write code.
I just want to write function which will return pandas dataframe.
When i try to use <code>pandas.read_sql()</code> function i receive error:</p>
<blockquote>
<p>TypeError: 'NoneType' object is not iterable</p>
</blockquote>
<p>When i try to use <code>pyodbs.execute()</code> i receive error:</p>
<blockquote>
<p>No results. Previous SQL was not a query.</p>
</blockquote>
<p>how to handle a sql script with multiple temporary tables creation and one final select statements?</p>
|
<pre><code>import pandas as pd
from sqlalchemy import *
engine = create_engine('mssql+pyodbc://python:python@Database/Tablename?driver=SQL+Server+Native+Client+11.0')
connection = engine.connect()
SQL='select * from ' + Tablename
Tfrom_sql=pd.read_sql(SQL, connection)
connection.close()
</code></pre>
|
python|sql|pandas|dataframe|pyodbc
| 0 |
1,909,210 | 59,579,449 |
Get the a variable defined in the command running python
|
<p>I have this script named test.py:</p>
<pre><code>import os
print(os.environ['LOL'])
</code></pre>
<p>That I run as follow :</p>
<blockquote>
<p>(LOL=HAHAHA; python3 test.py)</p>
</blockquote>
<p>But it raises a KeyError because it can't find the variable LOL.</p>
<p>I also tried with :</p>
<pre><code>os.getenv('LOL')
</code></pre>
<p>But it just returns None.</p>
<p>How can I access to the variable LOL in this context.</p>
|
<p>You are trying to access an environmental variable, so if you are on windows to set it you need to do something like:</p>
<pre><code>set LOL=HAHAHAHA
</code></pre>
<p>Then you should be able to access it. To make sure it was set correctly you can also just run:</p>
<pre><code>set
</code></pre>
<p>To get a full list of environmental variables.</p>
|
python|python-3.x
| 1 |
1,909,211 | 18,921,499 |
wxPython empty space when using fit() to size frame
|
<p>I'm trying to set up my GUI so that the frame automatically fits the contents, what it seems to be doing is going the other way and fitting the contents to the frame.</p>
<p>Is this usual and is there anything I can do about it?</p>
<p>Here is my code:</p>
<pre><code> panel = wx.Panel(self)
mainSizer = wx.BoxSizer(wx.VERTICAL)
usernameSizer = wx.BoxSizer(wx.HORIZONTAL)
self.usernameBox = wx.TextCtrl(panel, size=(200,35))
usernameText = wx.StaticText(panel, label="\tUsername")
usernameSizer.Add(self.usernameBox, 1)
usernameSizer.Add(usernameText, 1)
passwordSizer = wx.BoxSizer(wx.HORIZONTAL)
self.passwordBox = wx.TextCtrl(panel, size=(200,35))
passwordText = wx.StaticText(panel, label="\tPassword")
passwordSizer.Add(self.passwordBox, 1)
passwordSizer.Add(passwordText, 1)
urlSizer = wx.BoxSizer(wx.HORIZONTAL)
self.urlBox = wx.TextCtrl(panel, size=(200,35))
urlText = wx.StaticText(panel, label='\tFirst chapter URL')
urlSizer.Add(self.urlBox, 1)
urlSizer.Add(urlText, 1)
formatSizer = wx.BoxSizer(wx.HORIZONTAL)
self.formatBox = wx.ComboBox(panel, value='', choices=self.fileFormat, style=wx.CB_READONLY, name="combo", size=(200,35))
formatText = wx.StaticText(panel, label="\tFile format")
formatSizer.Add(self.formatBox, 1)
formatSizer.Add(formatText, 1)
downSizer = wx.BoxSizer(wx.HORIZONTAL)
downButton = wx.Button(panel, label='Download', size=(161,50))
font = wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
downButton.SetFont(font)
downSizer.Add(downButton, 0, wx.LEFT | wx.TOP, 20)
mainSizer.Add(usernameSizer, 0, wx.LEFT | wx.TOP, 20)
mainSizer.Add(passwordSizer, 0, wx.LEFT | wx.TOP, 20)
mainSizer.Add(urlSizer, 0, wx.LEFT | wx.TOP, 20)
mainSizer.Add(formatSizer, 0, wx.LEFT | wx.TOP, 20)
mainSizer.Add(downSizer, 0, wx.ALIGN_CENTER | wx.BOTTOM, 20)
panel.SetSizer(mainSizer)
panel.Fit()
self.Show(True)
</code></pre>
<p>This bunches all the widgets up at the top which is pretty much what I want, there is a lot of empty space below that however which I don't want.</p>
<p>If I set the proportional value to 1 instead of 0 when adding the sizers to mainSizer it takes up the entire frame, how can I get the frame to contract to the contents?</p>
|
<p>I think if you want to achieve this you need to set the proportion to 0 every time you add something to a<code>wxSizer</code>.</p>
<p>Also something that may help is to add the <code>wx.EXPAND</code> tag, so it'd be something like that:</p>
<p><code>sizer.Add(other_panel, 0, wx.EXPAND | wx.WATERVER, border_size)</code></p>
<p>In theory and having done that, your panel should take the size of its components. Also make sure that you call Fit on the window/dialog that owns the panels.
Sometimes (but rarely) calling the <code>Layout</code> function on the sizer helps.</p>
|
python|user-interface|wxwidgets
| 1 |
1,909,212 | 18,945,534 |
Is it possible to have csv.DictReader format certain columns as something other than string?
|
<p><code>csv.DictReader()</code> by default pulls values in columns as strings. <strong><em>Is there a way to specify the conversion for certain columns?</em></strong></p>
<p>I end up doing a lot of this minor annoyance every time I access the list of dictionaries created by <code>csv.DictReader()</code> that has non-string elements in it:</p>
<pre><code>with open("data.csv","r") as data_file:
items = csv.DictReader(data_file, fieldnames=('id', 'length', 'note'))
for item in items:
item['length'] = float(item['length']) #### <--- MINOR ANNOYANCE
# ... do loop stuff
</code></pre>
<p>It would be easier if I could tell <code>csv.DictReader</code> that when it gets to a certain field, it should do a <code>float()</code> (or <code>int()</code>, <code>date()</code> etc.) conversion.</p>
|
<p>Not out of the box, no. You can either subclass <code>DictReader()</code> or create a generator function that maps your rows for you:</p>
<pre><code>def convert_fields(iterable, **conversions):
for item in iterable:
for key in item.viewkeys() & conversions:
item[key] = conversions[key](item[key])
yield item
</code></pre>
<p>For Python 3, substitute <code>dict.viewkeys()</code> for <code>dict.keys()</code>, as Python 3 returns dictionary views by default.</p>
<p>Wrap your <code>csv.DictReader()</code> with that, adding conversion functions for each of your columns:</p>
<pre><code>with open("data.csv","r") as data_file:
items = csv.DictReader(data_file, fieldnames=('id', 'length', 'note'))
items = convert_fields(items, length=float)
for item in items:
# item['length'] is now always a float
</code></pre>
<p>for column names that don't map to a python identifier (with spaces, etc.) pass in a dictionary with <code>**{..}</code> syntax:</p>
<pre><code>with open("data.csv","r") as data_file:
items = csv.DictReader(data_file, fieldnames=('id', 'length', 'note'))
fieldconv = {'id': int, 'length': float, 'spaced column': float}
items = convert_fields(items, **fieldconv)
for item in items:
# item['length'] and item['spaced column'] are now floats
# item['id'] is always an int
</code></pre>
|
python|csv|python-2.7
| 3 |
1,909,213 | 67,269,542 |
How to force Python to report an error if a local variable is referenced out of its scope?
|
<pre><code>list1 = ["AAA", "BBB"]
for item in list1:
print(item)
print (item) # <--- out of scope, but Python doesn't report any error
</code></pre>
<p>For the code above, although <code>item</code> is out of its scope, Python will not report an error.</p>
<p>Is it possible to force Python to report an error?</p>
|
<p>the variable that's being used in a loop will eventually arrive at the <em><strong>index "-1"</strong></em> of an iterable object. So each time you use that <strong>same variable</strong> used in <strong>a previous loop</strong>, it will return <strong>list1[-1]</strong> which is indeed the last element in every iterable object in python</p>
<p><strong>Solution</strong>: you can use <code>del</code> keyword to delete that variable</p>
<pre><code>list1 = ["AAA", "BBB"]
for item in list1:
print(item)
del item #now item is not a defined variable in our program.
print (item) #<--- will throw an error because the variable "item" no longer exists
</code></pre>
<p><code>NameError</code> will be raised</p>
|
python|scope
| 0 |
1,909,214 | 36,487,092 |
How to parse through json in Python with dynamic key names?
|
<p>I am trying to pull <code>name</code> from the below JSON. The problem I am having is the host name in the JSON is dynamic so I don't know how to dig below that layer if that makes sense. So 'ip-10-12-68-170.b2c.test.com' has a different ip for each block of json.</p>
<pre><code>{
"host" : {
"ip-10-12-68-170.b2c.test.com" : {
"environment" : {
"testing1" : {
"ip" : "ip-10-12-68-170",
"name" : "testing",
"env.root" : "/",
"host" : "ip-10-12-68-170.b2c.test.com",
"sin" : "sin.80",
"env.description" : "Content Author Preview"
}
}
},
"ip-10-12-108.27.b2c.test.com" : {
"environment" : {
"esbqav" : {
"ip" : "ip-10-12-108.27",
"name" : "espv",
"env.root" : "/",
"host" : "ip-10-12-108.27.b2c.test.com",
"sin" : "sin.0",
"env.description" : "QA"
}
}
}
}
}
</code></pre>
<p>How do I grab <code>name</code> from this example?</p>
|
<p>It is possible using dictionary <code>values()</code> or <code>items()</code> methods, given that the structure is as in the example.</p>
<pre><code>import json
json_string = """
{
"host" : {
"ip-10-12-68-170.b2c.test.com" : {
"environment" : {
"testing1" : {
"ip" : "ip-10-12-68-170",
"name" : "testing",
"env.root" : "/",
"host" : "ip-10-12-68-170.b2c.test.com",
"sin" : "sin.80",
"env.description" : "Content Author Preview"
}
}
},
"ip-10-12-108.27.b2c.test.com" : {
"environment" : {
"esbqav" : {
"ip" : "ip-10-12-108.27",
"name" : "espv",
"env.root" : "/",
"host" : "ip-10-12-108.27.b2c.test.com",
"sin" : "sin.0",
"env.description" : "QA"
}
}
}
}
}
"""
json_data = json.loads(json_string)
for host in json_data.values():
for hostname in host.values():
environment = hostname.get('environment')
for env in environment.values():
name = env.get('name')
print name
</code></pre>
|
python|json
| 1 |
1,909,215 | 36,331,946 |
Working with 2 pythons on same machine
|
<p>I installed Linux Mint as Virtual Machine.
When I do:</p>
<pre><code>python --version
</code></pre>
<p>I get:</p>
<pre><code>Python 2.7.6
</code></pre>
<p>I installed seperate python folder acording to <a href="http://www.experts-exchange.com/articles/18641/Upgrade-Python-2-7-6-to-Python-2-7-10-on-Linux-Mint-OS.html" rel="nofollow noreferrer">this</a>.
and When I do:</p>
<pre><code>python2.7 --version
</code></pre>
<p>I get:</p>
<pre><code>Python 2.7.11
</code></pre>
<p>Now, I want to work only on Python 2.7.11</p>
<p>I installed pip
and installed a package using pip with <code>pip install paypalrestsdk</code>
It was successfull:</p>
<p><a href="https://i.stack.imgur.com/ZPOgo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZPOgo.png" alt="enter image description here"></a></p>
<p>However when I run the script using this package I get:
<a href="https://i.stack.imgur.com/WMLIW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WMLIW.png" alt="enter image description here"></a></p>
<p>i suspect that pip and the install were done on the <code>python 2.7.6</code> rather than the <code>python 2.7.11</code>
What can I do?</p>
|
<pre><code>wget https://bootstrap.pypa.io/get-pip.py
python2.7 get-pip.py
</code></pre>
<p>Using this pip install:</p>
<pre><code>pip install paypalrestsdk
</code></pre>
<p>Good luck!</p>
|
python|linux
| 0 |
1,909,216 | 36,401,617 |
Multi select option for a cell in excel using python
|
<p>I want to create an excel, which should have cell with multi-select dropdown.</p>
<p>e.g. if a cell is given options = [a", "b", "c", "d", "e"].
Editor selects "a", then the value in cell should be "a". In the subsequent selection for the same cell, if the editor selects "b", the final value in the cell should be "a,b".</p>
<p>I am able to create a drop-down list using <code>xlsxwriter</code> package using below sample code. But it does not support multiselect.</p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('data_validate.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A13', txt)
worksheet.data_validation('B13', {'validate':'list',
'source': ['open', "high", 'close']})
workbook.close()
</code></pre>
<p>This is an example take from <code>xlsxwriter</code> documentation.</p>
<p>I went through other libraries such as <code>xlrd</code>, <code>xlwt</code>, <code>PyXLL</code> and a few others, but could not find anything which could support multiselect or provide a work around to achieve the same.</p>
<p>Is there any inbuilt library, or way to achieve this in excel.
I don't want to use any windows and VB dependency.</p>
<p>Any help would be really appreciated.</p>
|
<p><a href="https://1drv.ms/x/s!AsxYl9DXJ0j99SpQxxsN1JuksBpt?e=uzObLt" rel="nofollow noreferrer">Here</a>/screenshot(s) refer:</p>
<p>Several fairly similar Qs (links below) - but not exactly.</p>
<hr />
<p><strong>Methods A-C</strong>
<em>prerequisite: Office 365 compatible version of Excel</em></p>
<p><strong>A</strong> <em>- returns duplicates in 'raw/original order</em>*</p>
<pre><code>=TEXTJOIN(",",1,C4:C23)
</code></pre>
<p><a href="https://i.stack.imgur.com/wSfPa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wSfPa.png" alt="Method A" /></a></p>
<p><strong>B</strong> <em>- as for A, but ordered</em>*</p>
<pre><code>=TEXTJOIN(",",1,SORT(C4:C23))
</code></pre>
<p><a href="https://i.stack.imgur.com/gqTSE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gqTSE.png" alt="Method B - ordered" /></a></p>
<p><strong>C</strong> <em>- as for B but unique</em>*</p>
<pre><code>=UNIQUE(TEXTJOIN(",",1,UNIQUE(SORT(C4:C23))))
</code></pre>
<p><a href="https://i.stack.imgur.com/gW5kB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gW5kB.png" alt="Method C - unique, sort" /></a></p>
<hr />
<p><strong>Method D</strong></p>
<p><em>other version Excel - can find efficient ways to set up for large number of validation lists feeding into final soln...</em></p>
<p><a href="https://i.stack.imgur.com/eUYSU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eUYSU.png" alt="Method D: older Excel versions" /></a></p>
<p>=TRANSPOSE(CONCATENATE(C4&",",C5&",",C6&",",C7&",",C8&",",C9&",",C10&",",C11&",",C12&",",C13&",",C14&",",C15&",",C16&",",C17&",",C18&",",C19&",",C20&",",C21&",",C22&",",C23))</p>
<hr />
<p><strong>Resources</strong> (personal archives RE: some of my previous contributions):</p>
<ol>
<li>Yours assumes individual drop-downs (as opposed to 'final result cell' are independent - <a href="https://stackoverflow.com/questions/68796774/excel-populate-dropdown-list-from-column-a-when-column-b-has-specific-value/68797130#68797130">this</a> doesn't.</li>
<li>Same goes for <a href="https://stackoverflow.com/questions/68412360/3-way-dependent-dropdown-with-unsorted-data-in-excel/68491566#68491566">this</a>, albeit with greater complexity.</li>
<li><a href="https://stackoverflow.com/questions/67793573/is-there-a-way-to-put-a-dropdown-on-a-cell-in-excel-to-select-the-value-you-want/67796070#67796070">This</a> example demonstrates how to combine several numerical values (e.g. taking their sum)</li>
<li>Similar example <a href="https://stackoverflow.com/questions/68194933/how-to-populate-values-in-a-drop-down-list-dynamically/68294424#68294424">here</a></li>
<li>As above, albeit Additional quirks / oddities re dependency and separate operations - hops this helps, best of luck with your</li>
</ol>
|
python|excel-formula|xlrd|xlwt|xlsxwriter
| 0 |
1,909,217 | 19,696,664 |
Populating a matrix with random numbers and computing sums of those numbers
|
<p>The title says it all.
The hardest part I'm having with this problem is that I'm not allowed to use <em>sum()</em>.</p>
<p>I don't know how to create matrices, and I was looking for some help creating and populating one.</p>
<p>This is what I've figured out so far.</p>
<pre><code>def random():
import random
x=random.random()
return x
def create_matrix(x,y):
random.seed(1)
def main():
random()
main()
</code></pre>
<p>I'm sorry it isn't much if anything, and I appreciate any help I receive.</p>
<pre><code>Enter the number of rows: 3
Enter the number of columns: 2
Enter the threshold for column sum: .5
---------------------------------------
|| || 1 | 2 | sum ||
---------------------------------------
|| 1 || 0.134 | 0.847 | 0.982 ||
|| 2 || 0.764 | 0.255 | 1.019 ||
|| 3 || 0.495 | 0.449 | 0.945 ||
---------------------------------------
|| sum || 0.63 | 0.70 | 2.9 ||
---------------------------------------
</code></pre>
<p>I am given this table, but I also am lacking in the knowledge of how to format this.
I recognize that the dashes are equal to the length of the formatted lines and the numbers denoting the rows and columns are centered.
Also, the decimals only carry out three places, the ones on the bottom are two places, and the final sum is only one place.</p>
|
<p>Is something like this useful?</p>
<pre><code>import random
def create_matrix(x,y):
matrix = []
for i in range(x):
matrix.append([])
for j in range(y):
matrix[i].append(random.random())
return matrix
def main():
matrix = create_matrix(3, 2)
for row in matrix:
print row
main()
</code></pre>
<p><strong>Edit</strong></p>
<p>To handle ValueError:</p>
<pre><code>def main():
while(True):
try:
x=int(input('Enter the number of rows: '))
y=int(input('Enter the number of cols: '))
matrix = create_matrix(x, y)
for row in matrix:
print row
break
except ValueError:
print "Just give integers please. Try again."
</code></pre>
<p><strong>Edit 2</strong></p>
<pre><code>def print_matrix(matrix):
print "-" + "------------"*len(matrix[0])
for i in range(len(matrix)):
print "|",
for j in range(len(matrix[i])):
print "{0:9} |".format(matrix[i][j]),
print
print "-" + "------------"*len(matrix[0])
</code></pre>
|
python-3.x|matrix|sum
| 0 |
1,909,218 | 22,098,649 |
Sort list after numerical value in string
|
<p>I have a list, where each item has the format "title, runtime" e.g. "Bluebird, 4005"</p>
<p>How can I sort that list in Python, according to the runtime part of the string for each item? </p>
<p>Is there a way to do this without using regex?</p>
|
<pre><code>words_list = ["Bluebird, 4005", "ABCD, 1", "EFGH, 2677", "IJKL, 2"]
print sorted(words_list, key = lambda x: int(x.split(",")[1]))
# ['ABCD, 1', 'IJKL, 2', 'EFGH, 2677', 'Bluebird, 4005']
</code></pre>
|
python|sorting
| 10 |
1,909,219 | 58,073,563 |
The prime function is not returning correct result
|
<p>I wrote a piece of code to check whether a number is a prime or not. It works in Powershell, but won't work on the online submission platform.</p>
<p>I have re-read how to define whther a number is prime and I can't find anything else that I might have missed in my code.</p>
<pre><code>x = int(input('Please enter a number: '))
if x > 1:
for i in range(2, x):
if (x % i) == 0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
break
else:
print('The number you inputted is not a prime number.')
</code></pre>
<p>Should print out whether a number is prime or not.</p>
|
<p>You can use the <code>for-else</code> construct so that a prime number is only determined when the loop finishes without breaking due to finding a divisor. Also, you only need to iterate up to the square root of the input number when looking for a divisor:</p>
<pre><code>x = int(input('Please enter a number: '))
for i in range(2, int(x ** .5) + 1):
if x % i == 0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
</code></pre>
|
python|primes
| 1 |
1,909,220 | 43,524,756 |
Difference between Linear Regression Coefficients between Python and R
|
<p>I'm trying to run a linear regression in Python that I have already done in R in order to find variables with 0 coefficients. The issue I'm running into is that the linear regression in R returns NAs for columns with low variance while the scikit learn regression returns the coefficients. In the R code, I find and save these variables by saving the variables with NAs as output from the linear regression, but I can't seem to figure out a way to mimic this behavior in python. The code I'm using can be found below. </p>
<p>R Code:</p>
<pre><code>a <- c(23, 45, 546, 42, 68, 15, 47)
b <- c(1, 2, 4, 6, 34, 2, 8)
c <- c(22, 33, 44, 55, 66, 77, 88)
d <- c(1, 1, 1, 1, 1, 1, 1)
e <- c(1, 1, 1, 1, 1, 1, 1.1)
f <- c(1, 1, 1, 1, 1, 1, 1.01)
g <- c(1, 1, 1, 1, 1, 1, 1.001)
df <- data.frame(a, b, c, d, e, f, g)
var_list = c('b', 'c', 'd', 'e', 'f', 'g')
target <- temp_dsin.df$a
reg_data <- cbind(target, df[, var_list])
if (nrow(reg_data) < length(var_list)){
message(paste0(' WARNING: Data set is rank deficient. Result may be doubtful'))
}
reg_model <- lm(target ~ ., data = reg_data)
print(reg_model$coefficients)
#store the independent variables with 0 coefficients
zero_coef_IndepVars.v <- names(which(is.na(reg_model$coefficients)))
print(zero_coef_IndepVars.v)
</code></pre>
<p>Python Code:</p>
<pre><code>import pandas as pd
from sklearn import linear_model
a = [23, 45, 546, 42, 68, 15, 47]
b = [1, 2, 4, 6, 34, 2, 8]
c = [22, 33, 44, 55, 66, 77, 88]
d = [1, 1, 1, 1, 1, 1, 1]
e = [1, 1, 1, 1, 1, 1, 1.1]
q = [1, 1, 1, 1, 1, 1, 1.01]
f = [1, 1, 1, 1, 1, 1, 1.001]
df = pd.DataFrame({'a': a,
'b': b,
'c': c,
'd': d,
'e': e,
'f': q,
'g': f})
var_list = ['b', 'c', 'd', 'e', 'f', 'g']
# build linear regression model and test for linear combination
target = df['a']
reg_data = pd.DataFrame()
reg_data['a'] = target
train_cols = df.loc[:,df.columns.str.lower().isin(var_list)]
if reg_data.shape[0] < len(var_list):
print(' WARNING: Data set is rank deficient. Result may be doubtful')
# Create linear regression object
reg_model = linear_model.LinearRegression()
# Train the model using the training sets
reg_model.fit(train_cols , reg_data['a'])
print(reg_model.coef_)
</code></pre>
<p>Output from R:</p>
<pre><code>(Intercept) b c d e f g
537.555988 -0.669253 -1.054719 NA -356.715149 NA NA
> print(zero_coef_IndepVars.v)
[1] "d" "f" "g"
</code></pre>
<p>Output from Python:</p>
<pre><code> b c d e f g
[-0.66925301 -1.05471932 0. -353.1483504 -35.31483504 -3.5314835]
</code></pre>
<p>As you can see, the values for columns 'b', 'c', and 'e' are close, but very different for 'd', 'f', and 'g'. For this example regression, I would want to return ['d', 'f', 'g'] as their outputs are NA from R. The issue is that the sklearn linear regression returns 0 for col 'd', while it returns -35.31 for col 'f' and -3.531 for col 'g'. </p>
<p>Does anyone know how R decides on whether to return NA or a value/how to implement this behavior into the Python version? Knowing where the differences stem from will likely help me implement the R behavior in python. I need the results of the python script to match the R outputs exactly. </p>
|
<p>It's a difference in implementation. <code>lm</code> in R uses underlying C code that is based on a QR decomposition. The model matrix is decomposed into an orthogonal matrix Q and a triangular matrix R. This causes what others called "a check on collinearity". R doesn't check that, the nature of the QR decomposition assures that the least collinear variables are getting "priority" in the fitting algorithm.</p>
<p>More info on QR decomposition in the context of linear regression:
<a href="https://www.stat.wisc.edu/~larget/math496/qr.html" rel="noreferrer">https://www.stat.wisc.edu/~larget/math496/qr.html</a></p>
<p>The code from sklearn is basically a wrapper around <code>numpy.linalg.lstsq</code>, which minimizes the Euclidean quadratic norm. If your model is <code>Y = AX</code>, it minimizes <code>||Y - AX||^2</code>. This is a different (and computationally less stable) algorithm, and it doesn't have the nice side effect of the QR decomposition.</p>
<p>Personal note: if you want to have robust fitting of models in a proven and tested computational framework and insist on using Python, look for linear regression implementations that are based on QR or SVD. The packages <code>scikit-learn</code> or <code>statsmodels</code> (still in beta as per 22 april 2017) should get you there. </p>
|
python|r|pandas|scikit-learn|regression
| 18 |
1,909,221 | 54,289,715 |
WindowsError: [Error2] The system cannot find the file specified
|
<p>I expect the program to open the link specified and then close the browser after some time.REPEAT this task 3 times.
But I end up getting the mentioned error.</p>
<pre><code>import time
import subprocess
total_breaks = 3
break_count = 0
print("This program started on " + time.ctime())
while(break_count < total_breaks):
browser = subprocess.Popen(['firefox', 'https://www.google.com/'])
sleep(10)
browser.terminate()
break_count = break_count + 1
</code></pre>
|
<p>You need to specify the path to firefox Just like the error shows:</p>
<blockquote>
<p>WindowsError: [Error2] The system cannot find the file specified</p>
</blockquote>
<pre><code>subprocess.Popen([r'C:\Program Files\Mozilla Firefox\Firefox.exe',
'-new-tab', 'http://www.google.com/'])
</code></pre>
|
python-3.x|subprocess
| 1 |
1,909,222 | 54,426,805 |
Printing in Django Template a Pandas dataframe with dynamic indexes and columns
|
<p>I have a script that creates dataframe with dynamic indexes values and name of the columns, as well as the number of columns. The only fixed value is the name of the index column that is "Transaction". Below an example.</p>
<p><a href="https://i.stack.imgur.com/33uGY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/33uGY.png" alt="enter image description here"></a>
I am passing this dataframe from a Django view to a Django Template, but I don't know how to access, in the template, the values of it.</p>
<pre><code>def myFunction(request):
df = myDfFunction() #returns the dataframe
return render(request, 'reports/my_page.html', {'df': df})
</code></pre>
<p>In the template I am trying to access it in many ways, without success.</p>
<pre><code><html>
<head>
<title>Page Title</title>
</head>
<body>
{% for row in df %}
<p>
{{ row[0][0] }}
</p>
{% endfor %}
</body>
</code></pre>
<p></p>
|
<p>You can convert your pandas dataframe to an html table and pass that to your template instead.</p>
<pre><code>def myFunction(request):
df = myDfFunction() #returns the dataframe
return render(request, 'reports/my_page.html', {'df': df.to_html()})
</code></pre>
<p>and you don't need to construct a table in your html file as this generates it.</p>
|
python|django|pandas
| 0 |
1,909,223 | 54,593,320 |
ValidationError or TypeError, ValueError - Exceptions
|
<p>I am quite a newbie understanding of how to catch exceptions in python. I have a question regarding those two types of ways of catching exceptions. I only found useful information about ValidationError regarding <a href="https://stackoverflow.com/questions/18781492/forms-validationerror-and-error-code">here</a> </p>
<p>But I did not quite understand if it can be used besides django or what are the error messages that I can expect about it. I saw this code sample regarding the validation of types. </p>
<pre><code>except (TypeError, ValueError) as error:
LOGGER.error('Error e.g.', exc_info=True)
except ValidationError:
LOGGER.error('Error e.g', exc_info=True)
</code></pre>
<p>So for <code>TypeError</code> and <code>ValueError</code> for me, it is clear:</p>
<p><strong>exception ValueError</strong></p>
<p>Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.</p>
<p><strong>exception TypeError</strong></p>
<p>Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.</p>
<p><strong>In conclusion,</strong>
I am trying to understanding what would be the advantage of the second code with <code>ValidationError</code>, but it could be tricky as I did not find good documentation about. If someone could share knowledge about ValidationError, I would highly appreciate,</p>
<p>I am raising this question because I am going to use related library and I have not seen the exceptions being treated like this.</p>
<p><a href="https://pypi.org/project/related/" rel="nofollow noreferrer">https://pypi.org/project/related/</a></p>
<p><strong>Thank you community!</strong></p>
|
<p>Python exceptions can be caught in this way:</p>
<pre class="lang-py prettyprint-override"><code>try:
<your code>
except <Exception>:
<CODE 2>
</code></pre>
<p>OR
LIKE THIS</p>
<pre class="lang-py prettyprint-override"><code>try:
<your code>
except(<exception1>,<exception2>):
<Code to handle exception>
</code></pre>
<blockquote>
<p>You are simply handling multiple exceptions together. You can
always split them. They are not 2 different ways.
In your case the as is for logging it .</p>
</blockquote>
<p>Here are a few examples:</p>
<pre class="lang-py prettyprint-override"><code>try:
<code>
except TypeError:
<Code for handling exception>
except ValueError:
<Code for handling exception>
except ValidationError:
<Code for handling exception>
except:
<Code for handling exception>
</code></pre>
<p>In the last case it catches exception of any type since no type is specified.<br />
<strong>In Python programs can raise any exception for anything.<br />
In fact exception is just a special class, even you can create one for your library.</strong></p>
<blockquote>
<p>So the best way to find about the exception is to read the docs of the library
not the exception class.</p>
</blockquote>
<p><strong>If your program catches the exception and wants more detail about it for creating a log file the code can be written like this.</strong></p>
<pre class="lang-py prettyprint-override"><code>except TypeError as e:
i=str(e)
</code></pre>
<p>In this case you are catching the exception and converting its detail to a string.<br />
This is from the Django docs about the error which you are talking about.</p>
<blockquote>
<p>Form validation happens when the data is cleaned. If you want to
customize this process, there are various places to make changes, each
one serving a different purpose. Three types of cleaning methods are
run during form processing. These are normally executed when you call
the is_valid() method on a form. There are other things that can also
trigger cleaning and validation (accessing the errors attribute or
calling full_clean() directly), but normally they wonβt be needed.</p>
<p>In general, any cleaning method can raise ValidationError if there is
a problem with the data it is processing, passing the relevant
information to the ValidationError constructor. See below for the best
practice in raising ValidationError. If no ValidationError is raised,
the method should return the cleaned (normalized) data as a Python
object.</p>
</blockquote>
<p>Some further references:</p>
<p><a href="https://docs.djangoproject.com/en/2.1/ref/forms/validation/" rel="nofollow noreferrer">The link to docs</a><br />
<a href="https://docs.python.org/3/library/exceptions.html" rel="nofollow noreferrer">This link has info about other common builtin exception classes.</a></p>
|
python|django|exception|error-handling|django-validation
| 4 |
1,909,224 | 71,428,644 |
Flattening a list of strings and lists to work on each item
|
<p>I am currently working with different input types -</p>
<p>My input could either look like this:</p>
<pre><code>
[term1, term2, term3,...]
</code></pre>
<p>or</p>
<pre><code>[[term1, term2], term3]
</code></pre>
<p>or</p>
<pre><code>[[term1, term2], [term3, term4]]
</code></pre>
<p>I would like to find a way to flatten it to a format over which I could loop in order to use the terms.</p>
<p>My code at the moment looks like this:</p>
<pre><code>
for entry in initial_list:
if type(entry) is str:
do_something(entry)
elif type(entry) is list:
for term in entry:
do_something(term)
</code></pre>
<p>The goal would be to perform the flattening in a more Pythonic way, using list comprehension or mapping, instead of explicit for loops.</p>
|
<p>You're very close. It might however be better to use <code>isinstance</code>. Try:</p>
<pre><code>result = list()
for entry in initial_list:
if isinstance(entry, str):
result.append(entry)
elif isinstance(entry, list):
for term in entry:
result.append(term)
</code></pre>
|
python|arrays
| 2 |
1,909,225 | 9,289,616 |
PUT binary data using requests lib
|
<p>I need to create a small WebDAV client that just upload files on the server.</p>
<p>I've found "requests" library that seems to be very easy to be used but I'm not able to use it properly.</p>
<p>The client should transfer binary files - so I've used the example bellow:</p>
<pre><code>>>> url = 'http://IPADDR/webdav'
>>> files = {'report.xls': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
</code></pre>
<p>from <a href="http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file" rel="nofollow">http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file</a>.</p>
<p>For me it's not working, I have the following error:</p>
<pre><code>File ".../site-packages/requests/packages/urllib3/connectionpool.py", line 260, in _make_request
conn.request(method, url, **httplib_request_kw)
File ".../httplib.py", line 941, in request
self._send_request(method, url, body, headers)
File ".../httplib.py", line 975, in _send_request
self.endheaders(body)
File ".../httplib.py", line 937, in endheaders
self._send_output(message_body)
File ".../httplib.py", line 795, in _send_output
msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 147: ordinal not in range(128)
</code></pre>
<p>Should be the input file somehow encoded? (I didn't found anything related in the "requests" documentation).</p>
|
<p>After some debugging, I've actually found what's happening.</p>
<p>I was able to fix the issue by removing the following import in my script:</p>
<pre><code>from __future__ import unicode_literals
</code></pre>
<p>This import seems to cause <a href="https://github.com/kennethreitz/requests/issues/448" rel="nofollow">unwanted string conversions</a> in urllib3 (which requests relies on).
As requests' author <a href="https://github.com/kennethreitz/requests/issues/444#issuecomment-6363650" rel="nofollow">explained</a>, this issue should be filed against <a href="https://github.com/shazow/urllib3" rel="nofollow">urllib3</a>.</p>
|
unicode|python-2.7|put|python-requests
| 0 |
1,909,226 | 39,260,133 |
Rename a particular instance in multiple files with the file name?
|
<p>I had to create about 500 copies of a xml file in the directory, which I managed to get done. As a part of the next problem is that I want to rename particular text in the file. How can I go about doing it?</p>
<p>This is what I have:
1000.xml, 1001.xml, 1002.xml...</p>
<p>1000.xml:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<addresses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='test.xsd'>
<address>
<name>Joe Tester</name>
<street>Baker street 5</street>
<id>1000</id>
</address>
<count>1000</count>
</code></pre>
<p></p>
<p>Essentially, this is copied to all the other files, but with a numerical and chronological name. How do I replace this "1000" with the "file name"? So, the new file should be -
1001.xml:</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<addresses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='test.xsd'>
<address>
<name>Joe Tester</name>
<street>Baker street 5</street>
<id>1001</id>
</address>
<count>1001</count>
</addresses>
</code></pre>
<p>I could do only this - <code>sed -i '' -e 's/1000/1001/g' $(find . -type f)</code> which will replace all the 1000 with 1001, but not the file name.</p>
|
<p>You've tagged it <code>perl</code> so here's how I'd do it:</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
#iterate the files.
foreach my $xml_file ( glob "*.xml" ) {
#regex match the number for the XML.
my ( $file_num ) = $xml_file =~ m/(\d+).xml/;
#create an XML::Twig, and set it to 'indented' output.
XML::Twig -> new ( pretty_print => 'indented',
#matches elements and runs the subroutine on 'it'. ($_) is the
#current element in this context.
twig_handlers => { 'address/id' => sub { $_ -> set_text($file_num) },
'count' => sub { $_ -> set_text($file_num) },
#parsefile_inplace reads and writes back any changes to the file
#as it goes.
} ) -> parsefile_inplace($xml_file);
}
</code></pre>
<p>This uses <code>XML::Twig</code>, which allows you do an in place edit. It does this via the element handlers, which upon hitting a suitable match, replaces the content with the right numeric value for the file.</p>
<p>I've opted to replace the defined content for <code>address/id</code> and <code>count</code>, rather than just doing straight search and replace, because then ... you don't have to worry about <code>1000</code> showing up anywhere else in the content. (Like the address). </p>
|
python|bash|perl
| 3 |
1,909,227 | 34,026,097 |
Using a Pi Camera Module with OpenCV Python
|
<p>I currently have some code which captures a still image from the Pi Camera Module and then identifies faces using the haarcascade xml file provided with OpenCV for Python. The code that I am using is the code shown towards the end of this blog post: <a href="http://rpihome.blogspot.co.uk/2015/03/face-detection-with-raspberry-pi.html" rel="nofollow">http://rpihome.blogspot.co.uk/2015/03/face-detection-with-raspberry-pi.html</a>, however it is slightly modified (fully working).</p>
<p>The only problem is that it currently only recognises faces on still images. Is there any way to make it so that I can continuously stream from the Pi Camera directly to OpenCV and then process the faces and display boxes around faces live in a window instead of saving a single frame to a file? I have tried several different tutorials online, but they all seem to not work for me.</p>
|
<p>Haven't tried it, but this should work.</p>
<pre><code>from picamera.array import PiRGBArray
from picamera import PiCamera
import cv2
import time
camera = PiCamera()
camera.resolution = (320, 240)
camera.framerate = 30
rawCapture = PiRGBArray(camera, size=(320, 240))
display_window = cv2.namedWindow("Faces")
face_cascade = cv2.CascadeClassifier('path_to_my_face_cascade.xml')
time.sleep(1)
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
image = frame.array
#FACE DETECTION STUFF
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
for (x,y,w,h) in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
#DISPLAY TO WINDOW
cv2.imshow("Faces", image)
key = cv2.waitKey(1)
rawCapture.truncate(0)
if key == 27:
camera.close()
cv2.destroyAllWindows()
break
</code></pre>
<p>Take a look at the documentation for picamera <a href="https://picamera.readthedocs.org/en/release-1.9/api.html" rel="nofollow">here.</a></p>
|
python|python-2.7|opencv|raspberry-pi
| 3 |
1,909,228 | 34,077,976 |
Error when trying to replace items in a list - Python
|
<p>I have created a list of lists by using the following code:</p>
<pre><code>grid = [['.' for i in range(0,width)] for j in range(0,height)]
</code></pre>
<p>Later in my program, I want to replace all the <code>'.'</code> in the list with random letters in my string <code>'ABCDEFG...'</code> I have tried the following code:</p>
<pre><code>letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
grid = [i.replace('.', random.choice(letters.upper())) for i in grid]
</code></pre>
<p>I have gotten this error:</p>
<pre><code>AttributeError: 'list' has no object 'replace'
</code></pre>
<p>I looked over the internet and everyone said to use list comprehension with this syntax to replace everything. But unfortunately it's not working.</p>
|
<p>Because <code>grid</code> is a list of lists. Hence, <code>i</code> is a list. You can't replace a list, since it's a function based for strings.</p>
<p>You want this:</p>
<pre><code>grid2 = [map(lambda x: x.replace('.', random.choice(letters.upper())), i) for i in grid]
</code></pre>
<p><code>map()</code> will iterate through each list implementing a certain function, <code>lambda x:</code>. If you're using Python 3, you'll need to call <code>list()</code> around the <code>map()</code>, since it returns a generator not a list.</p>
|
python|list|replace|list-comprehension
| 1 |
1,909,229 | 34,263,389 |
How to add pre and post-process actions to SCons build?
|
<p>I'm trying to add pre and post-process actions when building a project with SCons.</p>
<p>The SConstruct and SConscript files are at the top of the project.</p>
<p><strong>Pre-process actions</strong>:
Generating code(by calling different tools):
-> without knowing the exact files that will be generated after this pre-process (additional pre-process for deciding which files were generated can be created in order to feed SCons with them)</p>
<p>-> running external scripts(python, pearl scripts), <strong>executed before compilation</strong></p>
<p><strong>Post-process actions:</strong></p>
<p>->running external tools, running external scripts that should be <strong>executed after linking</strong></p>
<p>What I tried until now:</p>
<p>For pre-process:</p>
<ul>
<li>To use os.system from python in order to run a cmd. ( works fine but I'm looking for a "SCons solution" )</li>
<li>To use <code>AddPreAction(target, action)</code> function from SCons. Unfortunately this function is executed after compiling the project as the SCons user manual states: <code>"The specified pre_action would be executed before scons calls the link command that actually generates
the executable program binary foo, not before compiling the foo.c file into an object file."</code></li>
</ul>
<p>For post-process:</p>
<ul>
<li>To use <code>AddPostAction(target, action)</code> and this works fine, fortunately.</li>
</ul>
<p>I'm looking for solutions that will make SCons somehow aware of this pre and post processes.</p>
<p><strong>My question is the following:</strong></p>
<p>What is the best approach, for the requirements stated above, using SCons ? Is there a way to execute pre-process actions before compilation using SCons built-in functions ?</p>
|
<p>You don't give very much detail about what you've tried to get your pre-processing part working. In general, you should try to create real Builders for the Code generation part...this will make the detection and handling of dependencies easier for SCons (and for you as the user ;) ). You may want to check out our Wiki at <a href="https://bitbucket.org/scons/scons/wiki/ToolsForFools" rel="nofollow noreferrer">https://bitbucket.org/scons/scons/wiki/ToolsForFools</a> , where we explain in large detail how to write new Builders.</p>
<p>If you need to run additional scripts on every build, you should be able to trigger these fine with the <code>os.system()</code> or an appropriate <code>subprocess</code> call right at the start of your top-level SConstruct for example. But what I get from your latest edit, and I'll refer mainly to the first of the questions you asked, is that you're trying to model some sort of "staged" build process. You think you need a "preprocess" stage, where you can hook into and create all the additional headers and sources you might need, by calling your scripts. My guess is, that you're trying to rewrite something like an original make/autotools setup and would like to reuse parts wherever possible, which isn't a bad idea of course. But SCons isn't stage-driven, it's dependency-driven...so your current approach is a bad fit and might lead to problems sooner or later.</p>
<p>The best thing you can do, is to forget Pre- and PostActions and get your dependencies straight. In addition to writing your own Builder(s) to replace your scripts, you'd have to implement a proper Emitter for each of these Builders. This Emitter (check the Tools guide mentioned above) would have to parse your input file that goes into the script, and return the list of filenames that will be generated when the script gets actually run. Like this, SCons will then know <em>a priori</em> which files get generated once the build script is run, and can use these names for resolving dependencies already (even if the actual files don't exist yet).</p>
<p>For the post-processing part: this is usually handled by using the standard Python atexit handler. See e.g. <a href="https://stackoverflow.com/questions/8901296/how-do-i-run-some-code-after-every-build-in-scons">How do I run some code after every build in scons?</a> for an example.</p>
|
python|build|action|scons
| 1 |
1,909,230 | 65,995,458 |
Keras model.evaluate accuracy stuck at 50 percent while using ImageDataGenerator
|
<p>I am trying to find the accuracy of my saved Keras model using <code>model.evaluate</code>.</p>
<p>I have loaded in my model using this:</p>
<pre><code>model = keras.models.load_model("../input/modelpred/2_convPerSection_4_sections")
</code></pre>
<p>I have a CSV file with two columns, one for the filename of an image and one for the label. Here is a sample:</p>
<pre><code>id,label
95d04f434d05c1565abdd1cbf250499920ae8ecf.tif,0
169d0a4a1dbd477f9c1a00cd090eff28ac9ef2c1.tif,0
51cb2710ab9a05569bbdedd838293c37748772db.tif,1
4bbb675f8fde60e7f23b3354ee8df223d952c83c.tif,1
667a242a7a02095f25e0833d83062e8d14a897cd.tif,0
</code></pre>
<p>I have loaded this CSV into a pandas dataframe and fed it into an <code>ImageDataGenerator</code>:</p>
<pre><code>df = pd.read_csv("../input/cancercsv/df_test.csv", dtype=object)
test_path = "../input/histopathologic-cancer-detection/train"
test_data_generator = ImageDataGenerator(rescale=1./255).flow_from_dataframe(dataframe = df,
directory=test_path,
x_col = "id",
y_col = "label",
target_size=(96,96),
batch_size=16,
shuffle=False)
</code></pre>
<p>Now I try to evaluate my model using:</p>
<pre><code>val = model.evaluate(test_data_generator, verbose = 1)
print(val)
</code></pre>
<p>However, the accuracy doesn't change from 50 percent, but, my model had a 90 percent validation accuracy when trained.</p>
<p>Here is what is returned:</p>
<pre><code>163/625 [======>.......................] - ETA: 21s - loss: 1.1644 - accuracy: 0.5000
</code></pre>
<p>I was able to ensure that my model worked and the generator was properly feeding data, by creating an ROC curve using matplotlib and scikit-learn, which produced a 90 percent AUC, so I'm not sure where the problem is:</p>
<pre><code>predictions = model.predict_generator(test_data_generator, steps=len(test_data_generator), verbose = 1)
false_positive_rate, true_positive_rate, threshold = roc_curve(test_data_generator.classes, np.round(predictions))
area_under_curve = auc(false_positive_rate, true_positive_rate)
plt.plot([0, 1], [0, 1], 'k--')
plt.plot(false_positive_rate, true_positive_rate, label='AUC = {:.3f}'.format(area_under_curve))
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC curve')
plt.legend(loc='best')
plt.show()
</code></pre>
<p>Similar questions say that the problem came from setting shuffle parameter in the ImageDataGenerator to <code>True</code>, but mine has always been set to <code>False</code>. Another similar problem was fixed by retraining with a sigmoid activation rather than softmax, but I used sigmoid in my final layer, so that can't be the problem</p>
<p>This is my first time using Keras. What did I do wrong?</p>
|
<p>The problem was because of <code>class_mode</code> parameter in flow function. Default is <code>categorical</code>.</p>
<p>Setting it as <code>binary</code> solved the problem. Corrected code:</p>
<pre><code>test_data_generator = ImageDataGenerator(rescale=1./255).flow_from_dataframe(dataframe = df,
directory=test_path,
x_col = "id",
y_col = "label",
class_mode = 'binary',
target_size=(96,96),
batch_size=16,
shuffle=False)
</code></pre>
|
python|tensorflow|machine-learning|keras
| 1 |
1,909,231 | 7,166,321 |
PyDev not capturing unittest.TextTestRunner output?
|
<p>The PyDev PyUnit perspective correctly displays the output of my unit tests when I run them as "Python unit-test" from the module they live in with this basic usage pattern:</p>
<pre><code>import unittest
class MyTest(unittest.TestCase):
def test_something(self):
pass
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>However, when I import tests from another module like so...</p>
<pre><code>import unittest
import mypackage.mytests
if __name__ == '__main__':
unittest.main(module=mypackage.mytests)
</code></pre>
<p>...no tests are run. When I run the same module as "Python Run" or from a terminal, it behaves correctly, so for some reason the PyUnit perspective is not loading the tests correctly. I get the same results with this alternative method:</p>
<pre><code>import unittest
import mypackage.mytests
tests = unittest.TestLoader().loadTestsFromModule(mypackage.mytests)
unittest.TextTestRunner().run(tests)
</code></pre>
<p>Is there another way to import a module containing TestCase derived classes and get PyDev to capture the output of the test runner?</p>
|
<p>PyDev will not run your <code>__main__</code>, it'll collect the classes itself, so, you need to have your classes loaded in the module for it to find them (and do a run as > Python Unittest, or even use the Ctrl+F9 shortcut directly -- it won't show classes in that case, but pressing Enter directly after the Ctrl+F9 should work to run all the tests in the module in the latest PyDev).</p>
<p>e.g.: </p>
<pre><code>import unittest
from mypackage.mytests import *
</code></pre>
<p>If you had multiple and the TestCase classes had the same name, you'd need to do something as:</p>
<pre><code>import unittest
from mypackage.mytests import Test as Test1
from mypackage.mytests2 import Test as Test2
...
</code></pre>
<p>In which case you'd probably be better by creating a simple helper to load all the classes from a module and put subclasses of TestCase in the current module with different names (should be straightforward doing this through a dir/getattr in the module).</p>
<p>Still, note that in PyDev you may select multiple files/folder and do a run as > Python unittest and it'll run all the tests it finds in the module (or recursively in a directory), so, that may already be enough for you depending on your use case.</p>
|
python|pydev
| 1 |
1,909,232 | 39,757,947 |
XGBOOST verbose_eval in Jupyter not working
|
<p>I'm running the following in a python Jupyter notebook:</p>
<pre><code>import xgboost as xgb
bst_dx=xgb.train(paramMap,dset,num_round,verbose_eval=True)
</code></pre>
<p>For some reason I never see the actual verbose evaluation, which is supposed to print the current loss at the last evaluated boost. I've tried setting verbose_eval to 1,2,3,4, etc but that still doesn't do anything. I just get a silent output. Is there some setting I need to enable in Jupyter?</p>
|
<p>You also need to provide your evaluation data set/s and the number of rounds of no improvement after which you want to invoke an early stop. For example:</p>
<pre><code>xgb_params = {"objective": "multi:softprob", "max_depth": 8, "silent": 1, "num_class":5}
num_rounds = 1000
dtrain = xgb.DMatrix(trainX, trainY) #training data
dvalid = xgb.DMatrix(validX, validY) #validation data
thisxgb = xgb.train(xgb_params, dtrain, num_rounds, \
[(dtrain,'train'),(dvalid,'test')], \
early_stopping_rounds=10\
) #stop if no improvement in 10 rounds
</code></pre>
|
python|jupyter|jupyter-notebook|xgboost
| 2 |
1,909,233 | 39,816,636 |
How can I get data from Goodreads and use it in Telegram Bot API
|
<p>I've come up with an idea of writing an inline telegram bot and use a Goodreads API for this. But I don't know how to properly extract a book info from Goodreads and put it into special fields in bot api request. I will be so much grateful for helping me with this issue! :)</p>
|
<p>It should be pretty easy, just consume API, store data in the memory, and use it when you need it.</p>
<p>Here is example with Node.js: <a href="https://github.com/ro31337/exbot" rel="nofollow">https://github.com/ro31337/exbot</a></p>
<p>This app is using API feed to fetch data. You can see how it works by adding @goa_bot to your Telegram.</p>
|
python|python-3.x|telegram|telegram-bot|python-telegram-bot
| 0 |
1,909,234 | 16,337,303 |
Blocking a log off request with Python
|
<p>I have some software that occasionally logs me off automaticly. I want to block this, so I won't be logged off (windows 7). Are there a way to block log off requests using Python? If so, then how and if not; are there any other solutions?</p>
|
<p>Looks as if there's a possible solution in an <a href="http://msdn.microsoft.com/en-us/library/aa376876%28VS.85%29.aspx" rel="nofollow noreferrer">MSDN article</a>.</p>
<p>What you'd have to do is write a simple Windows application which handles the <code>WM_QUERYENDSESSION</code> event, and returns <code>FALSE</code>, then, in theory, as long as that application is running, the system won't log you out. It's possible that just leaving open an instance of <code>notepad.exe</code> with an unsaved file in it would achieve the same thing.</p>
<p>It, might, however, cause all other applications to terminate, so, if that's undesirable, you'd have to intercept the call to <code>ExitWindows</code> from softXpand, which is much more complicated.</p>
<p>Some security products like <a href="http://www.comodo.com/home/internet-security/free-internet-security.php" rel="nofollow noreferrer">Comodo Internet Security</a> will allow you to run an application in a sandbox, such that you can intercept and deny certain system calls, which might work.</p>
<p>See also: <a href="https://stackoverflow.com/questions/3625519/is-it-possible-to-block-exitwindows-or-exitwindowsex">this question</a>.</p>
|
python|windows|logoff
| 4 |
1,909,235 | 31,970,301 |
Reading a one-dimensional data series spread over columns with NumPy
|
<p>In my field a lot of data files are formatted like this:</p>
<pre><code>1.0 0.4 -0.3 0.2 1.0
2.2 -0.3 3.2 2.2 1.2
0.5 0.3 0.3 -4.4 1.2
0.2 1.2 -0.6
</code></pre>
<p>Where the data series represented is just a one-dimensional array of numbers (they've just been arbitrarily grouped into 5 columns per row, except for the last row).</p>
<p>I can read this with the following hack</p>
<pre><code>txtdata = open('data.dat').read().replace('\n', ' ')
data = np.fromstring(txtdata, sep=' ')
</code></pre>
<p>But surely there's a better way? One that doesn't involve iterating over the data twice? <code>loadtxt</code> and <code>genfromtxt</code> don't seem to support this.</p>
|
<p>Assuming you don't have extraneous whitespaces :</p>
<pre><code>with open('file') as f:
array = []
for line in f:
array.append([float(x) for x in line.split()])
</code></pre>
<p>You can condense the loop into a nested list comprehension:</p>
<pre><code>with open('file') as f:
array = [[float(x) for x in line.split()] for line in f]
</code></pre>
|
python|arrays|file|numpy|io
| 1 |
1,909,236 | 38,546,495 |
tflearn / tensorflow | Multi-stream/Multiscale/Ensemble model definition
|
<p>I am trying to define a multi-stream model with tflearn so that there are two copies of the same architecture (or you can think of it as an ensemble model) that I feed with different crops of the same image but not sure how I would go and implement that with tflearn.</p>
<p>I basically have this data:</p>
<pre><code>X_train1, X_test1, y_train1, y_test1 : Dataset 1 (16images x 299 x 299px x 3ch)
X_train2, X_test2, y_train2, y_test2 : Dataset 2 (16images x 299 x 299px x 3ch)
</code></pre>
<p>And I have created so far this based on the <code>logical.py</code> <a href="https://github.com/tflearn/tflearn/blob/master/examples/basics/logical.py" rel="nofollow">example</a> (simplified code):</p>
<pre><code>netIn1 = tflearn.input_data(shape=[None, 299, 299, 3]
net1 = tflearn.conv_2d(netIn1, 16, 3, regularizer='L2', weight_decay=0.0001)
...
net1 = tflearn.fully_connected(net1, nbClasses, activation='sigmoid')
net1 = tflearn.regression(net1, optimizer=adam, loss='binary_crossentropy')
netIn2 = tflearn.input_data(shape=[None, 299, 299, 3]
net2 = tflearn.conv_2d(netIn2, 16, 3, regularizer='L2', weight_decay=0.0001)
...
net2 = tflearn.fully_connected(net2, nbClasses, activation='sigmoid')
net2 = tflearn.regression(net2, optimizer=adam, loss='binary_crossentropy')
</code></pre>
<p>And then merge the two networks by concatenating:</p>
<pre><code>net = tflearn.merge([net1, net2], mode = 'concat', axis = 1)
</code></pre>
<p>And start training like this:</p>
<pre><code># Training
model = tflearn.DNN(net, checkpoint_path='model',
max_checkpoints=10, tensorboard_verbose=3,
clip_gradients=0.)
model.fit([X1,X2], [Y1,Y2], validation_set=([testX1, testX2], [testY1,testY2]))
</code></pre>
<p>So now my problem is how do I parse the inputs at the start of the network? How do I split the X1 to net1 and X2 to net2? </p>
|
<p>You do not need to split X1 and X2, they will automatically be assigned to your input layers netIn1 and netIn2 (in the same order you define them).</p>
|
python|machine-learning|computer-vision|tensorflow|deep-learning
| 0 |
1,909,237 | 38,841,133 |
Feedparser doesn't work, gives AttributeError
|
<p>I have this code:</p>
<pre><code>import jinja2
import webapp2
import os
from google.appengine.ext import db
import feedparser
from xml.dom import minidom
from google.appengine.api import memcache
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)
class News(db.Model):
title = db.StringProperty(required=True)
description = db.StringProperty(required=True)
url = db.StringProperty(required=True)
imageurl = db.StringProperty(required=True)
feeds = [ 'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=e&ict=ln&output=rss' # Entertainment
'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=snc&ict=ln&output=rss' # Science
'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=s&ict=ln&output=rss' # Sports
'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=b&ict=ln&output=rss' # Business
'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=tc&ict=ln&output=rss' # Technology
]
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write(feedparser.__file__)
self.response.write(render_str('mainpage.html'))
class Entertainment(webapp2.RequestHandler):
def get(self):
rssfeed = feedparser.parse(feeds[0])
self.response.write(rsfeed.entries[0].title)
self.response.write(rsfeed.entries[0].link)
self.response.write(rsfeed.entries[0].published)
self.response.write(rsfeed.entries[0].description)
app = webapp2.WSGIApplication([('/', MainPage),
('/entertainment', Entertainment)
], debug = True)
</code></pre>
<p><code>mainpage.html</code> has nothing except five <code><p></p></code> tags with one of them hyperlinked to <code>/entertainment</code>.</p>
<p>When I run it and click on the hyperlinked paragraph, I get this</p>
<p><code>AttributeError: 'module' object has no attribute 'parse'</code></p>
<p>I've followed <a href="https://stackoverflow.com/questions/11171073/feedparser-py-in-root-directory-but-still-not-working-on-dev-server">this question</a>, which is why I printed out the filepath in the <code>get</code> of <code>MainPage</code>. </p>
<p>My folder structure is :</p>
<ul>
<li><p>templates</p>
<ul>
<li>mainpage.html</li>
</ul></li>
<li><p>app.yaml</p></li>
<li><p>feedparser.py</p></li>
<li><p>newsapp.py</p></li>
<li><p>newsapp.pyc</p></li>
</ul>
<p>When I ran it the first time, feedparser pointed to <code>C:\Users\IBM_ADMIN\Downloads\7c\News Aggregator GAE\feedparser.pyc</code>. That was wrong, so I deleted the <code>.pyc</code> file, and then it pointed to <code>C:\Users\IBM_ADMIN\Downloads\7c\News Aggregator GAE\feedparser.py</code>. But it still gave the same error and the <code>.pyc</code> file got generated again. I know it gets generated because I'm compiling the feedparser file, but why does the feedparser module point to that location? And how can I get around that error?</p>
|
<p>The GAE app code is not necessarily able to run as a standalone application.</p>
<p>The proper way to execute it locally is through the SDK's local development server, see <a href="https://cloud.google.com/appengine/docs/python/tools/using-local-server" rel="nofollow">Using the Local Development Server</a>. </p>
<p>The local development server will properly set the execution environment to not accidentally reach modules outside your application. It should address your import issue.</p>
|
python|google-app-engine|feedparser
| 0 |
1,909,238 | 40,345,767 |
How to install trac from python source on a shared host with no admin previllages?
|
<p>I am trying to install <a href="https://trac.edgewall.org/" rel="nofollow">trac</a> on my shared host on NameCheap.
apt-get, pip and easy_install are all disabled on NameCheap shared hosts.</p>
<p>trac python source has an installation wrapper, but I cannot run it since it requires write access to /usr/lib/python/ folder, which my account does not have.</p>
<p>Does anyone know how I can install it in another path?
Thanks</p>
|
<p>You can just unzip the package (libs and modules and all) in a folder, add it to the PYTHONPATH, if you don't control this in the environment then in your scripts:</p>
<pre><code>from os import environ as ENV
ENV['PYTHONPATH'].append('path/to/new/lib')
</code></pre>
<p>and now you should be able to import it. Python is very portable.</p>
|
python
| 2 |
1,909,239 | 40,554,208 |
splitting using regex python for complicated strings
|
<p>I want to splitting a string such as Si(C3(COOH)2)4(H2O)7 into the following</p>
<p>[Si, (C3(COOH)2), 4, (H2O), 7]</p>
<p>That is, entire paranthesis expressions turn into an element by themselves. I've tried a number of different combinations with re.findall() to no avail. Any help is greatly appreciated.</p>
|
<p>You have to scan the string yourself, keeping track of the nesting depth. The significant 'events' are 'at beginning of string', 'at (', 'at )', and 'at end of string'. At each event, consider depth and reset it.</p>
<pre><code>inn = 'Si(C3(COOH)2)4(H2O)7'
out = ['Si', '(C3(COOH)2)', '4', '(H2O)', '7']
res = []
beg = 0
dep = 0
for i, c in enumerate(inn):
if c == '(':
if dep == 0 and beg < i:
res.append(inn[beg:i])
beg = i
dep += 1
elif c == ')':
if dep == 0:
raise ValueError("')' without prior '('")
elif dep == 1:
res.append(inn[beg:i+1])
beg = i+1
dep -= 1
if dep == 0:
res.append(inn[beg:i+1])
else:
raise ValueError("'(' without following ')'")
print(res, res == out)
# prints
# ['Si', '(C3(COOH)2)', '4', '(H2O)', '7'] True
</code></pre>
|
regex|string|python-3.x
| 0 |
1,909,240 | 9,976,683 |
wx Import Error
|
<p>I am trying to run this code. Previously, it was giving <code>No module wx</code> as an error. Then I downloaded the <code>wx</code> module and now it is giving this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python24\player.py", line 2, in -toplevel-
import wx
File "C:\Python24\wx__init__.py", line 45, in -toplevel-
from wxPython import wx
File "C:\Python24\wxPython__init__.py", line 20, in -toplevel-
import wxc
ImportError: DLL load failed: The specified module could not be found.
</code></pre>
<p>Here is my code:</p>
<pre><code>import os
import wx
import wx.media
import wx.lib.buttons as buttons
dirName = os.path.dirname(os.path.abspath(__file__))
bitmapDir = os.path.join(dirName, 'bitmaps')
########################################################################
class MediaPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent=parent)
self.frame = parent
self.currentVolume = 50
self.createMenu()
self.layoutControls()
sp = wx.StandardPaths.Get()
self.currentFolder = sp.GetDocumentsDir()
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.onTimer)
self.timer.Start(100)
#----------------------------------------------------------------------
def layoutControls(self):
"""
Create and layout the widgets
"""
try:
self.mediaPlayer = wx.media.MediaCtrl(self, style=wx.SIMPLE_BORDER)
except NotImplementedError:
self.Destroy()
raise
# create playback slider
self.playbackSlider = wx.Slider(self, size=wx.DefaultSize)
self.Bind(wx.EVT_SLIDER, self.onSeek, self.playbackSlider)
self.volumeCtrl = wx.Slider(self, style=wx.SL_VERTICAL|wx.SL_INVERSE)
self.volumeCtrl.SetRange(0, 100)
self.volumeCtrl.SetValue(self.currentVolume)
self.volumeCtrl.Bind(wx.EVT_SLIDER, self.onSetVolume)
# Create sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
audioSizer = self.buildAudioBar()
# layout widgets
mainSizer.Add(self.playbackSlider, 1, wx.ALL|wx.EXPAND, 5)
hSizer.Add(audioSizer, 0, wx.ALL|wx.CENTER, 5)
hSizer.Add(self.volumeCtrl, 0, wx.ALL, 5)
mainSizer.Add(hSizer)
self.SetSizer(mainSizer)
self.Layout()
#----------------------------------------------------------------------
def buildAudioBar(self):
"""
Builds the audio bar controls
"""
audioBarSizer = wx.BoxSizer(wx.HORIZONTAL)
self.buildBtn({'bitmap':'player_prev.png', 'handler':self.onPrev,
'name':'prev'},
audioBarSizer)
# create play/pause toggle button
img = wx.Bitmap(os.path.join(bitmapDir, "player_play.png"))
self.playPauseBtn = buttons.GenBitmapToggleButton(self, bitmap=img, name="play")
self.playPauseBtn.Enable(False)
img = wx.Bitmap(os.path.join(bitmapDir, "player_pause.png"))
self.playPauseBtn.SetBitmapSelected(img)
self.playPauseBtn.SetInitialSize()
self.playPauseBtn.Bind(wx.EVT_BUTTON, self.onPlay)
audioBarSizer.Add(self.playPauseBtn, 0, wx.LEFT, 3)
btnData = [{'bitmap':'player_stop.png',
'handler':self.onStop, 'name':'stop'},
{'bitmap':'player_next.png',
'handler':self.onNext, 'name':'next'}]
for btn in btnData:
self.buildBtn(btn, audioBarSizer)
return audioBarSizer
#----------------------------------------------------------------------
def buildBtn(self, btnDict, sizer):
""""""
bmp = btnDict['bitmap']
handler = btnDict['handler']
img = wx.Bitmap(os.path.join(bitmapDir, bmp))
btn = buttons.GenBitmapButton(self, bitmap=img, name=btnDict['name'])
btn.SetInitialSize()
btn.Bind(wx.EVT_BUTTON, handler)
sizer.Add(btn, 0, wx.LEFT, 3)
#----------------------------------------------------------------------
def createMenu(self):
"""
Creates a menu
"""
menubar = wx.MenuBar()
fileMenu = wx.Menu()
open_file_menu_item = fileMenu.Append(wx.NewId(), "&Open", "Open a File")
menubar.Append(fileMenu, '&File')
self.frame.SetMenuBar(menubar)
self.frame.Bind(wx.EVT_MENU, self.onBrowse, open_file_menu_item)
#----------------------------------------------------------------------
def loadMusic(self, musicFile):
"""
Load the music into the MediaCtrl or display an error dialog
if the user tries to load an unsupported file type
"""
if not self.mediaPlayer.Load(musicFile):
wx.MessageBox("Unable to load %s: Unsupported format?" % path,
"ERROR",
wx.ICON_ERROR | wx.OK)
else:
self.mediaPlayer.SetInitialSize()
self.GetSizer().Layout()
self.playbackSlider.SetRange(0, self.mediaPlayer.Length())
self.playPauseBtn.Enable(True)
#----------------------------------------------------------------------
def onBrowse(self, event):
"""
Opens file dialog to browse for music
"""
wildcard = "MP3 (*.mp3)|*.mp3|" \
"WAV (*.wav)|*.wav"
dlg = wx.FileDialog(
self, message="Choose a file",
defaultDir=self.currentFolder,
defaultFile="",
wildcard=wildcard,
style=wx.OPEN | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
self.currentFolder = os.path.dirname(path)
self.loadMusic(path)
dlg.Destroy()
#----------------------------------------------------------------------
def onNext(self, event):
"""
Not implemented!
"""
pass
#----------------------------------------------------------------------
def onPause(self):
"""
Pauses the music
"""
self.mediaPlayer.Pause()
#----------------------------------------------------------------------
def onPlay(self, event):
"""
Plays the music
"""
if not event.GetIsDown():
self.onPause()
return
if not self.mediaPlayer.Play():
wx.MessageBox("Unable to Play media : Unsupported format?",
"ERROR",
wx.ICON_ERROR | wx.OK)
else:
self.mediaPlayer.SetInitialSize()
self.GetSizer().Layout()
self.playbackSlider.SetRange(0, self.mediaPlayer.Length())
event.Skip()
#----------------------------------------------------------------------
def onPrev(self, event):
"""
Not implemented!
"""
pass
#----------------------------------------------------------------------
def onSeek(self, event):
"""
Seeks the media file according to the amount the slider has
been adjusted.
"""
offset = self.playbackSlider.GetValue()
self.mediaPlayer.Seek(offset)
#----------------------------------------------------------------------
def onSetVolume(self, event):
"""
Sets the volume of the music player
"""
self.currentVolume = self.volumeCtrl.GetValue()
print "setting volume to: %s" % int(self.currentVolume)
self.mediaPlayer.SetVolume(self.currentVolume)
#----------------------------------------------------------------------
def onStop(self, event):
"""
Stops the music and resets the play button
"""
self.mediaPlayer.Stop()
self.playPauseBtn.SetToggle(False)
#----------------------------------------------------------------------
def onTimer(self, event):
"""
Keeps the player slider updated
"""
offset = self.mediaPlayer.Tell()
self.playbackSlider.SetValue(offset)
########################################################################
class MediaFrame(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Python Music Player")
panel = MediaPanel(self)
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MediaFrame()
frame.Show()
app.MainLoop()
</code></pre>
<p>It may be that I didn't install <code>wx</code> correctly. I am using Python 2.4 and I was unable to find the <code>wx</code> module for Python 2.4. I downloaded <code>wx</code> for Python 2.5 and pasted the wx folder into the Python 2.4 directory. Can you please guide me how to add the <code>wx</code> module in Python 2.4?</p>
|
<p>Check <a href="http://sourceforge.net/projects/wxpython/files/wxPython/" rel="nofollow">here</a>.</p>
<p>The 2.8.10 version still has binary installers for 2.4</p>
|
python|wxpython
| 1 |
1,909,241 | 68,411,073 |
NoReverseMatch at /vistaprevia/pedidos/4/edit Reverse for 'editr' not found. 'editr' is not a valid view function or pattern name
|
<p>I have a problem with an edit view in django 3.2 and python 3.9.2, the problem is when a get into the link EDITAR in my view, it throws me the error "NoReverseMatch at /vistaprevia/pedidos/4/edit" and says to me that "Reverse for 'editr' not found. 'editr' is not a valid view function or pattern name.", I cant found what is going on with the code. Here is my code</p>
<p>Views.py</p>
<pre><code>from django.shortcuts import render, redirect, get_object_or_404
from django.views import generic
from django.views.generic.edit import UpdateView
from vistaprevia.models import Op
from vistaprevia.forms import CargarFormOp, EditarFormOp#, EditarFormRem
# Create your views here.
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
app_name = 'vistaprevia'
#VISTA QUE MUESTRA LOS ULTIMOS 10 PEDIDOS
def index(request):
ultimasop = Op.objects.all().order_by('-fecha')
return render(request, 'vistaprevia/index.html', context={'ultimasop':ultimasop})
#DETALLE PEDIDOS
class PedidoDetailView(generic.DetailView):
model = Op
#CARGA DE PEDIDOS, EMPIEZ LA ACCION, WIIIIIIIIII
def cargar_pedido(request):
if request.method=='POST':
form = CargarFormOp(request.POST)
if form.is_valid():
fecha = form.cleaned_data['fecha']
cliente = form.cleaned_data['cliente']
tipoop = form.cleaned_data['tipoop']
fact = form.cleaned_data['fact']
condicion = form.cleaned_data['condicion']
despacho = form.cleaned_data['despacho']
vendedor = form.cleaned_data['vendedor']
newdoc = Op(fecha=fecha, cliente=cliente, tipoop=tipoop,fact=fact, condicion=condicion, despacho=despacho ,vendedor=vendedor)
newdoc.save()
return redirect("index")
else:
form = CargarFormOp()
return render(request, 'vistaprevia/formulario.html', {'form': form})
#AGREGAMOS TODO LO REFERETE AL PAGO Y DEMAS, MENS COSAS PARA QUE HAGA EN MI TRABAJO, SUPER WIIIIIIIIII
def editar_pedido(request, pk):
pedid = get_object_or_404(Op, pk=pk)
if request.method=="POST":
form = EditarFormOp(request.POST, instance = pedid)
if form.is_valid():
pedid.npedido1 = form.save(commit=False)
pedid.nfactura1 = form.save(commit=False)
pedid.nrecibo1 = form.save(commit=False)
pedid.npedido2 = form.save(commit=False)
pedid.nfactura2 = form.save(commit=False)
pedid.nrecibo2 = form.save(commit=False)
pedid.fecharem1 = form.save(commit=False)
pedid.nrem1 = form.save(commit=False)
pedid.fecharem2 = form.save(commit=False)
pedid.nrem2 = form.save(commit=False)
pedid.save()
return redirect('pedido-detalle', pk=pedid.pk)
else:
form = EditarFormOp(instance=pedid)
return render(request, 'vistaprevia/editar_pedido.html', {'form':form})
</code></pre>
<p>forms.py</p>
<pre><code>from django.forms import ModelForm
from .models import Op
class CargarFormOp(ModelForm):
class Meta:
model = Op
fields = ['fecha', 'cliente', 'tipoop', 'fact', 'condicion', 'despacho', 'vendedor', 'estadoop', 'deudaop']
def __init__(self, *args, **kwargs):
super(CargarFormOp, self).__init__(*args, **kwargs)
class EditarFormOp(ModelForm):
class Meta:
model = Op
fields = ['npedido1', 'nfactura1', 'nrecibo1', 'npedido2', 'nfactura2', 'nrecibo2', 'fecharem1', 'nrem1', 'fecharem2', 'nrem2']
def __init__(self, *args, **kwargs):
super(EditarFormOp, self).__init__(*args, **kwargs)
</code></pre>
<p>urls.py</p>
<pre><code>from django.urls import path
from vistaprevia import views
app_name = 'vistaprevia'
urlpatterns = [
path('', views.index, name='index'),
path('cargar/', views.cargar_pedido, name='cargar'),
path('pedidos/<int:pk>', views.PedidoDetailView.as_view(), name='pedido-detalle'),
path('pedidos/<int:pk>/edit', views.editar_pedido, name='editr'),
]
</code></pre>
<p>op-detail.html</p>
<pre><code> <article class="col-12 col-sm-6 col-md-4 tarjeta3">
<h1>Remitos:</h1>
<p>Fecha: {{ fecharem1 }}</p>
<p>NΒ° Remito: {{ nrem1 }}(1)</p>
<p><a class="light bg-dark col-2" href="#">Remito 1</a></p>
<p>Fecha: {{ fecharem2 }} </p>
<p>NΒ° Remito (2): {{nrem2}}</p>
<p><a class="light bg-dark col-2" href="#">Remito 2</a></p>
<p><a class="light bg-dark col-2" href="{% url 'vistaprevia:editr' op.pk %}">Editar</a></p>
</article>
</code></pre>
<p>editar_pedido.html</p>
<pre><code>{% extends 'vistaprevia/plantilla.html' %}
{% load static %}
{% load i18n %}
{% block content %}
<!--muestra por pedidos-->
<main class="container-fluid">
<div class="row">
<article class="col-12 col-sm-6 col-md-4 tarjeta1">
<h1>Pedido: </h1>
<p>Fecha: {{ op.fecha }}</p>
<p>Cliente: {{ op.cliente }}</p>
<p>Tipo OP: {{ op.tipoop }}</p>
<p>% Facturado: {{ op.fact }}</p>
<p>Condicion de pago: {{ op.condicion }}</p>
<p>Despacho: {{ op.despacho }}</p>
<p>Vendedor: {{ op.vendedor }}</p>
<p><a class="light bg-dark col-2" href="#">Archivo OP</a></p>
<p><a class="light bg-dark col-2" href="#">Proforma (1)</a></p>
<p><a class="light bg-dark col-2" href="#">Proforma (2)</a></p>
</article>
<article class="col-12 col-sm-6 col-md-4 tarjeta2">
{{ form.as_p }}
<input type="submit" value="GUARDAR">
</article>
<article class="col-12 col-sm-6 col-md-4 tarjeta3">
<h1>Remitos:</h1>
<p>Fecha: {{ op.fecharem1 }}</p>
<p>NΒ° Remito: {{ op.nrem1 }}(1)</p>
<p><a class="light bg-dark col-2" href="#">Remito 1</a></p>
<p>Fecha: {{ op.fecharem2 }} </p>
<p>NΒ° Remito (2): {{ op.nrem2 }}</p>
<p><a class="light bg-dark col-2" href="#">Remito 2</a></p>
<p><a href="{% url 'editr' pk=op.opid %}" >Editar</a></p>
</article>
</div>
</main>
</code></pre>
|
<p>on <code>editar_pedido</code> change the return to this :</p>
<pre><code>return redirect(reverse('pedido-detalle', kwargs={"pk": pedid.pk}))
</code></pre>
|
python-3.x|django|django-views
| 0 |
1,909,242 | 2,234,056 |
how do I iterate over a "gslist" in Python?
|
<p>Let's say I get a glib <code>gpointer</code> to a glib <code>gslist</code> and would like to iterate over the latter, how would I do it?</p>
<p>I don't even know how to get to the <code>gslist</code> with the <code>gpointer</code> for starters!</p>
<p><strong>Update</strong>: I found a workaround - the python bindings in this instance wasn't complete so I had to find another solution.</p>
|
<p>How is <code>glib</code> exposed to Python in your application? Via SWIG, ctypes or something else? </p>
<p>You should basically use <code>glib</code>'s own functions to iterate over a list. Something like <code>g_slist_foreach</code>. Just pass it the pointer and its other parameters to do the job. Again, this heavily depends on how you access <code>glib</code> in your Python application.</p>
|
python|glib
| 0 |
1,909,243 | 63,199,994 |
Im having trouble creating the last 3 rules for the code
|
<ol>
<li>The first digit must be a 4.</li>
<li>The fourth digit must be one greater than the fifth digit; keep in mind that these
are separated by a dash since the format is ####-####-####.</li>
<li>The sum of all digits must be evenly divisible by 4.</li>
<li>If you treat the first two digits as a two-digit number, and the seventh and eighth
digits as a two-digit number, their sum must be 100.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>def verify(number) :
if input [0] == '4':
return True
if input [0] != '4':
return "violates rule #1"
input = "5000-0000-0000"
output = verify(input)
print(output)
</code></pre>
|
<p>Here is a version that doesn't use if statements:</p>
<pre class="lang-py prettyprint-override"><code>def verifya(number):
'''
It helps to break each part down
Say it out loud several times
Think about what it requires
write out some psuedo code
'''
try:
# https://stackoverflow.com/questions/743806/how-to-split-a-string-into-a-list
assert len(number.split('-')) == 3 \
and all([len(x) == 4
for x in number.split('-')])
# The first digit must be a 4.
# https://stackoverflow.com/questions/32839561/python-how-to-get-first-item-in-list-on-list-in-python3
assert number[0] == '4'
# The fourth digit must be one
# greater than the fifth digit;
g1, g2, g3 = number \
.split('-') # split up the string on the
# dashes so we get 5000, 0000, 0000
## keep in mind that these are # separated by a dash since the format is ####-####-####.
assert ((int(g1[-1] # the fourth number
) -\
int(
g2[0] # and
# subtract the 5th
)
# it should be one greater
) == 1)
# The sum of all digits must be evenly divisible by 4.
assert (sum([int(x) for x in y for y in [g1, g2, g3]]) % 4) == 0 # sum all characters and modulo by 4
assert ((int(
# If you treat the first two digits as a two-digit number
g1[:2]) +\
int(
# and the seventh and eighth digits as a two-digit number
g2[-2:]))
# their sum must be 100.
== 100) # https://stackoverflow.com/questions/509211/understanding-slice-notation
except:
return type('Homework', (), {"is": False})
return type('Homework', (), {"is": True})
</code></pre>
<p>You can then run it with:</p>
<pre><code>import pdb
pdb.set_trace()
import sys;print(getattr(verify("5000-0000-0000"), 'is'), file=sys.stdout)
</code></pre>
|
python|function
| 0 |
1,909,244 | 28,245,853 |
Django How to get a one variable from a user's list?
|
<p>I have something like this:</p>
<pre><code> a = User.objects.values_list('id', flat=True).order_by('id')
</code></pre>
<p>how can I get a one variable from user's list? </p>
<p>I tried a[0] but it doesn't work :(</p>
|
<p>Use the <a href="https://docs.djangoproject.com/en/1.7/ref/models/querysets/#first" rel="nofollow"><code>first()</code></a> method:</p>
<pre><code>a = User.objects.values_list('id', flat=True).order_by('id').first()
</code></pre>
<p>BTW, <code>a[0]</code> should work too. Are you sure that <code>User</code> table contains any records? If this table is empty then <code>first()</code> will return <code>None</code>.</p>
|
python|django|python-2.7
| 0 |
1,909,245 | 44,086,123 |
Concat changes the category type to object / float64
|
<p>If I am reading just a piece of csv I get the following data structure</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
MultiIndex: 100000 entries, (2015-11-01 00:00:00, 4980770) to (2016-06-01 00:00:00, 8850573)
Data columns (total 5 columns):
CHANNEL 100000 non-null category
MCC 92660 non-null category
DOMESTIC_FLAG 100000 non-null category
AMOUNT 100000 non-null float32
CNT 100000 non-null uint8
dtypes: category(3), float32(1), uint8(1)
memory usage: 1.9+ MB
</code></pre>
<p>If I am reading the whole csv and concat the blocks as per above I get the following structure:</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
MultiIndex: 30345312 entries, (2015-11-01 00:00:00, 4980770) to (2015-08-01 00:00:00, 88838)
Data columns (total 5 columns):
CHANNEL object
MCC float64
DOMESTIC_FLAG category
AMOUNT float32
CNT uint8
dtypes: category(1), float32(1), float64(1), object(1), uint8(1)
memory usage: 784.6+ MB
</code></pre>
<p>Why are categorical variables changed to object / float64? How can I avoid this type change? Esp. the float64</p>
<p>This is the concatenation code:</p>
<pre><code>df = pd.concat([process(chunk) for chunk in reader])
</code></pre>
<p>process function is just doing some cleaning and type assignments</p>
|
<p>Consider the following sample DataFrames:</p>
<pre><code>In [93]: df1
Out[93]:
A B
0 a a
1 b b
2 c c
3 a a
In [94]: df2
Out[94]:
A B
0 b b
1 c c
2 d d
3 e e
In [95]: df1.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 2 columns):
A 4 non-null object
B 4 non-null category
dtypes: category(1), object(1)
memory usage: 140.0+ bytes
In [96]: df2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 2 columns):
A 4 non-null object
B 4 non-null category
dtypes: category(1), object(1)
memory usage: 148.0+ bytes
</code></pre>
<p>NOTE: these two DFs have different categories:</p>
<pre><code>In [97]: df1.B.cat.categories
Out[97]: Index(['a', 'b', 'c'], dtype='object')
In [98]: df2.B.cat.categories
Out[98]: Index(['b', 'c', 'd', 'e'], dtype='object')
</code></pre>
<p>when we concatenate them Pandas won't merge categories - it'll create an <code>object</code> column:</p>
<pre><code>In [99]: m = pd.concat([df1, df2])
In [100]: m.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 8 entries, 0 to 3
Data columns (total 2 columns):
A 8 non-null object
B 8 non-null object
dtypes: object(2)
memory usage: 192.0+ bytes
</code></pre>
<p>But if we concatenate two DFs with the same categories - everything works as expected:</p>
<pre><code>In [102]: m = pd.concat([df1.sample(frac=.5), df1.sample(frac=.5)])
In [103]: m
Out[103]:
A B
3 a a
0 a a
3 a a
2 c c
In [104]: m.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 4 entries, 3 to 2
Data columns (total 2 columns):
A 4 non-null object
B 4 non-null category
dtypes: category(1), object(1)
memory usage: 92.0+ bytes
</code></pre>
|
python|pandas|dataframe|categorical-data
| 2 |
1,909,246 | 32,610,511 |
RabbitMQ, delivery tag value and message order after reconnect
|
<p>I use pika for python to communicate with RabbitMQ. I have 6 threads, which consume and acknowledge messages from the same queue. I use different connections(and channels) for each thread. So i have a few questions very close to each other:</p>
<ol>
<li><p>If connection to rabbit will close in 1 of the thread, and i will make reconnect, delivery tag value will reset and after reconnect it will start from 0?</p></li>
<li><p>After reconnect i will receive same unacknowledged messages in the same order for each thread or it will start distribute them again between all threads or it will start from reconnect point?</p></li>
</ol>
<p>It is important in my app, because there is delay between message receiving and acknowledgement, and i want to avoid duplicates on the next process steps. </p>
|
<ol>
<li><p>Delivery tag are channel-specific and server assigned. See details in <a href="https://www.rabbitmq.com/resources/specs/amqp-xml-doc0-9-1.pdf" rel="nofollow noreferrer">AMQP spec, section 1.1.
AMQPΒdefined Domains</a> or <a href="https://www.rabbitmq.com/amqp-0-9-1-reference.html#domain.delivery-tag" rel="nofollow noreferrer">RabbitMQ's documentation </a> for <code>delivery-tag</code>. RabbitMQ initial value for <code>delivery-tag</code> is <code>1</code>, </p>
<blockquote>
<p>Zero is reserved for client use, meaning "all messages so far received".</p>
</blockquote></li>
<li><p>With multiple consumers on a single queue there are no guarantee that consumers will get messages in the same order they was queued. See RabbitMQ's <a href="https://www.rabbitmq.com/semantics.html#ordering" rel="nofollow noreferrer">Broker Semantics, "Message ordering guarantees" paragraph</a> for details:</p>
<blockquote>
<p>Section 4.7 of the AMQP 0-9-1 core specification explains the conditions under which ordering is guaranteed: messages published in one channel, passing through one exchange and one queue and one outgoing channel will be received in the same order that they were sent. RabbitMQ offers stronger guarantees since release 2.7.0.</p>
<p>Messages can be returned to the queue using AMQP methods that feature a requeue parameter (basic.recover, basic.reject and basic.nack), or due to a channel closing while holding unacknowledged messages. Any of these scenarios caused messages to be requeued at the back of the queue for RabbitMQ releases earlier than 2.7.0. From RabbitMQ release 2.7.0, messages are always held in the queue in publication order, even in the presence of requeueing or channel closure.</p>
<p>With release 2.7.0 and later it is still possible for individual consumers to observe messages out of order if the queue has multiple subscribers. This is due to the actions of other subscribers who may requeue messages. From the perspective of the queue the messages are always held in the publication order.</p>
</blockquote>
<p>Also, see <a href="https://stackoverflow.com/a/21363518/1461984">this answer for "RabbitMQ - Message order of delivery" question</a>.</p></li>
</ol>
|
python|rabbitmq|pika
| 5 |
1,909,247 | 32,878,878 |
Unable to download files from NLTK
|
<p>I am trying to run the below code:</p>
<pre><code>import nltk
nltk.download()
</code></pre>
<p>I get the NLTK downloader where I select Corpora tab and try to download wordnet (or any other file) I am getting the below error</p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 495, in callit
func(*args)
File "C:\Python27\lib\site-packages\nltk\downloader.py", line 1914, in _monitor_message_queue
self._select(msg.package.id)
AttributeError: 'unicode' object has no attribute 'id'
Process finished with exit code -805306369 (0xCFFFFFFF)
</code></pre>
<p>and</p>
<pre><code><urlopen error [Errno 10109] getaddrinfo failed>
</code></pre>
<p>I believe it's a network issue, how can I resolve it? (Just an FYI, I can connect to the internet and browse normally)</p>
|
<p>I recommend that you avoid Tkinter. You can install corpora from the command line like this <code>sudo python nltk.downloader wordnet</code>. To download all corpora required for using the book, do <code>python nltk.downloader book</code>.</p>
|
python|nltk
| 0 |
1,909,248 | 14,050,431 |
how to change the python's stdin buffer size?
|
<p>I use python's stdin to recv message from other process</p>
<p>but want to change the stdin buff size for fast recv message</p>
<p>I know the subprocee can set the stdin buff when open a subprocess process</p>
<p>but One of my process is a c process whice send message</p>
<p>the other is a python process which recv message</p>
<p>how can i change the stdin buff size in python?</p>
<p>my host is a linux machine..</p>
|
<p>From <a href="https://stackoverflow.com/a/3670470/1287112">an answer to a similar question</a>:</p>
<blockquote>
<p>You can completely remove buffering from stdin/stdout by using python's -u flag:</p>
<pre><code>-u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)
see man page for details on internal buffering relating to '-u'
</code></pre>
<p>and the man page clarifies:</p>
<pre><code> -u Force stdin, stdout and stderr to be totally unbuffered. On
systems where it matters, also put stdin, stdout and stderr in
binary mode. Note that there is internal buffering in xread-
lines(), readlines() and file-object iterators ("for line in
sys.stdin") which is not influenced by this option. To work
around this, you will want to use "sys.stdin.readline()" inside
a "while 1:" loop.
</code></pre>
</blockquote>
<p>Other than that, it is not (well or widely) supported.</p>
|
python|linux|stdin
| 0 |
1,909,249 | 34,625,208 |
PyQt: hover and click events for graphicscene ellipse
|
<p>I'd like to find out if a user hovers over or clicks a GraphicsScene shape object (for example, the ellipse object I commented below). I'm new to PyQt and the documentation is much better for C++ than Python, so I'm having a bit of trouble figuring this one out.</p>
<pre><code>from PyQt4 import QtGui, QtCore
class MyFrame(QtGui.QGraphicsView):
def __init__( self, parent = None ):
super(MyFrame, self).__init__(parent)
self.setScene(QtGui.QGraphicsScene())
# add some items
x = 0
y = 0
w = 45
h = 45
pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.green))
brush = QtGui.QBrush(pen.color().darker(150))
# i want a mouse over and mouse click event for this ellipse
item = self.scene().addEllipse(x, y, w, h, pen, brush)
item.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
if ( __name__ == '__main__' ):
app = QtGui.QApplication([])
f = MyFrame()
f.show()
app.exec_()
</code></pre>
<p>Update!!!</p>
<p>Now I can get an event to take place based on a mouse click release. Unfortunately, only the last item I create can respond to events. What's going on here?</p>
<pre><code>from PyQt4 import QtGui, QtCore
class MyFrame(QtGui.QGraphicsView):
def __init__( self, parent = None ):
super(MyFrame, self).__init__(parent)
self.setScene(QtGui.QGraphicsScene())
# add some items
x = 0
y = 0
w = 20
h = 20
pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.green))
brush = QtGui.QBrush(pen.color().darker(150))
# i want a mouse over and mouse click event for this ellipse
for xi in range(10):
for yi in range(10):
item = callbackRect(x+xi*30, y+yi*30, w, h)
item.setAcceptHoverEvents(True)
item.setPen(pen)
item.setBrush(brush)
self.scene().addItem(item)
# item = self.scene().addEllipse(x, y, w, h, pen, brush)
item.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
class callbackRect(QtGui.QGraphicsRectItem):
'''
Rectangle call-back class.
'''
def mouseReleaseEvent(self, event):
# recolor on click
color = QtGui.QColor(180, 174, 185)
brush = QtGui.QBrush(color)
QtGui.QGraphicsRectItem.setBrush(self, brush)
return QtGui.QGraphicsRectItem.mouseReleaseEvent(self, event)
def hoverMoveEvent(self, event):
# Do your stuff here.
pass
if ( __name__ == '__main__' ):
app = QtGui.QApplication([])
f = MyFrame()
f.show()
app.exec_()
</code></pre>
<p><a href="https://i.stack.imgur.com/2ueH5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2ueH5.png" alt="Screen shot of only last item created being 'eventable'."></a></p>
|
<p>You can define your own ellipse class and replace both click and hover events:</p>
<pre><code>class MyEllipse(QtGui.QGraphicsEllipseItem):
def mouseReleaseEvent(self, event):
# Do your stuff here.
return QtGui.QGraphicsEllipseItem.mouseReleaseEvent(self, event)
def hoverMoveEvent(self, event):
# Do your stuff here.
pass
</code></pre>
<p>Usage:</p>
<pre><code>item = MyEllipse(x, y, w, h)
item.setAcceptHoverEvents(True)
item.setPen(pen)
item.setBrush(brush)
self.scene().addItem(item)
</code></pre>
<p>Hope it helps!</p>
|
python|pyqt4
| 2 |
1,909,250 | 12,097,568 |
What is the most efficient way of updating data in a MySQL table using Python avoiding loops?
|
<p>What is the best way to format data? </p>
<p>Here is the background :</p>
<p>I am using <a href="http://code.google.com/p/python-nameparser/" rel="nofollow">nameparser</a> to parse a name the best way possible. I built a wrapper that calls the nameparser and then stores the parsed name in the database (MySQL).</p>
<p>What would be the most efficient approach in this case? Following is my approach.</p>
<ol>
<li>Step 1 : call nameparser (provide tablename, id, name, first,
middle, last, suffix). </li>
<li>Step 2 : Store the parsed (returned) name in
a dict of this form in memory (I am parsing relatively small names
set - say 20,000 names). <code>{id:{'first':'John', 'middle':'V',
'last':'Doe', 'suffix':''}</code> </li>
<li>Step 3 : Store the dict in the MySQL
table with one query? (Not sure if it is possible with the data
structure described in Step 2.</li>
</ol>
<p>Here is my code :</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
from nameparser import HumanName
import time
cursor = db.cursor()
def name(table, id, name, first, middle, last, suffix):
cursor.execute('SELECT `' + id + '`,`' + name + '` FROM `' + table
+ '` WHERE `' + name + '` IS NOT NULL AND ' + id
+ ' IS NOT NULL')
numrows = int(cursor.rowcount)
namelist = []
namelist = cursor.fetchall()
for record in namelist:
parsed = HumanName(record[1])
parsed.capitalize()
mydict[int(record[0])] = {
'first': str(parsed.first),
'middle': str(parsed.middle),
'last': str(parsed.last),
'suffix': str(parsed.suffix),
}
mydict = {}
starttime = time.time()
split = name('NamesToParse','id','name','first','middle','last','suffix')
print mydict
print time.time() - starttime
</code></pre>
<p>Please suggest the best way of storing the data in the MySQL table. This is what I have so far and I still have to loop through each record. I am wondering if there is a way to <code>update</code> the existing table rather than having to create a temp table first and then updating the original table in one go? Hope I made sense. </p>
<pre><code>for id, val in mydict.items():
sorted_keys = sorted(map(str, val.keys()))
sorted_vals = map(encoding, [val[mydict] for mydict in sorted_keys]) # sorted by keys
formatted = ', '.join(["'%s'"] * len(sorted_vals))
db.execute("""insert into NamesToParseOut(%s) values (%s)""" % (', '.join(sorted_keys), formatted), sorted_vals)
</code></pre>
|
<p>Looks like I will take the List of tuples approach and insert in a temp table first followed by updating them with the original table. The time savings are amazing. I feel dictionary is an overkill for this task.</p>
<pre><code>mylistoftuples.append((int(record[0]), str(parsed.first),str(parsed.middle),str(parsed.last),str(parsed.suffix)))
cursor.executemany("""insert into NamesToParseOut(id, first, middle, last, suffix) values (%s, %s, %s, %s, %s)""", mylistoftuples)
</code></pre>
|
python|mysql|dictionary
| 0 |
1,909,251 | 23,256,226 |
What is the difference between the InRange method in opencv with python/cv2 and c#/emgu?
|
<p>I'm trying to convert a small opencv python script to emgu with C#.</p>
<p>In python the code</p>
<pre><code>COLOR_MIN = np.array([104, 34, 255], np.uint8)
COLOR_MAX = np.array([124, 34, 255], np.uint8)
frame_threshed = cv2.inRange(hsv_img, COLOR_MIN, COLOR_MAX)
cv2.imshow("frame thresh", frame_threshed)
</code></pre>
<p>correctly thresholds the image which is displayed by cv2.imshow.</p>
<p>I've converted the code to C# as follows:</p>
<pre><code>var min = new Hsv(104, 34, 255);
var max = new Hsv(124, 34, 255);
var thresh = hsvImg.InRange(min, max);
CvInvoke.cvShowImage("thresh", thresh);
</code></pre>
<p>Here only a black image is drawn - so nothing seems to be matching the threshold.</p>
<p>In both cases I'm using the same .PNG file as input. I wrote the python code on osx and the .net code is running inside a win8 VM - could this be something to do with color profiles?</p>
<p>Any tips or things to try to get the .NET version working would be greatly appreciated!! Thanks!</p>
|
<p>The issue seems to be I'm using an older version of emgu, and was going by the 2.4 docs for emgu in which the above should work.</p>
<p>In the version I'm using (2.2), the following works:</p>
<pre><code>var min = new Hsv(103, 33, 254);
var max = new Hsv(125, 35, 256);
var thresh = hsvImg.InRange(min, max);
CvInvoke.cvShowImage("thresh", thresh);
</code></pre>
<p>instead of checking by <= and >= it's using < and >.</p>
<p>It's my fault for accidentally clicking the wrong package in NuGet... more reason to always use the command line ;).</p>
|
c#|python|opencv|emgucv
| 1 |
1,909,252 | 7,974,883 |
Optimise comparison between two lists, giving indices that differ
|
<p>I have three lists: old, new and ignore. old and new are lists of strings. ignore is a list of indices that should be ignored if they do not match. The objective is to create a list of indices which are different and not ignored.</p>
<p>old and new may contain a different number of elements. If there is a difference in size between old and new the difference should be marked as not matching (unless ignored).</p>
<p>My current function is as follows:</p>
<pre><code>def CompareFields( old, new, ignore ):
if ( old == None ):
if ( new == None ):
return [];
else:
return xrange( len(new) )
elif ( new == None ):
return xrange( len(old) )
oldPadded = itertools.chain( old, itertools.repeat(None) )
newPadded = itertools.chain( new, itertools.repeat(None) )
comparisonIterator = itertools.izip( xrange( max( len(old ) , len( new ) ) ), oldPadded, newPadded )
changedItems = [ i for i,lhs,rhs in comparisonIterator if lhs != rhs and i not in ignore ]
return changedItems
</code></pre>
<p>The timings of the various options I have tried give the following timings for 100,000 runs:</p>
<pre><code>[4, 9]
CompareFields: 6.083546
set([9, 4])
Set based: 12.594869
[4, 9]
Function using yield: 13.063725
[4, 9]
Use a (precomputed) ignore bitmap: 7.009405
[4, 9]
Use a precomputed ignore bitmap and give a limit to itertools.repeat(): 8.297951
[4, 9]
Use precomputed ignore bitmap, limit padding and itertools.starmap()/operator.ne(): 11.868687
[4, 9]
Naive implementation: 7.438201
</code></pre>
<p>The latest version of python I have is 2.6 (it is RHEL5.5). I am currently compiling Pypy to give that a try.</p>
<p>So does anyone have any ideas how to get this function to run faster? Is it worth using Cython?</p>
<p>If I can't get it to run faster I will look at rewriting the whole tool in C++ or Java.</p>
<p><strong>Edit:</strong></p>
<p>Ok I timed the various answers:</p>
<pre><code>[4, 9]
CompareFields: 5.808944
[4, 9]
agf's itertools answer: 4.550836
set([9, 4])
agf's set based answer, but replaced list expression with a set to avoid duplicates: 9.149389
agf's set based answer, as described in answer: about 8 seconds
lucho's set based answer: 10.682579
</code></pre>
<p>So itertools seems to be the way to go for now. It is surprising that the set based solution performed so poorly. Although I am not surprised that using a lambda was slower.</p>
<p><strong>Edit:</strong> Java benchmark
Naive implementation, with way too many if statements: 128ms</p>
|
<p>For both of these solutions, you should do:</p>
<pre><code>ignore = set(ignore)
</code></pre>
<p>which will give you constant (average) time <code>in</code> tests.</p>
<p>I think this is the <code>itertools</code> / <code>zip</code> based method you were looking for:</p>
<pre><code>[i for i, (o, n) in enumerate(izip_longest(old, new))
if o != n and i not in ignore]
</code></pre>
<p>No need for <code>chain</code> / <code>repeat</code> to pad -- that's what <code>izip_longest</code> is for. <code>enumerate</code> is also more appropriate than <code>xrange</code>.</p>
<p>And a more Pythonic (and possibly faster) version of the <code>filter</code> / set difference method in Lucho's answer:</p>
<pre><code>[i for i, v in set(enumerate(new)).symmetric_difference(enumerate(old))
if i not in ignore]
</code></pre>
<p>List comprehensions are preferred over <code>filter</code> or <code>map</code> on a <code>lambda</code>, and there is no need to convert both lists to <code>set</code>s if you use the <code>symmetric_difference</code> method instead of the <code>^</code> / xor operator.</p>
|
python|list|optimization
| 4 |
1,909,253 | 8,114,916 |
Is there a way to "compile" Python code onto an Arduino (Uno)?
|
<p>I have a robotics type project with an <a href="http://arduino.cc/en/Main/ArduinoBoardUno">Arduino Uno</a>, and to make a long story short, I am experimenting with some AI algorithms. However, I need to implement some high level matrix algorithms that would be quite simple using <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a>/<a href="http://en.wikipedia.org/wiki/SciPy">SciPy</a>, but they are an utter nightmare in C or C++. Even with the libraries out there, this is just getting ridiculous.</p>
<p>Is there any way I can do this project in Python? I think I heard something about the <a href="http://arduino.cc/en/Main/ArduinoBoardMega">Mega</a> having this capability, but I have an Uno, and replacing it is not an option at this point (that would set the project back quite a bit.) Also, I heard somethings about using Python to communicate to the Arduino via USB, but I cannot have the USB cable in while the thing is running. I need to be able to upload the program and be done with it.</p>
<p>Are there any options out there, or have I just reached a dead end?</p>
|
<p>There was a talk about using Python with robotics at this years <a href="http://pycon-au.org/2011/about/">PyConAU</a> called <a href="http://www.youtube.com/user/PyConAU#p/u/17/nzCvomTixzU"><em>Ah! I see you have the machine that goes 'BING'!</em></a> by Dr. Graeme Cross.</p>
<p>The only option he recommended for using Python on a microcontroller board was <a href="http://wiki.python.org/moin/PyMite">PyMite</a> which I think also goes by the name of <a href="http://code.google.com/p/python-on-a-chip/">Python-On-A-Chip</a>. </p>
<p>It has been ported to a range of boards - specifically he mentions the Arduino Mega which you said is not an option for you, but it is possible it is supported on other Arduino boards.</p>
<p>However, because it is a "batteries not included" version of Python it is more than likely that you will have a real problem getting numpy/scipy etc up and running.</p>
<p>As other posters have suggested, implementing in C might be the path of least resistence.</p>
<p><em>Update:</em> again, not specifically for Arduino, but <a href="http://www.pymcu.com/overview.html">pyMCU</a> looks to provide python on a chip. The author states he may look at developing an Arduino version of pyMCU if there is enough interest.</p>
|
python|arduino|pyserial
| 22 |
1,909,254 | 529,240 |
What happened to types.ClassType in python 3?
|
<p>I have a script where I do some magic stuff to dynamically load a module, and instantiate the first class found in the module. But I can't use <code>types.ClassType</code> anymore in Python 3. What is the correct way to do this now?</p>
|
<p>I figured it out. It seems that classes are of type "type". Here is an example of how to distinguish between classes and other objects at runtime.</p>
<pre><code>>>> class C: pass
...
>>> type(C)
<class 'type'>
>>> isinstance(C, type)
True
>>> isinstance('string', type)
False
</code></pre>
|
class|types|python-3.x
| 22 |
1,909,255 | 906,649 |
How do I inspect the scope of a function where Python raises an exception?
|
<p>I've recently discovered the very useful '-i' flag to Python</p>
<pre>
-i : inspect interactively after running script, (also PYTHONINSPECT=x)
and force prompts, even if stdin does not appear to be a terminal
</pre>
<p>this is great for inspecting objects in the global scope, but what happens if the exception was raised in a function call, and I'd like to inspect the local variables of the function? Naturally, I'm interested in the scope of where the exception was first raised, is there any way to get to it?</p>
|
<p>At the interactive prompt, immediately type</p>
<pre><code>>>> import pdb
>>> pdb.pm()
</code></pre>
<p>pdb.pm() is the "post-mortem" debugger. It will put you at the scope where the exception was raised, and then you can use the usual pdb commands.</p>
<p>I use this <em>all the time</em>. It's part of the standard library (no ipython necessary) and doesn't require editing debugging commands into your source code.</p>
<p>The only trick is to remember to do it right away; if you type any other commands first, you'll lose the scope where the exception occurred.</p>
|
python|debugging
| 7 |
1,909,256 | 1,077,393 |
Python Unix time doesn't work in Javascript
|
<p>In Python, using calendar.timegm(), I get a 10 digit result for a unix timestamp. When I put this into Javscript's setTime() function, it comes up with a date in 1970. It evidently needs a unix timestamp that is 13 digits long. How can this happen? Are they both counting from the same date? </p>
<p>How can I use the same unix timestamp between these two languages?</p>
<p>In Python:</p>
<pre><code>In [60]: parseddate.utctimetuple()
Out[60]: (2009, 7, 17, 1, 21, 0, 4, 198, 0)
In [61]: calendar.timegm(parseddate.utctimetuple())
Out[61]: 1247793660
</code></pre>
<p>In Firebug:</p>
<pre><code>>>> var d = new Date(); d.setTime(1247793660); d.toUTCString()
"Thu, 15 Jan 1970 10:36:55 GMT"
</code></pre>
|
<p>timegm is based on Unix's <a href="http://linux.about.com/library/cmd/blcmdl3_gmtime.htm" rel="noreferrer">gmtime()</a> method, which return seconds since Jan 1, 1970.</p>
<p>Javascripts <a href="http://www.w3schools.com/jsref/jsref_setTime.asp" rel="noreferrer">setTime()</a> method is milliseconds since that date. You'll need to multiply your seconds times 1000 to convert to the format expected by Javascript.</p>
|
javascript|python|datetime|utc|unix-timestamp
| 11 |
1,909,257 | 418,835 |
Are there any graph/plotting/anything-like-that libraries for Python 3.0?
|
<p>As per the title. I am trying to create a simple scater plot, but haven't found any Python 3.0 libraries that can do it. Note, this isn't for a website, so the web ones are a bit useless.</p>
|
<p>The GChartWrapper (<a href="http://pypi.python.org/pypi/GChartWrapper/0.7" rel="nofollow noreferrer">http://pypi.python.org/pypi/GChartWrapper/0.7</a>) does work for py3k</p>
|
python|python-3.x|plot|graphing|scatter-plot
| 1 |
1,909,258 | 41,732,909 |
Download csv file with date using python
|
<p>This is the <a href="http://wesm.ph/chart/export/luzon_dmd_csv_export.php?date=20160115&hour=24" rel="nofollow noreferrer">link</a> that I need to download.</p>
<p>My problem is the date. My sample code does not accept this kind of URL. Can you help me on this guys? Thanks! </p>
<pre><code>import urllib2
url = "wesm.ph/chart/export/luzon_dmd_csv_export.php?date=201705&hour=24"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
</code></pre>
|
<pre><code>import requests
r = requests.get('http://wesm.ph/chart/export/luzon_dmd_csv_export.php?date=20160115&hour=24', stream=True)
with open('filename.csv', 'wb') as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
</code></pre>
<p>Just use <code>requests</code></p>
|
python|python-2.7
| 0 |
1,909,259 | 41,991,943 |
Yet another encoding issue with accented characters (scraping a Website with Python and BeautifulSoup)
|
<p>(PREFACE: I know, this problem has been talked about a hundred of times, but I still don't understand it)</p>
<p>I am trying to load a html-page and output the text, even though I am getting the webpage correctly, BeautifulSoup destroys somehow the encoding of accented characters which are not part of the first 127 ASCII-characters: </p>
<pre><code># -*- coding: utf-8 -*-
import sys
from urllib import urlencode
from urlparse import parse_qsl
import re
import urlparse
import json
import urllib
from bs4 import BeautifulSoup
url = "http://www.rtve.es/alacarta/interno/contenttable.shtml?ctx=29010&locale=es&module=&orderCriteria=DESC&pageSize=15&mode=TEXT&seasonFilter=40015"
html=urllib2.urlopen(url).read()
soup = BeautifulSoup(html)
div = soup.find_all("span", class_="detalle")
capitulo_detalle = div[0].text (doesn't work, capitulo_detalle is type str with utf-8, div[0].tex is type unicode)
</code></pre>
<p>Output of <code>div[0].text</code> should be something like: </p>
<p>S<strong>Γ‘</strong>tur se dirige al sur en busca de Estuarda y Gabi, pero un compa<strong>Γ±</strong>ero de viaje inesperado har<strong>Γ‘</strong> que cambie de rumbo. Los hombres de Juan siguen presos. El enemigo comienza a realizar ejecuciones. <strong>Γ</strong>guila Roja tiene...</p>
<p>But the result I get is: </p>
<p>u'S\xe1tur se dirige al sur en busca de Estuarda y Gabi, pero un compa\xf1ero de
viaje inesperado har\xe1 que cambie de rumbo. Los hombres de Juan siguen presos
. El enemigo comienza a realizar ejecuciones. \xc1guila Roja tiene...'</p>
<p><strong>--> What do I have to change to get the 'right' characters?</strong> </p>
<p>I know it must be a duplicate of these questions, but the answers doesn't seem to work here:
<a href="https://stackoverflow.com/questions/7219361/python-and-beautifulsoup-encoding-issues">Python and BeautifulSoup encoding issues</a>
<a href="https://stackoverflow.com/questions/20205455/how-to-correctly-parse-utf-8-encoded-html-to-unicode-strings-with-beautifulsoup">How to correctly parse UTF-8 encoded HTML to Unicode strings with BeautifulSoup?</a></p>
<p>I also read the typical documentations about unicode, utf-8, ascii, e.g. <a href="https://docs.python.org/3/howto/unicode.html" rel="nofollow noreferrer">https://docs.python.org/3/howto/unicode.html</a>, obviously without success...</p>
|
<p>I believe I finally got it...</p>
<pre><code>>>> div = soup.find("span", class_="detalle")
>>> div.text
u'S\xe1tur se dirige al sur en busca de Estuarda y Gabi, pero
</code></pre>
<p>---> this is unicode, \xe1 is the 'code' for 'Γ‘' (<a href="http://www.utf8-chartable.de/unicode-utf8-table.pl?start=4096&number=128&names=-&utf8=string-literal" rel="nofollow noreferrer">http://www.utf8-chartable.de/unicode-utf8-table.pl?start=4096&number=128&names=-&utf8=string-literal</a>)</p>
<pre><code>>>> print(div.text)
SΓ‘tur se dirige al sur en busca de Estuarda y Gabi, pero
</code></pre>
<p>---> 'print' evaluates the unicode code point correctly</p>
<pre><code>>>> div.text.encode('utf-8')
'S\xc3\xa1tur se dirige al sur en busca de Estuarda y Gabi, pero
</code></pre>
<p>---> Unicode is encoded to utf-8 according to the table given on the url cited above. I didn't understand why the output is shown as \xc3\xa1 and not as 'Γ‘'. </p>
<pre><code>>>> print div.text.encode('utf-8')
SβΓtur se dirige al sur en busca de Estuarda y Gabi, pero
</code></pre>
<p>---> and I didn't understand why print now evaluates it to a strange symbol....</p>
<pre><code>>>> blurr = div.text.encode('cp850')
>>> blurr
'S\xa0tur se dirige al sur en busca de Estuarda y Gabi, pero
>>> type(blurr)
<type 'str'>
</code></pre>
<p>---> Unicode encoded to codepage 850, used within the python-shell under Windows</p>
<pre><code>>>> print(blurr)
SΓ‘tur se dirige al sur en busca de Estuarda y Gabi, pero
</code></pre>
<p>---> Finally, it's right !!! </p>
<p>In Kodi I can use the utf-8 representation, so that e.g. the character 'Γ‘' is saved within the variable as \xc3\xa1, but when the content of the variable is displayed for example with "xbmcgui.Dialog().ok(addonname, blurr) it is shown correctly on the screen with an 'Γ‘'......</p>
<p>Und sowas soll man wissen......</p>
|
python|unicode|utf-8|character-encoding|beautifulsoup
| 0 |
1,909,260 | 47,258,520 |
Django HTML template to pdf consisting JS (Vue.js) charts and graphs
|
<p>I am trying to generate a PDF from Html page. The Html includes various data returned from django view and also from Vue.js</p>
<p>I tried using 'Weasyprint' but it only generated data that returned from Django but not the charts and graphs that were generated from Vue. What will be an easy way to generate all the data as well as the graphs in PDF from the Html page.</p>
|
<p>To generate a PDF with those charts, you will need to render the web-page first (in a browser) in order to run the client-side code and use that "result" to generate the final PDF. </p>
<p>It will depend on where you want to generate that PDF (on the server or on the client). In case it is on the server, one possible solution is to use <code>phantomJS</code> (or other similar projects) to render and save the result in a file with <a href="http://phantomjs.org/api/webpage/method/render.html" rel="nofollow noreferrer"><code>render()</code></a>.</p>
|
javascript|python|html|django|pdf
| 0 |
1,909,261 | 47,399,102 |
Loop through dict's inner list, add missing month
|
<p>I've been struggling with how to loop through a list, adding 0 for the missing months back in to the original dictionary. I am thinking to create a list of months, from <code>calendar</code>, loop through each of those, then loop through each month in my data...but can't quite figure out how to update the dictionary when there's a missing month in correct order.</p>
<pre><code>import calendar
my_dict = {'Green Car':
[('January', 340),
('February', 2589),
('March', 12750),
('April', 114470),
('July', 4935),
('August', 1632),
('September', 61),
('December', 3409)],
'Red Truck':
[('January', 2325185),
('February', 209794),
('March', 201874),
('April', 19291),
('May', 18705),
('July', 22697),
('August', 22796)],
'Police Car':
[('January', 2037),
('February', 2620),
('March', 1480),
('April', 15630),
('July', 40693),
('August', 2329)],
'Zamboni':
[('January', 256),
('February', 426690),
('March', 589),
('April', 4740),
('May', 880),
('July', 1016),
('August', 106),
('September', 539),
('October', 598),
('November', 539),
('December', 470)],
'Witch Broom':
[('February', 350),
('March', 3520),
('October', 2703),
('November', 2221),
('December', 664)]
}
def fill_months(reported_months):
const_months = list(calendar.month_name)
x = 0
print("Looking for months in", reported_months)
# print(const_months)
for const_month in const_months:
for month in reported_months:
if const_month != month[0] and len(const_month) > 0:
print(const_month, month[0])
print("You don't have", const_month, "in the months group:", reported_months)
def main():
for commod, months in my_dict.items():
# print(commod)
# print(commod, months)
fill_months(months)
if __name__ == '__main__':
main()
</code></pre>
<p>For each key ("Green Car", "Red Truck", etc.) I want to loop through and add in a missing moth with the value <code>0</code>. So the "Green Car" in the end would turn out to be:</p>
<pre><code>my_dict = {'Green Car':
[('January', 340),
('February', 2589),
('March', 12750),
('April', 114470),
('May', 0),
('June', 0),
('July', 4935),
('August', 1632),
('September', 61),
('October', 0),
('November', 0),
('December', 3409)],
</code></pre>
<hr>
<p>I'm getting somewhere with this - but the logic feels kind of kludgy:</p>
<pre><code>def fill_months(reported_months):
const_months = list(calendar.month_name)
x = 0
temp_months = []
for i in reported_months:
temp_months.append(i[0])
print("Looking for months in", reported_months)
# print(const_months)
for const_month in const_months:
if len(const_month) > 0:
if const_month not in temp_months:
reported_months.insert(x-1, (const_month, 0))
x += 1
print(reported_months)
</code></pre>
|
<p>This will add the months to your list and then sort the monthlists </p>
<pre><code># remove the leading empty '' from calendar.month_name list
monthnames = [x for x in calendar.month_name if x != '']
# scan dicts for missing monts, if found, append tuple (monthname,0) to list
for part in my_dict:
print(part)
for month in monthnames:
if not month in [x[0] for x in my_dict[part]]:
my_dict[part].append( (month,0) )
# modified https://stackoverflow.com/questions/10695139/sort-a-list-of-tuples-by-2nd-item-integer-value
# interrate through dict, assign sorted dict, use indexlookup into monthlist for sorting
for part in my_dict:
my_dict[part] = sorted(my_dict[part], key=lambda x: monthnames.index(x[0]))
print(my_dict)
</code></pre>
<p>Output:</p>
<pre><code>{'Red Truck'
: [('January', 2325185)
,( 'February', 209794)
,( 'March', 201874)
,( 'April', 19291)
,( 'May', 18705)
,( 'June', 0)
,( 'July', 22697)
,( 'August', 22796)
,( 'September', 0)
,( 'October', 0)
,( 'November', 0)
,( 'December', 0)],
'Witch Broom'
: [('January', 0)
,( 'February', 350)
,( 'March', 3520)
,( 'April', 0)
,( 'May', 0)
,( 'June', 0)
,( 'July', 0)
,( 'August', 0)
,( 'September', 0)
,( 'October', 2703)
,( 'November', 2221)
,( 'December', 664)],
'Police Car'
: [('January', 2037)
,( 'February', 2620)
,( 'March', 1480)
,( 'April', 15630)
,( 'May', 0)
,( 'June', 0)
,( 'July', 40693)
,( 'August', 2329)
,( 'September', 0)
,( 'October', 0)
,( 'November', 0)
,( 'December', 0)],
'Green Car'
: [('January', 340)
,( 'February', 2589)
,( 'March', 12750)
,( 'April', 114470)
,( 'May', 0)
,( 'June', 0)
,( 'July', 4935)
,( 'August', 1632)
,( 'September', 61)
,( 'October', 0)
,( 'November', 0)
,( 'December', 3409)],
'Zamboni'
: [('January', 256)
,( 'February', 426690)
,( 'March', 589)
,( 'April', 4740)
,( 'May', 880)
,( 'June', 0)
,( 'July', 1016)
,( 'August', 106)
,( 'September', 539)
,( 'October', 598)
,( 'November', 539)
,( 'December', 470)]}
</code></pre>
|
python|python-3.x|dictionary
| 1 |
1,909,262 | 47,195,688 |
Interactive Video using Python
|
<p>I was just wondering if making an interactive video in Python 3.6 would be possible? I looked at options for actually inputting videos into Tkinter using python-gstreamer but I couldn't get it to work. </p>
<p>So could anyone suggest a way and explain how to get a video to play in Python? So perhaps there could be a Tkinter window and this video could be displayed in this frame?</p>
<p>If Python isn't possible any other ideas are welcome.</p>
<p>Thank you</p>
|
<p>You can try this with the Video widget in a jupyter notebook: </p>
<pre class="lang-py prettyprint-override"><code>from ipywidgets import Video, Image
from IPython.display import display
from ipywidgets import Checkbox
fileA= 'videoA.mp4'
fileB= 'videoB.mp4'
video = Video.from_file(fileB)
top_toggle = Checkbox(description='Change Video')
def video_loader(filename):
with open(filename, 'rb') as f:
video.value = f.read()
def video_change(button):
if button['new']:
video_loader(fileA)
else:
video_loader(fileB)
top_toggle.observe(video_change, names='value')
display(top_toggle)
display(video)
</code></pre>
<p>See also here:
<a href="https://github.com/QuantStack/quantstack-talks/blob/master/2018-11-14-PyParis-widgets/notebooks/1.ipywidgets.ipynb" rel="nofollow noreferrer">https://github.com/QuantStack/quantstack-talks/blob/master/2018-11-14-PyParis-widgets/notebooks/1.ipywidgets.ipynb</a></p>
|
python|video|tkinter
| 1 |
1,909,263 | 47,319,355 |
List comprehension Python with multiple control flow
|
<p>I am trying to convert this function:</p>
<pre><code>templist = []
for each in characters:
if each in vowels:
templist.append('v')
elif (each in alphabet) & (each not in vowels):
templist.append('c')
else:
templist.append('?')
characters = templist
print(characters)
</code></pre>
<p>into list comprehension </p>
<pre><code>modified_list = ['v' for each in characters for item in vowels
if item in vowels
else 'c' if (item in alphabet) & (item not in vowels)
else '?']`
</code></pre>
<p>Kinda stuck here! Can't figure out what I am doing wrong.</p>
|
<p>You had several errors in your comprehension syntax. Most of all, you inserted your <code>for</code> clause into the middle of your conditional expression; it has to go at the end of the expression.</p>
<pre><code>modified_list = ['v' if each in vowels else
('c' if each in alphabet else '?')
for each in characters]
</code></pre>
<p>I also removed the useless <code>for</code> clauses, and the redundant test for a consonant: when you're in the <code>else</code> clause of your expression, you already know it's not a vowel -- no need to re-test.</p>
<p><strong>FULL TEST</strong></p>
<p>vowels = "aeiou"
alphabet = "qwertyuiopasdfghjklzxcvbnm"
characters = "Now is the time"</p>
<pre><code>templist = []
for each in characters:
if each in vowels:
templist.append('v')
elif (each in alphabet) & (each not in vowels):
templist.append('c')
else:
templist.append('?')
print(" original", ''.join(templist))
modified_list = ['v' if each in vowels else \
('c' if (each in alphabet) else '?') \
for each in characters]
print("comprehension", ''.join(modified_list))
</code></pre>
<p>Output:</p>
<pre><code> original ?vc?vc?ccv?cvcv
comprehension ?vc?vc?ccv?cvcv
</code></pre>
|
python|list-comprehension
| 3 |
1,909,264 | 11,916,737 |
Detect file type from the file contents, not the file name
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python">How to find the mime type of a file in python?</a> </p>
</blockquote>
<p>I want to detect the type of a file, but I don't want to look at the extension because it may be incorrect. The <code>mimetypes</code> module is filename based. </p>
<p>Is there a standard way to peek inside the file? </p>
|
<p>Try installing the <a href="http://pypi.python.org/pypi/python-magic/" rel="noreferrer">python-magic</a> module.</p>
<pre><code> >>> mime = magic.Magic(mime=True)
>>> mime.from_file("testdata/abc.pdf")
'application/pdf'
</code></pre>
|
python
| 7 |
1,909,265 | 11,593,793 |
google app engine (python27) fetch request url
|
<p>I have been trying to get the request url as follows</p>
<pre><code>import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
print self.request.get('url')
app = webapp2.WSGIApplication([('/.*', MainPage)], debug=True)
</code></pre>
<p>when the request is</p>
<pre><code>http://localhost:8080/index.html
</code></pre>
<p>it gives me something like</p>
<pre><code>Status: 200 Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Content-Length: 70
</code></pre>
<p>what I need to get is something like</p>
<pre><code>index.html
</code></pre>
<p><strong>edit:</strong> so that I can check the string and display the correct html/template file accordingly.</p>
<p>I have already checked <a href="https://developers.google.com/appengine/docs/python/tools/webapp/requestclass" rel="nofollow">Request documentation</a> and tried many alternatives yet I can't seem to find a solution. I'm quite new to web development. What am I missing?</p>
|
<p>you should start here: <a href="https://developers.google.com/appengine/docs/python/gettingstartedpython27/helloworld" rel="noreferrer">https://developers.google.com/appengine/docs/python/gettingstartedpython27/helloworld</a></p>
<p>you are not using a template or a templating module/engine so its irrelevant what path you are accessing because you are mapping everything with <code>/.*</code> </p>
<p>use <code>self.response.write()</code> not <code>print</code>.<br>
again its better for you if you start reading the documentation from the beginning before checking out the request class.</p>
<p><strong>EDIT:</strong></p>
<p>if you want to get the urlpath in the requesthandler and serve different templates based on the urlpath then do something like this: </p>
<pre><code>def get(self):
if self.request.path == '/foo':
# here i write something out
# but you would serve a template
self.response.write('urlpath is /foo')
elif self.request.path == '/bar':
self.response.write('urlpath is /bar')
else:
self.response.write('urlpath is %s' %self.request.path)
</code></pre>
<p>a better approach would be to have multiple ReqeustHandlers and map them in the <code>WSGIApplication</code>: </p>
<pre><code>app = webapp2.WSGIApplication([('/', MainPage),
('/foo', FooHandler),
('/bar', BarHandler),
('/.*', CatchEverythingElseHandler)], debug=True)
</code></pre>
|
python|google-app-engine|webapp2
| 6 |
1,909,266 | 33,568,748 |
Pass Raised Error in function to Exception Raised by UnitTest
|
<p>I would like to write a function that raises an error when it fails and then passes that to unittest. Consider the following:</p>
<pre><code>class undefinedTerms(unittest.TestCase):
def setUp(self):
self.A = frozenset((1,2,3,2,1,4,2,5,6,3,5,7,1,5,2,4,8))
self.B = frozenset((1,4,5,6,3,4,2,5,4,3,1,3,4,2,5,3,6,7,4,2,3,1))
self.C = frozenset((1,2,3,2,1,4,2,5,6,3,5,7,1,5,2,4))
self.D = (1,2,1)
def is_a_set(self,set_this):
try:
assert isinstance(set_this, (set,frozenset))
except TypeError:
raise TypeError("The object you passed is not a set.")
return True
def test_A_is_a_set(self):
self.assertTrue(self.is_a_set(self.A))
def test_B_is_a_set(self):
self.assertTrue(self.is_a_set(self.B))
def test_C_is_a_set(self):
self.assertTrue(self.is_a_set(self.C))
def test_D_is_a_set(self):
self.assertTrue(self.is_a_set(self.D), self.is_a_set(self.D))
suite = loader.loadTestsFromTestCase(undefinedTerms)
unittest.TextTestRunner(verbosity=2).run(suite)
</code></pre>
<p>This gives the following output.</p>
<pre><code>test_A_is_a_set (__main__.undefinedTerms) ... ok
test_B_is_a_set (__main__.undefinedTerms) ... ok
test_C_is_a_set (__main__.undefinedTerms) ... ok
test_D_is_a_set (__main__.undefinedTerms) ... FAIL
======================================================================
FAIL: test_D_is_a_set (__main__.undefinedTerms)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<ipython-input-33-4751f8653e7a>", line 27, in test_D_is_a_set
self.assertTrue(self.is_a_set(self.D), self.is_a_set(self.D))
File "<ipython-input-33-4751f8653e7a>", line 12, in is_a_set
(type(set_this) is set))
AssertionError
----------------------------------------------------------------------
Ran 4 tests in 0.001s
FAILED (failures=1)
</code></pre>
<p>What I would like is for the <code>AssertionError</code> to <em>be</em> the <code>TypeError</code> defined in the function. I am open to radically different implementations. </p>
<h2>Update</h2>
<p>I think I was unclear as to precisely what I am after. After reading comments and answers I believe what I want is to create a custom assertion. </p>
<p>This has previously been addressed <a href="https://stackoverflow.com/questions/6655724/how-to-write-a-custom-assertfoo-method-in-python">here</a>.</p>
|
<p>How about using <a href="https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertIsInstance" rel="nofollow"><code>.assertIsInstance()</code></a></p>
<pre><code>def assert_is_set(self, set_this):
self.assertIsInstance(set_this, (set, frozenset))
</code></pre>
<p>At this point, you don't really need a function and can just inline the check.</p>
<p>You can also use the more general <a href="https://docs.python.org/2/library/unittest.html#unittest.TestCase.fail" rel="nofollow"><code>.fail()</code></a> method if your conditions become more complex.</p>
<blockquote>
<p>Signals a test failure unconditionally, with msg or None for the error message</p>
</blockquote>
<pre><code>if something:
self.fail("Computer broken!")
</code></pre>
<p>The documentation page has a <a href="https://docs.python.org/2/library/unittest.html" rel="nofollow">list of all the assertions available</a> in TestCases</p>
|
python|python-unittest
| 1 |
1,909,267 | 46,640,281 |
Using mako for Cisco config generation. Is it possible to use the netaddr module (or any module) in templates?
|
<p>I am very new to python and mako and I may be having trouble with basic concepts. I have working templates but my CSV input could be cleaned up considerably if I could use the netaddr module to work with IP addresses in the template. What I would like to do is pass an interface IP variable like:
LAN_IP = '192.168.1.1/24' (I am doing this from a CSV) to the template and then somehow use the netaddr module to fill in the IP, subnet mask (in dotted decimal and inverse mask) and the network address so I can use that one CSV variable for bgp network statements, eigrp masks and ACLs, etc in the same configuration. I can do the following from a Python shell:</p>
<pre><code>>>> from netaddr import *
>>> LAN_IP = '192.168.1.1/24'
>>> IP = IPNetwork(LAN_IP)
>>> print(IP.ip)
192.168.1.1
>>> print(IP.network)
192.168.1.0
>>> print(IP.netmask)
255.255.255.0
>>> print(IP.hostmask)
0.0.0.255
</code></pre>
<p>EDIT. I was told to try the ipaddress built in fuction. Trying this from a Python prompt shows that it can work:</p>
<pre><code>MAKO_TEMPLATE_STRING = """\
<%def name="get_netmask(ip_string)"><%
import ipaddress
return ipaddress.IPv4Interface(ip_string).netmask
%></%def>
<%def name="get_address(ip_string)"><%
import ipaddress
return ipaddress.IPv4Interface(ip_string).ip
%></%def>
<%def name="get_subnet(ip_string)"><%
import ipaddress
return ipaddress.IPv4Interface(ip_string).network
%></%def>
<%def name="get_hostmask(ip_string)"><%
import ipaddress
return ipaddress.IPv4Interface(ip_string).hostmask
%></%def>
! Variable Input: ${data}
${get_address(data)} ${get_netmask(data)} ${get_subnet(data)} ${get_hostmask(data)}
"""
print(Template(MAKO_TEMPLATE_STRING).render(data="192.168.1.1/25"))
</code></pre>
<p>This gives me the following output:
! Variable Input: 192.168.1.1/25
192.168.1.1 255.255.255.128 192.168.1.0/25 0.0.0.127</p>
<p>Now, a new problem is that the ipaddress.IPv4Interface(ip_string).network definition returns the network PLUS the subnet "192.168.1.0/25" which netaddr did not do. I have not found any way to get ipaddress to return ONLY the subnet portion.</p>
<p>So for the template build I got a bit farther.... If I put ONLY this into the template, it validates:</p>
<pre><code><%def name="get_netmask(ip_string)"><%
import ipaddress
return ipaddress.IPv4Interface(ip_string).netmask
%></%def>
<%def name="get_address(ip_string)"><%
import ipaddress
return ipaddress.IPv4Interface(ip_string).ip
%></%def>
<%def name="get_network(ip_string)"><%
import ipaddress
return ipaddress.IPv4Interface(ip_string).network
%></%def>
</code></pre>
<p>But when I try any type of reference, I get an error.</p>
<pre><code>! Variable Input: ${LAN_IP} <--I tried with and without this line
${get_address(LAN_IP)} <--The template does not seem to like these references.
${get_netmask(LAN_IP)}
${get_subnet(LAN_IP)}
</code></pre>
<p>It seems to me that I am missing something really simple here but maybe I am approaching the problem the wrong way. Any help would be greatly appreciated as the Mako docs and Google have turned up little to illustrate how to do something like this.</p>
|
<p>The problem was with the validation code. Within the python section of the template, the class IPv4Interface will throw an exception due to the invalid value during the validation process. Therefore, the server rejects the form data and the template is not created.</p>
<p>Solution: It would work if you add an error handling to the python section of the template.</p>
<pre><code><%!
## python module-level code
import ipaddress
%>
<%def name="get_address(ip_string)">
<%
try:
return ipaddress.IPv4Interface(ip_string).ip
except Exception:
return "FAIL_OR_EMPTY"
%>
</%def>
! Variable Input: ${LAN_IP}
${get_address(LAN_IP)}
</code></pre>
<p>Explanation: During the server-side validation of the HTML form, the configuration template is rendered with a dummy parameter set to verify the syntax (see file app/forms.py, class ConfigTemplateForm). Your config template is validated with the following parameter set during the form validation:</p>
<pre><code>{
"hostname": "test",
"LAN_IP": "test"
}
</code></pre>
|
python|templates|mako|cisco-ios
| 1 |
1,909,268 | 46,918,968 |
Export data from Python to Excel
|
<p>I'm trying to export data from Python using (<a href="http://jupyter.org/" rel="nofollow noreferrer">http://jupyter.org/</a>) to Excel </p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
df = pd.read_csv('rr.csv')
df['COLLISION_DATE'] = pd.to_datetime(df['COLLISION_DATE'],format='%Y%m%d')
df['week'], df['month'], df['year'],df['day'] = df['COLLISION_DATE'].dt.week, df['COLLISION_DATE'].dt.month, df['COLLISION_DATE'].dt.year,df['COLLISION_DATE'].dt.day
df = df.groupby('month').size().to_frame('Number of Accidents')
df.plot.line()
plt.show()
df
df.to_excel('m.xlsx')
</code></pre>
<p>I'm getting error </p>
<pre><code>ModuleNotFoundError: `No module named 'openpyxl'
</code></pre>
<p>this is my first project using Python Any Idea whats wrong or any other code that I can Use ?</p>
|
<p>I am using Azure notebook (<a href="https://notebooks.azure.com" rel="nofollow noreferrer">https://notebooks.azure.com</a>) which is in an online Jupyter notebook. I tried one my DataFrame which I downloaded from Kaggle to export and seems it's working and below is the code.</p>
<pre><code>import pandas as pd
df = pd.read_csv('/home/nbuser/armenian_pubs.csv')
df.to_excel('data_set_2.xlsx')
</code></pre>
<p>Note that here you need to upload the any data set (CSV) file via Data > Upload menu from local system, then I used the DF to_excel of Panda method to create the Excel with just file name. This creates the file name on the <code>/library</code> folder and from there you can use Data > Download to download the file.</p>
<p><a href="https://i.stack.imgur.com/gMHSq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gMHSq.png" alt="enter image description here"></a></p>
<p>Hope this will help in your scenario.</p>
|
python|excel|pandas|export
| 1 |
1,909,269 | 37,781,066 |
CSV: Counting a string in a column if another column has a certain value
|
<p>I'm having a problem with a csv file where I need some information from. The following is what I need to do:</p>
<p>I have a CSV file that is ordered like this:</p>
<pre><code>bla country bla bla value
Germany Y
Germany Y
Germany N
Denmark N
Denmark N
Denmark Y
</code></pre>
<p>Now what I want to do with python is counting every time the Y value is in the same column. So in the end I get something like Germany:2 Denmark:1. </p>
<p>However I've only been able to figure out how to count the columns using the following code:</p>
<pre><code>import csv
from collections import Counter, defaultdict
from itertools import imap
from operator import itemgetter
header_counter = defaultdict(Counter)
with open('airlines.csv') as input_file:
r = csv.reader(input_file, delimiter=',')
headers = next(r)
for row in r:
row_val = sum([w.isdigit() for w in row])
for header, val in zip(headers, row):
if not any(map(str.isdigit, val)):
header_counter[header].update({val: row_val})
for k, v in header_counter.iteritems():
print k, v
</code></pre>
<p>I donut think the above code is of much use to anyone though as it only counts the rows per columns and filters out integers. Any help I can get is much appreciated I'm still fairly inexperienced.</p>
|
<p>Is this what you're looking for?</p>
<pre><code>import csv
from collections import Counter
data = '''country,value
Germany,Y
Germany,Y
Germany,N
Denmark,N
Denmark,N
Denmark,Y'''
r = csv.DictReader(data.split('\n'))
counter = Counter(
row.get('country')
for row in r
if row.get('value') == 'Y')
for k, v in counter.items():
print('{}: {}'.format(k, v))
</code></pre>
|
python|csv|iteration
| 1 |
1,909,270 | 37,942,714 |
Always getting MalformedPolicyDocument error while trying to create IAM role using Boto3
|
<p>I am using json from the default AWS policy AWSLambdaBasicExecutionRole:</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}
</code></pre>
<p>While this is the code i'm using to create the role:</p>
<pre><code>def create_lambda_role():
205 try:
206 iam = boto3.client('iam')
207
208 lambda_permissions_json = ''
209 with open('lambda/lambda_permissions.json', 'r') as thefile:
210 lambda_permissions_json = thefile.read()
211
212 iam.create_role(
213 RoleName='lambda_basic_execution',
214 AssumeRolePolicyDocument=str(lambda_permissions_json)
215 )
216 except botocore.exceptions.ClientError as e:
217 print e.response['Error']['Code']
218 return False
219
220 return True
</code></pre>
<p>But it always returns a MalformattedPolicyDocument error and I can't for the life of me see why.</p>
|
<p>The <code>AssumeRolePolicyDocument</code> parameter expects a JSON trust policy describing who can assume this role. You are providing a policy that is describing which resources this role will have access to.</p>
<p>For more information on trust policies, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html" rel="noreferrer">this</a> but the assume role policy should look something like this:</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole"
}
}
</code></pre>
<p>This is probably not what you want but the point is that the trust policy is describing who is allowed to assume this role, not what the role has access to.</p>
<p>You could then create another policy that contains your resource permissions and attach that policy to your new role.</p>
|
json|python-2.7|amazon-web-services|amazon-iam|boto3
| 5 |
1,909,271 | 29,854,966 |
"import wx" fails in PySCripter
|
<p>I have a 64-bit windows 7 OS where I installed ArcGIS with 64-bit Python 2.7.
I also installed 64 pyscripter editor.
When I import wx from Python 2.7 IDE no isse - I get this:</p>
<pre><code>Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
>>> import wx
>>>
>
</code></pre>
<p>When I import from PyScripter - fails I get this:</p>
<pre><code>*** Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32. ***
>>> import wx
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python27\ArcGISx6410.3\lib\site-packages\wx-3.0-msw\wx\__init__.py", line 45, in <module>
from wx._core import *
File "C:\Python27\ArcGISx6410.3\lib\site-packages\wx-3.0-msw\wx\_core.py", line 4, in <module>
import _core_
ImportError: DLL load failed: %1 is not a valid Win32 application.
>>>
</code></pre>
<p>Anybody can help me with this?</p>
|
<p>I think it is installing to the wrong location. Normally when you install Python packages, they get installed to <code>C:\Python27\lib\site-packages</code>. Somehow you installed wxPython to <code>C:\Python27\ArcGISx6410.3\lib\site-packages</code>. I would uninstall wxPython and when you re-run the wxPython installer, specify where to install it. </p>
<p>I should note that wxPython works fine for me on Windows 7 when it is installed in the correct location. I can import wx from both Python's interpreter and in PyScripter.</p>
|
python-2.7|import|64-bit|wxpython|pyscripter
| 0 |
1,909,272 | 29,837,203 |
Checkbuttons and buttons: using lambda
|
<p>I am trying to make a number of checkboxes based on a list, however it looks as if I am screwing up the <em>command call</em> and <em>variable aspect</em> of the button. </p>
<p>My code is:</p>
<pre><code>class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.courses = ["CSE 4444", "CSE 4343"]
self.vars = []
self.parent.title("Homework Helper")
self.course_buttons()
self.pack(fill=BOTH, expand=1)
def course_buttons(self):
x = 0
y = 0
for i in range(0, len(self.courses)):
self.vars.append(IntVar())
cb = Checkbutton(self, text=self.courses[i],
variable=self.vars[i],
command=lambda: self.onClick(i))
cb.select()
cb.grid(column=x, row=y)
y = y+1
def onClick(self, place):
print place
if self.vars[place].get() == 1:
print self.courses[place]
</code></pre>
<p>The test so far is for the course to be printed on the console when the check box is on, however it only works for the second button, button "CSE 4343". When I interact with button "CSE 4444", nothing is printed.</p>
<p>Also, the "place" value is onClick is always 1, whether I am clicking button "CSE 4343" or button "CSE 4444".</p>
|
<p>When you make a <code>lambda</code> function, its references only resolve into values when the function is called. So, if you create <code>lambda</code> functions in a loop with a mutating value (<code>i</code> in your code), each function gets the same <code>i</code> - the last one that was available.</p>
<p>However, when you define a function with a default parameter, that reference is resolved as soon as the function is defined. By adding such a parameter to your <code>lambda</code> functions, you can ensure that they get the value you intended them to.</p>
<pre><code>lambda i=i: self.onClick(i)
</code></pre>
<p>This is referred to as lexical <a href="https://stackoverflow.com/questions/13355233/python-lambda-closure-scoping">scoping</a> or closure, if you'd like to do more research.</p>
|
python|user-interface|tkinter
| 7 |
1,909,273 | 30,150,025 |
Connect python application to internet through proxy IP?
|
<p>At my workplace we access internet through a proxy server IP entered in Preferences > Network > Connection > Manual Proxy configuration. where the Proxy IP is entered, I want to learn how to do that setup in python so for my internet based application .</p>
|
<p>You can set http_proxy environment variable or you can set this information accordly with lib used. As example, requests libs:</p>
<pre><code>import requests
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
requests.get("http://example.org", proxies=proxies)
</code></pre>
<p><strong>UPDATE</strong></p>
<p>A tool that can help in corporate environments is cntlm <a href="http://cntlm.sourceforge.net/" rel="nofollow">http://cntlm.sourceforge.net/</a> , an NTLM / NTLM Session Response / NTLMv2 authenticating HTTP proxy.</p>
<p>Once configured, you only have to point to your proxy in <a href="http://localhost:3128" rel="nofollow">http://localhost:3128</a>.</p>
|
python|sockets|ip|urllib2|proxy-server
| 1 |
1,909,274 | 61,416,541 |
Static resource problem referencing .js file in html using Flask
|
<p>When opened directly, my html file will load my OpenLayers JavaScript file (which loads a map frame). However when I run the html from my Flask python app, the JavaScript file/object doesn't load (no map showing, just some heading text).</p>
<p>This issue appears to be sorted here:</p>
<p><a href="https://stackoverflow.com/questions/14711552/external-javascript-file-is-not-getting-added-when-running-on-flask">External JavaScript file is not getting added when running on Flask</a></p>
<p>However due to my folder structure, I can't seem to get the .js to load. No errors, just no map loading in the page. I think I need some help with the syntax of the 'static' reference. I think this is the issue, however I am very new to website building. This is my project folder structure:</p>
<pre><code>ol_app.py
/pages
olquickstart.html
/static
/scripts
ol_script.js
/libs
/v6.3.1-dist
ol.css
ol.css.map
ol.js
ol.js.map
</code></pre>
<p>My Flask python app:</p>
<pre><code>from flask import Flask, render_template
import os
import webbrowser
from threading import Timer
template_dir = os.path.abspath(r'D:\PathToProject\ol_quickstart\pages')
app = Flask(__name__, template_folder=template_dir)
#home page
@app.route('/')
def index():
return '<a href="http://127.0.0.1:5000/ol_qs">OL QuickStart</a>'
#openlayers test page
@app.route('/ol_qs')
def ol_qs():
return render_template("olquickstart.html")
#run app
def open_browser():
webbrowser.open_new('http://127.0.0.1:5000/')
if __name__ == "__main__":
Timer(1, open_browser).start();
app.run(port=5000)
</code></pre>
<p>my html:</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../libs/v6.3.1-dist/ol.css" type="text/css">
<style>
.map {
height: 900px;
width: 100%;
}
</style>
<script src="../libs/v6.3.1-dist/ol.js"></script>
<title>OpenLayers Quickstart</title>
</head>
<body>
<h2>OL Quickstart Map</h2>
<div id="js-map" class="map"></div>
<!-- <script src='../static/scripts/ol_script.js'></script> I USE THIS LINE WHEN OPENING THE HTML DIRECTLY WITHOUT FLASK-->
<script type="text/javascript"
src="{{ url_for('static', filename='scripts/ol_script.js') }}"></script>
</body>
</html>
</code></pre>
<p>Is this part the problem?</p>
<p><code><script type="text/javascript"
src="{{ url_for('static', filename='scripts/ol_script.js') }}"></script></code></p>
|
<p>Looks like you need to move the <code>libs</code> directory into <code>static</code> and then include those files with similar <code>url_for</code> functions to what you already have:</p>
<pre><code><link rel="stylesheet" type="text/css"
href="{{ url_for('static', filename='libs/v6.3.1-dist/ol.css') }}">
<script type="text/javascript"
src="{{ url_for('static', filename='libs/v6.3.1-dist/ol.js') }}"></script>
</code></pre>
<p>Your exsiting one for <code>scripts/ol_script.js</code> looks correct.</p>
<p>However to debug this yourself you should load the dev tools in your webbrowser and view the <code>Network</code> tab to ensure that each JS file loads sucessfully and doesn't 404.</p>
<p>Similarly the <code>Console</code> tab will show you any javascript errors within the page.</p>
|
javascript|python|html|css|flask
| 1 |
1,909,275 | 61,379,451 |
How to extract 1 hour data from python dataframe?
|
<p>I have a dataframe which consist of Length & Time , here I'm attaching a sample dataframe, I was trying to fetch 1 hour data from this dataframe, can you help me to fetch 1 hour data, (if you have ideas to extract data, please let me know)</p>
<pre><code>Length,Time
0.0,2019-08-26 14:46:36.040
0.0,2019-08-26 14:46:36.043
0.0,2019-08-26 14:56:40.156
0.0,2019-08-26 14:56:40.160
6033.0,2019-08-26 15:01:22.963
6033.0,2019-08-26 15:01:23.034
0.0,2019-08-26 15:01:32.759
0.0,2019-08-26 15:01:32.763
0.0,2019-08-26 16:05:13.365
0.0,2019-08-26 16:05:13.368
0.0,2019-08-26 16:12:08.760
0.0,2019-08-26 16:12:08.760
2658.0,2019-08-26 16:14:48.129
2658.0,2019-08-26 17:14:48.132
0.0,2019-08-26 17:22:49.358
0.0,2019-08-26 17:22:49.361
0.0,2019-08-26 17:22:50.152
0.0,2019-08-26 17:22:50.156
0.0,2019-08-26 17:23:08.735
0.0,2019-08-26 18:23:08.735
0.0,2019-08-26 18:23:08.738
0.0,2019-08-26 18:23:08.738
</code></pre>
<p>Thank you</p>
|
<p>You can filter maximal hour per data in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>h = df['Time'].dt.hour
df = df[h.eq(h.max())]
print (df)
Length Time
19 0.0 2019-08-26 18:23:08.735
20 0.0 2019-08-26 18:23:08.738
21 0.0 2019-08-26 18:23:08.738
</code></pre>
|
python|pandas|dataframe
| 1 |
1,909,276 | 27,702,727 |
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
|
<p>I've got simple <code>python</code> functions.</p>
<pre><code>def readMainTemplate(templateFile):
template = open(templateFile, 'r')
data = template.read()
index1 = data.index['['] #originally I passed it into data[]
index2 = data.index[']']
template.close()
return data[index1:index2]
def writeMainTemplate(template, name):
file = open(name, 'w')
file.write(template)
file.close()
#runMainTemplate('main.template')
def runMainTemplate(template):
code = readMainTemplate(template)
writeMainTemplate(code, 'main.cpp')
</code></pre>
<p>They basically suppose to read from file some kind of template(something like this)</p>
<pre><code>--template "main"
[
#include <iostream>
using namespace std;
int main()
{
return 0;
}
]
</code></pre>
<p>and then write it to file(basically generating <code>main.cpp</code> template)</p>
<p>I run it from command line using this command</p>
<pre><code>python -c "from genmain import runMainTemplate; runMainTemplate('main.template')"
</code></pre>
<p>but I've got this error</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
File "genmain.py", line 18, in runMainTemplate
code = readMainTemplate(template)
File "genmain.py", line 6, in readMainTemplate
index1 = data.index['['] #originally I passed it into data[]
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
</code></pre>
<p>I thought that <code>data = template.read()</code> supposed to return <code>string</code> and string should allow to perform operation slicing <code>[:]</code>. </p>
<p><strong>But why there is an error?</strong></p>
<p><em>Also a question</em>: <strong>where I should put <code>python</code> scripts in order to run it anywhere in filesystem?(I want to generate file anywhere in the filesystem in the current folder by providing path to the template)</strong></p>
|
<p>The problem is that <code>index</code> is a method and needs to be called with <code>()</code> not <code>[]</code>. To use Kasra's example:</p>
<pre><code>>>> s="aeer"
>>> s.index('a')
0
</code></pre>
|
python
| 23 |
1,909,277 | 36,994,067 |
no feed_previous argument for tensorflow basic_rnn_seq2seq function
|
<p>The <code>embedding_rnn_seq2seq</code> function in tensorflows seq2seq module provides a <code>feed_previous</code> argument, which means that during decoding it only uses the first decoder input, and then for subsequent decoder inputs it uses the previous decoder output. Is there a simple way to get this behavior from the <code>basic_rnn_seq2seq</code> function?</p>
|
<p>This API is now deprecated, but if anyone's still looking for a solution I suggest looking at this GitHub repo: <a href="https://github.com/raindeer/seq2seq_experiments/blob/master/model.py#L81" rel="nofollow noreferrer">raindeer/seq2seq_experiments</a></p>
<p>In short, to create their decoder, the author uses the following (the important part being <code>loop_function</code>):</p>
<pre><code>def _init_seq2seq(self, encoder_inputs, decoder_inputs, cell, feed_previous):
def inference_loop_function(prev, _):
prev = tf.nn.xw_plus_b(prev, self.w_softmax, self.b_softmax)
return tf.to_float(tf.equal(prev, tf.reduce_max(prev, reduction_indices=[1], keep_dims=True)))
loop_function = inference_loop_function if feed_previous else None
with variable_scope.variable_scope('seq2seq'):
_, final_enc_state = rnn.rnn(cell, encoder_inputs, dtype=dtypes.float32)
return seq2seq.rnn_decoder(decoder_inputs, final_enc_state, cell, loop_function=loop_function)
</code></pre>
|
tensorflow
| 0 |
1,909,278 | 36,898,001 |
Error 1318: Incorrect number of arguments for PROCEDURE ComicHub.sp_createUser; expected 3, got 4
|
<p>I keep Error 1318 when running this code, I am supposed to have 4 arguments: <code>username</code>, <code>email</code>, <code>password</code> and <code>location</code>. It is picking up 4, but thinks it only wants 3 arguments. Code for Database and Python is below.</p>
<p>Python:</p>
<pre><code>@app.route('/userSignUp',methods = ['POST'])
def userSignUp():
try:
#read values from signup form
_username = request.form['username']
_email = request.form['email']
_password = request.form['password']
_location = request.form['location']
#validate recieved values
if _username and _email and _password and _location:
cur = mysql.connection.cursor()
_hashed_password = generate_password_hash(_password)
cur.callproc('sp_createUser', (_username, _email, _hashed_password, _location))
data = cur.fetchall()
cur.close()
if len(data) is 0:
mysql.connection.commit()
return json.dumps({'success':'User created successfully!'})
else:
return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
except Exception as e:
return json.dumps({'error':str(e)})
</code></pre>
<p>SQL:</p>
<pre><code># Create Database for ComicHub
CREATE DATABASE ComicHub;
# Create Table 'users' for ComicHub
CREATE TABLE `ComicHub`.`tbl_user` (
`user_id` BIGINT NULL AUTO_INCREMENT,
`user_username` VARCHAR(45) NULL,
`user_email` VARCHAR(45) NULL,
`user_password` VARCHAR(45) NULL,
`user_location` VARCHAR(66) NULL,
PRIMARY KEY (`user_id`)
);
# PROCEDURE for creating users from passed in data
USE `ComicHub`;
DELIMITER $$
CREATE PROCEDURE `sp_createUser` (
IN p_username VARCHAR(20),
IN p_email VARCHAR(20),
IN p_password VARCHAR(20),
IN P_location VARCHAR(20)
)
BEGIN
#check if user already exists
IF (select exists (select 1 from tbl_user where user_username = p_username) ) THEN
select 'Username Already Exists!';
ELSE
insert into tbl_user
(
user_username,
user_email,
user_password,
user_location
)
values
(
p_username,
p_email,
p_password,
p_location
);
END IF;
END$$
DELIMITER ;
</code></pre>
|
<p>Nevermind, fixed now, I realised I hadn't updated the database in MySQL Workbench. Stupid I know but its been a long day!</p>
|
python|mysql|database|numbers|procedure
| 0 |
1,909,279 | 20,052,041 |
k nearest neighbours algorithm python
|
<p>this is my code for the k nearest neighbor algorithm:</p>
<pre><code>import numpy as np
from EuclideanDistance import EuclideanDistance
dataset = np.loadtxt('C:\Users\Toshiba\Documents\machine learning\RealEstate.csv', delimiter=',', usecols=(2,3,4,5))
p1 = ()
def normalizeToZscores(data):
'''Normalizes the variables to z-scores'''
zScores = list()
for s in data:
zScore = (s - np.mean(data))/np.std(data)
zScores.append(zScore)
return np.asarray(zScores)
def InOutBudget(data):
'''Decides whether a particular house is within
or outside the budget of $153000 and assigns values of 1 and 0 respectively'''
data2 = list()
for i in data:
if (i > 153000): data2.append(0)
else: data2.append(1)
return np.array(data2)
classes = dataset[:,0]
classes = classes.reshape((dataset.shape[0],1))
classes = InOutBudget(classes)
data = dataset[:20,:]
data = normalizeToZscores(data)
p1s = dataset[20:400,:]
def measureDis(data, p1):
listD = []
for x in data:
D = EuclideanDistance(x, p1)
listD.append(D)
return listD
def most_common(lst):
'''Finds the most frequently occuring element of a list.
It will be used to predict a class based on the classification
of the k-nearest neighbours'''
return max(set(lst), key=lst.count)
def findKnn(k):
'''K nearest neighbours algorithm'''
knns = list()
errors = list()
#for i in k:
for p1 in p1s:
# Create a list of tuples containing distance and class,
# Then sort them by shortest distance
tuples = zip(measureDis(data,p1), classes[20:400])
tuples = sorted(tuples)
knn = tuples[:k]
print knn
knn = [x[1] for x in knn]
knn = most_common(knn)
knns = knns.append(knn)
print knn
error = np.abs(knn - p1)
errors = errors.append(error)
errorsNum = np.sum(errors)
return knns
</code></pre>
<p>But I keep getting:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Toshiba\workspace\assignment5\src\knn2.py", line 76, in <module> knn = findKnn(k)
File "C:\Users\Toshiba\workspace\assignment5\src\knn2.py", line 64, in findKnn knns = knns.append(knn)
AttributeError: 'NoneType' object has no attribute 'append'
</code></pre>
<p>I know the code is really amateur, but could someone please help me just solve the issue?</p>
|
<p>list.append doesn't return the list. Simply do:</p>
<pre><code>knns.append(knn)
</code></pre>
<p>instead of:</p>
<pre><code>knns = knns.append(knn)
</code></pre>
|
python|algorithm
| 6 |
1,909,280 | 4,328,271 |
Best way for a beginner to learn screen scraping by Python
|
<p>This might be one of those questions that are difficult to answer, but here goes:</p>
<p>I don't consider my self programmer - but I would like to :-) I've learned R, because I was sick and tired of spss, and because a friend introduced me to the language - so I am not a complete stranger to programming logic. </p>
<p>Now I would like to learn python - primarily to do screen scraping and text analysis, but also for writing webapps with Pylons or Django.</p>
<p>So: How should I go about learning to screen scrape with python? I started going through the <a href="http://doc.scrapy.org/" rel="noreferrer" title="scrappy docs">scrappy docs</a> but I feel to much "magic" is going on - after all - I am trying to learn, not just do.</p>
<p>On the other hand: There is no reason to reinvent the wheel, and if Scrapy is to screen scraping what Django is to webpages, then It might after all be worth jumping straight into Scrapy. What do you think?</p>
<p>Oh - BTW: The kind of screen scraping: I want to scrape newspaper sites (i.e. fairly complex and big) for mentions of politicians etc. - That means I will need to scrape daily, incrementally and recursively - and I need to log the results into a database of sorts - which lead me to a bonus question: Everybody is talking about nonSQL DB. Should I learn to use e.g. mongoDB right away (I don't think I need strong consistency), or is that foolish for what I want to do?</p>
<p>Thank you for any thoughts - and I apologize if this is to general to be considered a programming question.</p>
|
<p>I agree that the Scrapy docs give off that impression. But, I believe, as I found for myself, that if you are patient with Scrapy, and go through the tutorials first, and then bury yourself into the rest of the documentation, you will not only start to understand the different parts to Scrapy better, but you will appreciate why it does what it does the way it does it. It is a framework for writing spiders and screen scrappers in the real sense of a framework. You will still have to learn XPath, but I find that it is best to learn it regardless. After all, you do intend to scrape websites, and an understanding of what XPath is and how it works is only going to make things easier for you.</p>
<p>Once you have, for example, understood the concept of <code>pipelines</code> in Scrapy, you will be able to appreciate how easy it is to do all sorts of stuff with scrapped items, including storing them into a database.</p>
<p><code>BeautifulSoup</code> is a wonderful Python library that can be used to scrape websites. But, in contrast to Scrapy, it is not a framework by any means. For smaller projects where you don't have to invest time in writing a proper spider and have to deal with scraping a good amount of data, you can get by with BeautifulSoup. But for anything else, you will only begin to appreciate the sort of things Scrapy provides.</p>
|
python|screen-scraping|beautifulsoup|lxml|scrapy
| 47 |
1,909,281 | 51,438,186 |
Pass *args directly to function
|
<p>How can I pass *args from one function directly into another one called within it and maintain its functionality?</p>
<p>If I do it like this:</p>
<pre><code>def parent(*args):
child(args)
def child(*args):
print(args)
</code></pre>
<p>I get this output:</p>
<pre><code>>>> parent(1, 2, 3, 4)
>>> ((1, 2, 3, 4),)
</code></pre>
<p>but:</p>
<pre><code>>>> child(1, 2, 3, 4)
>>> (1, 2, 3, 4)
</code></pre>
<p>I want the parent function to print out the same as if I called the child function directly.</p>
<p>Thanks!</p>
|
<p>Just unpack them before you give it to the next function.</p>
<pre><code>def parent(*args):
child(*args)
def child(*args):
print(args)
</code></pre>
|
python
| 4 |
1,909,282 | 51,185,292 |
Opencv detect all generic objects shapes on a table (birdview)
|
<p>I would like to detect all kind of object shapes which are on a flat table. The table can have a gray, white or black surface color.</p>
<p>The objects can be any shape and can have different colors.</p>
<p>What is an efficient way to solve this problem?</p>
<p><strong>I have tried:</strong></p>
<p>1.) Convert to Grayscale, bilateral filter, canny edges then use findContours, also tried with adaptive threshold.</p>
<p>2.) OpenCV SimpleBlobDetector</p>
<p><strong>Original Picture</strong></p>
<p><a href="https://i.stack.imgur.com/fafz6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fafz6.png" alt="Original"></a></p>
<p><strong>Contours</strong></p>
<p><a href="https://i.stack.imgur.com/CpR8T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CpR8T.png" alt="Contours"></a></p>
<p><strong>Blob Detector</strong></p>
<p><a href="https://i.stack.imgur.com/aQkO4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aQkO4.png" alt="Blob"></a></p>
|
<p>An option could be the <a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_watershed/py_watershed.html#watershed" rel="nofollow noreferrer">Watershed Algorithm</a>. In the linked example coins are detected with this Algorithm. </p>
|
python|opencv|computer-vision
| 1 |
1,909,283 | 51,232,766 |
Extract a sample from a Pandas DataFrame keeping all values of the same type
|
<p>I have a huge CSV which is made like this:</p>
<pre><code>type, value
A 1
B 4
C 6
A 25
D 5
B 7
</code></pre>
<p>Since there are too many rows to be processed, I would like to take a sample, but the peculiarity of this sample has to be the following: all the rows of the same type have to be taken.</p>
<p>I started with taking a random sample of the rows:</p>
<pre><code>num_lines = sum(1 for line in open('file.csv') - 1
sample_lines = int(num_lines * 0.01)
skip = sorted(random.sample(range(num_lines), num_lines - sample_lines))
df = pd.read_csv('file.csv', sep=';', skiprows=skip)
</code></pre>
<p>But this gives me only a <em>random sample of the rows</em>. What I would like to obtain is a <em>random sample of the types</em>.</p>
<p>I have the general process in mind:</p>
<ol>
<li>Import the whole CSV in a Pandas DataFrame</li>
<li>Generate the (random) list of types to extract (e.g. [A, B])</li>
<li>Extract from the DataFrame only the rows with type 'A' or 'B'</li>
</ol>
<p>The result should be something like this:</p>
<pre><code>type value
A 1
B 4
A 25
B 7
</code></pre>
<p>Thank you for any help you could give.</p>
|
<p>Is this a correct approach?</p>
<p>First, create the DataFrame by importing it from a CSV.
Then, creating the array which contains the list of all the possible types, and selecting only n of them (randomly).
And lastly, Saving a new DataFrame with only these n types (but with all the data related to them).</p>
<pre><code>n = 10
df = pd.read_csv('file.csv', sep=';')
random_types = np.random.choice(df.type.unique(), n)
m = df['type'].isin(random_types)
df_sample = df.loc[m]
</code></pre>
<p>This approach has the disadvantage that the entire CSV has to be loaded in memory, though.</p>
<p><strong>Full example</strong></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(400)
data = '''\
type value
A 1
B 4
C 6
A 25
D 5
B 7'''
fileobj = pd.compat.StringIO(data)
df = pd.read_csv(fileobj, sep='\s+')
n = 2
random_types = np.random.choice(df.type.unique(), n)
print(df.loc[df['type'].isin(random_types)])
</code></pre>
<p>Returns:</p>
<pre><code> type value
0 A 1
3 A 25
4 D 5
</code></pre>
|
python|pandas
| 2 |
1,909,284 | 51,545,670 |
Pandas to_sql 'append' to an existing table causes Python crash
|
<p>My problem is essentially this: When I try to use to_sql with if_exists = 'append' and name is set to a table on my SQL Server that already exists python crashes.</p>
<p>This is my code:</p>
<pre><code>@event.listens_for(engine, 'before_cursor_execute') def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany):
if executemany:
cursor.fast_executemany = True
df.to_sql(name = 'existingSQLTable', con = engine, if_exists = 'append', index = False, chunksize = 10000, dtype = dataTypes)
</code></pre>
<p>I didn't include it but dataTypes is a dictionary of all the column names and their data type.</p>
<p>This is the error I get:</p>
<pre><code> Traceback (most recent call last):
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1116, in _execute_context
context)
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 447, in do_executemany
cursor.executemany(statement, parameters)
pyodbc.IntegrityError: ('23000', "[23000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Violation of PRIMARY KEY constraint 'PK__existingSQLTable__'. Cannot insert duplicate key in object 'dbo.existingSQLTable'. The duplicate key value is (20008.7, 2008-08-07, Fl). (2627) (SQLExecute); [23000] [Microsoft][SQL Server Native Client 11.0][SQL Server]The statement has been terminated. (3621)")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
Table.to_sql(name = 'existingSQLTable', con = engine, if_exists = 'append', index = False, chunksize = 10000, dtype = dataTypes)
File "C:\Apps\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1165, in to_sql
chunksize=chunksize, dtype=dtype)
File "C:\Apps\Anaconda3\lib\site-packages\pandas\io\sql.py", line 571, in to_sql
chunksize=chunksize, dtype=dtype)
File "C:\Apps\Anaconda3\lib\site-packages\pandas\io\sql.py", line 1250, in to_sql
table.insert(chunksize)
File "C:\Apps\Anaconda3\lib\site-packages\pandas\io\sql.py", line 770, in insert
self._execute_insert(conn, keys, chunk_iter)
File "C:\Apps\Anaconda3\lib\site-packages\pandas\io\sql.py", line 745, in _execute_insert
conn.execute(self.insert_statement(), data)
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 914, in execute
return meth(self, multiparams, params)
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 323, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1010, in _execute_clauseelement
compiled_sql, distilled_params
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1146, in _execute_context
context)
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1341, in _handle_dbapi_exception
exc_info
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 202, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 185, in reraise
raise value.with_traceback(tb)
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1116, in _execute_context
context)
File "C:\Apps\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 447, in do_executemany
cursor.executemany(statement, parameters)
</code></pre>
<p>Based on the errors, to me it appears that there's something wrong with the flag fast_executemany, but I've read a lot of documentation on it, and don't see anything wrong with it.</p>
<p>Things that may be of note:</p>
<ol>
<li>A table that does not already exist with if_exists = 'replace' works as expected</li>
<li>A table that does not already exist with if_exists = 'append' works as expected</li>
<li>A table that already exist with if_exists = 'replace' works as expected</li>
<li>My DataFrame is about 3 million rows and 25 columns (mostly floats and some short strings)</li>
<li>I can successfully write 900,000 rows absolute maximum without python crashing. </li>
<li>I'm using a SQL Server, pandas 0.23.3, pyodbc 4.0.23 (I also get the same error with 4.0.22), Jupyter Notebook (I've also tried it in IDLE with the same result), Windows 10, Python 3.5.1, and Anaconda 3.</li>
</ol>
<p>The obvious solution to me was to break the DataFrame up into chunks of 900,000 rows. While the first chunk is successfully uploaded, I cannot append even a single row to it without python crashing. </p>
<p>Is this error a result of the code meant to speed up the process (which it does fantastically)? Am I misunderstanding the to_sql function? Or is there something else going on? Any suggestions would be great! Also, if anyone has a similar problem it would be great to know!</p>
|
<p>As @Jon Clements explained, the problem was that there were rows which had identical primary keys (but the rows weren't themselves identical). I used the pandas df.drop_duplicates function, with the subset parameter set to the primary key columns. This solved the Violation of PK error. </p>
|
python-3.x|pandas|sql-server-2012|sqlalchemy|pandas-to-sql
| 2 |
1,909,285 | 73,823,191 |
Modifying the function in Python ( NLP)
|
<pre><code>final_list = [ ]
words = ['good', 'bad', 'excellent','delivery', 'quality','upset','better','poor','refund','fake','cheat','quick','long','scam','cheaper','aluminium']
def func(words, list1):
cnt = 0
final_list = [ ]
for i in list1:
no_of_words = len(i.split())
# print(no_of_words)
# print(i)
if no_of_words>2:
for word in i.split(): # Only printing the records where occurence of words >2
# print(word)
if word in words:
cnt+=1
if cnt>2:
final_list.append(i)
cnt = 0
return final_list
final_list = func(words, )
print( *final_list, sep = ' \n\n')
</code></pre>
<p>The above given code prints the row elements of the column 'list1' in which row elements contain words of the list 'words' where words > 2.</p>
<p>For eg. I am a good delivery person, but still customers cheat me sometimes.</p>
<p>Consider this to be one of the row elements. If this row is given it will get printed because (words>2) condition is satisfied i,e good,delivery, cheat are present in my list 'words'.</p>
<p>But I want to modify the function. Along with the above condition we also want to check if individual words>2 in the row element</p>
<p>for e.g.. I am a good delivery boy, I do good things to people, I don't cheat anyone, yet people are not good to me and cheat me often.</p>
<p>This above given example will not get printed.
Because:</p>
<ol>
<li>Words>2 -> True //good, delivery , cheat are present ( words>2)</li>
<li>Individual words>2 -> False // good- 3 times, delivery - 1 time , cheat - 2 times ( Doesn't satisfy the condition of individual items > 2, hence won't get printed)</li>
</ol>
<p>Kindly help me modifying my function.</p>
|
<p>you can split the each element in a list and match with your list words and check if the duplicates of elements is greater than 2.</p>
<pre><code>from collections import Counter
list1 = ['good good delivery good cheat delivery cheat delivery cheat', 'good
cheat', 'fake good good fake']
words = ['good', 'bad', 'excellent', 'delivery', 'quality', 'upset', 'better',
'poor', 'refund', 'fake', 'cheat','quick', 'long', 'scam', 'cheaper', 'aluminium']
repeated_words = []
for word in list1:
data = word.split()
match_data = [i for i in data if any((j in i) for j in words)]
count_data = [k for k, v in Counter(match_data).items() if v > 2]
if count_data:
repeated_words.append(word)
print(repeated_words)
>>>> ['good good delivery good cheat delivery cheat delivery cheat']
</code></pre>
|
python|python-3.x|pandas|list|csv
| 0 |
1,909,286 | 73,550,725 |
Create/ re-create a list of dictionaries from a dictionary via Python Recursion function
|
<p>So, I'm trying to parse this json object into multiple events, as it's the expected input for a ETL tool. I know this is quite straight forward if we do this via loops, if statements and explicitly defining the search fields for given events. This method is not feasible because I have multiple heavily nested JSON objects and I would prefer to let the python recursions handle the heavy lifting. The following is a sample object, which consist of string, list and dict (basically covers most use-cases, from the data I have).</p>
<pre><code>{
"event_name": "restaurants",
"properties": {
"_id": "5a9909384309cf90b5739342",
"name": "Mangal Kebab Turkish Restaurant",
"restaurant_id": "41009112",
"borough": "Queens",
"cuisine": "Turkish",
"address": {
"building": "4620",
"coord": {
"0": -73.9180155,
"1": 40.7427742
},
"street": "Queens Boulevard",
"zipcode": "11104"
},
"grades": [
{
"date": 1414540800000,
"grade": "A",
"score": 12
},
{
"date": 1397692800000,
"grade": "A",
"score": 10
},
{
"date": 1381276800000,
"grade": "A",
"score": 12
}
]
}
}
</code></pre>
<p>And I want to convert it to this following list of dictionaries</p>
<pre><code>[
{
"event_name": "restaurants",
"properties": {
"restaurant_id": "41009112",
"name": "Mangal Kebab Turkish Restaurant",
"cuisine": "Turkish",
"_id": "5a9909384309cf90b5739342",
"borough": "Queens"
}
},
{
"event_name": "restaurant_address",
"properties": {
"zipcode": "11104",
"ref_id": "41009112",
"street": "Queens Boulevard",
"building": "4620"
}
},
{
"event_name": "restaurant_address_coord"
"ref_id": "41009112"
"0": -73.9180155,
"1": 40.7427742
},
{
"event_name": "restaurant_grades",
"properties": {
"date": 1414540800000,
"ref_id": "41009112",
"score": 12,
"grade": "A",
"index": "0"
}
},
{
"event_name": "restaurant_grades",
"properties": {
"date": 1397692800000,
"ref_id": "41009112",
"score": 10,
"grade": "A",
"index": "1"
}
},
{
"event_name": "restaurant_grades",
"properties": {
"date": 1381276800000,
"ref_id": "41009112",
"score": 12,
"grade": "A",
"index": "2"
}
}
]
</code></pre>
<p>And most importantly these events will be broken up into independent structured tables to conduct joins, we need to create primary keys/ unique identifiers. So the deeply nested dictionaries should have its corresponding parents_id field as ref_id. In this case ref_id = restaurant_id from its parent dictionary.</p>
<p>Most of the example on the internet flatten's the whole object to be normalized and into a dataframe, but to utilise this ETL tool to its full potential it would be ideal to solve this problem via recursions and outputting as list of dictionaries.</p>
|
<p>This is what one might call <strong>a brute force method</strong>. Create a translator function to move each item into the correct part of the new structure (like a schema).</p>
<pre class="lang-py prettyprint-override"><code># input dict
d = {
"event_name": "demo",
"properties": {
"_id": "5a9909384309cf90b5739342",
"name": "Mangal Kebab Turkish Restaurant",
"restaurant_id": "41009112",
"borough": "Queens",
"cuisine": "Turkish",
"address": {
"building": "4620",
"coord": {
"0": -73.9180155,
"1": 40.7427742
},
"street": "Queens Boulevard",
"zipcode": "11104"
},
"grades": [
{
"date": 1414540800000,
"grade": "A",
"score": 12
},
{
"date": 1397692800000,
"grade": "A",
"score": 10
},
{
"date": 1381276800000,
"grade": "A",
"score": 12
}
]
}
}
def convert_structure(d: dict):
''' function to convert to new structure'''
# the new dict
e = {}
e['event_name'] = d['event_name']
e['properties'] = {}
e['properties']['restaurant_id'] = d['properties']['restaurant_id']
# and so forth...
# keep building the new structure / template
# return a list
return [e]
# run & print
x = convert_structure(d)
print(x)
</code></pre>
<p>the reuslt (for the part done) looks like this:</p>
<pre><code>[{'event_name': 'demo', 'properties': {'restaurant_id': '41009112'}}]
</code></pre>
<p>If a pattern is identified, then the above could be improved...</p>
|
python|json|parsing|data-structures|etl
| 0 |
1,909,287 | 17,268,370 |
Working out why a block of code gives a certain output
|
<p>Consider the following function:</p>
<pre><code>def fun(lst):
for item in lst:
cmp = 0
for other in lst:
if item < other:
cmp -= 1
elif item > other:
cmp += 1
if not cmp:
return item
nums = [1,3,2,2]
print("fun({0}) = {1}".format(nums,fun(nums)))
</code></pre>
<p>I know that the ouput of this code is:</p>
<p>fun([1, 3, 2, 2]) = 2</p>
<p>But I don't know why. Can someone explain why this is the output?</p>
<p>Does anyone have any tips on how to make interpreting a block of code easier... </p>
<p>As I won't obviously have access to python in my exam and I'm struggling to work out what some blocks of code actually do.</p>
<p>Thank you.</p>
|
<blockquote>
<p>Does anyone have any tips on how to make interpreting a block of code easier... </p>
</blockquote>
<p>Write it out. Give each name its own space on the page and track changes to the values while running through the code. After some practice you'll be able to track the simple values easily, only needing to write out the non-scalar values.</p>
|
python|output
| 1 |
1,909,288 | 17,535,670 |
How to convert UTC-4 to US/Eastern in python?
|
<p>I read time stamps from text file. These time stamps are in UTC-4. I need to convert them to US/Eastern.</p>
<pre><code>import datetime
datetime_utc4 = datetime.datetime.strptime("12/31/2012 16:15", "%m/%d/%Y %H:%M")
</code></pre>
<p>How do I convert it to US/Eastern? One-line answer would be best.</p>
<p>Note: my original question stated EST to EDT. But it does not change the essence of the question, which is how to go from one time zone to another. Upon some reading (following comments) I gather that python (pytz in particular) does not treat EST and EDT as separate time zones, rather as two flavors of US/Eastern. But this is an implementation detail. It is common to refer to EST and EDT as two different time zones, see e.g. <a href="http://www.timeanddate.com/library/abbreviations/timezones/na/edt.html" rel="nofollow">here</a>.</p>
|
<p>Based on your update and comments, I now understand that you have data that is fixed at UTC-4 and you want to correct this so that it is valid in US Eastern Time, including both EST/EDT where appropriate. Here is how you do that with <a href="http://pytz.sourceforge.net/" rel="noreferrer">pytz</a>. </p>
<pre><code>from datetime import datetime
import pytz
dt = datetime.strptime("12/31/2012 16:15", "%m/%d/%Y %H:%M") \
.replace(tzinfo = pytz.FixedOffset(-240)) \
.astimezone(pytz.timezone('America/New_York'))
</code></pre>
<p>Note that I used the <code>America/New_York</code> time zone id. This is the most correct form of identifier. You could instead use <code>US/Eastern</code> and it would work just fine, but be aware that this is an alias, and it is just there for backwards compatibility.</p>
|
python|time|timezone
| 5 |
1,909,289 | 69,836,366 |
Break from Python async for
|
<p>I have a situation where I want to break from an async for loop. I managed to reduce the issue to the application below. I expect to enter the 'finally' section of the context manager when breaking from the loop in main. In other words, the expected result is</p>
<blockquote>
<p>try</p>
<p>456</p>
<p>finally</p>
<p>done</p>
</blockquote>
<p>but what I get is</p>
<blockquote>
<p>try</p>
<p>456</p>
<p>done</p>
<p>finally</p>
</blockquote>
<p>and then an exception when the application closes.</p>
<p>Here is the code</p>
<pre><code>import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def receiving():
try:
print('try')
yield 123
finally:
print('finally')
async def request_all():
async with receiving():
yield 456
async def main():
async for r in request_all():
print(r)
break
print('done')
asyncio.run(main())
</code></pre>
<p>I found <a href="https://bugs.python.org/issue33786" rel="nofollow noreferrer">this</a> bug report that seems similar, but as far as I can tell it has been resolved before 3.8. I tested my issue on 3.8.2 and 3.9.6</p>
|
<p>I can see how this behaviour is confusing, but I don't think it's a bug. If you bypass the exhaustion of the async Iterator with <code>break</code>, you never leave the <code>async with</code> in <code>request_all</code>, so the <code>finally</code>-block will not get executed until the event loop finishes. This has the advantage that you <em>could</em> exhaust the generator at a later point.</p>
<p>If you are sure, you don't need your generator anymore, you could close the async_generator instead of <code>break</code>ing to get your expected behaviour:</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def receiving():
try:
print('try')
yield 123
finally:
print('finally')
async def request_all():
async with receiving():
yield 456
async def main():
gen = request_all()
async for r in gen:
print(r)
await gen.aclose() #instead of break
print('done')
asyncio.run(main())
</code></pre>
|
python|python-asyncio
| 6 |
1,909,290 | 72,877,628 |
Request.get Download image before Image fully loads
|
<p>I am trying to download images from the website. <code>Request.Get</code> sometimes didn't download data, My assumption is when the images are heavy, <code>Request.get(url)</code> fails because the image takes some time to upload.</p>
<p>Failed</p>
<pre><code>Remote URL https://gd3.alicdn.com/imgextra/i3/917765107/O1CN01FUj4ea1nb3SEtYlCB_!!917765107.jpg
filename 1657077308/693904.jpg size 0
</code></pre>
<p>Success</p>
<pre><code>Remote URL https://gd1.alicdn.com/imgextra/i1/917765107/O1CN016sR7UO1nb3SNr1Fo2_!!917765107.jpg
filename 1657077186/735590.jpg size 14032
</code></pre>
<p>Code:</p>
<pre><code># Getting image from remote url
response = requests.get(remote_url, stream=True)
# Get the content of image
imageResponse = response.raw
len(response.content)
</code></pre>
<p>Also check this , Image downloaded but Blank</p>
<pre><code>remote_url = "https://img.alicdn.com/imgextra/i3/917765107/O1CN01WwxHa81nb3SLAupPq_!!917765107.jpg"
imageResponse = requests.get(remote_url, stream=True)
print(len(imageResponse.content))
</code></pre>
|
<p>Use <code>requests.Session</code>, it can fix the problem. If does not, then you have probably been blocked from <code>gd3.alicdn.com</code> host cause of making many requests.</p>
<pre><code>import requests
urls = [
"https://gd3.alicdn.com/imgextra/i3/917765107/O1CN01FUj4ea1nb3SEtYlCB_!!917765107.jpg",
"https://gd1.alicdn.com/imgextra/i1/917765107/O1CN016sR7UO1nb3SNr1Fo2_!!917765107.jpg",
"https://img.alicdn.com/imgextra/i3/917765107/O1CN01WwxHa81nb3SLAupPq_!!917765107.jpg"
]
for url in urls:
with requests.Session() as session:
response = session.get(url, stream=True)
print(len(response.content))
</code></pre>
|
python|image|python-requests
| 1 |
1,909,291 | 64,669,182 |
Seaborn split violin plot not splitting properly
|
<p>I am trying to make a split violin plot but the plot is never actually split when generated. I have tried following the <a href="https://seaborn.pydata.org/generated/seaborn.violinplot.html" rel="nofollow noreferrer">seaborn guide</a> but I'm not sure what is wrong since it does not produce a 2 colored split violin like in the guide.</p>
<p>My DF looks like this:</p>
<pre><code> Accuracy Train_Time Model
0 0 0.825165 170.013132 LSTM
1 1 0.849305 171.778840 LSTM
2 2 0.826628 174.107146 LSTM
3 3 0.834674 176.774985 LSTM
4 0 0.927944 18.521901 CNN
5 1 0.929042 18.595950 CNN
6 2 0.930139 18.421983 CNN
7 3 0.927213 18.329449 CNN
</code></pre>
<p>And my seaborn plot code looks like this:</p>
<pre><code>sns.set_theme(style="whitegrid")
ax = sns.violinplot(y="Accuracy", hue="Model", data=comp_df, palette="Set2", split=True)
plt.show()
</code></pre>
|
<p><code>hue</code>-nesting can only be used <em>in addition</em> to a <code>x</code>. In your case, you need to create a dummy column with the same value for the whole dataset.</p>
<pre><code>comp_df['dummy'] = 0
ax = sns.violinplot(y="Accuracy", x='dummy', hue="Model", data=comp_df, palette="Set2", split=True)
</code></pre>
|
python|python-3.x|seaborn
| 1 |
1,909,292 | 63,758,068 |
Flask-restful - During handling of the above exception, another exception occurred
|
<p>As part a Flask-restful API I have a login Resource:</p>
<pre><code>class LoginApi(Resource):
def post(self):
try:
body = request.get_json()
user = User.objects.get(email=body.get('email'))
authorized = user.check_password(body.get('password'))
if not authorized:
raise UnauthorizedError
expires = datetime.timedelta(days=7)
access_token = create_access_token(identity=str(user.id), expires_delta=expires)
return {'token': access_token}, 200
except DoesNotExist:
raise UnauthorizedError
except Exception as e:
raise InternalServerError
</code></pre>
<p>There are 4 scenarios for login route:</p>
<ol>
<li>Email and Password are correct</li>
<li>Email does not exist in the database - in this case the UnauthorizedError is raised correctly.</li>
<li>Email exists but password is incorrect - in this case I have an issue (described below)</li>
<li>Some other Error - InternalServerError is raised correctly.</li>
</ol>
<p>So for number 3 - instead of getting an UnauthorizedError, I am getting an InternalServerError.</p>
<p>The <code>if not authorized:</code> statement is working correctly (If i put a print in there I can see it work). However for some reason I am getting the following when trying to raise the error:</p>
<blockquote>
<p>During handling of the above exception, another exception occurred:</p>
</blockquote>
<p>I came across <a href="https://www.python.org/dev/peps/pep-0409/" rel="nofollow noreferrer">this PEP article</a> which seems to suggest changing to <code>raise UnauthorizedError from None</code> but the issue persists. Does anyone know how I can implement this successfully? Ideally I would like the same error to be raised from scenarios 2 and 3, otherwise there is a potential for someone to know whether or not an email exists in the database, from the errors they get back.</p>
|
<p>The if statement is raising UnAuthorized, but that happens in the excepts, you have to raise DoesNotExist to make it so that UnAuthorized can be raised in the except.</p>
|
python|flask|flask-restful
| 1 |
1,909,293 | 52,912,958 |
Python - why isnt my function outputting 'a' ten times? Beginner question
|
<pre><code>def testfunction():
for i in range(10):
return('a')
print(testfunction())
</code></pre>
<p>I want 'a' outputed 10 times in one line. If I use print instead of return, it gives me 10 'a's but each on a new line. Can you help?</p>
|
<p><code>return</code> terminates the current function, while print is a call to another function(atleast in python 3) </p>
<p>Any code after a return statement will not be run.
Python's way of printing 10 a's would be:</p>
<pre><code>print('a' * 10)
</code></pre>
<p>In your case it would look like the following:</p>
<pre><code>def testfunction ():
return 'a' * 10
print(testfunction ())
</code></pre>
|
python|function|for-loop
| 3 |
1,909,294 | 71,583,531 |
python string(js variable type) to dictionary
|
<p>How do I convert this string to a dictionary</p>
<p>I'm trying regex <code>r"},\s\]"</code>, but didn't get the desired result.</p>
<p><strong>HTTP request body</strong></p>
<p><strong>Content-Type: text/html</strong></p>
<pre><code>var sample = {
"date": "2022. 03. 23. 16:18",
"list":
[
{
"name": "USD",
"var1":"1236.26",
"var2":"1193.74",
"var3":"1226.90",
"var4":"1203.10",
"var5":"1215.00"
},
{
"name": "JPY",
"var1":"1020.81",
"var2":"985.71",
"var3":"1013.09",
"var4":"993.43",
"var5":"1003.26"
},
]
}
</code></pre>
|
<p>First we need to get rid of any trailing commas:</p>
<pre><code>_sample = sample.replace("\n", "").replace(" ", "").replace(",]", "]")
</code></pre>
<p>You can also use regex for this:</p>
<pre><code>import re
_sample = re.sub(r",(\s)+]", "]", sample)
</code></pre>
<p>Then use <code>json.loads()</code> to parse it into a dict.</p>
<pre><code>import json
outcome = json.loads(_sample)
</code></pre>
<p><strong>Beyond the OQ</strong><br />
If it is also possible that we'd have trailing commas after the last key-value of a dictionary: e.g. <code>{"var5": "1215.00",}</code> you can update the above code to:</p>
<pre><code>_sample = sample.replace("\n", "").replace(" ", "").replace(",}", "}").replace(",]", "]")
</code></pre>
<p>Or with regex:</p>
<pre><code>regex = r"(,(\s)+]|,(\s)+})"
</code></pre>
|
python-3.x|python-re
| 2 |
1,909,295 | 61,875,731 |
How to extract text from a specific line of a text file in Python?
|
<p>I have a log file, which currently stores the following information:</p>
<pre><code>RTSP0 rtsp://admin:****@192.168.0.104:554/onvif1
RTSP1 rtsp://admin:****@192.168.0.104:554/onvif2
CAMERA_HASH a586c0c691aa7e3fb37d1ff318bf4d6fdb83b24b
RTSP0 rtsp://admin:****@192.168.0.104:554/onvif1
RTSP1 rtsp://admin:****@192.168.0.104:554/onvif2
CAMERA_HASH a586c0c691aa7e3fb37d1ff318bf4d6fdb83b24b
RTSP0 rtsp://admin:****@192.168.0.104:554/onvif1
RTSP1 rtsp://admin:****@192.168.0.104:554/onvif2
CAMERA_HASH a586c0c691aa7e3fb37d1ff318bf4d6fdb83b24b
</code></pre>
<p>Every time a camera is connected, two new RTSP streams (i.e. RTSP0 and RTSP1) and a HASH number is added to the log file. I need to extract the RTSP stream of the most recent camera connected (i.e. the recent RTSP0 stream). Is there a way to read through the file and extract only this specific stream?
Currently, I am doing:</p>
<pre><code>searchfile = open('/Eya/pine_onvif/logs/camera_hash.log', 'r')
search = searchfile.readlines()
stream = []
line_cont = []
streamValue = []
for i,line in enumerate(search):
if 'RTSP0' in line:
line_cont = line
stream = line.split(' ')
streamValue = stream[1]
filename = streamValue
print(streamValue)
searchfile.close()
</code></pre>
<p>But this method is yielding an output such as the following:</p>
<pre><code>rtsp://admin:****@192.168.0.104:554/onvif1
rtsp://admin:****@192.168.0.104:554/onvif1
rtsp://admin:****@192.168.0.104:554/onvif1
</code></pre>
<p>I'm unable to retrieve only the last line of the <code>streamValue</code> array.</p>
|
<p>For your second question, you should use the 'reversed' read, that loop from the end of file, then use a simple <code>break</code> once you find the first rtsp line:</p>
<pre><code>for line in reversed(list(searchfile)):
hash = re.match(r"RTSP[.0-9] (rtsp:\/\/.*)", line.rstrip())
if hash is not None :
print(hash.group(1))
break
</code></pre>
|
python-3.x|split
| 1 |
1,909,296 | 72,577,345 |
How do you append a set of Series with duplicate label names (index) to the end of a DataFrame as rows without using the deprecated append method?
|
<p>I need to append a pandas Series as a row to the end of a pandas Dataframe. What makes this tricky is that I am using dates as my index, which are not unique in my case. This is what I want to be the result with the date values being the index.</p>
<pre><code>+βββββββββββ+βββββββββ+ββββββββββββββ+ββββββββββ+ββββββββ+
| | counts | day of week | weekend | month |
+βββββββββββ+βββββββββ+ββββββββββββββ+ββββββββββ+ββββββββ+
| 8/5/2015 | 1111 | 2 | FALSE | 8 |
| 8/5/2015 | 1076 | 3 | FALSE | 8 |
| 8/5/2015 | 1060 | 4 | FALSE | 8 |
| 8/6/2015 | 1540 | 5 | TRUE | 8 |
| 8/7/2015 | 1493 | 6 | TRUE | 8 |
| 8/7/2015 | 1060 | 0 | FALSE | 8 |
| 8/7/2015 | 1113 | 1 | FALSE | 8 |
| 8/8/2015 | 1027 | 2 | FALSE | 8 |
| 8/8/2015 | 1053 | 3 | FALSE | 8 |
| 8/8/2015 | 1051 | 4 | FALSE | 8 |
| 8/8/2015 | 1278 | 5 | TRUE | 8 |
| 8/8/2015 | 1086 | 6 | TRUE | 8 |
+βββββββββββ+βββββββββ+ββββββββββββββ+ββββββββββ+ββββββββ+
</code></pre>
<p>While this was easily possible with the <strong>append</strong> method, it is being deprecated and I am not sure that <strong>concat</strong> can replicate all of its functionality. (<em>On a side note, why does the pandas team keep deprecating great functionality?</em>).</p>
|
<p>My solution involves the <strong>loc</strong> method:</p>
<pre><code>df.loc[len(df)] = series_row
df= df.rename(index={label_name: series_row.name})
</code></pre>
<p>In case you don't follow, we insert a new row at the end of the Dataframe. If we stop there, the label name will be an int value, specifically the size of the Dataframe.</p>
<pre><code>df.loc[len(df)] = series_row
+βββ+βββββββββ+ββββββββββββββ+ββββββββββ+ββββββββ+
| | counts | day of week | weekend | month |
+βββ+βββββββββ+ββββββββββββββ+ββββββββββ+ββββββββ+
| 1 | 1111 | 2 | FALSE | 8 |
+βββ+βββββββββ+ββββββββββββββ+ββββββββββ+ββββββββ+
</code></pre>
<p>To keep the <strong>append</strong> method's functionality, we need to rename the label to whatever we want which in this case was a date string.</p>
<pre><code>df= df.rename(index={label_name: series_row.name})
+βββββββββββ+βββββββββ+ββββββββββββββ+ββββββββββ+ββββββββ+
| | counts | day of week | weekend | month |
+βββββββββββ+βββββββββ+ββββββββββββββ+ββββββββββ+ββββββββ+
| 8/5/2015 | 1111 | 2 | FALSE | 8 |
+βββββββββββ+βββββββββ+ββββββββββββββ+ββββββββββ+ββββββββ+
</code></pre>
|
python|pandas|dataframe|series
| 1 |
1,909,297 | 62,313,731 |
cmd.exe pops up new window when python subcommand.Popen calls script in different directory
|
<p>What specific syntax changes or config changes need to be made so that the entire output from calling the Python 3.7.7 scripts below from <code>cmd.exe</code> in Windows 10 will be output into the same single <code>CMD.exe</code> window? </p>
<p>The problem below is that the lowest level script ( <code>someCommand.py</code> ) triggers its own console window to be launched with its output and then closes as soon as it is done running, so that the output from the lowest level script ( <code>someCommand.py</code> ) is not returned to the <code>cmd.exe</code> console window that calls it. </p>
<p><hr><strong>The High Level Calling Command</strong><hr> </p>
<p>Here is the command run in the <code>cmd.exe</code> window to call the high level script: </p>
<pre><code>python topLevelScript.py "firstInputsPath" "secondInputsPath"
</code></pre>
<p><hr><strong>The Script Called By High-Level Command</strong><hr> </p>
<p>Here are the contents of <code>topLevelScript.py</code> </p>
<pre><code>print("Inside topLevelScript.py script.")
import sys
import sharedFunctions as sharedfunc
pathToInputs1 = str(sys.argv[1])
pathToInputs2 = str(sys.argv[2])
pathToCalls = "C:\\some\\path\\"
commandToCalls = "someCommand.py"
print ('pathToInputs1:', pathToInputs1 )
print ('pathToInputs2:', pathToInputs2 )
sharedfunc.applyFoundation(commandToCalls, pathToCalls, pathToInputs1, pathToInputs2)
</code></pre>
<p><hr><strong>A Shared Functions Module Called As 2nd Level</strong><hr> </p>
<p><code>sharedFunctions.py</code> is located in the same directory as <code>topLevelScript.py</code>, which is also the same directory from which the call to <code>topLevelScript.py</code> was made by <code>cmd.exe</code> above. The contents of <code>sharedFunctions.py</code> are: </p>
<pre><code>import subprocess
def applyFoundation(scriptName, workingDir, inputs1Path, inputs2Path ):
print("Inside sharedFunctions.py script and applyFoundation(..., ...) function. ")
print ('inputs1Path:', inputs1Path )
print ('inputs2Path:', inputs2Path )
print("scriptName is: " +scriptName)
print("workingDir is: " +workingDir)
proc = subprocess.Popen( scriptName,cwd=workingDir,stdout=subprocess.PIPE, shell=True)
while True:
line = proc.stdout.readline()
if line:
thetext=line.decode('utf-8').rstrip('\r|\n')
decodedline=ansi_escape.sub('', thetext)
print(decodedline)
else:
break
</code></pre>
<p><hr><strong>The Lowest Level Script, Which is Wrongly Outputting To A New cmd.exe Window:</strong><hr> </p>
<p>All of the above prints its console output in the same <code>cmd.exe</code> window that called it, except for the output of the <code>subprocess.Popen(...)</code> command from above, which launched the following <code>someCommand.py</code> and printed its output in a new child <code>cmd.exe</code> window which it launched and then destroyed quickly without recording any of its output: </p>
<pre><code>print("Inside someCommand.py script. ")
import os
import subprocess
subprocess.run("some cli command", shell=True, check=True)
</code></pre>
<p>Note that <code>someCommand.py</code> is also located in a different path/directory than both the calling scripts in addition to simply being called by <code>subprocess.Popen(...)</code> </p>
<blockquote>
<p><strong>What specific changes need to be made so that the output from <code>someCommand.py</code> will be printed in the same <code>cmd.exe</code> console window that calls the higher level parent <code>topLevelScript.py</code> and <code>sharedFunctions.py</code> programs?</strong> </p>
</blockquote>
<p><hr><strong>@Gerrat 's suggestion</strong><hr></p>
<p>Per @Gerrat 's suggestion below, I changed the <code>subprocess.Popen(...)</code> line to read as follows instead: </p>
<pre><code>mycommand = workingDir+scriptName
cp = subprocess.run(mycommand, shell=True, check=True, capture_output=True, universal_newlines=True)
print(cp.stdout)
</code></pre>
<p>But I am still seeing the same problem of a new console window being created and destroyed for the lowest level script without passing any of its output to the persistent calling window. </p>
|
<p>Given that <code>subprocess.run</code> returns a <a href="https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess" rel="nofollow noreferrer">CompletedProcess</a>,<br>
I would think that you could just change <code>someCommand.py</code> as follows:</p>
<pre><code>cp = subprocess.run("some cli command", shell=True, check=True, capture_output=True, universal_newlines=True)
print(cp.stdout)
</code></pre>
|
python|python-3.x|cmd|subprocess|popen
| 0 |
1,909,298 | 35,560,106 |
Incorrect number of bindings supplied
|
<p>I have a list like this:</p>
<pre><code>result1 = ['"United States"', '"China"', '"Sweden"', '"Europe"', '"Russian Federation"', '"China"']
</code></pre>
<p>And I want to insert it into a table:</p>
<pre><code>con.execute("INSERT INTO TableName(contry) VALUES(?)", result1)
</code></pre>
<p>But I get an error:</p>
<blockquote>
<p>Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied.</p>
</blockquote>
<p>Any help would be much appreciated. Or if you need more code, please let me know.</p>
|
<p>Your code as written is trying to insert a single row, and in that row you're specifying 74 values instead of the 1 that your query wants.</p>
<p>Additionally, the beauty of parameterized queries is you do not need to (and should not) quote strings or do anything else in particular to avoid SQL injection attacks. Thus, the strings in your country list probably should not be quoted (unless you want them to actually contain quotation marks in the database for some reason).</p>
<p>You're probably looking for <a href="https://www.python.org/dev/peps/pep-0249/#id18" rel="nofollow noreferrer">con.executemany</a> instead, which takes a list of lists. Thus you want something like:</p>
<pre><code>result1 = [['United States'], ['China'], ['Sweden'], ...]
con.executemany("INSERT INTO TableName(contry) VALUES(?)", result1)
</code></pre>
<p>Note that this (probably) runs 74 separate INSERT statements instead of 1 multi-row INSERT, depending on the database you're using. Certain higher-level SQL frameworks (like <a href="http://www.sqlalchemy.org/" rel="nofollow noreferrer">SQLAlchemy</a>) provide tools to handle this better, and your specific flavor of database API may provide similar tools.</p>
<p>Lacking either of those, your other option to do a multiple-row insert is something like this: (Written much more verbosely than it needs to be)</p>
<pre><code>import itertools
def insert_many(con, table, data):
"""
Inserts multiple rows into a table.
This will fail horribly if data is empty or the number of
parameters (len(data) * len(data[0])) exceeds the limits of your
particular DBAPI.
:param con: Database connection or cursor
:param table: Name of table, optionally including columns.
e.g. 'TableName' or 'TableName(country)'
:param data: List of lists of data elements. All inner lists must be the same length.
"""
# Represents enough parameters for one set of values. (1, in your case)
one_value = "({qmarks})".format(qmarks=", ".join("?" for _ in rows[0]))
# Represents all sets of values (74 copies of the above, in your case)
all_values = ", ".join(one_value for _ in data)
# Flattened version of your 2-dimensional array.
# The 'list' may not be required; I'm not certain offhand if execute() will accept an iterator.
data = list(itertools.chain(*data))
con.execute(
"INSERT INTO {table} VALUES {values}".format(table=table, values=values),
data
)
insert_many(con, "TableName(country)", [['United States'], ['China'], ['Sweden'], ...])
</code></pre>
|
python|sqlite
| 0 |
1,909,299 | 58,618,291 |
How can I save the SSL keys for https when I use `urllib2`?
|
<p>I need to save the SSL keys in a file, in order to decrypt the TCP packet via Wireshark later.
What should I do?</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import urllib2
import json
data={}
data_json = json.dumps(data, encoding='UTF-8', ensure_ascii=False)
requrl = "https://52.31.41.56/test" # look, the protocol is https
req = urllib2.Request(url=requrl, data=data_json)
req.add_header('Content-Type', 'application/json')
# how can I record the SSL keys in a file, for Wireshark decryption
rsp_fp = urllib2.urlopen(req)
rsp_data = rsp_fp.read()
print(rsp_data)
</code></pre>
|
<h2>Use sslkeylogfile</h2>
<h3>Example Usage</h3>
<p>Use <a href="https://pypi.org/project/sslkeylog/" rel="nofollow noreferrer">sslkeylog</a>, which is compatible with both Python2 and Python3. I'm modifying your code to save the SSL key logs while making a connection to Stack Overflow.</p>
<pre class="lang-py prettyprint-override"><code>import urllib2
import sslkeylog
# Save SSL keys to "sslkeylog.txt" in this directory
# Note that you only have to do this once while this is in scope
sslkeylog.set_keylog("sslkeylog.txt")
# Make an HTTPS connection to Stack Overflow
requrl = "https://stackoverflow.com"
req = urllib2.Request(url=requrl)
rsp_fp = urllib2.urlopen(req)
</code></pre>
<h3>Verification</h3>
<p>Then if we check sslkeylog.txt, we can see that there is now an entry:</p>
<pre class="lang-sh prettyprint-override"><code>bash$ cat sslkeylogfile.txt
CLIENT_RANDOM a655a2e200ddc96c1571fe29af1962013ccbab1b9e9b865db112a9c1492c449a 3280c9fbee32df623074f80519f278420971aaa6eb91ab0f1f973d505a03ddbcc4fba2ca83f6d733addebdb0358e606d
</code></pre>
|
python-2.7|ssl|urllib2|wireshark
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.